@runtypelabs/persona 1.48.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +140 -8
  2. package/dist/index.cjs +90 -39
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +1098 -24
  5. package/dist/index.d.ts +1098 -24
  6. package/dist/index.global.js +134 -83
  7. package/dist/index.global.js.map +1 -1
  8. package/dist/index.js +90 -39
  9. package/dist/index.js.map +1 -1
  10. package/dist/install.global.js +1 -1
  11. package/dist/install.global.js.map +1 -1
  12. package/dist/widget.css +849 -513
  13. package/package.json +1 -1
  14. package/src/artifacts-session.test.ts +80 -0
  15. package/src/client.test.ts +20 -21
  16. package/src/client.ts +153 -4
  17. package/src/components/approval-bubble.ts +45 -42
  18. package/src/components/artifact-card.ts +91 -0
  19. package/src/components/artifact-pane.ts +501 -0
  20. package/src/components/composer-builder.ts +32 -27
  21. package/src/components/event-stream-view.ts +40 -40
  22. package/src/components/feedback.ts +36 -36
  23. package/src/components/forms.ts +11 -11
  24. package/src/components/header-builder.test.ts +32 -0
  25. package/src/components/header-builder.ts +55 -36
  26. package/src/components/header-layouts.ts +58 -125
  27. package/src/components/launcher.ts +36 -21
  28. package/src/components/message-bubble.ts +92 -65
  29. package/src/components/messages.ts +2 -2
  30. package/src/components/panel.ts +42 -11
  31. package/src/components/reasoning-bubble.ts +23 -23
  32. package/src/components/registry.ts +4 -0
  33. package/src/components/suggestions.ts +1 -1
  34. package/src/components/tool-bubble.ts +32 -32
  35. package/src/defaults.ts +30 -4
  36. package/src/index.ts +80 -2
  37. package/src/install.ts +22 -0
  38. package/src/plugins/types.ts +23 -0
  39. package/src/postprocessors.ts +2 -2
  40. package/src/runtime/host-layout.ts +174 -0
  41. package/src/runtime/init.test.ts +236 -0
  42. package/src/runtime/init.ts +114 -55
  43. package/src/session.ts +135 -2
  44. package/src/styles/tailwind.css +1 -1
  45. package/src/styles/widget.css +849 -513
  46. package/src/types/theme.ts +376 -0
  47. package/src/types.ts +338 -15
  48. package/src/ui.docked.test.ts +104 -0
  49. package/src/ui.ts +940 -227
  50. package/src/utils/artifact-gate.test.ts +255 -0
  51. package/src/utils/artifact-gate.ts +142 -0
  52. package/src/utils/artifact-resize.test.ts +64 -0
  53. package/src/utils/artifact-resize.ts +67 -0
  54. package/src/utils/attachment-manager.ts +10 -10
  55. package/src/utils/code-generators.test.ts +52 -0
  56. package/src/utils/code-generators.ts +40 -36
  57. package/src/utils/dock.ts +17 -0
  58. package/src/utils/dom-context.test.ts +504 -0
  59. package/src/utils/dom-context.ts +896 -0
  60. package/src/utils/dom.ts +12 -1
  61. package/src/utils/message-fingerprint.test.ts +187 -0
  62. package/src/utils/message-fingerprint.ts +105 -0
  63. package/src/utils/migration.ts +220 -0
  64. package/src/utils/morph.ts +1 -1
  65. package/src/utils/plugins.ts +175 -0
  66. package/src/utils/positioning.ts +4 -4
  67. package/src/utils/theme.test.ts +157 -0
  68. package/src/utils/theme.ts +224 -60
  69. package/src/utils/tokens.ts +701 -0
package/dist/index.cjs CHANGED
@@ -1,35 +1,70 @@
1
- "use strict";var qa=Object.create;var Ks=Object.defineProperty;var Va=Object.getOwnPropertyDescriptor;var za=Object.getOwnPropertyNames;var Ja=Object.getPrototypeOf,Ka=Object.prototype.hasOwnProperty;var Ya=(n,t)=>{for(var r in t)Ks(n,r,{get:t[r],enumerable:!0})},Ki=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of za(t))!Ka.call(n,o)&&o!==r&&Ks(n,o,{get:()=>t[o],enumerable:!(e=Va(t,o))||e.enumerable});return n};var Xa=(n,t,r)=>(r=n!=null?qa(Ja(n)):{},Ki(t||!n||!n.__esModule?Ks(r,"default",{value:n,enumerable:!0}):r,n)),Ga=n=>Ki(Ks({},"__esModule",{value:!0}),n);var sc={};Ya(sc,{AgentWidgetClient:()=>Wn,AgentWidgetSession:()=>Gn,AttachmentManager:()=>Bn,DEFAULT_DARK_THEME:()=>Kr,DEFAULT_LIGHT_THEME:()=>Jr,DEFAULT_WIDGET_CONFIG:()=>it,VERSION:()=>On,attachHeaderToContainer:()=>Fn,buildComposer:()=>Qn,buildDefaultHeader:()=>Br,buildExpandedHeader:()=>$r,buildHeader:()=>mn,buildHeaderWithLayout:()=>Zn,buildMinimalHeader:()=>Fr,componentRegistry:()=>rs,createActionManager:()=>Ps,createAgentExperience:()=>yr,createBestAvailableVoiceProvider:()=>ar,createBubbleWithLayout:()=>xa,createCSATFeedback:()=>vr,createComponentMiddleware:()=>Wa,createComponentStreamParser:()=>gr,createDirectivePostprocessor:()=>Qi,createFlexibleJsonStreamParser:()=>sa,createImagePart:()=>ca,createJsonStreamParser:()=>er,createLocalStorageAdapter:()=>pr,createMarkdownProcessor:()=>xs,createMarkdownProcessorFromConfig:()=>Ss,createMessageActions:()=>Dr,createNPSFeedback:()=>wr,createPlainTextParser:()=>Zs,createRegexJsonParser:()=>Qs,createStandardBubble:()=>es,createTextPart:()=>sr,createTypingIndicator:()=>$n,createVoiceProvider:()=>Hn,createXmlParser:()=>tr,default:()=>nc,defaultActionHandlers:()=>Nn,defaultJsonActionParser:()=>Ws,directivePostprocessor:()=>ea,escapeHtml:()=>Ys,extractComponentDirectiveFromMessage:()=>fr,fileToImagePart:()=>da,generateAssistantMessageId:()=>Pn,generateCodeSnippet:()=>Da,generateMessageId:()=>ra,generateUserMessageId:()=>Xn,getDisplayText:()=>ia,getHeaderLayout:()=>Nr,getImageParts:()=>la,hasComponentDirective:()=>mr,hasImages:()=>aa,headerLayouts:()=>dr,initAgentWidget:()=>Qr,isComponentDirectiveType:()=>La,isVoiceSupported:()=>Ts,markdownPostprocessor:()=>Wr,mergeWithDefaults:()=>ur,normalizeContent:()=>oa,pluginRegistry:()=>Ls,renderComponentDirective:()=>hr,renderLoadingIndicatorWithFallback:()=>Or,validateImageFile:()=>ua});module.exports=Ga(sc);var Xi=require("marked"),Za=n=>{if(n)return n},xs=n=>{var o,s;let t=n==null?void 0:n.markedOptions,r=new Xi.Marked({gfm:(o=t==null?void 0:t.gfm)!=null?o:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),e=Za(n==null?void 0:n.renderer);return e&&r.use({renderer:e}),i=>r.parse(i)},Ss=n=>n?xs({markedOptions:n.options,renderer:n.renderer}):xs(),Qa=xs(),Wr=n=>Qa(n),Ys=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Gi=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Yi=n=>`%%FORM_PLACEHOLDER_${n}%%`,Zi=(n,t)=>{let r=n;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=Yi(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,o)=>{let s=Yi(t.length);return t.push({token:s,type:o}),s}),r},Qi=n=>{let t=Ss(n);return r=>{let e=[],o=Zi(r,e),s=t(o);return e.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),v=`<div class="tvw-form-directive" data-tv-form="${Gi(a)}"></div>`;s=s.replace(d,v)}),s}},ea=n=>{let t=[],r=Zi(n,t),e=Wr(r);return t.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${Gi(s)}"></div>`;e=e.replace(i,d)}),e};var hn=require("partial-json"),Xs=n=>n.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),As=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},el=n=>{var i,a;let t=(i=n.completedAt)!=null?i:Date.now(),r=(a=n.startedAt)!=null?a:t,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,t-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},ta=n=>n.status==="complete"?el(n):n.status==="pending"?"Waiting":"",tl=n=>{var o,s,i;let r=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((i=(s=n.startedAt)!=null?s:n.completedAt)!=null?i:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var na=n=>n.status==="complete"?tl(n):"Using tool...",nl=()=>{let n=null,t=0,r=e=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=e.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
3
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,a=e.match(i);if(a&&a[1])try{return a[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>n,processChunk:async e=>{if(e.length<=t)return n!==null?{text:n,raw:e}:null;let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(e);return s!==null&&(n=s),t=e.length,n!==null?{text:n,raw:e}:null},close:async()=>{}}},Gs=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Zs=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Qs=()=>{var t;let n=nl();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:n.processChunk(r)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},er=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=t)return n!==null||n===""?{text:n||"",raw:r}:null;try{let o=(0,hn.parse)(r,hn.STR|hn.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?Xs(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=Xs(o.text)))}catch{}return t=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},sa=n=>{let t=null,r=0,o=n||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Xs(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Xs(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return t!==null?{text:t,raw:s}:null;try{let a=(0,hn.parse)(s,hn.STR|hn.OBJ),d=o(a);d!==null&&(t=d)}catch{}return r=s.length,{text:t||"",raw:s}},close:()=>{}}},tr=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let e=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(n=e[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var sl="https://api.runtype.com/v1/dispatch",Pr="https://api.runtype.com",Rr=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function rl(n){switch(n){case"json":return er;case"regex-json":return Qs;case"xml":return tr;default:return Zs}}var Wn=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var r,e,o;this.apiUrl=(r=t.apiUrl)!=null?r:sl,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(e=t.streamParser)!=null?e:rl(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders}setSSEEventCallback(t){this.onSSEEvent=t}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var e;let r=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Pr;return t==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var t,r;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 e=await this.sessionInitPromise;return this.clientSession=e,(r=(t=this.config).onSessionInit)==null||r.call(t,e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let t=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},e=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){let a=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):e.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let o=await e.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Pr}/v1/client/feedback`}async sendFeedback(t){var s,i;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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let a=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isAgentMode()?this.dispatchAgent(t,r):this.isClientTokenMode()?this.dispatchClientToken(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var o,s,i,a;let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let w=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:w}),w}let c=await this.buildPayload(t.messages),v=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([w])=>w!=="sessionId"&&w!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(Rr).map(w=>{var C,y,A;return{id:w.id,role:w.role,content:(A=(y=(C=w.contentParts)!=null?C:w.llmContent)!=null?y:w.rawContent)!=null?A:w.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...v&&Object.keys(v).length>0&&{metadata:v},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:e.signal});if(!m.ok){let w=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}if(m.status===429){let y=new Error(w.hint||"Message limit reached for this session.");throw r({type:"error",error:y}),y}let C=new Error(w.error||"Failed to send message");throw r({type:"error",error:C}),C}if(!m.body){let w=new Error("No response body received");throw r({type:"error",error:w}),w}r({type:"status",status:"connected"});try{await this.streamResponse(m.body,r,t.assistantMessageId)}finally{r({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")&&r({type:"error",error:c}),c}}async dispatchProxy(t,r){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,e){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,e)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var i;let o=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Pr}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async buildAgentPayload(t){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Rr).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),e={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:t,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(e.context=o)}return e}async buildPayload(t){let e={messages:t.slice().filter(Rr).sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:t,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(e.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...e},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return e}async handleCustomSSEEvent(t,r,e,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let a=()=>{if(e.current)return e.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:s()};return e.current=d,o(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,o(d)}return i.done&&(e.current&&(e.current.streaming=!1,o(e.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,e){var fe,Fe,Mt,gt,ft,Ht,je,ne,xe,He,$e,ze,Ot,he,Z,ct,bt,kt,Ct,Kt,te,Pe,xt,ve,Se,Je,Bt,It,qt,I,nt,O,Q,re,Ne,oe,Xe,Ge,pe,D,Ee,st,rt,Yt,Qt,Ze,en,vn,wn,rn,T,yn,ln,Sn,as,cn,dn,Dn,jn,Rs,Hs,Bs,ls,_n,Ae,cs,Xt,Dt,Fs,$s,ds,An,un,Ns,Os,Ds,Er,En,Tn,ot,Un,qn,us,ps,gs,hs,Ft,Vt,pn,ke,ms,Mn,tn,js,Vn,zn,kn,bn,_s,Us,Gt,Jn,qs,Vs,gn,Qe,et,Cn,fs,vs,Tr,Lt,Mr,$t;let o=t.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,c=()=>a+d++,v=q=>{let We=q.reasoning?{...q.reasoning,chunks:[...q.reasoning.chunks]}:void 0,_e=q.toolCall?{...q.toolCall,chunks:q.toolCall.chunks?[...q.toolCall.chunks]:void 0}:void 0,dt=q.tools?q.tools.map(vt=>({...vt,chunks:vt.chunks?[...vt.chunks]:void 0})):void 0;return{...q,reasoning:We,toolCall:_e,tools:dt}},p=q=>{r({type:"message",message:v(q)})},m=null,w={current:null},C=new Map,y=new Map,A={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},H=q=>{if(q==null)return null;try{return String(q)}catch{return null}},Y=q=>{var We,_e,dt,vt,Tt;return H((Tt=(vt=(dt=(_e=(We=q.stepId)!=null?We:q.step_id)!=null?_e:q.step)!=null?dt:q.parentId)!=null?vt:q.flowStepId)!=null?Tt:q.flow_step_id)},k=q=>{var We,_e,dt,vt,Tt,at,f;return H((f=(at=(Tt=(vt=(dt=(_e=(We=q.callId)!=null?We:q.call_id)!=null?_e:q.requestId)!=null?dt:q.request_id)!=null?vt:q.toolCallId)!=null?Tt:q.tool_call_id)!=null?at:q.stepId)!=null?f:q.step_id)},P=()=>m||(m={id:e!=null?e:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(m),m),L=(q,We)=>{A.lastId=We,q&&A.byStep.set(q,We)},F=(q,We)=>{var Tt;let _e=(Tt=q.reasoningId)!=null?Tt:q.id,dt=Y(q);if(_e){let at=String(_e);return L(dt,at),at}if(dt){let at=A.byStep.get(dt);if(at)return A.lastId=at,at}if(A.lastId&&!We)return A.lastId;if(!We)return null;let vt=`reason-${c()}`;return L(dt,vt),vt},ue=q=>{let We=C.get(q);if(We)return We;let _e={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,_e),p(_e),_e},z=(q,We)=>{x.lastId=We,q&&x.byCall.set(q,We)},V=(q,We)=>{var Tt;let _e=(Tt=q.toolId)!=null?Tt:q.id,dt=k(q);if(_e){let at=String(_e);return z(dt,at),at}if(dt){let at=x.byCall.get(dt);if(at)return x.lastId=at,at}if(x.lastId&&!We)return x.lastId;if(!We)return null;let vt=`tool-${c()}`;return z(dt,vt),vt},X=q=>{let We=y.get(q);if(We)return We;let _e={id:`tool-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:q,status:"pending"}};return y.set(q,_e),p(_e),_e},_=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){let We=Number(q);if(!Number.isNaN(We)&&Number.isFinite(We))return We;let _e=Date.parse(q);if(!Number.isNaN(_e))return _e}return Date.now()},Ce=q=>{if(typeof q=="string")return q;if(q==null)return"";try{return JSON.stringify(q)}catch{return String(q)}},se=new Map,G=new Map,U=null,N=new Map,ee=(fe=this.config.iterationDisplay)!=null?fe:"separate";for(;;){let{done:q,value:We}=await o.read();if(q)break;i+=s.decode(We,{stream:!0});let _e=i.split(`
1
+ "use strict";var Nc=Object.create;var ks=Object.defineProperty;var Oc=Object.getOwnPropertyDescriptor;var Dc=Object.getOwnPropertyNames;var _c=Object.getPrototypeOf,jc=Object.prototype.hasOwnProperty;var Vc=(e,n)=>{for(var t in n)ks(e,t,{get:n[t],enumerable:!0})},al=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Dc(n))!jc.call(e,o)&&o!==t&&ks(e,o,{get:()=>n[o],enumerable:!(r=Oc(n,o))||r.enumerable});return e};var qc=(e,n,t)=>(t=e!=null?Nc(_c(e)):{},al(n||!e||!e.__esModule?ks(t,"default",{value:e,enumerable:!0}):t,e)),Uc=e=>al(ks({},"__esModule",{value:!0}),e);var Wp={};Vc(Wp,{AgentWidgetClient:()=>Gn,AgentWidgetSession:()=>xr,AttachmentManager:()=>tr,DEFAULT_COMPONENTS:()=>vo,DEFAULT_DARK_THEME:()=>Do,DEFAULT_LIGHT_THEME:()=>Oo,DEFAULT_PALETTE:()=>bo,DEFAULT_SEMANTIC:()=>xo,DEFAULT_WIDGET_CONFIG:()=>gt,VERSION:()=>or,accessibilityPlugin:()=>Ic,animationsPlugin:()=>Wc,applyThemeVariables:()=>On,attachHeaderToContainer:()=>nr,brandPlugin:()=>Rc,buildComposer:()=>Sr,buildDefaultHeader:()=>Mo,buildHeader:()=>Ln,buildHeaderWithLayout:()=>wr,buildMinimalHeader:()=>ko,collectEnrichedPageContext:()=>Cc,componentRegistry:()=>Pn,createActionManager:()=>ls,createAgentExperience:()=>ro,createBestAvailableVoiceProvider:()=>Ds,createBubbleWithLayout:()=>Vl,createCSATFeedback:()=>to,createComponentMiddleware:()=>ac,createComponentStreamParser:()=>Gs,createDirectivePostprocessor:()=>pl,createFlexibleJsonStreamParser:()=>fl,createImagePart:()=>Cl,createJsonStreamParser:()=>Rs,createLocalStorageAdapter:()=>Xs,createMarkdownProcessor:()=>Xr,createMarkdownProcessorFromConfig:()=>Xn,createMessageActions:()=>Io,createNPSFeedback:()=>no,createPlainTextParser:()=>Is,createPlugin:()=>$c,createRegexJsonParser:()=>Ws,createStandardBubble:()=>Ar,createTextPart:()=>$s,createTheme:()=>vr,createThemeObserver:()=>Us,createTypingIndicator:()=>rr,createVoiceProvider:()=>er,createWidgetHostLayout:()=>cs,createXmlParser:()=>Hs,default:()=>Ip,defaultActionHandlers:()=>sr,defaultJsonActionParser:()=>is,defaultParseRules:()=>Yo,detectColorScheme:()=>es,directivePostprocessor:()=>ul,escapeHtml:()=>yr,extractComponentDirectiveFromMessage:()=>eo,fileToImagePart:()=>wl,formatEnrichedContext:()=>wc,generateAssistantMessageId:()=>Zn,generateCodeSnippet:()=>Lc,generateMessageId:()=>hl,generateStableSelector:()=>Xo,generateUserMessageId:()=>br,getActiveTheme:()=>To,getColorScheme:()=>Eo,getDisplayText:()=>bl,getHeaderLayout:()=>Lo,getImageParts:()=>vl,hasComponentDirective:()=>Qs,hasImages:()=>xl,headerLayouts:()=>zs,highContrastPlugin:()=>Bc,initAgentWidget:()=>Uo,isComponentDirectiveType:()=>oc,isDockedMountMode:()=>jt,isVoiceSupported:()=>Qr,markdownPostprocessor:()=>fo,mergeWithDefaults:()=>Ys,migrateV1Theme:()=>qs,normalizeContent:()=>yl,pluginRegistry:()=>as,reducedMotionPlugin:()=>Hc,renderComponentDirective:()=>Zs,renderLoadingIndicatorWithFallback:()=>Po,resolveDockConfig:()=>Cr,resolveTokens:()=>js,themeToCssVariables:()=>Vs,validateImageFile:()=>Sl,validateTheme:()=>Co,validateV1Theme:()=>Il});module.exports=Uc(Wp);var ll=require("marked"),zc=e=>{if(e)return e},Xr=e=>{var o,s;let n=e==null?void 0:e.markedOptions,t=new ll.Marked({gfm:(o=n==null?void 0:n.gfm)!=null?o:!0,breaks:(s=n==null?void 0:n.breaks)!=null?s:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=zc(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},Xn=e=>e?Xr({markedOptions:e.options,renderer:e.renderer}):Xr(),Jc=Xr(),fo=e=>Jc(e),yr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),cl=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),il=e=>`%%FORM_PLACEHOLDER_${e}%%`,dl=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=il(n.length);return n.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=il(n.length);return n.push({token:s,type:o}),s}),t},pl=e=>{let n=Xn(e);return t=>{let r=[],o=dl(t,r),s=n(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),g=`<div class="persona-form-directive" data-tv-form="${cl(i)}"></div>`;s=s.replace(d,g)}),s}},ul=e=>{let n=[],t=dl(e,n),r=fo(t);return n.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${cl(s)}"></div>`;r=r.replace(a,d)}),r};var Mn=require("partial-json"),Ls=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Gr=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)}},Kc=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},gl=e=>e.status==="complete"?Kc(e):e.status==="pending"?"Waiting":"",Yc=e=>{var o,s,a;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s: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 ml=e=>e.status==="complete"?Yc(e):"Using tool...",Xc=()=>{let e=null,n=0,t=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
3
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[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 o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(e=s),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Ps=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Is=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ws=()=>{var n;let e=Xc();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)}},Rs=()=>{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 o=(0,Mn.parse)(t,Mn.STR|Mn.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Ls(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Ls(o.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},fl=e=>{let n=null,t=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Ls(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ls(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=t)return n!==null?{text:n,raw:s}:null;try{let i=(0,Mn.parse)(s,Mn.STR|Mn.OBJ),d=o(i);d!==null&&(n=d)}catch{}return t=s.length,{text:n||"",raw:s}},close:()=>{}}},Hs=()=>{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 Gc="https://api.runtype.com/v1/dispatch",ho="https://api.runtype.com",yo=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 Zc(e){switch(e){case"json":return Rs;case"regex-json":return Ws;case"xml":return Hs;default:return Is}}var Gn=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,o;this.apiUrl=(t=n.apiUrl)!=null?t:Gc,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:Zc(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],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$/,""))||ho;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 s,a;let n=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||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 o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.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$/,""))||ho}/v1/client/feedback`}async sendFeedback(n){var s,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 o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),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 o,s,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,(s=(o=this.config).onSessionExpired)==null||s.call(o);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(yo).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 o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...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:s,body:JSON.stringify(o),signal:r.signal},o)}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:s,body:JSON.stringify(o),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 o=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...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:s,body:JSON.stringify(o),signal:r.signal},o)}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:s,body:JSON.stringify(o),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 o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ho}/v1/agents/${n.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,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(yo).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let a=new Date(o.createdAt).getTime(),i=new Date(s.createdAt).getTime();return a-i}).map(o=>{var s,a,i;return{role:o.role,content:(i=(a=(s=o.contentParts)!=null?s:o.llmContent)!=null?a:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(r.context=o)}return r}async buildPayload(n){let r={messages:n.slice().filter(yo).sort((o,s)=>{let a=new Date(o.createdAt).getTime(),i=new Date(s.createdAt).getTime();return a-i}).map(o=>{var s,a,i;return{role:o.role,content:(i=(a=(s=o.contentParts)!=null?s:o.llmContent)!=null?a:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(r.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...r},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return r}async handleCustomSSEEvent(n,t,r,o,s){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:s()};return r.current=d,o(d),d};if(a.text!==void 0){let d=i();d.content+=a.text,o(d)}return a.done&&(r.current&&(r.current.streaming=!1,o(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 ft,It,le,se,q,ne,oe,Ee,Ke,te,X,He,Ve,et,Vt,Dt,ie,Ue,Te,tt,_e,Xe,Wt,Rt,Mt,H,Z,z,Pe,Ce,Ie,Be,ut,ye,be,$e,de,bt,Gt,pn,un,ds,Wn,ar,Ge,gn,Rn,an,Pr,mn,dt,tn,vn,Ir,ir,Wr,Dn,fn,_n,xt,hn,Rr,Hn,yn,W,Bn,$n,Hr,Cn,jn,Br,wn,Sn,lr,cr,ps,us,gs,$r,dr,qe,Fr,nn,zt,ms,fs,Nr,Vn,An,hs,ys,bs,uo,qn,pr,ht,ur,gr,Or,Dr,_r,jr,qt,Zt,En,Re,Vr,Un,ln,xs,mr,fr,zn,Fn,vs,Cs,cn,Jn,ws;let o=n.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,g=G=>{let Fe=G.reasoning?{...G.reasoning,chunks:[...G.reasoning.chunks]}:void 0,we=G.toolCall?{...G.toolCall,chunks:G.toolCall.chunks?[...G.toolCall.chunks]:void 0}:void 0,Ne=G.tools?G.tools.map(vt=>({...vt,chunks:vt.chunks?[...vt.chunks]:void 0})):void 0;return{...G,reasoning:Fe,toolCall:we,tools:Ne}},p=G=>{t({type:"message",message:g(G)})},y=null,m={current:null},C=new Map,v=new Map,E={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=G=>{if(G==null)return null;try{return String(G)}catch{return null}},U=G=>{var Fe,we,Ne,vt,Nt;return k((Nt=(vt=(Ne=(we=(Fe=G.stepId)!=null?Fe:G.step_id)!=null?we:G.step)!=null?Ne:G.parentId)!=null?vt:G.flowStepId)!=null?Nt:G.flow_step_id)},M=G=>{var Fe,we,Ne,vt,Nt,Ct,b;return k((b=(Ct=(Nt=(vt=(Ne=(we=(Fe=G.callId)!=null?Fe:G.call_id)!=null?we:G.requestId)!=null?Ne:G.request_id)!=null?vt:G.toolCallId)!=null?Nt:G.tool_call_id)!=null?Ct:G.stepId)!=null?b:G.step_id)},O=()=>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),S=(G,Fe)=>{E.lastId=Fe,G&&E.byStep.set(G,Fe)},N=(G,Fe)=>{var Nt;let we=(Nt=G.reasoningId)!=null?Nt:G.id,Ne=U(G);if(we){let Ct=String(we);return S(Ne,Ct),Ct}if(Ne){let Ct=E.byStep.get(Ne);if(Ct)return E.lastId=Ct,Ct}if(E.lastId&&!Fe)return E.lastId;if(!Fe)return null;let vt=`reason-${c()}`;return S(Ne,vt),vt},Q=G=>{let Fe=C.get(G);if(Fe)return Fe;let we={id:`reason-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:G,status:"streaming",chunks:[]}};return C.set(G,we),p(we),we},K=(G,Fe)=>{x.lastId=Fe,G&&x.byCall.set(G,Fe)},re=new Set,J=new Map,pe=new Set,Le=new Map,Ye=G=>{if(!G)return!1;let Fe=G.replace(/_+/g,"_").replace(/^_|_$/g,"");return Fe==="emit_artifact_markdown"||Fe==="emit_artifact_component"},fe=(G,Fe)=>{var Nt;let we=(Nt=G.toolId)!=null?Nt:G.id,Ne=M(G);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&&!Fe)return x.lastId;if(!Fe)return null;let vt=`tool-${c()}`;return K(Ne,vt),vt},ee=G=>{let Fe=v.get(G);if(Fe)return Fe;let we={id:`tool-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:G,status:"pending"}};return v.set(G,we),p(we),we},Y=G=>{if(typeof G=="number"&&Number.isFinite(G))return G;if(typeof G=="string"){let Fe=Number(G);if(!Number.isNaN(Fe)&&Number.isFinite(Fe))return Fe;let we=Date.parse(G);if(!Number.isNaN(we))return we}return Date.now()},V=G=>{if(typeof G=="string")return G;if(G==null)return"";try{return JSON.stringify(G)}catch{return String(G)}},j=new Map,ce=new Map,he=null,mt=new Map,lt=(ft=this.config.iterationDisplay)!=null?ft:"separate";for(;;){let{done:G,value:Fe}=await o.read();if(G)break;a+=s.decode(Fe,{stream:!0});let we=a.split(`
5
5
 
6
- `);i=(Fe=_e.pop())!=null?Fe:"";for(let dt of _e){let vt=dt.split(`
7
- `),Tt="message",at="";for(let $ of vt)$.startsWith("event:")?Tt=$.replace("event:","").trim():$.startsWith("data:")&&(at+=$.replace("data:","").trim());if(!at)continue;let f;try{f=JSON.parse(at)}catch($){r({type:"error",error:$ instanceof Error?$:new Error("Failed to parse chat stream payload")});continue}let Re=Tt!=="message"?Tt:(Mt=f.type)!=null?Mt:"message";if((gt=this.onSSEEvent)==null||gt.call(this,Re,f),this.parseSSEEvent){w.current=m;let $=await this.handleCustomSSEEvent(f,r,w,p,c);if(w.current&&!m&&(m=w.current),$)continue}if(Re==="reason_start"){let $=(ft=F(f,!0))!=null?ft:`reason-${c()}`,b=ue($);b.reasoning=(Ht=b.reasoning)!=null?Ht:{id:$,status:"streaming",chunks:[]},b.reasoning.startedAt=(ne=b.reasoning.startedAt)!=null?ne:_((je=f.startedAt)!=null?je:f.timestamp),b.reasoning.completedAt=void 0,b.reasoning.durationMs=void 0,b.streaming=!0,b.reasoning.status="streaming",p(b)}else if(Re==="reason_delta"||Re==="reason_chunk"){let $=(He=(xe=F(f,!1))!=null?xe:F(f,!0))!=null?He:`reason-${c()}`,b=ue($);b.reasoning=($e=b.reasoning)!=null?$e:{id:$,status:"streaming",chunks:[]},b.reasoning.startedAt=(Ot=b.reasoning.startedAt)!=null?Ot:_((ze=f.startedAt)!=null?ze:f.timestamp);let R=(ct=(Z=(he=f.reasoningText)!=null?he:f.text)!=null?Z:f.delta)!=null?ct:"";if(R&&f.hidden!==!0&&b.reasoning.chunks.push(String(R)),b.reasoning.status=f.done?"complete":"streaming",f.done){b.reasoning.completedAt=_((bt=f.completedAt)!=null?bt:f.timestamp);let ae=(kt=b.reasoning.startedAt)!=null?kt:Date.now();b.reasoning.durationMs=Math.max(0,((Ct=b.reasoning.completedAt)!=null?Ct:Date.now())-ae)}b.streaming=b.reasoning.status!=="complete",p(b)}else if(Re==="reason_complete"){let $=(te=(Kt=F(f,!1))!=null?Kt:F(f,!0))!=null?te:`reason-${c()}`,b=C.get($);if(b!=null&&b.reasoning){b.reasoning.status="complete",b.reasoning.completedAt=_((Pe=f.completedAt)!=null?Pe:f.timestamp);let ae=(xt=b.reasoning.startedAt)!=null?xt:Date.now();b.reasoning.durationMs=Math.max(0,((ve=b.reasoning.completedAt)!=null?ve:Date.now())-ae),b.streaming=!1,p(b)}let R=Y(f);R&&A.byStep.delete(R)}else if(Re==="tool_start"){let $=(Se=V(f,!0))!=null?Se:`tool-${c()}`,b=X($),R=(Je=b.toolCall)!=null?Je:{id:$,status:"pending"};R.name=(Bt=f.toolName)!=null?Bt:R.name,R.status="running",f.args!==void 0?R.args=f.args:f.parameters!==void 0&&(R.args=f.parameters),R.startedAt=(qt=R.startedAt)!=null?qt:_((It=f.startedAt)!=null?It:f.timestamp),R.completedAt=void 0,R.durationMs=void 0,b.toolCall=R,b.streaming=!0;let ae=f.agentContext;(ae||f.executionId)&&(b.agentMetadata={executionId:(I=ae==null?void 0:ae.executionId)!=null?I:f.executionId,iteration:(nt=ae==null?void 0:ae.iteration)!=null?nt:f.iteration}),p(b)}else if(Re==="tool_chunk"||Re==="tool_delta"){let $=(Q=(O=V(f,!1))!=null?O:V(f,!0))!=null?Q:`tool-${c()}`,b=X($),R=(re=b.toolCall)!=null?re:{id:$,status:"running"};R.startedAt=(oe=R.startedAt)!=null?oe:_((Ne=f.startedAt)!=null?Ne:f.timestamp);let ae=(pe=(Ge=(Xe=f.text)!=null?Xe:f.delta)!=null?Ge:f.message)!=null?pe:"";ae&&(R.chunks=(D=R.chunks)!=null?D:[],R.chunks.push(String(ae))),R.status="running",b.toolCall=R,b.streaming=!0;let Te=f.agentContext;(Te||f.executionId)&&(b.agentMetadata=(rt=b.agentMetadata)!=null?rt:{executionId:(Ee=Te==null?void 0:Te.executionId)!=null?Ee:f.executionId,iteration:(st=Te==null?void 0:Te.iteration)!=null?st:f.iteration}),p(b)}else if(Re==="tool_complete"){let $=(Qt=(Yt=V(f,!1))!=null?Yt:V(f,!0))!=null?Qt:`tool-${c()}`,b=X($),R=(Ze=b.toolCall)!=null?Ze:{id:$,status:"running"};R.status="complete",f.result!==void 0&&(R.result=f.result),typeof f.duration=="number"&&(R.duration=f.duration),R.completedAt=_((en=f.completedAt)!=null?en:f.timestamp);let ae=(vn=f.duration)!=null?vn:f.executionTime;if(typeof ae=="number")R.durationMs=ae;else{let Wt=(wn=R.startedAt)!=null?wn:Date.now();R.durationMs=Math.max(0,((rn=R.completedAt)!=null?rn:Date.now())-Wt)}b.toolCall=R,b.streaming=!1;let Te=f.agentContext;(Te||f.executionId)&&(b.agentMetadata=(ln=b.agentMetadata)!=null?ln:{executionId:(T=Te==null?void 0:Te.executionId)!=null?T:f.executionId,iteration:(yn=Te==null?void 0:Te.iteration)!=null?yn:f.iteration}),p(b);let Ke=k(f);Ke&&x.byCall.delete(Ke)}else if(Re==="step_chunk"||Re==="step_delta"){let $=f.stepType,b=f.executionType;if($==="tool"||b==="context")continue;let R=P(),ae=(dn=(cn=(as=(Sn=f.text)!=null?Sn:f.delta)!=null?as:f.content)!=null?cn:f.chunk)!=null?dn:"";if(ae){let Ke=((Dn=G.get(R.id))!=null?Dn:"")+ae;R.rawContent=Ke,se.has(R.id)||se.set(R.id,this.createStreamParser());let Wt=se.get(R.id),lt=Ke.trim().startsWith("{")||Ke.trim().startsWith("[");if(lt&&G.set(R.id,Ke),Wt.__isPlainTextParser===!0){R.content+=ae,G.delete(R.id),se.delete(R.id),R.rawContent=void 0,p(R);continue}let wt=Wt.processChunk(Ke);if(wt instanceof Promise)wt.then(De=>{var ht;let qe=typeof De=="string"?De:(ht=De==null?void 0:De.text)!=null?ht:null;if(qe!==null&&qe.trim()!==""){let Ve=m;Ve&&Ve.id===R.id&&(Ve.content=qe,p(Ve))}else if(!lt&&!Ke.trim().startsWith("<")){let Ve=m;Ve&&Ve.id===R.id&&(Ve.content+=ae,G.delete(Ve.id),se.delete(Ve.id),Ve.rawContent=void 0,p(Ve))}}).catch(()=>{R.content+=ae,G.delete(R.id),se.delete(R.id),R.rawContent=void 0,p(R)});else{let De=typeof wt=="string"?wt:(jn=wt==null?void 0:wt.text)!=null?jn:null;De!==null&&De.trim()!==""?(R.content=De,p(R)):!lt&&!Ke.trim().startsWith("<")&&(R.content+=ae,G.delete(R.id),se.delete(R.id),R.rawContent=void 0,p(R))}}if(f.isComplete){let Te=(Hs=(Rs=f.result)==null?void 0:Rs.response)!=null?Hs:R.content;if(Te){let Ke=G.get(R.id),Wt=Ke!=null?Ke:Ce(Te);R.rawContent=Wt;let lt=se.get(R.id),St=null,wt=!1;if(lt&&(St=lt.getExtractedText(),St===null&&(St=Gs(Wt)),St===null)){let De=lt.processChunk(Wt);De instanceof Promise?(wt=!0,De.then(qe=>{var Ve;let ht=typeof qe=="string"?qe:(Ve=qe==null?void 0:qe.text)!=null?Ve:null;if(ht!==null){let At=m;At&&At.id===R.id&&(At.content=ht,At.streaming=!1,se.delete(At.id),G.delete(At.id),p(At))}})):St=typeof De=="string"?De:(Bs=De==null?void 0:De.text)!=null?Bs:null}if(!wt){St!==null&&St.trim()!==""?R.content=St:G.has(R.id)||(R.content=Ce(Te));let De=se.get(R.id);if(De){let qe=(ls=De.close)==null?void 0:ls.call(De);qe instanceof Promise&&qe.catch(()=>{}),se.delete(R.id)}G.delete(R.id),R.streaming=!1,p(R)}}}}else if(Re==="step_complete"){let $=f.stepType,b=f.executionType;if($==="tool"||b==="context")continue;let R=(_n=f.result)==null?void 0:_n.response,ae=P();if(R!=null){let Te=se.get(ae.id),Ke=!1,Wt=!1;if(Te){let lt=Te.getExtractedText(),St=G.get(ae.id),wt=St!=null?St:Ce(R);if(ae.rawContent=wt,lt!==null&&lt.trim()!=="")ae.content=lt,Ke=!0;else{let De=Gs(wt);if(De!==null)ae.content=De,Ke=!0;else{let qe=Te.processChunk(wt);if(qe instanceof Promise)Wt=!0,qe.then(ht=>{var At;let Ve=typeof ht=="string"?ht:(At=ht==null?void 0:ht.text)!=null?At:null;if(Ve!==null&&Ve.trim()!==""){let jt=m;jt&&jt.id===ae.id&&(jt.content=Ve,jt.streaming=!1,se.delete(jt.id),G.delete(jt.id),p(jt))}else{let jt=Te.getExtractedText(),Zt=m;Zt&&Zt.id===ae.id&&(jt!==null&&jt.trim()!==""?Zt.content=jt:G.has(Zt.id)||(Zt.content=Ce(R)),Zt.streaming=!1,se.delete(Zt.id),G.delete(Zt.id),p(Zt))}});else{let ht=typeof qe=="string"?qe:(Ae=qe==null?void 0:qe.text)!=null?Ae:null;if(ht!==null&&ht.trim()!=="")ae.content=ht,Ke=!0;else{let Ve=Te.getExtractedText();Ve!==null&&Ve.trim()!==""&&(ae.content=Ve,Ke=!0)}}}}}if(!Wt){if(!ae.rawContent){let lt=G.get(ae.id);ae.rawContent=lt!=null?lt:Ce(R)}if(!Ke&&!G.has(ae.id)&&(ae.content=Ce(R)),Te){let lt=(cs=Te.close)==null?void 0:cs.call(Te);lt instanceof Promise&&lt.catch(()=>{})}se.delete(ae.id),G.delete(ae.id),ae.streaming=!1,p(ae)}}else se.delete(ae.id),G.delete(ae.id),ae.streaming=!1,p(ae)}else if(Re==="flow_complete"){let $=(Xt=f.result)==null?void 0:Xt.response;if($!=null){let b=P(),R=G.get(b.id),ae=R!=null?R:Ce($);b.rawContent=ae;let Te=Ce($),Ke=se.get(b.id);if(Ke){let St=Gs(ae);if(St!==null)Te=St;else{let wt=Ke.processChunk(ae);wt instanceof Promise&&wt.then(qe=>{var Ve;let ht=typeof qe=="string"?qe:(Ve=qe==null?void 0:qe.text)!=null?Ve:null;if(ht!==null){let At=m;At&&At.id===b.id&&(At.content=ht,At.streaming=!1,p(At))}});let De=Ke.getExtractedText();De!==null&&(Te=De)}}se.delete(b.id),G.delete(b.id);let Wt=Te!==b.content,lt=b.streaming!==!1;Wt&&(b.content=Te),b.streaming=!1,(Wt||lt)&&p(b)}else if(m!==null){let b=m;se.delete(b.id),G.delete(b.id),b.streaming!==!1&&(b.streaming=!1,p(b))}r({type:"status",status:"idle"})}else if(Re==="agent_start")U={executionId:f.executionId,agentId:(Dt=f.agentId)!=null?Dt:"virtual",agentName:(Fs=f.agentName)!=null?Fs:"",status:"running",currentIteration:0,maxIterations:($s=f.maxIterations)!=null?$s:1,startedAt:_(f.startedAt)};else if(Re==="agent_iteration_start"){if(U&&(U.currentIteration=f.iteration),ee==="separate"&&f.iteration>1){let $=m;$&&($.streaming=!1,p($),N.set(f.iteration-1,$),m=null)}}else if(Re!=="agent_turn_start"){if(Re==="agent_turn_delta"){if(f.contentType==="text"){let $=P();$.content+=(ds=f.delta)!=null?ds:"",$.agentMetadata={executionId:f.executionId,iteration:f.iteration,turnId:f.turnId,agentName:U==null?void 0:U.agentName},p($)}else if(f.contentType==="thinking"){let $=(An=f.turnId)!=null?An:`agent-think-${f.iteration}`,b=ue($);b.reasoning=(un=b.reasoning)!=null?un:{id:$,status:"streaming",chunks:[]},b.reasoning.chunks.push((Ns=f.delta)!=null?Ns:""),b.agentMetadata={executionId:f.executionId,iteration:f.iteration,turnId:f.turnId},p(b)}else if(f.contentType==="tool_input"){let $=(Os=f.toolCallId)!=null?Os:x.lastId;if($){let b=y.get($);b!=null&&b.toolCall&&(b.toolCall.chunks=(Ds=b.toolCall.chunks)!=null?Ds:[],b.toolCall.chunks.push((Er=f.delta)!=null?Er:""),p(b))}}}else if(Re==="agent_turn_complete"){let $=f.turnId;if($){let b=C.get($);if(b!=null&&b.reasoning){b.reasoning.status="complete",b.reasoning.completedAt=_(f.completedAt);let R=(En=b.reasoning.startedAt)!=null?En:Date.now();b.reasoning.durationMs=Math.max(0,((Tn=b.reasoning.completedAt)!=null?Tn:Date.now())-R),b.streaming=!1,p(b)}}}else if(Re==="agent_tool_start"){let $=(ot=f.toolCallId)!=null?ot:`agent-tool-${c()}`;z(k(f),$);let b=X($),R=(Un=b.toolCall)!=null?Un:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};R.name=(qn=f.toolName)!=null?qn:R.name,R.status="running",f.parameters!==void 0&&(R.args=f.parameters),R.startedAt=_((us=f.startedAt)!=null?us:f.timestamp),b.toolCall=R,b.streaming=!0,b.agentMetadata={executionId:f.executionId,iteration:f.iteration},p(b)}else if(Re==="agent_tool_delta"){let $=(ps=f.toolCallId)!=null?ps:x.lastId;if($){let b=(gs=y.get($))!=null?gs:X($);b.toolCall&&(b.toolCall.chunks=(hs=b.toolCall.chunks)!=null?hs:[],b.toolCall.chunks.push((Ft=f.delta)!=null?Ft:""),b.toolCall.status="running",b.streaming=!0,p(b))}}else if(Re==="agent_tool_complete"){let $=(Vt=f.toolCallId)!=null?Vt:x.lastId;if($){let b=(pn=y.get($))!=null?pn:X($);if(b.toolCall){b.toolCall.status="complete",f.result!==void 0&&(b.toolCall.result=f.result),typeof f.executionTime=="number"&&(b.toolCall.durationMs=f.executionTime),b.toolCall.completedAt=_((ke=f.completedAt)!=null?ke:f.timestamp),b.streaming=!1,p(b);let R=k(f);R&&x.byCall.delete(R)}}}else if(Re!=="agent_iteration_complete"){if(Re==="agent_reflection"||Re==="agent_reflect"){let $=`agent-reflection-${f.executionId}-${f.iteration}`,b={id:$,role:"assistant",content:(ms=f.reflection)!=null?ms:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(Mn=f.reflection)!=null?Mn:""]},agentMetadata:{executionId:f.executionId,iteration:f.iteration}};p(b)}else if(Re==="agent_complete"){U&&(U.status=f.success?"complete":"error",U.completedAt=_(f.completedAt),U.stopReason=f.stopReason);let $=m;$&&($.streaming=!1,p($)),r({type:"status",status:"idle"})}else if(Re==="agent_error"){let $=typeof f.error=="string"?f.error:(js=(tn=f.error)==null?void 0:tn.message)!=null?js:"Agent execution error";f.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):r({type:"error",error:new Error($)})}else if(Re!=="agent_ping")if(Re==="agent_approval_start"){let $=(Vn=f.approvalId)!=null?Vn:`approval-${c()}`,b={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(zn=U==null?void 0:U.agentId)!=null?zn:"virtual",executionId:(bn=(kn=f.executionId)!=null?kn:U==null?void 0:U.executionId)!=null?bn:"",toolName:(_s=f.toolName)!=null?_s:"",toolType:f.toolType,description:(Gt=f.description)!=null?Gt:`Execute ${(Us=f.toolName)!=null?Us:"tool"}`,parameters:f.parameters}};p(b)}else if(Re==="step_await"&&f.awaitReason==="approval_required"){let $=(Jn=f.approvalId)!=null?Jn:`approval-${c()}`,b={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(qs=U==null?void 0:U.agentId)!=null?qs:"virtual",executionId:(gn=(Vs=f.executionId)!=null?Vs:U==null?void 0:U.executionId)!=null?gn:"",toolName:(Qe=f.toolName)!=null?Qe:"",toolType:f.toolType,description:(Cn=f.description)!=null?Cn:`Execute ${(et=f.toolName)!=null?et:"tool"}`,parameters:f.parameters}};p(b)}else if(Re==="agent_approval_complete"){let $=f.approvalId;if($){let R={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:(fs=f.decision)!=null?fs:"approved",agentId:(vs=U==null?void 0:U.agentId)!=null?vs:"virtual",executionId:(Lt=(Tr=f.executionId)!=null?Tr:U==null?void 0:U.executionId)!=null?Lt:"",toolName:(Mr=f.toolName)!=null?Mr:"",description:($t=f.description)!=null?$t:"",resolvedAt:Date.now()}};p(R)}}else Re==="error"&&f.error&&r({type:"error",error:f.error instanceof Error?f.error:new Error(String(f.error))})}}}}}};function ra(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${n}_${t}`}function Xn(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function Pn(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var nr="[Image]";function oa(n){return typeof n=="string"?[{type:"text",text:n}]:n}function ia(n){return typeof n=="string"?n:n.filter(t=>t.type==="text").map(t=>t.text).join("")}function aa(n){return typeof n=="string"?!1:n.some(t=>t.type==="image")}function la(n){return typeof n=="string"?[]:n.filter(t=>t.type==="image")}function sr(n){return{type:"text",text:n}}function ca(n,t){return{type:"image",image:n,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function da(n){return new Promise((t,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;t({type:"image",image:o,mimeType:n.type,alt:n.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(n)})}function ua(n,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(n.type)?n.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var pa=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ol=["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"],xn=[...pa,...ol];function il(n){return pa.includes(n)||n.startsWith("image/")}function rr(n){return il(n.type)}async function ga(n){return new Promise((t,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;rr(n)?t({type:"image",image:o,mimeType:n.type,alt:n.name}):t({type:"file",data:o,mimeType:n.type,filename:n.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(n)})}function ha(n,t=xn,r=10*1024*1024){return t.includes(n.type)?n.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${t.join(", ")}`}}function al(n){let t=n.split(".");return t.length>1?t.pop().toLowerCase():""}function ma(n,t){let r=al(t).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"}[n]||r||"FILE"}var or=class{constructor(t=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=t}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let e=r.AudioContext||r.webkitAudioContext;this.ctx=new e({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let r=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),r=d,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let e=this.ensureContext(),o=this.pcmToFloat32(r),s=e.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let i=e.createBufferSource();i.buffer=s,i.connect(e.destination);let a=e.currentTime;this.nextStartTime<a&&(this.nextStartTime=a),i.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(i),this.pendingCount++,this.playing=!0,i.onended=()=>{let d=this.activeSources.indexOf(i);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.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(t){this.finishedCallbacks.push(t)}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 t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),e=new Float32Array(r),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<r;s++){let i=o.getInt16(s*2,!0);e[s]=i/32768}return e}};var ir=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,r,e,o,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(r),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let i=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(i);let a=0;for(let v=0;v<i.length;v++)a+=i[v]*i[v];let d=Math.sqrt(a/i.length);(e==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):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 Es=class{constructor(t){this.config=t;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 ir;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(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,r,e;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",i=(t=this.config)==null?void 0:t.host,a=(r=this.config)==null?void 0:r.agentId,d=(e=this.config)==null?void 0:e.clientToken;if(!a||!d)throw new Error("agentId and clientToken are required");if(!i)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${s}//${i}/ws/agents/${a}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let v=`${s}//${i}/ws/agents/${a}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((m,w)=>{if(!this.ws)return w(new Error("WebSocket not created"));let C=!1,y=x=>{C||(C=!0,clearTimeout(A),w(new Error(x)))},A=setTimeout(()=>y("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(A),m())},{once:!0}),this.ws.addEventListener("error",()=>{y("WebSocket connection failed to "+v+"."+p)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let H=x.code!==1006?` (code ${x.code})`:"";y("WebSocket connection failed"+H+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(r=>r(new Error("WebSocket error"))),this.statusCallbacks.forEach(r=>r("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let r=JSON.parse(t.data);this.handleWebSocketMessage(r)}catch{this.errorCallbacks.forEach(e=>e(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var r,e;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(r=t.response.audio)!=null&&r.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(t.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(e=t.response.audio)!=null&&e.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(t.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new or(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(r=>r("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("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 t,r,e,o;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 s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let i=this.audioContext,a=(r=(t=this.config)==null?void 0:t.pauseDuration)!=null?r:2e3,d=(o=(e=this.config)==null?void 0:e.silenceThreshold)!=null?o:.01;this.vad.start(i,this.mediaStream,"silence",{threshold:d,duration:a},()=>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(m=>m("processing")),this.processingStartCallbacks.forEach(m=>m());let v=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:v});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(s){throw this.errorCallbacks.forEach(i=>i(s)),this.statusCallbacks.forEach(i=>i("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,i;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let r=this.audioContext,e=(i=(s=this.config)==null?void 0:s.silenceThreshold)!=null?i:.01;this.vad.start(r,this.mediaStream,"speech",{threshold:e,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(r=>r(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var r;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(e=>e(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(e=>e("error"));return}try{let e=await this.blobToBase64(t),o=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:e,format:o,sampleRate:16e3,voiceId:(r=this.config)==null?void 0:r.voiceId,requestId:s}))}catch(e){this.errorCallbacks.forEach(o=>o(e)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((r,e)=>{let o=new FileReader;o.onload=()=>{let i=o.result.split(",")[1];r(i)},o.onerror=e,o.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let r=atob(t.base64),e=new Uint8Array(r.length);for(let c=0;c<r.length;c++)e[c]=r.charCodeAt(c);let o=t.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,i=new Blob([e],{type:s}),a=URL.createObjectURL(i),d=new Audio(a);this.currentAudio=d,this.currentAudioUrl=a,d.onended=()=>{URL.revokeObjectURL(a),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}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(t=>t.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(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Rn=class{constructor(t={}){this.config=t;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(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var a;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),i=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:i?.8:.5,provider:"browser"})),i&&!((a=this.config)!=null&&a.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(o=>o(e)),this.statusCallbacks.forEach(o=>o("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Hn(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Es(n.runtype);case"browser":if(!Rn.isSupported())throw new Error("Browser speech recognition not supported");return new Rn(n.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function ar(n){if((n==null?void 0:n.type)==="runtype"&&n.runtype)return Hn({type:"runtype",runtype:n.runtype});if(Rn.isSupported())return Hn({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ts(n){try{return ar(n),!0}catch{return!1}}var Gn=class n{constructor(t={},r){this.config=t;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var r,e,o,s,i,a,d;t.type==="message"?(this.upsertMessage(t.message),(r=t.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(e=t.message.agentMetadata.agentName)!=null?e:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):t.type==="status"?(this.setStatus(t.status),t.status==="connecting"?this.setStreaming(!0):(t.status==="idle"||t.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=t.status==="error"?"error":"complete"))):t.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(d=(a=this.callbacks).onError)==null||d.call(a,t.error))};var e;this.messages=[...(e=t.initialMessages)!=null?e:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Wn(t),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ts((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,r,e;return(e=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?e:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var r,e,o;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Hn(s);let i=(r=this.config.voiceRecognition)!=null?r:{},a=(e=i.processingText)!=null?e:"\u{1F3A4} Processing voice...",d=(o=i.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let v=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=v.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var v,p,m,w,C,y;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((v=c.transcript)!=null&&v.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&&((m=c.text)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(w=c.text)!=null&&w.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let A=(y=this.pendingVoiceAssistantMessageId)!=null?y:(C=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:C.id;A&&this.ttsSpokenMessageIds.add(A)}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 v,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(v=this.callbacks).onVoiceStatusChanged)==null||p.call(v,c)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,e,o,s,i,a,d,c,v;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((e=t.runtype)==null?void 0:e.agentId)||"",clientToken:((o=t.runtype)==null?void 0:o.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(i=t.runtype)==null?void 0:i.voiceId,pauseDuration:(a=t.runtype)==null?void 0:a.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=t.browser)==null?void 0:c.language)||"en-US",continuous:(v=t.browser)==null?void 0:v.continuous}};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(r=(t=this.callbacks).onError)==null||r.call(t,e instanceof Error?e:new Error(String(e))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Wn(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:e,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:d,streaming:c=!1,voiceProcessing:v}=t,m={id:i!=null?i:r==="user"?Xn():r==="assistant"?Pn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:e,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...v!==void 0&&{voiceProcessing:v}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let e of t){let{role:o,content:s,llmContent:i,contentParts:a,id:d,createdAt:c,sequence:v,streaming:p=!1}=e,w={id:d!=null?d:o==="user"?Xn():o==="assistant"?Pn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:v!=null?v:this.nextSequence(),streaming:p,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(w)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(t,r){var c,v,p,m,w;let e=t.trim();if(!e&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let o=Xn(),s=Pn(),i={id:o,role:"user",content:e||nr,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(C){let y=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!y){let A={id:s,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(A)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,y||(C instanceof Error?(p=(v=this.callbacks).onError)==null||p.call(v,C):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(C))))}}async continueConversation(){var o,s,i,a,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Pn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let e=[...this.messages];try{await this.client.dispatch({messages:e,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(c){let v={id:t,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(v),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,c):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(c)))}}async connectStream(t,r){var o,s,i;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=!1;for(let a of this.messages)a.streaming&&(a.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(a){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(i=(s=this.callbacks).onError)==null||i.call(s,a instanceof Error?a:new Error(String(a)))}}async resolveApproval(t,r){var d,c,v;let e=`approval-${t.id}`,o={...t,status:r,resolvedAt:Date.now()},s={id:e,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s);let i=this.config.approval,a=i&&typeof i=="object"?i.onDecision:void 0;try{let p;if(a?p=await a({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),p){let m=null;if(p instanceof Response){if(!p.ok){let w=await p.json().catch(()=>null);throw new Error((d=w==null?void 0:w.error)!=null?d:`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m):r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(v=(c=this.callbacks).onError)==null||v.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(t.map(e=>{var o;return{...e,streaming:!1,sequence:(o=e.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let e=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!e)return;if(this.ttsSpokenMessageIds.has(e.id)){this.ttsSpokenMessageIds.delete(e.id);return}let o=e.content;o.trim()&&this.speak(o,t)}speak(t,r){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let e=window.speechSynthesis;e.cancel();let o=new SpeechSynthesisUtterance(t),s=e.getVoices();if(r.voice){let i=s.find(a=>a.name===r.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=r.pickVoice?r.pickVoice(s):n.pickBestVoice(s));r.rate!==void 0&&(o.rate=r.rate),r.pitch!==void 0&&(o.pitch=r.pitch),setTimeout(()=>e.speak(o),50)}static pickBestVoice(t){var e;let r=["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 o of r){let s=t.find(i=>i.name===o);if(s)return s}return(e=t.find(o=>o.lang.startsWith("en")))!=null?e:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),e=this.messages.findIndex(o=>o.id===r.id);if(e===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===e?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((r,e)=>{var d,c;let o=new Date(r.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(d=r.sequence)!=null?d:0,a=(c=e.sequence)!=null?c:0;return i!==a?i-a:r.id.localeCompare(e.id)})}};var g=(n,t)=>{let r=document.createElement(n);return t&&(r.className=t),r};var ll=Xa(require("lucide"),1),ie=(n,t=24,r="currentColor",e=2)=>{try{let o=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=ll[o];return s?cl(s,t,r,e):(console.warn(`Lucide icon "${n}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${n}":`,o),null}};function cl(n,t,r,e){if(!n||!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([c,v])=>{c!=="stroke"&&d.setAttribute(c,String(v))}),o.appendChild(d)}}}),o}var lr={allowedTypes:xn,maxFileSize:10*1024*1024,maxFiles:4};function dl(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ul(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-json":"file"}var Bn=class n{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,e,o;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:lr.allowedTypes,maxFileSize:(e=t.maxFileSize)!=null?e:lr.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:lr.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:lr.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,e,o,s,i,a,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(e=(r=this.config).onFileRejected)==null||e.call(r,c,"count");continue}let v=ha(c,this.config.allowedTypes,this.config.maxFileSize);if(!v.valid){let p=(o=v.error)!=null&&o.includes("type")?"type":"size";(i=(s=this.config).onFileRejected)==null||i.call(s,c,p);continue}try{let p=await ga(c),m=rr(c)?URL.createObjectURL(c):null,w={id:dl(),file:c,previewUrl:m,contentPart:p};this.attachments.push(w),this.renderPreview(w)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(a=this.config).onAttachmentsChange)==null||d.call(a,this.getAttachments())}}removeAttachment(t){var s,i,a;let r=this.attachments.findIndex(d=>d.id===t);if(r===-1)return;let e=this.attachments[r];e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var t,r;for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=rr(t.file),e=g("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(e.setAttribute("data-attachment-id",t.id),e.style.width="48px",e.style.height="48px",r&&t.previewUrl){let i=g("img");i.src=t.previewUrl,i.alt=t.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",e.appendChild(i)}else{let i=g("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=ul(t.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let c=g("span");c.textContent=ma(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--cw-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",i.appendChild(c),e.appendChild(i)}let o=g("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ie("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(t.id)}),e.appendChild(o),this.previewsContainer.appendChild(e)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new n({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var Hr=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},pl=n=>{var s,i,a;let t=(s=n==null?void 0:n.colorScheme)!=null?s:"light",r=(i=n==null?void 0:n.theme)!=null?i:{},e=(a=n==null?void 0:n.darkTheme)!=null?a:r;return t==="light"?r:t==="dark"||Hr()==="dark"?e:r},fa=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{n(Hr())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),e=()=>n(Hr());r.addEventListener?(r.addEventListener("change",e),t.push(()=>r.removeEventListener("change",e))):r.addListener&&(r.addListener(e),t.push(()=>r.removeListener(e)))}return()=>{t.forEach(r=>r())}},cr=(n,t)=>{let r=pl(t);Object.entries(r).forEach(([e,o])=>{if(o==null||o==="")return;let s=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);n.style.setProperty(`--cw-${s}`,String(o))})};var va=require("idiomorph"),wa=(n,t,r={})=>{let{preserveTypingAnimation:e=!0}=r;va.Idiomorph.morph(n,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&e&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Rt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var sn={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var Ms=(n,t)=>{let r=g("button");r.type="button",r.innerHTML=`
8
- <span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
- <img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
10
- <span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
11
- <span class="tvw-text-sm tvw-font-semibold tvw-text-cw-primary" data-role="launcher-title"></span>
12
- <span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
6
+ `);a=(It=we.pop())!=null?It:"";for(let Ne of we){let vt=Ne.split(`
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 De=Nt!=="message"?Nt:(le=b.type)!=null?le:"message";if((se=this.onSSEEvent)==null||se.call(this,De,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(De==="reason_start"){let T=(q=N(b,!0))!=null?q:`reason-${c()}`,w=Q(T);w.reasoning=(ne=w.reasoning)!=null?ne:{id:T,status:"streaming",chunks:[]},w.reasoning.startedAt=(Ee=w.reasoning.startedAt)!=null?Ee:Y((oe=b.startedAt)!=null?oe:b.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",p(w)}else if(De==="reason_delta"||De==="reason_chunk"){let T=(te=(Ke=N(b,!1))!=null?Ke:N(b,!0))!=null?te:`reason-${c()}`,w=Q(T);w.reasoning=(X=w.reasoning)!=null?X:{id:T,status:"streaming",chunks:[]},w.reasoning.startedAt=(Ve=w.reasoning.startedAt)!=null?Ve:Y((He=b.startedAt)!=null?He:b.timestamp);let I=(Dt=(Vt=(et=b.reasoningText)!=null?et:b.text)!=null?Vt:b.delta)!=null?Dt:"";if(I&&b.hidden!==!0&&w.reasoning.chunks.push(String(I)),w.reasoning.status=b.done?"complete":"streaming",b.done){w.reasoning.completedAt=Y((ie=b.completedAt)!=null?ie:b.timestamp);let ae=(Ue=w.reasoning.startedAt)!=null?Ue:Date.now();w.reasoning.durationMs=Math.max(0,((Te=w.reasoning.completedAt)!=null?Te:Date.now())-ae)}w.streaming=w.reasoning.status!=="complete",p(w)}else if(De==="reason_complete"){let T=(_e=(tt=N(b,!1))!=null?tt:N(b,!0))!=null?_e:`reason-${c()}`,w=C.get(T);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=Y((Xe=b.completedAt)!=null?Xe:b.timestamp);let ae=(Wt=w.reasoning.startedAt)!=null?Wt:Date.now();w.reasoning.durationMs=Math.max(0,((Rt=w.reasoning.completedAt)!=null?Rt:Date.now())-ae),w.streaming=!1,p(w)}let I=U(b);I&&E.byStep.delete(I)}else if(De==="tool_start"){let T=(Mt=fe(b,!0))!=null?Mt:`tool-${c()}`,w=(H=b.toolName)!=null?H:b.name;if(Ye(w)){re.add(T);continue}let I=ee(T),ae=(Z=I.toolCall)!=null?Z:{id:T,status:"pending"};ae.name=w!=null?w:ae.name,ae.status="running",b.args!==void 0?ae.args=b.args:b.parameters!==void 0&&(ae.args=b.parameters),ae.startedAt=(Pe=ae.startedAt)!=null?Pe:Y((z=b.startedAt)!=null?z:b.timestamp),ae.completedAt=void 0,ae.durationMs=void 0,I.toolCall=ae,I.streaming=!0;let Se=b.agentContext;(Se||b.executionId)&&(I.agentMetadata={executionId:(Ce=Se==null?void 0:Se.executionId)!=null?Ce:b.executionId,iteration:(Ie=Se==null?void 0:Se.iteration)!=null?Ie:b.iteration}),p(I)}else if(De==="tool_chunk"||De==="tool_delta"){let T=(ut=(Be=fe(b,!1))!=null?Be:fe(b,!0))!=null?ut:`tool-${c()}`;if(re.has(T))continue;let w=ee(T),I=(ye=w.toolCall)!=null?ye:{id:T,status:"running"};I.startedAt=($e=I.startedAt)!=null?$e:Y((be=b.startedAt)!=null?be:b.timestamp);let ae=(Gt=(bt=(de=b.text)!=null?de:b.delta)!=null?bt:b.message)!=null?Gt:"";ae&&(I.chunks=(pn=I.chunks)!=null?pn:[],I.chunks.push(String(ae))),I.status="running",w.toolCall=I,w.streaming=!0;let Se=b.agentContext;(Se||b.executionId)&&(w.agentMetadata=(Wn=w.agentMetadata)!=null?Wn:{executionId:(un=Se==null?void 0:Se.executionId)!=null?un:b.executionId,iteration:(ds=Se==null?void 0:Se.iteration)!=null?ds:b.iteration}),p(w)}else if(De==="tool_complete"){let T=(Ge=(ar=fe(b,!1))!=null?ar:fe(b,!0))!=null?Ge:`tool-${c()}`;if(re.has(T)){re.delete(T);continue}let w=ee(T),I=(gn=w.toolCall)!=null?gn:{id:T,status:"running"};I.status="complete",b.result!==void 0&&(I.result=b.result),typeof b.duration=="number"&&(I.duration=b.duration),I.completedAt=Y((Rn=b.completedAt)!=null?Rn:b.timestamp);let ae=(an=b.duration)!=null?an:b.executionTime;if(typeof ae=="number")I.durationMs=ae;else{let kt=(Pr=I.startedAt)!=null?Pr:Date.now();I.durationMs=Math.max(0,((mn=I.completedAt)!=null?mn:Date.now())-kt)}w.toolCall=I,w.streaming=!1;let Se=b.agentContext;(Se||b.executionId)&&(w.agentMetadata=(vn=w.agentMetadata)!=null?vn:{executionId:(dt=Se==null?void 0:Se.executionId)!=null?dt:b.executionId,iteration:(tn=Se==null?void 0:Se.iteration)!=null?tn:b.iteration}),p(w);let nt=M(b);nt&&x.byCall.delete(nt)}else if(De==="step_chunk"||De==="step_delta"){let T=b.stepType,w=b.executionType;if(T==="tool"||w==="context")continue;let I=O(),ae=(Dn=(Wr=(ir=(Ir=b.text)!=null?Ir:b.delta)!=null?ir:b.content)!=null?Wr:b.chunk)!=null?Dn:"";if(ae){let nt=((fn=ce.get(I.id))!=null?fn:"")+ae;I.rawContent=nt,j.has(I.id)||j.set(I.id,this.createStreamParser());let kt=j.get(I.id),wt=nt.trim().startsWith("{")||nt.trim().startsWith("[");if(wt&&ce.set(I.id,nt),kt.__isPlainTextParser===!0){I.content+=ae,ce.delete(I.id),j.delete(I.id),I.rawContent=void 0,p(I);continue}let Lt=kt.processChunk(nt);if(Lt instanceof Promise)Lt.then(rt=>{var Et;let at=typeof rt=="string"?rt:(Et=rt==null?void 0:rt.text)!=null?Et:null;if(at!==null&&at.trim()!==""){let it=y;it&&it.id===I.id&&(it.content=at,p(it))}else if(!wt&&!nt.trim().startsWith("<")){let it=y;it&&it.id===I.id&&(it.content+=ae,ce.delete(it.id),j.delete(it.id),it.rawContent=void 0,p(it))}}).catch(()=>{I.content+=ae,ce.delete(I.id),j.delete(I.id),I.rawContent=void 0,p(I)});else{let rt=typeof Lt=="string"?Lt:(_n=Lt==null?void 0:Lt.text)!=null?_n:null;rt!==null&&rt.trim()!==""?(I.content=rt,p(I)):!wt&&!nt.trim().startsWith("<")&&(I.content+=ae,ce.delete(I.id),j.delete(I.id),I.rawContent=void 0,p(I))}}if(b.isComplete){let Se=(hn=(xt=b.result)==null?void 0:xt.response)!=null?hn:I.content;if(Se){let nt=ce.get(I.id),kt=nt!=null?nt:V(Se);I.rawContent=kt;let wt=j.get(I.id),Ht=null,Lt=!1;if(wt&&(Ht=wt.getExtractedText(),Ht===null&&(Ht=Ps(kt)),Ht===null)){let rt=wt.processChunk(kt);rt instanceof Promise?(Lt=!0,rt.then(at=>{var it;let Et=typeof at=="string"?at:(it=at==null?void 0:at.text)!=null?it:null;if(Et!==null){let Bt=y;Bt&&Bt.id===I.id&&(Bt.content=Et,Bt.streaming=!1,j.delete(Bt.id),ce.delete(Bt.id),p(Bt))}})):Ht=typeof rt=="string"?rt:(Rr=rt==null?void 0:rt.text)!=null?Rr:null}if(!Lt){Ht!==null&&Ht.trim()!==""?I.content=Ht:ce.has(I.id)||(I.content=V(Se));let rt=j.get(I.id);if(rt){let at=(Hn=rt.close)==null?void 0:Hn.call(rt);at instanceof Promise&&at.catch(()=>{}),j.delete(I.id)}ce.delete(I.id),I.streaming=!1,p(I)}}}}else if(De==="step_complete"){let T=b.stepType,w=b.executionType;if(T==="tool"||w==="context")continue;let I=(yn=b.result)==null?void 0:yn.response,ae=O();if(I!=null){let Se=j.get(ae.id),nt=!1,kt=!1;if(Se){let wt=Se.getExtractedText(),Ht=ce.get(ae.id),Lt=Ht!=null?Ht:V(I);if(ae.rawContent=Lt,wt!==null&&wt.trim()!=="")ae.content=wt,nt=!0;else{let rt=Ps(Lt);if(rt!==null)ae.content=rt,nt=!0;else{let at=Se.processChunk(Lt);if(at instanceof Promise)kt=!0,at.then(Et=>{var Bt;let it=typeof Et=="string"?Et:(Bt=Et==null?void 0:Et.text)!=null?Bt:null;if(it!==null&&it.trim()!==""){let Jt=y;Jt&&Jt.id===ae.id&&(Jt.content=it,Jt.streaming=!1,j.delete(Jt.id),ce.delete(Jt.id),p(Jt))}else{let Jt=Se.getExtractedText(),rn=y;rn&&rn.id===ae.id&&(Jt!==null&&Jt.trim()!==""?rn.content=Jt:ce.has(rn.id)||(rn.content=V(I)),rn.streaming=!1,j.delete(rn.id),ce.delete(rn.id),p(rn))}});else{let Et=typeof at=="string"?at:(W=at==null?void 0:at.text)!=null?W:null;if(Et!==null&&Et.trim()!=="")ae.content=Et,nt=!0;else{let it=Se.getExtractedText();it!==null&&it.trim()!==""&&(ae.content=it,nt=!0)}}}}}if(!kt){if(!ae.rawContent){let wt=ce.get(ae.id);ae.rawContent=wt!=null?wt:V(I)}if(!nt&&!ce.has(ae.id)&&(ae.content=V(I)),Se){let wt=(Bn=Se.close)==null?void 0:Bn.call(Se);wt instanceof Promise&&wt.catch(()=>{})}j.delete(ae.id),ce.delete(ae.id),ae.streaming=!1,p(ae)}}else j.delete(ae.id),ce.delete(ae.id),ae.streaming=!1,p(ae)}else if(De==="flow_complete"){let T=($n=b.result)==null?void 0:$n.response;if(T!=null){let w=O(),I=ce.get(w.id),ae=I!=null?I:V(T);w.rawContent=ae;let Se=V(T),nt=j.get(w.id);if(nt){let Ht=Ps(ae);if(Ht!==null)Se=Ht;else{let Lt=nt.processChunk(ae);Lt instanceof Promise&&Lt.then(at=>{var it;let Et=typeof at=="string"?at:(it=at==null?void 0:at.text)!=null?it:null;if(Et!==null){let Bt=y;Bt&&Bt.id===w.id&&(Bt.content=Et,Bt.streaming=!1,p(Bt))}});let rt=nt.getExtractedText();rt!==null&&(Se=rt)}}j.delete(w.id),ce.delete(w.id);let kt=Se!==w.content,wt=w.streaming!==!1;kt&&(w.content=Se),w.streaming=!1,(kt||wt)&&p(w)}else if(y!==null){let w=y;j.delete(w.id),ce.delete(w.id),w.streaming!==!1&&(w.streaming=!1,p(w))}t({type:"status",status:"idle"})}else if(De==="agent_start")he={executionId:b.executionId,agentId:(Hr=b.agentId)!=null?Hr:"virtual",agentName:(Cn=b.agentName)!=null?Cn:"",status:"running",currentIteration:0,maxTurns:(jn=b.maxTurns)!=null?jn:1,startedAt:Y(b.startedAt)};else if(De==="agent_iteration_start"){if(he&&(he.currentIteration=b.iteration),lt==="separate"&&b.iteration>1){let T=y;T&&(T.streaming=!1,p(T),mt.set(b.iteration-1,T),y=null)}}else if(De!=="agent_turn_start"){if(De==="agent_turn_delta"){if(b.contentType==="text"){let T=O();T.content+=(Br=b.delta)!=null?Br:"",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=(wn=b.turnId)!=null?wn:`agent-think-${b.iteration}`,w=Q(T);w.reasoning=(Sn=w.reasoning)!=null?Sn:{id:T,status:"streaming",chunks:[]},w.reasoning.chunks.push((lr=b.delta)!=null?lr:""),w.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},p(w)}else if(b.contentType==="tool_input"){let T=(cr=b.toolCallId)!=null?cr:x.lastId;if(T){let w=v.get(T);w!=null&&w.toolCall&&(w.toolCall.chunks=(ps=w.toolCall.chunks)!=null?ps:[],w.toolCall.chunks.push((us=b.delta)!=null?us:""),p(w))}}}else if(De==="agent_turn_complete"){let T=b.turnId;if(T){let w=C.get(T);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=Y(b.completedAt);let I=(gs=w.reasoning.startedAt)!=null?gs:Date.now();w.reasoning.durationMs=Math.max(0,(($r=w.reasoning.completedAt)!=null?$r:Date.now())-I),w.streaming=!1,p(w)}}}else if(De==="agent_tool_start"){let T=(dr=b.toolCallId)!=null?dr:`agent-tool-${c()}`;K(M(b),T);let w=ee(T),I=(qe=w.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};I.name=(nn=(Fr=b.toolName)!=null?Fr:b.name)!=null?nn:I.name,I.status="running",b.parameters!==void 0&&(I.args=b.parameters),I.startedAt=Y((zt=b.startedAt)!=null?zt:b.timestamp),w.toolCall=I,w.streaming=!0,w.agentMetadata={executionId:b.executionId,iteration:b.iteration},p(w)}else if(De==="agent_tool_delta"){let T=(ms=b.toolCallId)!=null?ms:x.lastId;if(T){let w=(fs=v.get(T))!=null?fs:ee(T);w.toolCall&&(w.toolCall.chunks=(Nr=w.toolCall.chunks)!=null?Nr:[],w.toolCall.chunks.push((Vn=b.delta)!=null?Vn:""),w.toolCall.status="running",w.streaming=!0,p(w))}}else if(De==="agent_tool_complete"){let T=(An=b.toolCallId)!=null?An:x.lastId;if(T){let w=(hs=v.get(T))!=null?hs:ee(T);if(w.toolCall){w.toolCall.status="complete",b.result!==void 0&&(w.toolCall.result=b.result),typeof b.executionTime=="number"&&(w.toolCall.durationMs=b.executionTime),w.toolCall.completedAt=Y((ys=b.completedAt)!=null?ys:b.timestamp),w.streaming=!1,p(w);let I=M(b);I&&x.byCall.delete(I)}}}else if(De!=="agent_iteration_complete"){if(De==="agent_reflection"||De==="agent_reflect"){let T=`agent-reflection-${b.executionId}-${b.iteration}`,w={id:T,role:"assistant",content:(bs=b.reflection)!=null?bs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"complete",chunks:[(uo=b.reflection)!=null?uo:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};p(w)}else if(De==="agent_complete"){he&&(he.status=b.success?"complete":"error",he.completedAt=Y(b.completedAt),he.stopReason=b.stopReason);let T=y;T&&(T.streaming=!1,p(T)),t({type:"status",status:"idle"})}else if(De==="agent_error"){let T=typeof b.error=="string"?b.error:(pr=(qn=b.error)==null?void 0:qn.message)!=null?pr:"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=(ht=b.approvalId)!=null?ht:`approval-${c()}`,w={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(ur=he==null?void 0:he.agentId)!=null?ur:"virtual",executionId:(Or=(gr=b.executionId)!=null?gr:he==null?void 0:he.executionId)!=null?Or:"",toolName:(Dr=b.toolName)!=null?Dr:"",toolType:b.toolType,description:(jr=b.description)!=null?jr:`Execute ${(_r=b.toolName)!=null?_r:"tool"}`,parameters:b.parameters}};p(w)}else if(De==="step_await"&&b.awaitReason==="approval_required"){let T=(qt=b.approvalId)!=null?qt:`approval-${c()}`,w={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(Zt=he==null?void 0:he.agentId)!=null?Zt:"virtual",executionId:(Re=(En=b.executionId)!=null?En:he==null?void 0:he.executionId)!=null?Re:"",toolName:(Vr=b.toolName)!=null?Vr:"",toolType:b.toolType,description:(ln=b.description)!=null?ln:`Execute ${(Un=b.toolName)!=null?Un:"tool"}`,parameters:b.parameters}};p(w)}else if(De==="agent_approval_complete"){let T=b.approvalId;if(T){let I={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:(xs=b.decision)!=null?xs:"approved",agentId:(mr=he==null?void 0:he.agentId)!=null?mr:"virtual",executionId:(zn=(fr=b.executionId)!=null?fr:he==null?void 0:he.executionId)!=null?zn:"",toolName:(Fn=b.toolName)!=null?Fn:"",description:(vs=b.description)!=null?vs:"",resolvedAt:Date.now()}};p(I)}}else if(De==="artifact_start"||De==="artifact_delta"||De==="artifact_update"||De==="artifact_complete"){if(De==="artifact_start"){let T=b.artifactType,w=String(b.id),I=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:w,artifactType:T,title:I,component:typeof b.component=="string"?b.component:void 0}),Le.set(w,{markdown:"",title:I}),!pe.has(w)){pe.add(w);let ae={id:`artifact-ref-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:w,title:I,artifactType:T,status:"streaming"}})};J.set(w,ae),p(ae)}}else if(De==="artifact_delta"){let T=String(b.id),w=typeof b.delta=="string"?b.delta:String((Cs=b.delta)!=null?Cs:"");t({type:"artifact_delta",id:T,artDelta:w});let I=Le.get(T);I&&(I.markdown+=w)}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 w=J.get(T);if(w){w.streaming=!1;try{let I=JSON.parse((cn=w.rawContent)!=null?cn:"{}");if(I.props){I.props.status="complete";let ae=Le.get(T);ae!=null&&ae.markdown&&(I.props.markdown=ae.markdown)}w.rawContent=JSON.stringify(I)}catch{}Le.delete(T),p(w),J.delete(T)}}}else if(De==="transcript_insert"){let T=b.message;if(!T||typeof T!="object")continue;let w=String((Jn=T.id)!=null?Jn:`msg-${c()}`),I=T.role,Se={id:w,role:I==="user"?"user":I==="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 nt=JSON.parse(Se.rawContent),kt=(ws=nt==null?void 0:nt.props)==null?void 0:ws.artifactId;typeof kt=="string"&&pe.add(kt)}catch{}y=null,m.current=null,j.delete(w),ce.delete(w)}else De==="error"&&b.error&&t({type:"error",error:b.error instanceof Error?b.error:new Error(String(b.error))})}}}}}};function hl(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function br(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function Zn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Bs="[Image]";function yl(e){return typeof e=="string"?[{type:"text",text:e}]:e}function bl(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function xl(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function vl(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function $s(e){return{type:"text",text:e}}function Cl(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 o=r.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Sl(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 Al=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Qc=["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"],kn=[...Al,...Qc];function ed(e){return Al.includes(e)||e.startsWith("image/")}function Fs(e){return ed(e.type)}async function El(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Fs(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Tl(e,n=kn,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 td(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Ml(e,n){let t=td(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 Ns=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(),o=this.pcmToFloat32(t),s=r.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=r.createBufferSource();a.buffer=s,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.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),o=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let s=0;s<t;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}};var Os=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,o,s){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<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):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 Zr=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 Os;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 o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.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=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let g=`${s}//${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(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}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(o=>o({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(o=>o("speaking")),this.playAudio(n.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(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(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Ns(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,o;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 s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(o=(r=this.config)==null?void 0:r.silenceThreshold)!=null?o:.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(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}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 s,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=(s=this.config)==null?void 0:s.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),o=this.getFormatFromMimeType(n.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:o,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:s}))}catch(r){this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];t(a)},o.onerror=r,o.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 o=n.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([r],{type:s}),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 Qn=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=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("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 er(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Zr(e.runtype);case"browser":if(!Qn.isSupported())throw new Error("Browser speech recognition not supported");return new Qn(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ds(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return er({type:"runtype",runtype:e.runtype});if(Qn.isSupported())return er({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Qr(e){try{return Ds(e),!0}catch{return!1}}var xr=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,o,s,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:(o=n.message.agentMetadata.iteration)!=null?o: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,((s=this.agentExecution)==null?void 0:s.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(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Gn(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 Qr((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,o;try{let s=n||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=er(s);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"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(s){console.error("Failed to setup voice:",s)}}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,o,s,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:((o=n.runtype)==null?void 0:o.clientToken)||"",host:(s=n.runtype)==null?void 0:s.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 Gn(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:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:g}=n,y={id:a!=null?a:t==="user"?br():t==="assistant"?Zn():`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,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...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:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:g,streaming:p=!1}=r,m={id:d!=null?d:o==="user"?br():o==="assistant"?Zn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,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 o=br(),s=Zn(),a={id:o,role:"user",content:r||Bs,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:s},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:s,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 o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=Zn();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=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c)))}}async connectStream(n,t){var o,s,a;if(this.streaming)return;(o=this.abortController)==null||o.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=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(n,t){var d,c,g;let r=`approval-${n.id}`,o={...n,status:t,resolvedAt:Date.now()},s={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s);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 o;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(o=n.props)!=null?o:{}};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 o=this.artifacts.get(n.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let o=this.artifacts.get(n.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...n.props},n.component&&(o.component=n.component));break}case"artifact_complete":{let o=this.artifacts.get(n.id);o&&(o.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 o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o: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(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=r.content;o.trim()&&this.speak(o,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(n),s=r.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=t.pickVoice?t.pickVoice(s):e.pickBestVoice(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),setTimeout(()=>r.speak(o),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 o of t){let s=n.find(a=>a.name===o);if(s)return s}return(r=n.find(o=>o.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(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>s===r?{...o,...t}:o),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 o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;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},bn=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};var nd=qc(require("lucide"),1),ue=(e,n=24,t="currentColor",r=2)=>{try{let o=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),s=nd[o];return s?rd(s,n,t,r):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function rd(e,n,t,r){if(!e||!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let a=s[0],i=s[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))}),o.appendChild(d)}}}),o}var _s={allowedTypes:kn,maxFileSize:10*1024*1024,maxFiles:4};function sd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function od(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 tr=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:_s.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:_s.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:_s.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:_s.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,o,s,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=Tl(c,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let p=(o=g.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,p);continue}try{let p=await El(c),y=Fs(c)?URL.createObjectURL(c):null,m={id:sd(),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 s,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 o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.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=Fs(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=od(n.file.type),d=ue(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=f("span");c.textContent=Ml(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 o=f("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ue("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(o),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 bo={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"}},xo={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"}},vo={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 kl(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?kl(e,r):r}function js(e){let n={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=kl(e,a);d!==void 0&&(n[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.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 Co(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 Ll(e,n){let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=Ll(s,o):t[r]=o}return t}function ad(e,n){return n?Ll(e,n):e}function vr(e,n={}){var o,s,a,i,d,c,g,p,y,m,C,v,E;let t={palette:bo,semantic:xo,components:vo},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.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:ad(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let x=Co(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 Vs(e){var d,c,g,p,y,m,C,v,E,x,k,U,M,O,S,N,Q,K,re,J,pe,Le,Ye,fe,ee,Y,V,j,ce,he,mt,lt,ft,It,le,se,q,ne,oe,Ee,Ke,te,X,He,Ve,et,Vt,Dt,ie,Ue,Te,tt,_e,Xe,Wt,Rt,Mt,H;let n=js(e),t={};for(let[Z,z]of Object.entries(n)){let Pe=Z.replace(/\./g,"-");t[`--persona-${Pe}`]=z.value}t["--persona-primary"]=(d=t["--persona-semantic-colors-primary"])!=null?d:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(c=t["--persona-semantic-colors-secondary"])!=null?c:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(g=t["--persona-semantic-colors-accent"])!=null?g:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(p=t["--persona-semantic-colors-surface"])!=null?p:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(y=t["--persona-semantic-colors-background"])!=null?y:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(m=t["--persona-semantic-colors-container"])!=null?m:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(C=t["--persona-semantic-colors-text"])!=null?C:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(v=t["--persona-semantic-colors-text-muted"])!=null?v:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(E=t["--persona-semantic-colors-text-inverse"])!=null?E:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(x=t["--persona-semantic-colors-border"])!=null?x:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(k=t["--persona-semantic-colors-divider"])!=null?k:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(U=t["--persona-components-voice-recording-indicator"])!=null?U:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(M=t["--persona-components-voice-recording-background"])!=null?M:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(O=t["--persona-components-voice-processing-icon"])!=null?O:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(S=t["--persona-components-voice-speaking-icon"])!=null?S:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(N=t["--persona-components-approval-requested-background"])!=null?N:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Q=t["--persona-components-approval-requested-border"])!=null?Q:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(K=t["--persona-components-approval-requested-text"])!=null?K:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(re=t["--persona-components-approval-approve-background"])!=null?re:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(J=t["--persona-components-approval-deny-background"])!=null?J:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(pe=t["--persona-components-attachment-image-background"])!=null?pe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Le=t["--persona-components-attachment-image-border"])!=null?Le:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(Ye=t["--persona-semantic-typography-fontFamily"])!=null?Ye:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(fe=t["--persona-semantic-typography-fontSize"])!=null?fe:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ee=t["--persona-semantic-typography-fontWeight"])!=null?ee:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(Y=t["--persona-semantic-typography-lineHeight"])!=null?Y:t["--persona-palette-typography-lineHeight-normal"],t["--persona-radius-sm"]=(V=t["--persona-palette-radius-sm"])!=null?V:"0.125rem",t["--persona-radius-md"]=(j=t["--persona-palette-radius-md"])!=null?j:"0.375rem",t["--persona-radius-lg"]=(ce=t["--persona-palette-radius-lg"])!=null?ce:"0.5rem",t["--persona-radius-xl"]=(he=t["--persona-palette-radius-xl"])!=null?he:"0.75rem",t["--persona-launcher-radius"]=(lt=(mt=t["--persona-components-launcher-borderRadius"])!=null?mt:t["--persona-palette-radius-full"])!=null?lt:"9999px",t["--persona-button-radius"]=(It=(ft=t["--persona-components-button-primary-borderRadius"])!=null?ft:t["--persona-palette-radius-full"])!=null?It:"9999px",t["--persona-panel-radius"]=(se=(le=t["--persona-components-panel-borderRadius"])!=null?le:t["--persona-radius-xl"])!=null?se:"0.75rem",t["--persona-input-radius"]=(ne=(q=t["--persona-components-input-borderRadius"])!=null?q:t["--persona-radius-lg"])!=null?ne:"0.5rem",t["--persona-message-user-radius"]=(Ee=(oe=t["--persona-components-message-user-borderRadius"])!=null?oe:t["--persona-radius-lg"])!=null?Ee:"0.5rem",t["--persona-message-assistant-radius"]=(te=(Ke=t["--persona-components-message-assistant-borderRadius"])!=null?Ke:t["--persona-radius-lg"])!=null?te:"0.5rem",t["--persona-header-bg"]=(X=t["--persona-components-header-background"])!=null?X:t["--persona-surface"],t["--persona-header-border"]=(He=t["--persona-components-header-border"])!=null?He:t["--persona-divider"],t["--persona-message-user-bg"]=(Ve=t["--persona-components-message-user-background"])!=null?Ve:t["--persona-accent"],t["--persona-message-user-text"]=(et=t["--persona-components-message-user-text"])!=null?et:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Vt=t["--persona-components-message-user-shadow"])!=null?Vt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Dt=t["--persona-components-message-assistant-background"])!=null?Dt:t["--persona-surface"],t["--persona-message-assistant-text"]=(ie=t["--persona-components-message-assistant-text"])!=null?ie:t["--persona-text"],t["--persona-message-assistant-border"]=(Ue=t["--persona-components-message-assistant-border"])!=null?Ue:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Te=t["--persona-components-message-assistant-shadow"])!=null?Te:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-tool-bubble-shadow"]=(tt=t["--persona-components-toolBubble-shadow"])!=null?tt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(_e=t["--persona-components-reasoningBubble-shadow"])!=null?_e:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Xe=t["--persona-components-composer-shadow"])!=null?Xe:"none",t["--persona-md-inline-code-bg"]=(Wt=t["--persona-components-markdown-inlineCode-background"])!=null?Wt:t["--persona-container"],t["--persona-md-inline-code-color"]=(Rt=t["--persona-components-markdown-inlineCode-foreground"])!=null?Rt:t["--persona-text"],t["--persona-md-link-color"]=(H=(Mt=t["--persona-components-markdown-link-foreground"])!=null?Mt:t["--persona-accent"])!=null?H:"#3b82f6";let r=t["--persona-components-markdown-heading-h1-fontSize"];r&&(t["--persona-md-h1-size"]=r);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let s=t["--persona-components-markdown-heading-h2-fontSize"];s&&(t["--persona-md-h2-size"]=s);let a=t["--persona-components-markdown-heading-h2-fontWeight"];a&&(t["--persona-md-h2-weight"]=a);let i=t["--persona-components-markdown-prose-fontFamily"];return i&&i!=="inherit"&&(t["--persona-md-prose-font-family"]=i),t}var wo={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"},Pl={radiusSm:"palette.radius.md",radiusMd:"palette.radius.lg",radiusLg:"palette.radius.xl",launcherRadius:"palette.radius.full",buttonRadius:"palette.radius.full"};function qs(e,n={}){if(!e)return{};let t={palette:{colors:{primary:{},gray:{},secondary:{},accent:{},success:{},warning:{},error:{}}},semantic:{colors:{interactive:{},feedback:{}}}};for(let[r,o]of Object.entries(e))if(o)if(r in wo){let s=wo[r],[a,i,d,c]=s.split(".");if(a==="palette"&&i==="colors"){let g=d;t.palette.colors[g]&&(t.palette.colors[g][c||"500"]=o)}else if(a==="semantic"){let g=s.replace("semantic.colors.","").split(".");g.length===1?t.semantic.colors[g[0]]=o:t.semantic.colors[g[0]]={...t.semantic.colors[g[0]],[g[1]]:o}}}else if(r in Pl){t.palette.radius||(t.palette.radius={});let s=r.replace("radius","").toLowerCase();t.palette.radius[s||"md"]=o}else r==="inputFontFamily"?(t.palette.typography||(t.palette.typography={fontFamily:{}}),t.palette.typography.fontFamily={sans:o==="sans-serif"?"system-ui, sans-serif":void 0,serif:o==="serif"?"Georgia, serif":void 0,mono:o==="mono"?"monospace":void 0}):r==="inputFontWeight"?(t.palette.typography||(t.palette.typography={fontWeight:{}}),t.palette.typography.fontWeight={normal:o}):r==="panelBorder"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.border=o):r==="panelShadow"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.shadow=o):r==="panelBorderRadius"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.borderRadius=o):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=o):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=o):r==="toolBubbleShadow"?(t.components||(t.components={}),t.components.toolBubble||(t.components.toolBubble={}),t.components.toolBubble.shadow=o):r==="reasoningBubbleShadow"?(t.components||(t.components={}),t.components.reasoningBubble||(t.components.reasoningBubble={}),t.components.reasoningBubble.shadow=o):r==="composerShadow"&&(t.components||(t.components={}),t.components.composer||(t.components.composer={}),t.components.composer.shadow=o);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 Il(e){let n=[],t=e;if(!t)return{valid:!0,warnings:[]};let r=new Set(["panelBorder","panelShadow","panelBorderRadius","messageUserShadow","messageAssistantShadow","toolBubbleShadow","reasoningBubbleShadow","composerShadow"]),o=Object.keys(t).filter(s=>!(s in wo||s in Pl||s==="inputFontFamily"||s==="inputFontWeight"||s.startsWith("panel")||r.has(s)));return o.length>0&&n.push(`The following v1 theme properties have no v2 equivalent and will be ignored: ${o.join(", ")}`),{valid:!0,warnings:n}}var id={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"}}},So=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ao=(e,n)=>{if(!e)return n;if(!n)return e;let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];So(s)&&So(o)?t[r]=Ao(s,o):t[r]=o}return t},ld=e=>So(e)&&("palette"in e||"semantic"in e||"components"in e),Wl=e=>{if(!e)return;let n=qs(e,{warn:!1});return ld(e)?Ao(n,e):n},es=()=>{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"},cd=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":es()},Eo=e=>cd(e),dd=e=>vr(e),pd=e=>{var t;let n=vr(void 0,{validate:!1});return vr({...e,palette:{...n.palette,colors:{...id.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},To=e=>{let n=Eo(e),t=Wl(e==null?void 0:e.theme),r=Wl(e==null?void 0:e.darkTheme);return n==="dark"?pd(Ao(t,r)):dd(t)},ud=e=>Vs(e),On=(e,n)=>{var s;let t=To(n),r=ud(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let o=(s=n==null?void 0:n.toolCall)==null?void 0:s.shadow;o!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},Us=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(es())});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(es());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 Rl=require("idiomorph"),Hl=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Rl.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&r&&(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};function Bl(e,n){var t,r,o,s,a,i,d,c,g,p,y,m,C,v,E,x,k,U;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",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,(U=(k=e.contentParts)==null?void 0:k.length)!=null?U:0,n].join("\0")}function $l(){return new Map}function Fl(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Nl(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function Ol(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}var _t={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var gd={side:"right",width:"420px",collapsedWidth:"72px"},jt=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},Cr=e=>{var n,t;return{...gd,...(t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock)!=null?t:{}}};var dn={"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 ts=(e,n)=>{let t=f("button");t.type="button",t.innerHTML=`
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
+ <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
10
+ <span class="persona-flex persona-flex-col persona-items-start persona-text-left">
11
+ <span class="persona-text-sm persona-font-semibold persona-text-persona-primary" data-role="launcher-title"></span>
12
+ <span class="persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
- <span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
15
- `,r.addEventListener("click",t);let e=s=>{var x,H,Y,k,P,L,F,ue,z,V,X,_;let i=(x=s.launcher)!=null?x:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(H=i.title)!=null?H:"Chat Assistant");let d=r.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(Y=i.subtitle)!=null?Y:"Get answers fast");let c=r.querySelector(".tvw-flex-col");c&&(i.textHidden?c.style.display="none":c.style.display="");let v=r.querySelector("[data-role='launcher-icon']");if(v)if(i.agentIconHidden)v.style.display="none";else{let Ce=(k=i.agentIconSize)!=null?k:"40px";if(v.style.height=Ce,v.style.width=Ce,v.innerHTML="",i.agentIconName){let se=parseFloat(Ce)||24,G=ie(i.agentIconName,se*.6,"#ffffff",2);G?(v.appendChild(G),v.style.display=""):(v.textContent=(P=i.agentIconText)!=null?P:"\u{1F4AC}",v.style.display="")}else i.iconUrl?v.style.display="none":(v.textContent=(L=i.agentIconText)!=null?L:"\u{1F4AC}",v.style.display="")}let p=r.querySelector("[data-role='launcher-image']");if(p){let Ce=(F=i.agentIconSize)!=null?F:"40px";p.style.height=Ce,p.style.width=Ce,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(p.src=i.iconUrl,p.style.display="block"):p.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Ce=(ue=i.callToActionIconSize)!=null?ue:"32px";m.style.height=Ce,m.style.width=Ce,i.callToActionIconBackgroundColor?(m.style.backgroundColor=i.callToActionIconBackgroundColor,m.classList.remove("tvw-bg-cw-primary")):(m.style.backgroundColor="",m.classList.add("tvw-bg-cw-primary"));let se=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,se=(parseFloat(i.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),i.callToActionIconHidden)m.style.display="none";else if(m.style.display="",m.innerHTML="",i.callToActionIconName){let G=parseFloat(Ce)||24,U=Math.max(G-se,8),N=ie(i.callToActionIconName,U,"currentColor",2);N?m.appendChild(N):m.textContent=(z=i.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(V=i.callToActionIconText)!=null?V:"\u2197"}let w=i.position&&sn[i.position]?sn[i.position]:sn["bottom-right"],C="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${C} ${w}`;let y="1px solid #e5e7eb",A="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(X=i.border)!=null?X:y,r.style.boxShadow=(_=i.shadow)!=null?_:A},o=()=>{r.removeEventListener("click",t),r.remove()};return n&&e(n),{element:r,update:e,destroy:o}};var mn=n=>{var V,X,_,Ce,se,G,U,N,ee,fe,Fe,Mt,gt,ft,Ht,je,ne,xe,He,$e,ze,Ot,he,Z,ct,bt,kt,Ct,Kt,te,Pe,xt;let{config:t,showClose:r=!0}=n,e=g("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(V=t==null?void 0:t.launcher)!=null?V:{},s=(X=o.headerIconSize)!=null?X:"48px",i=(_=o.closeButtonSize)!=null?_:"32px",a=(Ce=o.closeButtonPlacement)!=null?Ce:"inline",d=(se=o.headerIconHidden)!=null?se:!1,c=o.headerIconName,v=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(v.style.height=s,v.style.width=s,!d)if(c){let ve=parseFloat(s)||24,Se=ie(c,ve*.6,"#ffffff",1);Se?v.replaceChildren(Se):v.textContent=(U=(G=t==null?void 0:t.launcher)==null?void 0:G.agentIconText)!=null?U:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let ve=g("img");ve.src=t.launcher.iconUrl,ve.alt="",ve.className="tvw-rounded-xl tvw-object-cover",ve.style.height=s,ve.style.width=s,v.replaceChildren(ve)}else v.textContent=(fe=(ee=t==null?void 0:t.launcher)==null?void 0:ee.agentIconText)!=null?fe:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(Mt=(Fe=t==null?void 0:t.launcher)==null?void 0:Fe.title)!=null?Mt:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(ft=(gt=t==null?void 0:t.launcher)==null?void 0:gt.subtitle)!=null?ft:"Here to help you get answers fast",p.append(m,w),d?e.append(p):e.append(v,p);let C=(Ht=o.clearChat)!=null?Ht:{},y=(je=C.enabled)!=null?je:!0,A=(ne=C.placement)!=null?ne:"inline",x=null,H=null;if(y){let ve=(xe=C.size)!=null?xe:"32px",Se=(He=C.iconName)!=null?He:"refresh-cw",Je=($e=C.iconColor)!=null?$e:"",Bt=(ze=C.backgroundColor)!=null?ze:"",It=(Ot=C.borderWidth)!=null?Ot:"",qt=(he=C.borderColor)!=null?he:"",I=(Z=C.borderRadius)!=null?Z:"",nt=(ct=C.paddingX)!=null?ct:"",O=(bt=C.paddingY)!=null?bt:"",Q=(kt=C.tooltipText)!=null?kt:"Clear chat",re=(Ct=C.showTooltip)!=null?Ct:!0;H=g("div",A==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),A==="top-right"&&(H.style.right="48px"),x=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),x.style.height=ve,x.style.width=ve,x.type="button",x.setAttribute("aria-label",Q);let Ne=ie(Se,"20px",Je||"",1);if(Ne&&x.appendChild(Ne),Je&&(x.style.color=Je,x.classList.remove("tvw-text-cw-muted")),Bt&&(x.style.backgroundColor=Bt,x.classList.remove("hover:tvw-bg-gray-100")),It||qt){let oe=It||"0px",Xe=qt||"transparent";x.style.border=`${oe} solid ${Xe}`,x.classList.remove("tvw-border-none")}if(I&&(x.style.borderRadius=I,x.classList.remove("tvw-rounded-full")),nt?(x.style.paddingLeft=nt,x.style.paddingRight=nt):(x.style.paddingLeft="",x.style.paddingRight=""),O?(x.style.paddingTop=O,x.style.paddingBottom=O):(x.style.paddingTop="",x.style.paddingBottom=""),H.appendChild(x),re&&Q&&x&&H){let oe=null,Xe=()=>{if(oe||!x)return;oe=g("div","tvw-clear-chat-tooltip"),oe.textContent=Q;let pe=g("div");pe.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(pe);let D=x.getBoundingClientRect();oe.style.position="fixed",oe.style.left=`${D.left+D.width/2}px`,oe.style.top=`${D.top-8}px`,oe.style.transform="translate(-50%, -100%)",document.body.appendChild(oe)},Ge=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};H.addEventListener("mouseenter",Xe),H.addEventListener("mouseleave",Ge),x.addEventListener("focus",Xe),x.addEventListener("blur",Ge),H._cleanupTooltip=()=>{Ge(),H&&(H.removeEventListener("mouseenter",Xe),H.removeEventListener("mouseleave",Ge)),x&&(x.removeEventListener("focus",Xe),x.removeEventListener("blur",Ge))}}A==="inline"&&e.appendChild(H)}let Y=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":y&&A==="inline"?"":"tvw-ml-auto"),k=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");k.style.height=i,k.style.width=i,k.type="button";let P=(Kt=o.closeButtonTooltipText)!=null?Kt:"Close chat",L=(te=o.closeButtonShowTooltip)!=null?te:!0;k.setAttribute("aria-label",P),k.style.display=r?"":"none";let F=(Pe=o.closeButtonIconName)!=null?Pe:"x",ue=(xt=o.closeButtonIconText)!=null?xt:"\xD7",z=ie(F,"20px",o.closeButtonColor||"",1);if(z?k.appendChild(z):k.textContent=ue,o.closeButtonColor?(k.style.color=o.closeButtonColor,k.classList.remove("tvw-text-cw-muted")):(k.style.color="",k.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(k.style.backgroundColor=o.closeButtonBackgroundColor,k.classList.remove("hover:tvw-bg-gray-100")):(k.style.backgroundColor="",k.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let ve=o.closeButtonBorderWidth||"0px",Se=o.closeButtonBorderColor||"transparent";k.style.border=`${ve} solid ${Se}`,k.classList.remove("tvw-border-none")}else k.style.border="",k.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(k.style.borderRadius=o.closeButtonBorderRadius,k.classList.remove("tvw-rounded-full")):(k.style.borderRadius="",k.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(k.style.paddingLeft=o.closeButtonPaddingX,k.style.paddingRight=o.closeButtonPaddingX):(k.style.paddingLeft="",k.style.paddingRight=""),o.closeButtonPaddingY?(k.style.paddingTop=o.closeButtonPaddingY,k.style.paddingBottom=o.closeButtonPaddingY):(k.style.paddingTop="",k.style.paddingBottom=""),Y.appendChild(k),L&&P){let ve=null,Se=()=>{if(ve)return;ve=g("div","tvw-clear-chat-tooltip"),ve.textContent=P;let Bt=g("div");Bt.className="tvw-clear-chat-tooltip-arrow",ve.appendChild(Bt);let It=k.getBoundingClientRect();ve.style.position="fixed",ve.style.left=`${It.left+It.width/2}px`,ve.style.top=`${It.top-8}px`,ve.style.transform="translate(-50%, -100%)",document.body.appendChild(ve)},Je=()=>{ve&&ve.parentNode&&(ve.parentNode.removeChild(ve),ve=null)};Y.addEventListener("mouseenter",Se),Y.addEventListener("mouseleave",Je),k.addEventListener("focus",Se),k.addEventListener("blur",Je),Y._cleanupTooltip=()=>{Je(),Y.removeEventListener("mouseenter",Se),Y.removeEventListener("mouseleave",Je),k.removeEventListener("focus",Se),k.removeEventListener("blur",Je)}}return a!=="top-right"&&e.appendChild(Y),{header:e,iconHolder:v,headerTitle:m,headerSubtitle:w,closeButton:k,closeButtonWrapper:Y,clearChatButton:x,clearChatButtonWrapper:H}},Fn=(n,t,r)=>{var i,a,d,c;let e=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=e.closeButtonPlacement)!=null?a:"inline",s=(c=(d=e.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(t.header),o==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};var Br=n=>mn({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Fr=n=>{var C,y,A,x;let{config:t,showClose:r=!0,onClose:e}=n,o=(C=t==null?void 0:t.launcher)!=null?C:{},s=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=g("span","tvw-text-base tvw-font-semibold");i.textContent=(y=o.title)!=null?y:"Chat Assistant",s.appendChild(i);let a=(A=o.closeButtonSize)!=null?A:"32px",d=g("div",""),c=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");c.style.height=a,c.style.width=a,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=r?"":"none";let v=(x=o.closeButtonIconName)!=null?x:"x",p=ie(v,"20px",o.closeButtonColor||"",2);p?c.appendChild(p):c.textContent="\xD7",e&&c.addEventListener("click",e),d.appendChild(c),s.appendChild(d);let m=g("div");m.style.display="none";let w=g("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:c,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},$r=n=>{var k,P,L,F,ue,z,V,X;let{config:t,showClose:r=!0,onClose:e,onClearChat:o}=n,s=(k=t==null?void 0:t.launcher)!=null?k:{},i=g("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=g("div","tvw-flex tvw-items-center tvw-gap-3"),d=(P=s.headerIconSize)!=null?P:"56px",c=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=d,c.style.width=d;let v=s.headerIconName;if(v){let _=parseFloat(d)||24,Ce=ie(v,_*.5,"#ffffff",2);Ce?c.replaceChildren(Ce):c.textContent=(L=s.agentIconText)!=null?L:"\u{1F4AC}"}else if(s.iconUrl){let _=g("img");_.src=s.iconUrl,_.alt="",_.className="tvw-rounded-xl tvw-object-cover",_.style.height=d,_.style.width=d,c.replaceChildren(_)}else c.textContent=(F=s.agentIconText)!=null?F:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col tvw-flex-1"),m=g("span","tvw-text-lg tvw-font-semibold");m.textContent=(ue=s.title)!=null?ue:"Chat Assistant";let w=g("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(z=s.subtitle)!=null?z:"Here to help you get answers fast",p.append(m,w),a.append(c,p);let C=(V=s.closeButtonSize)!=null?V:"32px",y=g("div",""),A=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");A.style.height=C,A.style.width=C,A.type="button",A.setAttribute("aria-label","Close chat"),A.style.display=r?"":"none";let x=(X=s.closeButtonIconName)!=null?X:"x",H=ie(x,"20px",s.closeButtonColor||"",2);H?A.appendChild(H):A.textContent="\xD7",e&&A.addEventListener("click",e),y.appendChild(A),a.appendChild(y),i.appendChild(a);let Y=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return Y.textContent="Online and ready to help",i.appendChild(Y),{header:i,iconHolder:c,headerTitle:m,headerSubtitle:w,closeButton:A,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}},dr={default:Br,minimal:Fr,expanded:$r},Nr=n=>{var t;return(t=dr[n])!=null?t:dr.default},Zn=(n,t,r)=>{var i,a,d;if(t!=null&&t.render){let c=t.render({config:n,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),v=g("div");v.style.display="none";let p=g("span"),m=g("span"),w=g("button");w.style.display="none";let C=g("div");return C.style.display="none",{header:c,iconHolder:v,headerTitle:p,headerSubtitle:m,closeButton:w,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=t==null?void 0:t.layout)!=null?i:"default",s=Nr(e)({config:n,showClose:(d=(a=t==null?void 0:t.showCloseButton)!=null?a:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var gl=n=>{switch(n){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'}},Qn=n=>{var ne,xe,He,$e,ze,Ot,he,Z,ct,bt,kt,Ct,Kt,te,Pe,xt,ve,Se,Je,Bt,It,qt,I,nt,O,Q,re,Ne,oe,Xe,Ge;let{config:t}=n,r=g("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),e=g("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=g("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");o.style.outline="none";let s=g("textarea");s.placeholder=(xe=(ne=t==null?void 0:t.copy)==null?void 0:ne.inputPlaceholder)!=null?xe:"Type your message\u2026",s.className="tvw-w-full tvw-min-h-[24px] tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none tvw-composer-textarea",s.rows=1;let i=($e=(He=t==null?void 0:t.theme)==null?void 0:He.inputFontFamily)!=null?$e:"sans-serif",a=(Ot=(ze=t==null?void 0:t.theme)==null?void 0:ze.inputFontWeight)!=null?Ot:"400";s.style.fontFamily=gl(i),s.style.fontWeight=a;let v=3*20;s.style.maxHeight=`${v}px`,s.style.overflowY="auto";let p=()=>{s.style.height="auto";let pe=Math.min(s.scrollHeight,v);s.style.height=`${pe}px`};s.addEventListener("input",p),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let m=(he=t==null?void 0:t.sendButton)!=null?he:{},w=(Z=m.useIcon)!=null?Z:!1,C=(ct=m.iconText)!=null?ct:"\u2191",y=m.iconName,A=(bt=m.tooltipText)!=null?bt:"Send message",x=(kt=m.showTooltip)!=null?kt:!1,H=(Ct=m.size)!=null?Ct:"40px",Y=m.backgroundColor,k=m.textColor,P=g("div","tvw-send-button-wrapper"),L=g("button",w?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(L.type="submit",w){if(L.style.width=H,L.style.height=H,L.style.minWidth=H,L.style.minHeight=H,L.style.fontSize="18px",L.style.lineHeight="1",L.innerHTML="",y){let pe=parseFloat(H)||24,D=k&&typeof k=="string"&&k.trim()?k.trim():"currentColor",Ee=ie(y,pe,D,2);Ee?(L.appendChild(Ee),L.style.color=D):(L.textContent=C,k?L.style.color=k:L.classList.add("tvw-text-white"))}else L.textContent=C,k?L.style.color=k:L.classList.add("tvw-text-white");Y?L.style.backgroundColor=Y:L.classList.add("tvw-bg-cw-primary")}else L.textContent=(te=(Kt=t==null?void 0:t.copy)==null?void 0:Kt.sendButtonLabel)!=null?te:"Send",k?L.style.color=k:L.classList.add("tvw-text-white");if(m.borderWidth&&(L.style.borderWidth=m.borderWidth,L.style.borderStyle="solid"),m.borderColor&&(L.style.borderColor=m.borderColor),m.paddingX?(L.style.paddingLeft=m.paddingX,L.style.paddingRight=m.paddingX):(L.style.paddingLeft="",L.style.paddingRight=""),m.paddingY?(L.style.paddingTop=m.paddingY,L.style.paddingBottom=m.paddingY):(L.style.paddingTop="",L.style.paddingBottom=""),x&&A){let pe=g("div","tvw-send-button-tooltip");pe.textContent=A,P.appendChild(pe)}P.appendChild(L);let F=(Pe=t==null?void 0:t.voiceRecognition)!=null?Pe:{},ue=F.enabled===!0,z=null,V=null,X=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),_=((xt=F.provider)==null?void 0:xt.type)==="runtype";if(ue&&(X||_)){V=g("div","tvw-send-button-wrapper"),z=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),z.type="button",z.setAttribute("aria-label","Start voice recognition");let pe=(ve=F.iconName)!=null?ve:"mic",D=(Se=F.iconSize)!=null?Se:H,Ee=parseFloat(D)||24,st=(Je=F.backgroundColor)!=null?Je:Y,rt=(Bt=F.iconColor)!=null?Bt:k;z.style.width=D,z.style.height=D,z.style.minWidth=D,z.style.minHeight=D,z.style.fontSize="18px",z.style.lineHeight="1";let Yt=rt||"currentColor",Qt=ie(pe,Ee,Yt,1.5);Qt?(z.appendChild(Qt),z.style.color=Yt):(z.textContent="\u{1F3A4}",z.style.color=Yt),st?z.style.backgroundColor=st:z.classList.add("tvw-bg-cw-primary"),rt?z.style.color=rt:!rt&&!k&&z.classList.add("tvw-text-white"),F.borderWidth&&(z.style.borderWidth=F.borderWidth,z.style.borderStyle="solid"),F.borderColor&&(z.style.borderColor=F.borderColor),F.paddingX&&(z.style.paddingLeft=F.paddingX,z.style.paddingRight=F.paddingX),F.paddingY&&(z.style.paddingTop=F.paddingY,z.style.paddingBottom=F.paddingY),V.appendChild(z);let Ze=(It=F.tooltipText)!=null?It:"Start voice recognition";if(((qt=F.showTooltip)!=null?qt:!1)&&Ze){let vn=g("div","tvw-send-button-tooltip");vn.textContent=Ze,V.appendChild(vn)}}let se=(I=t==null?void 0:t.attachments)!=null?I:{},G=se.enabled===!0,U=null,N=null,ee=null,fe=null;if(G){fe=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),fe.style.display="none",ee=g("input"),ee.type="file",ee.accept=((nt=se.allowedTypes)!=null?nt:xn).join(","),ee.multiple=((O=se.maxFiles)!=null?O:4)>1,ee.style.display="none",ee.setAttribute("aria-label","Attach files"),N=g("div","tvw-send-button-wrapper"),U=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),U.type="button",U.setAttribute("aria-label",(Q=se.buttonTooltipText)!=null?Q:"Attach file");let pe=(re=se.buttonIconName)!=null?re:"paperclip",D=H,Ee=parseFloat(D)||40,st=Math.round(Ee*.6);U.style.width=D,U.style.height=D,U.style.minWidth=D,U.style.minHeight=D,U.style.fontSize="18px",U.style.lineHeight="1",U.style.backgroundColor="transparent",U.style.color="var(--cw-primary, #111827)",U.style.border="none",U.style.borderRadius="6px",U.style.transition="background-color 0.15s ease",U.addEventListener("mouseenter",()=>{U.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),U.addEventListener("mouseleave",()=>{U.style.backgroundColor="transparent"});let rt=ie(pe,st,"currentColor",1.5);rt?U.appendChild(rt):U.textContent="\u{1F4CE}",U.addEventListener("click",Ze=>{Ze.preventDefault(),ee==null||ee.click()}),N.appendChild(U);let Yt=(Ne=se.buttonTooltipText)!=null?Ne:"Attach file",Qt=g("div","tvw-send-button-tooltip");Qt.textContent=Yt,N.appendChild(Qt)}o.addEventListener("click",pe=>{pe.target!==L&&pe.target!==P&&pe.target!==z&&pe.target!==V&&pe.target!==U&&pe.target!==N&&s.focus()}),fe&&(fe.style.gap="8px",o.append(fe)),ee&&o.append(ee),o.append(s);let Fe=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),Mt=g("div","tvw-flex tvw-items-center tvw-gap-2");N&&Mt.append(N);let gt=g("div","tvw-flex tvw-items-center tvw-gap-1");V&&gt.append(V),gt.append(P),Fe.append(Mt,gt),o.append(Fe);let ft=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Ht=(oe=t==null?void 0:t.statusIndicator)!=null?oe:{},je=(Xe=Ht.visible)!=null?Xe:!0;return ft.style.display=je?"":"none",ft.textContent=(Ge=Ht.idleText)!=null?Ge:"Online",r.append(e,o,ft),{footer:r,suggestions:e,composerForm:o,textarea:s,sendButton:L,sendButtonWrapper:P,micButton:z,micButtonWrapper:V,statusText:ft,attachmentButton:U,attachmentButtonWrapper:N,attachmentInput:ee,attachmentPreviewsContainer:fe,actionsRow:Fe,leftActions:Mt,rightActions:gt}};var ya=n=>{var d,c,v,p,m,w,C;if(!((c=(d=n==null?void 0:n.launcher)==null?void 0:d.enabled)!=null?c:!0)){let y=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),A=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),x=(p=(v=n==null?void 0:n.launcher)==null?void 0:v.width)!=null?p:"100%";return y.style.width=x,A.style.width="100%",y.appendChild(A),{wrapper:y,panel:A}}let r=(m=n==null?void 0:n.launcher)!=null?m:{},e=r.position&&sn[r.position]?sn[r.position]:sn["bottom-right"],o=g("div",`tvw-widget-wrapper tvw-fixed ${e} tvw-z-50 tvw-transition`),s=g("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(C=(w=n==null?void 0:n.launcher)==null?void 0:w.width)!=null?C:n==null?void 0:n.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,o.appendChild(s),{wrapper:o,panel:s}},ba=(n,t=!0)=>{var w,C,y,A,x,H,Y;let r=g("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),e=(w=n==null?void 0:n.layout)==null?void 0:w.header,o=((C=n==null?void 0:n.layout)==null?void 0:C.showHeader)!==!1,s=e?Zn(n,e,{showClose:t}):mn({config:n,showClose:t}),i=g("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(A=(y=n==null?void 0:n.copy)==null?void 0:y.welcomeTitle)!=null?A:"Hello \u{1F44B}";let c=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(H=(x=n==null?void 0:n.copy)==null?void 0:x.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",a.append(d,c);let v=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,v);let p=Qn({config:n}),m=((Y=n==null?void 0:n.layout)==null?void 0:Y.showFooter)!==!1;return o?Fn(r,s,n):(s.header.style.display="none",Fn(r,s,n)),r.append(i),m||(p.footer.style.display="none"),r.append(p.footer),{container:r,body:i,messagesWrapper:v,suggestions:p.suggestions,textarea:p.textarea,sendButton:p.sendButton,sendButtonWrapper:p.sendButtonWrapper,micButton:p.micButton,micButtonWrapper:p.micButtonWrapper,composerForm:p.composerForm,statusText:p.statusText,introTitle:d,introSubtitle:c,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:p.footer,attachmentButton:p.attachmentButton,attachmentButtonWrapper:p.attachmentButtonWrapper,attachmentInput:p.attachmentInput,attachmentPreviewsContainer:p.attachmentPreviewsContainer,actionsRow:p.actionsRow,leftActions:p.leftActions,rightActions:p.rightActions}};var hl=320,ml=320,fl=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),vl=(n,t,r)=>{if(n.length===0)return null;try{let e=g("div","tvw-flex tvw-flex-col tvw-gap-2");e.setAttribute("data-message-attachments","images"),t&&(e.style.marginBottom="8px");let o=0,s=!1,i=()=>{s||(s=!0,e.remove(),r==null||r())};return n.forEach((a,d)=>{var p;let c=g("img");c.alt=((p=a.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=`${hl}px`,c.style.maxHeight=`${ml}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--cw-container, #f3f4f6)",c.style.border="1px solid var(--cw-border, #e5e7eb)";let v=!1;o+=1,c.addEventListener("error",()=>{v||(v=!0,o=Math.max(0,o-1),c.remove(),o===0&&i())}),c.addEventListener("load",()=>{v=!0}),c.src=a.image,e.appendChild(c)}),o===0?(i(),null):e}catch{return r==null||r(),null}},$n=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",n.appendChild(t),n.appendChild(r),n.appendChild(e),n.appendChild(o),n},Or=(n,t,r)=>{let e={config:r!=null?r:{},streaming:!0,location:n,defaultRenderer:$n};if(t){let o=t(e);if(o!==null)return o}return $n()},wl=(n,t)=>{let r=g("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),e=t==="user"?n.userAvatar:n.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let o=g("img");o.src=e,o.alt=t==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=e,r.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},Ca=(n,t)=>{let r=g("div","tvw-text-xs tvw-text-cw-muted"),e=new Date(n.createdAt);return t.format?r.textContent=t.format(e):r.textContent=e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},yl=(n,t="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(t){case"flat":n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},Dr=(n,t,r)=>{var w,C,y,A,x,H;let e=(w=t.showCopy)!=null?w:!0,o=(C=t.showUpvote)!=null?C:!0,s=(y=t.showDownvote)!=null?y:!0,i=(A=t.visibility)!=null?A:"hover",a=(x=t.align)!=null?x:"right",d=(H=t.layout)!=null?H:"pill-inside",c={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],v={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],p=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${v} ${i==="hover"?"tvw-message-actions-hover":""}`);p.id=`actions-${n.id}`,p.setAttribute("data-actions-for",n.id);let m=(Y,k,P)=>{let L=document.createElement("button");L.className="tvw-message-action-btn",L.setAttribute("aria-label",k),L.setAttribute("title",k),L.setAttribute("data-action",P);let F=ie(Y,14,"currentColor",2);return F&&L.appendChild(F),L};return e&&p.appendChild(m("copy","Copy message","copy")),o&&p.appendChild(m("thumbs-up","Upvote","upvote")),s&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},es=(n,t,r,e,o,s)=>{var V,X,_,Ce,se,G,U;let i=r!=null?r:{},a=(V=i.layout)!=null?V:"bubble",d=i.avatar,c=i.timestamp,v=(X=d==null?void 0:d.show)!=null?X:!1,p=(_=c==null?void 0:c.show)!=null?_:!1,m=(Ce=d==null?void 0:d.position)!=null?Ce:"left",w=(se=c==null?void 0:c.position)!=null?se:"below",C=yl(n.role,a),y=g("div",C.join(" "));y.id=`bubble-${n.id}`,y.setAttribute("data-message-id",n.id);let A=fl(n),x=(U=(G=n.content)==null?void 0:G.trim())!=null?U:"",Y=A.length>0&&x===nr,k=document.createElement("div"),P=t({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),L=null;if(Y?(L=document.createElement("div"),L.innerHTML=P,L.style.display="none",k.appendChild(L)):k.innerHTML=P,p&&w==="inline"&&n.createdAt){let N=Ca(n,c);N.classList.add("tvw-ml-2","tvw-inline"),k.appendChild(N)}if(A.length>0){let N=vl(A,!Y&&!!x,()=>{Y&&L&&(L.style.display="")});N?y.appendChild(N):Y&&L&&(L.style.display="")}if(y.appendChild(k),p&&w==="below"&&n.createdAt){let N=Ca(n,c);N.classList.add("tvw-mt-1"),y.appendChild(N)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let N=Or("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);N&&y.appendChild(N)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let N=Dr(n,e,o);y.appendChild(N)}if(!v||n.role==="system")return y;let ue=g("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),z=wl(d,n.role);return m==="right"||m==="left"&&n.role==="user"?ue.append(y,z):ue.append(z,y),y.classList.remove("tvw-max-w-[85%]"),y.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),ue},xa=(n,t,r,e,o,s)=>{let i=r!=null?r:{};return n.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):es(n,t,r,e,o,s)};var ts=new Set,Sa=(n,t)=>{let r=ts.has(n),e=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".tvw-border-t");if(!e||!o)return;e.setAttribute("aria-expanded",r?"true":"false");let s=e.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=ie(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},jr=n=>{let t=n.reasoning,r=g("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${n.id}`,r.setAttribute("data-message-id",n.id),!t)return r;let e=ts.has(n.id),o=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",e?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=g("div","tvw-flex tvw-flex-col tvw-text-left"),i=g("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=g("span","tvw-text-xs tvw-text-cw-primary");a.textContent=ta(t),s.appendChild(a),t.status==="complete"?i.style.display="none":i.style.display="";let d=g("div","tvw-flex tvw-items-center"),v=ie(e?"chevron-up":"chevron-down",16,"currentColor",2);v?d.appendChild(v):d.textContent=e?"Hide":"Show";let p=g("div","tvw-flex tvw-items-center tvw-ml-auto");p.append(d),o.append(s,p);let m=g("div","tvw-border-t tvw-px-4 tvw-py-3");m.style.display=e?"":"none";let w=t.chunks.join(""),C=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return C.textContent=w||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(C),(()=>{o.setAttribute("aria-expanded",e?"true":"false"),d.innerHTML="";let x=ie(e?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=e?"Hide":"Show",m.style.display=e?"":"none"})(),r.append(o,m),r};var ns=new Set,Aa=(n,t,r)=>{var c;let e=ns.has(n),o=(c=r==null?void 0:r.toolCall)!=null?c:{},s=t.querySelector('button[data-expand-header="true"]'),i=t.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",e?"true":"false");let a=s.querySelector(".tvw-ml-auto"),d=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(d){d.innerHTML="";let v=o.toggleTextColor||o.headerTextColor||"currentColor",p=ie(e?"chevron-up":"chevron-down",16,v,2);p?d.appendChild(p):d.textContent=e?"Hide":"Show"}i.style.display=e?"":"none"},_r=(n,t)=>{var y;let r=n.toolCall,e=(y=t==null?void 0:t.toolCall)!=null?y:{},o=g("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),e.backgroundColor&&(o.style.backgroundColor=e.backgroundColor),e.borderColor&&(o.style.borderColor=e.borderColor),e.borderWidth&&(o.style.borderWidth=e.borderWidth),e.borderRadius&&(o.style.borderRadius=e.borderRadius),!r)return o;let s=ns.has(n.id),i=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),e.headerBackgroundColor&&(i.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(i.style.paddingLeft=e.headerPaddingX,i.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(i.style.paddingTop=e.headerPaddingY,i.style.paddingBottom=e.headerPaddingY);let a=g("div","tvw-flex tvw-flex-col tvw-text-left"),d=g("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(d.style.color=e.headerTextColor),d.textContent=na(r),a.appendChild(d);let c=g("div","tvw-flex tvw-items-center"),v=e.toggleTextColor||e.headerTextColor||"currentColor",p=ie(s?"chevron-up":"chevron-down",16,v,2);p?c.appendChild(p):c.textContent=s?"Hide":"Show";let m=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(c),i.append(a,m);let w=g("div","tvw-border-t tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",e.contentBackgroundColor&&(w.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(w.style.color=e.contentTextColor),e.contentPaddingX&&(w.style.paddingLeft=e.contentPaddingX,w.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(w.style.paddingTop=e.contentPaddingY,w.style.paddingBottom=e.contentPaddingY),r.name){let A=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?A.style.color=e.contentTextColor:e.headerTextColor&&(A.style.color=e.headerTextColor),A.textContent=r.name,w.appendChild(A)}if(r.args!==void 0){let A=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Arguments";let H=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(H.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(H.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(H.style.color=e.codeBlockTextColor),H.textContent=As(r.args),A.append(x,H),w.appendChild(A)}if(r.chunks&&r.chunks.length){let A=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Activity";let H=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(H.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(H.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(H.style.color=e.codeBlockTextColor),H.textContent=r.chunks.join(`
16
- `),A.append(x,H),w.appendChild(A)}if(r.status==="complete"&&r.result!==void 0){let A=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Result";let H=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(H.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(H.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(H.style.color=e.codeBlockTextColor),H.textContent=As(r.result),A.append(x,H),w.appendChild(A)}if(r.status==="complete"&&typeof r.duration=="number"){let A=g("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(A.style.color=e.contentTextColor),A.textContent=`Duration: ${r.duration}ms`,w.appendChild(A)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let A=e.toggleTextColor||e.headerTextColor||"currentColor",x=ie(s?"chevron-up":"chevron-down",16,A,2);x?c.appendChild(x):c.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),o.append(i,w),o};var Ur=(n,t)=>{var y,A,x,H,Y,k,P,L,F,ue,z;let r=n.approval,e=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(r==null?void 0:r.status)==="pending",s=g("div",["vanilla-message-bubble","vanilla-approval-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-border","tvw-shadow-sm","tvw-overflow-hidden"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),e!=null&&e.backgroundColor&&(s.style.backgroundColor=e.backgroundColor),e!=null&&e.borderColor&&(s.style.borderColor=e.borderColor),!r)return s;let i=g("div","tvw-flex tvw-items-start tvw-gap-3 tvw-px-4 tvw-py-3"),a=g("div","tvw-flex-shrink-0 tvw-mt-0.5");a.setAttribute("data-approval-icon","true");let d=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",c=r.status==="approved"?"#16a34a":r.status==="denied"?"#dc2626":r.status==="timeout"?"#ca8a04":(y=e==null?void 0:e.titleColor)!=null?y:"currentColor",v=ie(d,20,c,2);v&&a.appendChild(v);let p=g("div","tvw-flex-1 tvw-min-w-0"),m=g("div","tvw-flex tvw-items-center tvw-gap-2"),w=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary");if(e!=null&&e.titleColor&&(w.style.color=e.titleColor),w.textContent=(A=e==null?void 0:e.title)!=null?A:"Approval Required",m.appendChild(w),!o){let V=g("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded-full tvw-text-xs tvw-font-medium");V.setAttribute("data-approval-status",r.status),r.status==="approved"?(V.className+=" tvw-approval-badge-approved",V.textContent="Approved"):r.status==="denied"?(V.className+=" tvw-approval-badge-denied",V.textContent="Denied"):r.status==="timeout"&&(V.className+=" tvw-approval-badge-timeout",V.textContent="Timeout"),m.appendChild(V)}p.appendChild(m);let C=g("p","tvw-text-sm tvw-mt-0.5 tvw-text-cw-muted");if(e!=null&&e.descriptionColor&&(C.style.color=e.descriptionColor),C.textContent=r.description,p.appendChild(C),r.parameters){let V=g("pre","tvw-mt-2 tvw-text-xs tvw-p-2 tvw-rounded tvw-overflow-x-auto tvw-max-h-32 tvw-bg-cw-container tvw-text-cw-primary");e!=null&&e.parameterBackgroundColor&&(V.style.backgroundColor=e.parameterBackgroundColor),e!=null&&e.parameterTextColor&&(V.style.color=e.parameterTextColor),V.style.fontSize="0.75rem",V.style.lineHeight="1rem",V.textContent=As(r.parameters),p.appendChild(V)}if(o){let V=g("div","tvw-flex tvw-gap-2 tvw-mt-2");V.setAttribute("data-approval-buttons","true");let X=g("button","tvw-inline-flex tvw-items-center tvw-px-3 tvw-py-1.5 tvw-rounded-md tvw-text-xs tvw-font-medium tvw-border-none tvw-cursor-pointer");X.type="button",X.style.backgroundColor=(x=e==null?void 0:e.approveButtonColor)!=null?x:"#16a34a",X.style.color=(H=e==null?void 0:e.approveButtonTextColor)!=null?H:"#ffffff",X.setAttribute("data-approval-action","approve");let _=ie("shield-check",14,(Y=e==null?void 0:e.approveButtonTextColor)!=null?Y:"#ffffff",2);_&&(_.style.marginRight="4px",X.appendChild(_));let Ce=document.createTextNode((k=e==null?void 0:e.approveLabel)!=null?k:"Approve");X.appendChild(Ce);let se=g("button","tvw-inline-flex tvw-items-center tvw-px-3 tvw-py-1.5 tvw-rounded-md tvw-text-xs tvw-font-medium tvw-cursor-pointer");se.type="button",se.style.backgroundColor=(P=e==null?void 0:e.denyButtonColor)!=null?P:"transparent",se.style.color=(L=e==null?void 0:e.denyButtonTextColor)!=null?L:"#dc2626",se.style.border=`1px solid ${(F=e==null?void 0:e.denyButtonTextColor)!=null?F:"#fca5a5"}`,se.setAttribute("data-approval-action","deny");let G=ie("shield-x",14,(ue=e==null?void 0:e.denyButtonTextColor)!=null?ue:"#dc2626",2);G&&(G.style.marginRight="4px",se.appendChild(G));let U=document.createTextNode((z=e==null?void 0:e.denyLabel)!=null?z:"Deny");se.appendChild(U),V.append(X,se),p.appendChild(V)}return i.append(a,p),s.appendChild(i),s};var Ea=n=>{let t=[];return{buttons:t,render:(e,o,s,i,a)=>{if(n.innerHTML="",t.length=0,!e||!e.length||(i!=null?i:o?o.getMessages():[]).some(w=>w.role==="user"))return;let v=document.createDocumentFragment(),p=o?o.isStreaming():!1,m=w=>{switch(w){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'}};e.forEach(w=>{let C=g("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");C.type="button",C.textContent=w,C.disabled=p,a!=null&&a.fontFamily&&(C.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(C.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(C.style.paddingLeft=a.paddingX,C.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(C.style.paddingTop=a.paddingY,C.style.paddingBottom=a.paddingY),C.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(w))}),v.appendChild(C),t.push(C)}),n.appendChild(v)}}};var ks=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(r=this.store)==null||r.put(t)}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 t=await this.store.getAll();if(t.length===0)return 0;let r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let e of r)this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(e.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Is=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let e=indexedDB.open(this.dbName,1);e.onupgradeneeded=()=>{let o=e.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},e.onsuccess=()=>{this.db=e.result,t()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)e.put(o)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{r(i.error)}}catch(e){r(e)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let e=indexedDB.deleteDatabase(this.dbName);e.onsuccess=()=>{t()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)e.put(o)}catch{}}};function ss(n,t){t&&t.split(/\s+/).forEach(r=>r&&n.classList.add(r))}var bl={flow_:{bg:"#dcfce7",text:"#166534"},step_:{bg:"#dbeafe",text:"#1e40af"},reason_:{bg:"#ffedd5",text:"#9a3412"},tool_:{bg:"#f3e8ff",text:"#6b21a8"},agent_:{bg:"#ccfbf1",text:"#115e59"},error:{bg:"#fecaca",text:"#991b1b"}},Cl={bg:"#f3f4f6",text:"#4b5563"},xl=["flowName","stepName","reasoningText","text","name","tool","toolName"],Sl=100;function Al(n,t){let r={...bl,...t};if(r[n])return r[n];for(let e of Object.keys(r))if(e.endsWith("_")&&n.startsWith(e))return r[e];return Cl}function El(n,t){return`+${((n-t)/1e3).toFixed(3)}s`}function Tl(n){let t=new Date(n),r=String(t.getHours()).padStart(2,"0"),e=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${e}:${o}.${s}`}function Ml(n,t){try{let r=JSON.parse(n);if(typeof r!="object"||r===null)return null;for(let e of t){let o=e.split("."),s=r;for(let i of o)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function kl(n){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(n):new Promise(r=>{let e=document.createElement("textarea");e.value=n,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),r()})}function Il(n){let t;try{t=JSON.parse(n.payload)}catch{t=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:t},null,2)}function Ll(n,t,r){let e,o;try{o=JSON.parse(n.payload),e=JSON.stringify(o,null,2)}catch{o=n.payload,e=n.payload}let s=t.find(a=>a.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let a=s.renderEventStreamPayload({event:n,config:r,defaultRenderer:()=>i(),parsedPayload:o});if(a)return a}return i();function i(){let a=g("div","tvw-bg-cw-container tvw-border-t tvw-border-cw-divider tvw-px-3 tvw-py-2 tvw-ml-4 tvw-mr-3 tvw-mb-1 tvw-rounded-b tvw-overflow-auto tvw-max-h-[300px]"),d=g("pre","tvw-m-0 tvw-whitespace-pre-wrap tvw-break-all tvw-text-[11px] tvw-text-cw-secondary tvw-font-mono");return d.textContent=e,a.appendChild(d),a}}function qr(n,t,r,e,o,s,i,a){var m;let d=o.has(n.id),c=g("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");ss(c,(m=e.classNames)==null?void 0:m.eventRow);let v=i.find(w=>w.renderEventStreamRow);if(v!=null&&v.renderEventStreamRow&&a){let w=v.renderEventStreamRow({event:n,index:t,config:a,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(w)return c.appendChild(w),c}return c.appendChild(p()),c;function p(){var _,Ce;let w=g("div",""),C=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-3 tvw-py-3 hover:tvw-bg-cw-container tvw-cursor-pointer tvw-group");C.setAttribute("data-event-id",n.id);let y=g("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),A=ie(d?"chevron-down":"chevron-right","14px","currentColor",2);A&&y.appendChild(A);let x=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),H=(_=e.timestampFormat)!=null?_:"relative";x.textContent=H==="relative"?El(n.timestamp,r):Tl(n.timestamp);let Y=null;e.showSequenceNumbers!==!1&&(Y=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),Y.textContent=String(t+1));let k=Al(n.type,e.badgeColors),P=g("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded tvw-text-[11px] tvw-font-mono tvw-font-medium tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-border");P.style.backgroundColor=k.bg,P.style.color=k.text,P.style.borderColor=k.text+"50",P.textContent=n.type;let L=(Ce=e.descriptionFields)!=null?Ce:xl,F=Ml(n.payload,L),ue=null;F&&(ue=g("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),ue.textContent=F);let z=g("div","tvw-flex-1 tvw-min-w-0"),V=g("button","tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-flex-shrink-0 tvw-border-none tvw-bg-transparent tvw-p-0"),X=ie("clipboard","12px","currentColor",1.5);return X&&V.appendChild(X),V.addEventListener("click",async se=>{se.stopPropagation(),await kl(Il(n)),V.innerHTML="";let G=ie("check","12px","currentColor",1.5);G&&V.appendChild(G),setTimeout(()=>{V.innerHTML="";let U=ie("clipboard","12px","currentColor",1.5);U&&V.appendChild(U)},1500)}),C.appendChild(y),C.appendChild(x),Y&&C.appendChild(Y),C.appendChild(P),ue&&C.appendChild(ue),C.appendChild(z),C.appendChild(V),w.appendChild(C),d&&w.appendChild(Ll(n,i,a)),w}}function Ta(n){var c,v;let{buffer:t,getFullHistory:r,onClose:e,config:o,plugins:s=[]}=n,i=(v=(c=o==null?void 0:o.features)==null?void 0:c.eventStream)!=null?v:{},a=s.find(p=>p.renderEventStreamView);if(a!=null&&a.renderEventStreamView&&o){let p=a.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>d().element,onClose:e});if(p)return{element:p,update:()=>{},destroy:()=>{}}}return d();function d(){let p=i.classNames,m=g("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");ss(m,p==null?void 0:p.panel);let w=[],C="",y="",A=null,x=[],H={},Y=0,k=!1,P=0,L=0,F=!1,ue=null,z=!1,V=0,X=new Set,_=new Map,Ce="",se="",G=null,U,N,ee,fe,Fe;function Mt(){let O=g("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),Q=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-4 tvw-py-3 tvw-pb-0 tvw-border-cw-divider tvw-bg-cw-surface tvw-overflow-hidden");ss(Q,p==null?void 0:p.headerBar);let re=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");re.textContent="Events",U=g("span","tvw-text-[11px] tvw-font-mono tvw-bg-cw-container tvw-text-cw-muted tvw-px-2 tvw-py-0.5 tvw-rounded tvw-border tvw-border-cw-border"),U.textContent="0";let Ne=g("div","tvw-flex-1");N=g("select","tvw-text-xs tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded tvw-px-2.5 tvw-py-1 tvw-text-cw-primary tvw-cursor-pointer");let oe=g("option","");oe.value="",oe.textContent="All events",N.appendChild(oe),ee=g("button","tvw-inline-flex tvw-items-center tvw-gap-1.5 tvw-rounded tvw-text-xs tvw-text-cw-muted hover:tvw-bg-cw-container hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border tvw-border-cw-border tvw-bg-cw-surface tvw-flex-shrink-0 tvw-px-2.5 tvw-py-1"),ee.type="button",ee.title="Copy All";let Ge=ie("clipboard-copy","12px","currentColor",1.5);Ge&&ee.appendChild(Ge);let pe=g("span","tvw-text-xs");pe.textContent="Copy All",ee.appendChild(pe),Q.appendChild(re),Q.appendChild(U),Q.appendChild(Ne),Q.appendChild(N),Q.appendChild(ee);let D=g("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");ss(D,p==null?void 0:p.searchBar);let Ee=ie("search","14px","var(--cw-muted, #9ca3af)",1.5),st=g("span","tvw-absolute tvw-left-6 tvw-top-1/2 tvw--translate-y-1/2 tvw-pointer-events-none tvw-flex tvw-items-center");Ee&&st.appendChild(Ee),fe=g("input","tvw-text-sm tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded-md tvw-pl-8 tvw-pr-3 tvw-py-1 tvw-w-full tvw-text-cw-primary"),ss(fe,p==null?void 0:p.searchInput),fe.type="text",fe.placeholder="Search event payloads...",Fe=g("button","tvw-absolute tvw-right-5 tvw-top-1/2 tvw--translate-y-1/2 tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-0 tvw-leading-none"),Fe.type="button",Fe.style.display="none";let rt=ie("x","12px","currentColor",2);return rt&&Fe.appendChild(rt),D.appendChild(st),D.appendChild(fe),D.appendChild(Fe),O.appendChild(Q),O.appendChild(D),O}let gt,ft=s.find(O=>O.renderEventStreamToolbar);if(ft!=null&&ft.renderEventStreamToolbar&&o){let O=ft.renderEventStreamToolbar({config:o,defaultRenderer:()=>Mt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Q=>{C=Q,ct(),Ct()},onSearchChange:Q=>{y=Q,ct(),Ct()}});gt=O!=null?O:Mt()}else gt=Mt();let Ht=g("div","tvw-text-xs tvw-text-cw-muted tvw-text-center tvw-py-0.5 tvw-px-4 tvw-bg-cw-container tvw-border-b tvw-border-cw-divider tvw-italic tvw-flex-shrink-0");Ht.style.display="none";let je=g("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),ne=g("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");ne.style.height="100%";let xe=g("div","tvw-absolute tvw-bottom-3 tvw-left-1/2 tvw-transform tvw--translate-x-1/2 tvw-bg-cw-accent tvw-text-white tvw-text-xs tvw-px-3 tvw-py-1.5 tvw-rounded-full tvw-cursor-pointer tvw-shadow-md tvw-z-10 tvw-flex tvw-items-center tvw-gap-1");ss(xe,p==null?void 0:p.scrollIndicator),xe.style.display="none";let He=ie("arrow-down","12px","currentColor",2);He&&xe.appendChild(He);let $e=g("span","");xe.appendChild($e);let ze=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");ze.style.display="none",je.appendChild(ne),je.appendChild(ze),je.appendChild(xe),m.setAttribute("tabindex","0"),m.appendChild(gt),m.appendChild(Ht),m.appendChild(je);function Ot(){let O=t.getAll(),Q={};for(let pe of O)Q[pe.type]=(Q[pe.type]||0)+1;let re=Object.keys(Q).sort(),Ne=re.length!==x.length||!re.every((pe,D)=>pe===x[D]),oe=!Ne&&re.some(pe=>Q[pe]!==H[pe]),Xe=O.length!==Object.values(H).reduce((pe,D)=>pe+D,0);if(!Ne&&!oe&&!Xe||(x=re,H=Q,!N))return;let Ge=N.value;if(N.options[0].textContent="All events",Ne){for(;N.options.length>1;)N.remove(1);for(let pe of re){let D=g("option","");D.value=pe,D.textContent=`${pe} (${Q[pe]||0})`,N.appendChild(D)}Ge&&re.includes(Ge)?N.value=Ge:Ge&&(N.value="",C="")}else for(let pe=1;pe<N.options.length;pe++){let D=N.options[pe];D.textContent=`${D.value} (${Q[D.value]||0})`}}function he(){let O=t.getAll();if(C&&(O=O.filter(Q=>Q.type===C)),y){let Q=y.toLowerCase();O=O.filter(re=>re.type.toLowerCase().includes(Q)||re.payload.toLowerCase().includes(Q))}return O}function Z(){return C!==""||y!==""}function ct(){Y=0,P=0,k=!1,xe.style.display="none"}function bt(O){X.has(O)?X.delete(O):X.add(O),G=O;let Q=ne.scrollTop,re=k;z=!0,k=!0,Ct(),ne.scrollTop=Q,k=re,z=!1}function kt(){return ne.scrollHeight-ne.scrollTop-ne.clientHeight<=50}function Ct(){L=Date.now(),F=!1,Ot();let O=t.getEvictedCount();O>0?(Ht.textContent=`${O.toLocaleString()} older events truncated`,Ht.style.display=""):Ht.style.display="none",w=he();let Q=w.length,re=t.getSize()>0;U&&(U.textContent=String(t.getSize())),Q===0&&re&&Z()?(ze.textContent=y?`No events matching '${y}'`:"No events matching filter",ze.style.display="",ne.style.display="none"):(ze.style.display="none",ne.style.display=""),ee&&(ee.title=Z()?`Copy Filtered (${Q})`:"Copy All"),k&&Q>Y&&(P+=Q-Y,$e.textContent=`${P} new event${P===1?"":"s"}`,xe.style.display=""),Y=Q;let Ne=t.getAll(),oe=Ne.length>0?Ne[0].timestamp:0,Xe=new Set(w.map(D=>D.id));for(let D of X)Xe.has(D)||X.delete(D);let Ge=C!==Ce||y!==se,pe=_.size===0&&w.length>0;if(Ge||pe||w.length===0){ne.innerHTML="",_.clear();let D=document.createDocumentFragment();for(let Ee=0;Ee<w.length;Ee++){let st=qr(w[Ee],Ee,oe,i,X,bt,s,o);_.set(w[Ee].id,st),D.appendChild(st)}ne.appendChild(D),Ce=C,se=y,G=null}else{if(G!==null){let Ee=_.get(G);if(Ee&&Ee.parentNode===ne){let st=w.findIndex(rt=>rt.id===G);if(st>=0){let rt=qr(w[st],st,oe,i,X,bt,s,o);ne.insertBefore(rt,Ee),Ee.remove(),_.set(G,rt)}}G=null}let D=new Set(w.map(Ee=>Ee.id));for(let[Ee,st]of _)D.has(Ee)||(st.remove(),_.delete(Ee));for(let Ee=0;Ee<w.length;Ee++){let st=w[Ee];if(!_.has(st.id)){let rt=qr(st,Ee,oe,i,X,bt,s,o);_.set(st.id,rt),ne.appendChild(rt)}}}k||(ne.scrollTop=ne.scrollHeight)}function Kt(){if(Date.now()-L>=Sl){ue!==null&&(cancelAnimationFrame(ue),ue=null),Ct();return}F||(F=!0,ue=requestAnimationFrame(()=>{ue=null,Ct()}))}let te=(O,Q)=>{if(!ee)return;ee.innerHTML="";let re=ie(O,"12px","currentColor",1.5);re&&ee.appendChild(re);let Ne=g("span","tvw-text-xs");Ne.textContent="Copy All",ee.appendChild(Ne),setTimeout(()=>{ee.innerHTML="";let oe=ie("clipboard-copy","12px","currentColor",1.5);oe&&ee.appendChild(oe);let Xe=g("span","tvw-text-xs");Xe.textContent="Copy All",ee.appendChild(Xe),ee.disabled=!1},Q)},Pe=async()=>{if(ee){ee.disabled=!0;try{let O;Z()?O=w:r?(O=await r(),O.length===0&&(O=t.getAll())):O=t.getAll();let Q=O.map(re=>{try{return JSON.parse(re.payload)}catch{return re.payload}});await navigator.clipboard.writeText(JSON.stringify(Q,null,2)),te("check",1500)}catch{te("x",1500)}}},xt=()=>{N&&(C=N.value,ct(),Ct())},ve=()=>{!fe||!Fe||(Fe.style.display=fe.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{y=fe.value,ct(),Ct()},150))},Se=()=>{!fe||!Fe||(fe.value="",y="",Fe.style.display="none",A&&clearTimeout(A),ct(),Ct())},Je=()=>{if(z)return;let O=ne.scrollTop,Q=O>V;V=O,kt()&&Q?(k=!1,P=0,xe.style.display="none"):kt()||(k=!0)},Bt=O=>{O.deltaY<0&&(k=!0)},It=()=>{ne.scrollTop=ne.scrollHeight,k=!1,P=0,xe.style.display="none"},qt=O=>{let Q=O.target;if(!Q||Q.closest("button"))return;let re=Q.closest("[data-event-id]");if(!re)return;let Ne=re.getAttribute("data-event-id");Ne&&bt(Ne)},I=O=>{if((O.metaKey||O.ctrlKey)&&O.key==="f"){O.preventDefault(),fe==null||fe.focus(),fe==null||fe.select();return}O.key==="Escape"&&(fe&&document.activeElement===fe?(Se(),fe.blur(),m.focus()):e&&e())};ee&&ee.addEventListener("click",Pe),N&&N.addEventListener("change",xt),fe&&fe.addEventListener("input",ve),Fe&&Fe.addEventListener("click",Se),ne.addEventListener("scroll",Je),ne.addEventListener("wheel",Bt,{passive:!0}),ne.addEventListener("click",qt),xe.addEventListener("click",It),m.addEventListener("keydown",I);function nt(){A&&clearTimeout(A),ue!==null&&(cancelAnimationFrame(ue),ue=null),F=!1,_.clear(),ee&&ee.removeEventListener("click",Pe),N&&N.removeEventListener("change",xt),fe&&fe.removeEventListener("input",ve),Fe&&Fe.removeEventListener("click",Se),ne.removeEventListener("scroll",Je),ne.removeEventListener("wheel",Bt),ne.removeEventListener("click",qt),xe.removeEventListener("click",It),m.removeEventListener("keydown",I)}return{element:m,update:Kt,destroy:nt}}}var Ma={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"}},Vr=(n,t,r,e)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var C,y,A;if(s.dataset.enhanced==="true")return;let i=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let a=(y=Ma[i])!=null?y:Ma.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=g("div","tvw-space-y-1"),c=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=a.title,d.appendChild(c),a.description){let x=g("p","tvw-text-sm tvw-text-cw-muted");x.textContent=a.description,d.appendChild(x)}let v=document.createElement("form");v.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(x=>{var L,F;let H=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");H.htmlFor=`${t.id}-${i}-${x.name}`;let Y=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");Y.textContent=x.label,H.appendChild(Y);let k=(L=x.type)!=null?L:"text",P;k==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=k),P.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",P.id=`${t.id}-${i}-${x.name}`,P.name=x.name,P.placeholder=(F=x.placeholder)!=null?F:"",x.required&&(P.required=!0),H.appendChild(P),v.appendChild(H)});let p=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),m=g("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),w=g("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");w.type="submit",w.textContent=(A=a.submitLabel)!=null?A:"Submit",p.appendChild(m),p.appendChild(w),v.appendChild(p),s.replaceChildren(d,v),v.addEventListener("submit",async x=>{var P,L;x.preventDefault();let H=(P=r.formEndpoint)!=null?P:"/form",Y=new FormData(v),k={};Y.forEach((F,ue)=>{k[ue]=F}),k.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let F=await fetch(H,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!F.ok)throw new Error(`Form submission failed (${F.status})`);let ue=await F.json();m.textContent=(L=ue.message)!=null?L:"Thanks! We'll be in touch soon.",ue.success&&ue.nextPrompt&&await e.sendMessage(String(ue.nextPrompt))}catch(F){m.textContent=F instanceof Error?F.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var zr=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var e;let r=this.plugins.get(t);r&&((e=r.onUnregister)==null||e.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var e,o;return((e=r.priority)!=null?e:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let e=new Set(t.map(s=>s.id));return[...r.filter(s=>!e.has(s.id)),...t].sort((s,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},Ls=new zr;var Jr={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"},Kr={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"},it={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Jr,darkTheme:Kr,colorScheme:"light",launcher:{enabled:!0,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 ur(n){var t,r,e,o,s,i,a,d,c,v,p,m,w,C,y,A,x,H,Y;return n?{...it,...n,theme:{...it.theme,...n.theme},darkTheme:{...it.darkTheme,...n.darkTheme},launcher:{...it.launcher,...n.launcher,clearChat:{...(t=it.launcher)==null?void 0:t.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...it.copy,...n.copy},sendButton:{...it.sendButton,...n.sendButton},statusIndicator:{...it.statusIndicator,...n.statusIndicator},voiceRecognition:{...it.voiceRecognition,...n.voiceRecognition},features:{...it.features,...n.features},suggestionChips:(e=n.suggestionChips)!=null?e:it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...it.layout,...n.layout,header:{...(o=it.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=it.layout)==null?void 0:i.messages,...(a=n.layout)==null?void 0:a.messages,avatar:{...(c=(d=it.layout)==null?void 0:d.messages)==null?void 0:c.avatar,...(p=(v=n.layout)==null?void 0:v.messages)==null?void 0:p.avatar},timestamp:{...(w=(m=it.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(y=(C=n.layout)==null?void 0:C.messages)==null?void 0:y.timestamp}},slots:{...(A=it.layout)==null?void 0:A.slots,...(x=n.layout)==null?void 0:x.slots}},markdown:{...it.markdown,...n.markdown,options:{...(H=it.markdown)==null?void 0:H.options,...(Y=n.markdown)==null?void 0:Y.options}},messageActions:{...it.messageActions,...n.messageActions}}:it}var ka=()=>{let n=new Map,t=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=n.get(o))==null||i.delete(s)};return{on:t,off:r,emit:(o,s)=>{var i;(i=n.get(o))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Wl=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},Pl=n=>{let t=n.trim(),r=t.indexOf("{");if(r===-1)return null;let e=0;for(let o=r;o<t.length;o+=1){let s=t[o];if(s==="{"&&(e+=1),s==="}"&&(e-=1,e===0))return t.slice(r,o+1)}return null},Ws=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=Wl(n),r=Pl(t);if(!r)return null;let e=JSON.parse(r);if(!e||typeof e!="object"||!e.action)return null;let{action:o,...s}=e;return{type:String(o),payload:s,raw:e}}catch{return null}},Yr=n=>typeof n=="string"?n:n==null?"":String(n),Nn={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Yr(n.payload.text)},messageAndClick:(n,t)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,e=Yr(r.element);if(e&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(e);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:Yr(r.text)}}},Ia=n=>Array.isArray(n)?n.map(t=>String(t)):[],Ps=n=>{let t=new Set(Ia(n.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(Ia(n.getSessionMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(t);n.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.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 a=i?n.parsers.reduce((c,v)=>c||(v==null?void 0:v({text:i,message:s.message}))||null,null):null;if(!a)return null;t.add(s.message.id),e();let d={action:a,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let v=()=>{n.emit("action:resubmit",d)},p=c(a,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:v});if(!p)continue;if(p.handled){let m=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:m,resubmit:p.resubmit}}}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",v)}return{text:"",persist:!0}},syncFromMetadata:r}};var Rl=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Hl=n=>n.map(t=>({...t,streaming:!1})),pr=(n="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?Rl(r.getItem(n)):null},save:r=>{let e=t();if(e)try{let o={...r,messages:r.messages?Hl(r.messages):void 0};e.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=t();if(r)try{r.removeItem(n)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var Xr=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([r,e])=>{this.register(r,e)})}},rs=new Xr;var os=require("partial-json");function Bl(n){if(!n||typeof n!="object"||!("component"in n))return!1;let t=n.component;return typeof t=="string"&&t.length>0}function Fl(n,t){if(!Bl(n))return null;let r=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:r,raw:t}}function gr(){let n=null,t=0;return{getExtractedDirective:()=>n,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=t)return n;try{let o=(0,os.parse)(r,os.STR|os.OBJ),s=Fl(o,r);s&&(n=s)}catch{}return t=r.length,n},reset:()=>{n=null,t=0}}}function La(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function hr(n,t){let{config:r,message:e,onPropsUpdate:o}=t,s=rs.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:e,config:r,updateProps:a=>{o&&o(a)}};try{return s(n.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,a),null}}function Wa(){let n=gr();return{processChunk:t=>n.processChunk(t),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function mr(n){if(!n.rawContent)return!1;try{let t=JSON.parse(n.rawContent);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function fr(n){if(!n.rawContent)return null;try{let t=JSON.parse(n.rawContent);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string")return{component:t.component,props:t.props&&typeof t.props=="object"&&t.props!==null?t.props:{},raw:n.rawContent}}catch{}return null}var $l=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function vr(n){let{onSubmit:t,onDismiss:r,title:e="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:c=$l}=n,v=document.createElement("div");v.className="tvw-feedback-container tvw-feedback-csat",v.setAttribute("role","dialog"),v.setAttribute("aria-label","Customer satisfaction feedback");let p=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let C=document.createElement("h3");C.className="tvw-feedback-title",C.textContent=e,w.appendChild(C);let y=document.createElement("p");y.className="tvw-feedback-subtitle",y.textContent=o,w.appendChild(y),m.appendChild(w);let A=document.createElement("div");A.className="tvw-feedback-rating tvw-feedback-rating-csat",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let L=1;L<=5;L++){let F=document.createElement("button");F.type="button",F.className="tvw-feedback-rating-btn tvw-feedback-star-btn",F.setAttribute("role","radio"),F.setAttribute("aria-checked","false"),F.setAttribute("aria-label",`${L} star${L>1?"s":""}: ${c[L-1]}`),F.title=c[L-1],F.dataset.rating=String(L),F.innerHTML=`
17
- <svg class="tvw-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
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=s=>{var U,M,O,S,N,Q,K,re,J,pe,Le,Ye;let a=(U=s.launcher)!=null?U:{},i=jt(s),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=(O=a.subtitle)!=null?O:"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 fe=(S=a.agentIconSize)!=null?S:"40px";if(p.style.height=fe,p.style.width=fe,p.innerHTML="",a.agentIconName){let ee=parseFloat(fe)||24,Y=ue(a.agentIconName,ee*.6,"var(--persona-text-inverse, #ffffff)",2);Y?(p.appendChild(Y),p.style.display=""):(p.textContent=(N=a.agentIconText)!=null?N:"\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 fe=(K=a.agentIconSize)!=null?K:"40px";y.style.height=fe,y.style.width=fe,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 fe=(re=a.callToActionIconSize)!=null?re:"32px";m.style.height=fe,m.style.width=fe,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(fe)||24,V=Math.max(Y-ee,8),j=ue(a.callToActionIconName,V,"currentColor",2);j?m.appendChild(j):m.textContent=(J=a.callToActionIconText)!=null?J:"\u2197"}else m.textContent=(pe=a.callToActionIconText)!=null?pe:"\u2197"}let C=a.position&&dn[a.position]?dn[a.position]:dn["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=(Le=a.border)!=null?Le:x,t.style.boxShadow=(Ye=a.shadow)!=null?Ye:k,i){let fe=Cr(s);t.style.width=`calc(${fe.collapsedWidth} - 16px)`,t.style.minWidth="40px",t.style.maxWidth=`calc(${fe.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=""},o=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:o}};var Ln=e=>{var re,J,pe,Le,Ye,fe,ee,Y,V,j,ce,he,mt,lt,ft,It,le,se,q,ne,oe,Ee,Ke,te,X,He,Ve,et,Vt,Dt,ie,Ue;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.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 o=(re=n==null?void 0:n.launcher)!=null?re:{},s=(J=o.headerIconSize)!=null?J:"48px",a=(pe=o.closeButtonSize)!=null?pe:"32px",i=(Le=o.closeButtonPlacement)!=null?Le:"inline",d=(Ye=o.headerIconHidden)!=null?Ye:!1,c=o.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=s,g.style.width=s,!d)if(c){let Te=parseFloat(s)||24,tt=ue(c,Te*.6,"var(--persona-text-inverse, #ffffff)",1);tt?g.replaceChildren(tt):g.textContent=(ee=(fe=n==null?void 0:n.launcher)==null?void 0:fe.agentIconText)!=null?ee:"\u{1F4AC}"}else if((Y=n==null?void 0:n.launcher)!=null&&Y.iconUrl){let Te=f("img");Te.src=n.launcher.iconUrl,Te.alt="",Te.className="persona-rounded-xl persona-object-cover",Te.style.height=s,Te.style.width=s,g.replaceChildren(Te)}else g.textContent=(j=(V=n==null?void 0:n.launcher)==null?void 0:V.agentIconText)!=null?j:"\u{1F4AC}";let p=f("div","persona-flex persona-flex-col"),y=f("span","persona-text-base persona-font-semibold");y.textContent=(he=(ce=n==null?void 0:n.launcher)==null?void 0:ce.title)!=null?he:"Chat Assistant";let m=f("span","persona-text-xs persona-text-persona-muted");m.textContent=(lt=(mt=n==null?void 0:n.launcher)==null?void 0:mt.subtitle)!=null?lt:"Here to help you get answers fast",p.append(y,m),d?r.append(p):r.append(g,p);let C=(ft=o.clearChat)!=null?ft:{},v=(It=C.enabled)!=null?It:!0,E=(le=C.placement)!=null?le:"inline",x=null,k=null;if(v){let Te=(se=C.size)!=null?se:"32px",tt=(q=C.iconName)!=null?q:"refresh-cw",_e=(ne=C.iconColor)!=null?ne:"",Xe=(oe=C.backgroundColor)!=null?oe:"",Wt=(Ee=C.borderWidth)!=null?Ee:"",Rt=(Ke=C.borderColor)!=null?Ke:"",Mt=(te=C.borderRadius)!=null?te:"",H=(X=C.paddingX)!=null?X:"",Z=(He=C.paddingY)!=null?He:"",z=(Ve=C.tooltipText)!=null?Ve:"Clear chat",Pe=(et=C.showTooltip)!=null?et:!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=Te,x.style.width=Te,x.type="button",x.setAttribute("aria-label",z);let Ce=ue(tt,"20px",_e||"",1);if(Ce&&x.appendChild(Ce),_e&&(x.style.color=_e,x.classList.remove("persona-text-persona-muted")),Xe&&(x.style.backgroundColor=Xe,x.classList.remove("hover:persona-bg-gray-100")),Wt||Rt){let Ie=Wt||"0px",Be=Rt||"transparent";x.style.border=`${Ie} solid ${Be}`,x.classList.remove("persona-border-none")}if(Mt&&(x.style.borderRadius=Mt,x.classList.remove("persona-rounded-full")),H?(x.style.paddingLeft=H,x.style.paddingRight=H):(x.style.paddingLeft="",x.style.paddingRight=""),Z?(x.style.paddingTop=Z,x.style.paddingBottom=Z):(x.style.paddingTop="",x.style.paddingBottom=""),k.appendChild(x),Pe&&z&&x&&k){let Ie=null,Be=()=>{if(Ie||!x)return;let ye=x.ownerDocument,be=ye.body;if(!be)return;Ie=bn(ye,"div","persona-clear-chat-tooltip"),Ie.textContent=z;let $e=bn(ye,"div");$e.className="persona-clear-chat-tooltip-arrow",Ie.appendChild($e);let de=x.getBoundingClientRect();Ie.style.position="fixed",Ie.style.left=`${de.left+de.width/2}px`,Ie.style.top=`${de.top-8}px`,Ie.style.transform="translate(-50%, -100%)",be.appendChild(Ie)},ut=()=>{Ie&&Ie.parentNode&&(Ie.parentNode.removeChild(Ie),Ie=null)};k.addEventListener("mouseenter",Be),k.addEventListener("mouseleave",ut),x.addEventListener("focus",Be),x.addEventListener("blur",ut),k._cleanupTooltip=()=>{ut(),k&&(k.removeEventListener("mouseenter",Be),k.removeEventListener("mouseleave",ut)),x&&(x.removeEventListener("focus",Be),x.removeEventListener("blur",ut))}}E==="inline"&&r.appendChild(k)}let U=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 O=(Vt=o.closeButtonTooltipText)!=null?Vt:"Close chat",S=(Dt=o.closeButtonShowTooltip)!=null?Dt:!0;M.setAttribute("aria-label",O),M.style.display=t?"":"none";let N=(ie=o.closeButtonIconName)!=null?ie:"x",Q=(Ue=o.closeButtonIconText)!=null?Ue:"\xD7",K=ue(N,"20px",o.closeButtonColor||"",1);if(K?M.appendChild(K):M.textContent=Q,o.closeButtonColor?(M.style.color=o.closeButtonColor,M.classList.remove("persona-text-persona-muted")):(M.style.color="",M.classList.add("persona-text-persona-muted")),o.closeButtonBackgroundColor?(M.style.backgroundColor=o.closeButtonBackgroundColor,M.classList.remove("hover:persona-bg-gray-100")):(M.style.backgroundColor="",M.classList.add("hover:persona-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let Te=o.closeButtonBorderWidth||"0px",tt=o.closeButtonBorderColor||"transparent";M.style.border=`${Te} solid ${tt}`,M.classList.remove("persona-border-none")}else M.style.border="",M.classList.add("persona-border-none");if(o.closeButtonBorderRadius?(M.style.borderRadius=o.closeButtonBorderRadius,M.classList.remove("persona-rounded-full")):(M.style.borderRadius="",M.classList.add("persona-rounded-full")),o.closeButtonPaddingX?(M.style.paddingLeft=o.closeButtonPaddingX,M.style.paddingRight=o.closeButtonPaddingX):(M.style.paddingLeft="",M.style.paddingRight=""),o.closeButtonPaddingY?(M.style.paddingTop=o.closeButtonPaddingY,M.style.paddingBottom=o.closeButtonPaddingY):(M.style.paddingTop="",M.style.paddingBottom=""),U.appendChild(M),S&&O){let Te=null,tt=()=>{if(Te)return;let Xe=M.ownerDocument,Wt=Xe.body;if(!Wt)return;Te=bn(Xe,"div","persona-clear-chat-tooltip"),Te.textContent=O;let Rt=bn(Xe,"div");Rt.className="persona-clear-chat-tooltip-arrow",Te.appendChild(Rt);let Mt=M.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${Mt.left+Mt.width/2}px`,Te.style.top=`${Mt.top-8}px`,Te.style.transform="translate(-50%, -100%)",Wt.appendChild(Te)},_e=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};U.addEventListener("mouseenter",tt),U.addEventListener("mouseleave",_e),M.addEventListener("focus",tt),M.addEventListener("blur",_e),U._cleanupTooltip=()=>{_e(),U.removeEventListener("mouseenter",tt),U.removeEventListener("mouseleave",_e),M.removeEventListener("focus",tt),M.removeEventListener("blur",_e)}}return i!=="top-right"&&r.appendChild(U),{header:r,iconHolder:g,headerTitle:y,headerSubtitle:m,closeButton:M,closeButtonWrapper:U,clearChatButton:x,clearChatButtonWrapper:k}},nr=(e,n,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(n.header),o==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var Mo=e=>Ln({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat});function md(e,n,t){var r,o;if(n!=null&&n.length)for(let s 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",(o=(r=s.ariaLabel)!=null?r:s.label)!=null?o:s.id),s.icon){let i=ue(s.icon,14,"currentColor",2);i&&a.appendChild(i)}else s.label&&(a.textContent=s.label);a.addEventListener("click",()=>t==null?void 0:t(s.id)),e.appendChild(a)}}var ko=e=>{var x,k,U,M,O;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=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"),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");c.textContent=(k=a.title)!=null?k:"Chat Assistant",d.appendChild(c),md(d,o==null?void 0:o.trailingActions,(U=o==null?void 0:o.onAction)!=null?U:s),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=(O=a.closeButtonIconName)!=null?O:"x",C=ue(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}},zs={default:Mo,minimal:ko},Lo=e=>{var n;return(n=zs[e])!=null?n:zs.default},wr=(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",s=Lo(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&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var fd=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'}},Sr=e=>{var le,se,q,ne,oe,Ee,Ke,te,X,He,Ve,et,Vt,Dt,ie,Ue,Te,tt,_e,Xe,Wt,Rt,Mt,H,Z,z,Pe,Ce,Ie,Be,ut;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"),r=f("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),o=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");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let s=f("textarea");s.setAttribute("data-persona-composer-input",""),s.placeholder=(se=(le=n==null?void 0:n.copy)==null?void 0:le.inputPlaceholder)!=null?se:"Type your message\u2026",s.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",s.rows=1;let a=(ne=(q=n==null?void 0:n.theme)==null?void 0:q.inputFontFamily)!=null?ne:"sans-serif",i=(Ee=(oe=n==null?void 0:n.theme)==null?void 0:oe.inputFontWeight)!=null?Ee:"400";s.style.fontFamily=fd(a),s.style.fontWeight=i;let g=3*20;s.style.maxHeight=`${g}px`,s.style.overflowY="auto";let p=()=>{s.style.height="auto";let ye=Math.min(s.scrollHeight,g);s.style.height=`${ye}px`};s.addEventListener("input",p),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let y=(Ke=n==null?void 0:n.sendButton)!=null?Ke:{},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=(Ve=y.showTooltip)!=null?Ve:!1,k=(et=y.size)!=null?et:"40px",U=y.backgroundColor,M=y.textColor,O=f("div","persona-send-button-wrapper"),S=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(S.type="submit",S.setAttribute("data-persona-composer-submit",""),m){if(S.style.width=k,S.style.height=k,S.style.minWidth=k,S.style.minHeight=k,S.style.fontSize="18px",S.style.lineHeight="1",S.innerHTML="",v){let ye=parseFloat(k)||24,be=M&&typeof M=="string"&&M.trim()?M.trim():"currentColor",$e=ue(v,ye,be,2);$e?(S.appendChild($e),S.style.color=be):(S.textContent=C,M?S.style.color=M:S.classList.add("persona-text-white"))}else S.textContent=C,M?S.style.color=M:S.classList.add("persona-text-white");U?S.style.backgroundColor=U:S.classList.add("persona-bg-persona-primary")}else S.textContent=(Dt=(Vt=n==null?void 0:n.copy)==null?void 0:Vt.sendButtonLabel)!=null?Dt:"Send",M?S.style.color=M:S.classList.add("persona-text-white");if(y.borderWidth&&(S.style.borderWidth=y.borderWidth,S.style.borderStyle="solid"),y.borderColor&&(S.style.borderColor=y.borderColor),y.paddingX?(S.style.paddingLeft=y.paddingX,S.style.paddingRight=y.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),y.paddingY?(S.style.paddingTop=y.paddingY,S.style.paddingBottom=y.paddingY):(S.style.paddingTop="",S.style.paddingBottom=""),x&&E){let ye=f("div","persona-send-button-tooltip");ye.textContent=E,O.appendChild(ye)}O.appendChild(S);let N=(ie=n==null?void 0:n.voiceRecognition)!=null?ie:{},Q=N.enabled===!0,K=null,re=null,J=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),pe=((Ue=N.provider)==null?void 0:Ue.type)==="runtype";if(Q&&(J||pe)){re=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 ye=(Te=N.iconName)!=null?Te:"mic",be=(tt=N.iconSize)!=null?tt:k,$e=parseFloat(be)||24,de=(_e=N.backgroundColor)!=null?_e:U,bt=(Xe=N.iconColor)!=null?Xe:M;K.style.width=be,K.style.height=be,K.style.minWidth=be,K.style.minHeight=be,K.style.fontSize="18px",K.style.lineHeight="1";let Gt=bt||"currentColor",pn=ue(ye,$e,Gt,1.5);pn?(K.appendChild(pn),K.style.color=Gt):(K.textContent="\u{1F3A4}",K.style.color=Gt),de?K.style.backgroundColor=de:K.classList.add("persona-bg-persona-primary"),bt?K.style.color=bt:!bt&&!M&&K.classList.add("persona-text-white"),N.borderWidth&&(K.style.borderWidth=N.borderWidth,K.style.borderStyle="solid"),N.borderColor&&(K.style.borderColor=N.borderColor),N.paddingX&&(K.style.paddingLeft=N.paddingX,K.style.paddingRight=N.paddingX),N.paddingY&&(K.style.paddingTop=N.paddingY,K.style.paddingBottom=N.paddingY),re.appendChild(K);let un=(Wt=N.tooltipText)!=null?Wt:"Start voice recognition";if(((Rt=N.showTooltip)!=null?Rt:!1)&&un){let Wn=f("div","persona-send-button-tooltip");Wn.textContent=un,re.appendChild(Wn)}}let Ye=(Mt=n==null?void 0:n.attachments)!=null?Mt:{},fe=Ye.enabled===!0,ee=null,Y=null,V=null,j=null;if(fe){j=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),j.style.display="none",V=f("input"),V.type="file",V.accept=((H=Ye.allowedTypes)!=null?H:kn).join(","),V.multiple=((Z=Ye.maxFiles)!=null?Z:4)>1,V.style.display="none",V.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=Ye.buttonTooltipText)!=null?z:"Attach file");let ye=(Pe=Ye.buttonIconName)!=null?Pe:"paperclip",be=k,$e=parseFloat(be)||40,de=Math.round($e*.6);ee.style.width=be,ee.style.height=be,ee.style.minWidth=be,ee.style.minHeight=be,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=ue(ye,de,"currentColor",1.5);bt?ee.appendChild(bt):ee.textContent="\u{1F4CE}",ee.addEventListener("click",un=>{un.preventDefault(),V==null||V.click()}),Y.appendChild(ee);let Gt=(Ce=Ye.buttonTooltipText)!=null?Ce:"Attach file",pn=f("div","persona-send-button-tooltip");pn.textContent=Gt,Y.appendChild(pn)}o.addEventListener("click",ye=>{ye.target!==S&&ye.target!==O&&ye.target!==K&&ye.target!==re&&ye.target!==ee&&ye.target!==Y&&s.focus()}),j&&(j.style.gap="8px",o.append(j)),V&&o.append(V),o.append(s);let ce=f("div","persona-flex persona-items-center persona-justify-between persona-w-full"),he=f("div","persona-flex persona-items-center persona-gap-2");Y&&he.append(Y);let mt=f("div","persona-flex persona-items-center persona-gap-1");re&&mt.append(re),mt.append(O),ce.append(he,mt),o.append(ce);let lt=f("div","persona-mt-2 persona-text-right persona-text-xs persona-text-persona-muted");lt.setAttribute("data-persona-composer-status","");let ft=(Ie=n==null?void 0:n.statusIndicator)!=null?Ie:{},It=(Be=ft.visible)!=null?Be:!0;return lt.style.display=It?"":"none",lt.textContent=(ut=ft.idleText)!=null?ut:"Online",t.append(r,o,lt),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:S,sendButtonWrapper:O,micButton:K,micButtonWrapper:re,statusText:lt,attachmentButton:ee,attachmentButtonWrapper:Y,attachmentInput:V,attachmentPreviewsContainer:j,actionsRow:ce,leftActions:he,rightActions:mt}};var Dl=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(jt(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:{},o=r.position&&dn[r.position]?dn[r.position]:dn["bottom-right"],s=f("div",`persona-widget-wrapper persona-fixed ${o} 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,s.appendChild(a),{wrapper:s,panel:a}},_l=(e,n=!0)=>{var v,E,x,k,U,M,O,S,N;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"),r=(v=e==null?void 0:e.layout)==null?void 0:v.header,o=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,s=r?wr(e,r,{showClose:n}):Ln({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";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=(U=e==null?void 0:e.copy)==null?void 0:U.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=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;p&&(g.style.maxWidth=p,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((S=e==null?void 0:e.copy)==null?void 0:S.showWelcomeCard)!==!1?a.append(i,g):(a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3"),a.append(g));let m=Sr({config:e}),C=((N=e==null?void 0:e.layout)==null?void 0:N.showFooter)!==!1;return o?nr(t,s,e):(s.header.style.display="none",nr(t,s,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:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.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=320,yd=320,bd=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),xd=(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 o=0,s=!1,a=()=>{s||(s=!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=`${hd}px`,c.style.maxHeight=`${yd}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;o+=1,c.addEventListener("error",()=>{g||(g=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{g=!0}),c.src=i.image,r.appendChild(c)}),o===0?(a(),null):r}catch{return t==null||t(),null}},rr=()=>{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 o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(o),e},Po=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:rr};if(n){let o=n(r);if(o!==null)return o}return rr()},vd=(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 o=f("img");o.src=r,o.alt=n==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}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},jl=(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},Cd=(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},Io=(e,n,t)=>{var m,C,v,E,x,k;let r=(m=n.showCopy)!=null?m:!0,o=(C=n.showUpvote)!=null?C:!0,s=(v=n.showDownvote)!=null?v:!0;if(!r&&!o&&!s){let U=f("div");return U.style.display="none",U.id=`actions-${e.id}`,U.setAttribute("data-actions-for",e.id),U}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=(U,M,O)=>{let S=document.createElement("button");S.className="persona-message-action-btn",S.setAttribute("aria-label",M),S.setAttribute("title",M),S.setAttribute("data-action",O);let N=ue(U,14,"currentColor",2);return N&&S.appendChild(N),S};return r&&p.appendChild(y("copy","Copy message","copy")),o&&p.appendChild(y("thumbs-up","Upvote","upvote")),s&&p.appendChild(y("thumbs-down","Downvote","downvote")),p},Ar=(e,n,t,r,o,s)=>{var re,J,pe,Le,Ye,fe,ee;let a=t!=null?t:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,g=(J=d==null?void 0:d.show)!=null?J:!1,p=(pe=c==null?void 0:c.show)!=null?pe:!1,y=(Le=d==null?void 0:d.position)!=null?Le:"left",m=(Ye=c==null?void 0:c.position)!=null?Ye:"below",C=Cd(e.role,i),v=f("div",C.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),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=bd(e),x=(ee=(fe=e.content)==null?void 0:fe.trim())!=null?ee:"",U=E.length>0&&x===Bs,M=document.createElement("div");M.classList.add("persona-message-content");let O=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),S=null;if(U?(S=document.createElement("div"),S.innerHTML=O,S.style.display="none",M.appendChild(S)):M.innerHTML=O,p&&m==="inline"&&e.createdAt){let Y=jl(e,c);Y.classList.add("persona-ml-2","persona-inline"),M.appendChild(Y)}if(E.length>0){let Y=xd(E,!U&&!!x,()=>{U&&S&&(S.style.display="")});Y?v.appendChild(Y):U&&S&&(S.style.display="")}if(v.appendChild(M),p&&m==="below"&&e.createdAt){let Y=jl(e,c);Y.classList.add("persona-mt-1"),v.appendChild(Y)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let Y=Po("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.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=Io(e,r,o);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=vd(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},Vl=(e,n,t,r,o,s)=>{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}):Ar(e,n,t,r,o,s)};var Er=new Set,ql=(e,n)=>{let t=Er.has(e),r=n.querySelector('button[data-expand-header="true"]'),o=n.querySelector(".persona-border-t");if(!r||!o)return;r.setAttribute("aria-expanded",t?"true":"false");let s=r.querySelector(".persona-ml-auto"),a=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(a){a.innerHTML="";let d=ue(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}o.style.display=t?"":"none"},Wo=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=Er.has(e.id),o=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");o.type="button",o.setAttribute("aria-expanded",r?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=f("div","persona-flex persona-flex-col persona-text-left"),a=f("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",s.appendChild(a);let i=f("span","persona-text-xs persona-text-persona-primary");i.textContent=gl(n),s.appendChild(i),n.status==="complete"?a.style.display="none":a.style.display="";let d=f("div","persona-flex persona-items-center"),g=ue(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),o.append(s,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),(()=>{o.setAttribute("aria-expanded",r?"true":"false"),d.innerHTML="";let x=ue(r?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=r?"Hide":"Show",y.style.display=r?"":"none"})(),t.append(o,y),t};var Tr=new Set,Ul=(e,n,t)=>{var c;let r=Tr.has(e),o=(c=t==null?void 0:t.toolCall)!=null?c:{},s=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t");if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let i=s.querySelector(".persona-ml-auto"),d=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let g=o.toggleTextColor||o.headerTextColor||"currentColor",p=ue(r?"chevron-up":"chevron-down",16,g,2);p?d.appendChild(p):d.textContent=r?"Hide":"Show"}a.style.display=r?"":"none"},Ro=(e,n)=>{var v;let t=e.toolCall,r=(v=n==null?void 0:n.toolCall)!=null?v:{},o=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(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),!t)return o;let s=Tr.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",s?"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=ml(t),i.appendChild(d);let c=f("div","persona-flex persona-items-center"),g=r.toggleTextColor||r.headerTextColor||"currentColor",p=ue(s?"chevron-up":"chevron-down",16,g,2);p?c.appendChild(p):c.textContent=s?"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=s?"":"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=Gr(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=Gr(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",s?"true":"false"),c.innerHTML="";let E=r.toggleTextColor||r.headerTextColor||"currentColor",x=ue(s?"chevron-up":"chevron-down",16,E,2);x?c.appendChild(x):c.textContent=s?"Hide":"Show",m.style.display=s?"":"none"})(),o.append(a,m),o};var Ho=(e,n)=>{var v,E,x,k,U,M,O,S,N,Q,K,re;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,o=(t==null?void 0:t.status)==="pending",s=f("div",["persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(v=r==null?void 0:r.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(E=r==null?void 0:r.borderColor)!=null?E:"var(--persona-approval-border, #fef08a)",!t)return s;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=ue(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),!o){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=Gr(t.parameters),p.appendChild(J)}if(o){let J=f("div","persona-flex persona-gap-2 persona-mt-2");J.setAttribute("data-approval-buttons","true");let pe=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");pe.type="button",pe.style.backgroundColor=(U=r==null?void 0:r.approveButtonColor)!=null?U:"var(--persona-approval-approve-bg, #22c55e)",pe.style.color=(M=r==null?void 0:r.approveButtonTextColor)!=null?M:"#ffffff",pe.setAttribute("data-approval-action","approve");let Le=ue("shield-check",14,(O=r==null?void 0:r.approveButtonTextColor)!=null?O:"#ffffff",2);Le&&(Le.style.marginRight="4px",pe.appendChild(Le));let Ye=document.createTextNode((S=r==null?void 0:r.approveLabel)!=null?S:"Approve");pe.appendChild(Ye);let fe=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");fe.type="button",fe.style.backgroundColor=(N=r==null?void 0:r.denyButtonColor)!=null?N:"transparent",fe.style.color=(Q=r==null?void 0:r.denyButtonTextColor)!=null?Q:"var(--persona-feedback-error, #dc2626)",fe.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,fe.setAttribute("data-approval-action","deny");let ee=ue("shield-x",14,(K=r==null?void 0:r.denyButtonTextColor)!=null?K:"var(--persona-feedback-error, #dc2626)",2);ee&&(ee.style.marginRight="4px",fe.appendChild(ee));let Y=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");fe.appendChild(Y),J.append(pe,fe),p.appendChild(J)}return a.append(i,p),s.appendChild(a),s};var zl=e=>{let n=[];return{buttons:n,render:(r,o,s,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:o?o.getMessages():[]).some(m=>m.role==="user"))return;let g=document.createDocumentFragment(),p=o?o.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",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(m))}),g.appendChild(C),n.push(C)}),e.appendChild(g)}}};var ns=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 rs=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 o=r.result;o.objectStoreNames.contains(this.storeName)||o.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 o of n)r.put(o)}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 s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{n(s.result)},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{n()},s.onerror=()=>{t(s.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 o of n)r.put(o)}catch{}}};function Mr(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var wd={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)"}},Sd={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ad=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ed=100;function Td(e,n){let t={...wd,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return Sd}function Md(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function kd(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0"),s=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${o}.${s}`}function Ld(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let o=r.split("."),s=t;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Pd(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 Id(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 Wd(e,n,t){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=n.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let i=s.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:o});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 Bo(e,n,t,r,o,s,a,i){var y;let d=o.has(e.id),c=f("div","persona-border-b persona-border-persona-divider persona-text-xs");Mr(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:()=>s(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(p()),c;function p(){var pe,Le;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=ue(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=(pe=r.timestampFormat)!=null?pe:"relative";x.textContent=k==="relative"?Md(e.timestamp,t):kd(e.timestamp);let U=null;r.showSequenceNumbers!==!1&&(U=f("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),U.textContent=String(n+1));let M=Td(e.type,r.badgeColors),O=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");O.style.backgroundColor=M.bg,O.style.color=M.text,O.style.borderColor=M.text+"50",O.textContent=e.type;let S=(Le=r.descriptionFields)!=null?Le:Ad,N=Ld(e.payload,S),Q=null;N&&(Q=f("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Q.textContent=N);let K=f("div","persona-flex-1 persona-min-w-0"),re=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=ue("clipboard","12px","currentColor",1.5);return J&&re.appendChild(J),re.addEventListener("click",async Ye=>{Ye.stopPropagation(),await Pd(Id(e)),re.innerHTML="";let fe=ue("check","12px","currentColor",1.5);fe&&re.appendChild(fe),setTimeout(()=>{re.innerHTML="";let ee=ue("clipboard","12px","currentColor",1.5);ee&&re.appendChild(ee)},1500)}),C.appendChild(v),C.appendChild(x),U&&C.appendChild(U),C.appendChild(O),Q&&C.appendChild(Q),C.appendChild(K),C.appendChild(re),m.appendChild(C),d&&m.appendChild(Wd(e,a,i)),m}}function Jl(e){var c,g;let{buffer:n,getFullHistory:t,onClose:r,config:o,plugins:s=[]}=e,a=(g=(c=o==null?void 0:o.features)==null?void 0:c.eventStream)!=null?g:{},i=s.find(p=>p.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&o){let p=i.renderEventStreamView({config:o,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");Mr(y,p==null?void 0:p.panel);let m=[],C="",v="",E=null,x=[],k={},U=0,M=!1,O=0,S=0,N=!1,Q=null,K=!1,re=0,J=new Set,pe=new Map,Le="",Ye="",fe=null,ee,Y,V,j,ce;function he(){let Z=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");Mr(z,p==null?void 0:p.headerBar);let Pe=f("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Pe.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 Ce=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 Ie=f("option","");Ie.value="",Ie.textContent="All events",Y.appendChild(Ie),V=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"),V.type="button",V.title="Copy All";let ut=ue("clipboard-copy","12px","currentColor",1.5);ut&&V.appendChild(ut);let ye=f("span","persona-text-xs");ye.textContent="Copy All",V.appendChild(ye),z.appendChild(Pe),z.appendChild(ee),z.appendChild(Ce),z.appendChild(Y),z.appendChild(V);let be=f("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Mr(be,p==null?void 0:p.searchBar);let $e=ue("search","14px","var(--persona-muted, #9ca3af)",1.5),de=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");$e&&de.appendChild($e),j=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"),Mr(j,p==null?void 0:p.searchInput),j.type="text",j.placeholder="Search event payloads...",ce=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"),ce.type="button",ce.style.display="none";let bt=ue("x","12px","currentColor",2);return bt&&ce.appendChild(bt),be.appendChild(de),be.appendChild(j),be.appendChild(ce),Z.appendChild(z),Z.appendChild(be),Z}let mt,lt=s.find(Z=>Z.renderEventStreamToolbar);if(lt!=null&&lt.renderEventStreamToolbar&&o){let Z=lt.renderEventStreamToolbar({config:o,defaultRenderer:()=>he(),eventCount:n.getSize(),filteredCount:0,onFilterChange:z=>{C=z,X(),et()},onSearchChange:z=>{v=z,X(),et()}});mt=Z!=null?Z:he()}else mt=he();let ft=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");ft.style.display="none";let It=f("div","persona-flex-1 persona-min-h-0 persona-relative"),le=f("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");le.style.height="100%";let se=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");Mr(se,p==null?void 0:p.scrollIndicator),se.style.display="none";let q=ue("arrow-down","12px","currentColor",2);q&&se.appendChild(q);let ne=f("span","");se.appendChild(ne);let oe=f("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");oe.style.display="none",It.appendChild(le),It.appendChild(oe),It.appendChild(se),y.setAttribute("tabindex","0"),y.appendChild(mt),y.appendChild(ft),y.appendChild(It);function Ee(){let Z=n.getAll(),z={};for(let ye of Z)z[ye.type]=(z[ye.type]||0)+1;let Pe=Object.keys(z).sort(),Ce=Pe.length!==x.length||!Pe.every((ye,be)=>ye===x[be]),Ie=!Ce&&Pe.some(ye=>z[ye]!==k[ye]),Be=Z.length!==Object.values(k).reduce((ye,be)=>ye+be,0);if(!Ce&&!Ie&&!Be||(x=Pe,k=z,!Y))return;let ut=Y.value;if(Y.options[0].textContent="All events",Ce){for(;Y.options.length>1;)Y.remove(1);for(let ye of Pe){let be=f("option","");be.value=ye,be.textContent=`${ye} (${z[ye]||0})`,Y.appendChild(be)}ut&&Pe.includes(ut)?Y.value=ut:ut&&(Y.value="",C="")}else for(let ye=1;ye<Y.options.length;ye++){let be=Y.options[ye];be.textContent=`${be.value} (${z[be.value]||0})`}}function Ke(){let Z=n.getAll();if(C&&(Z=Z.filter(z=>z.type===C)),v){let z=v.toLowerCase();Z=Z.filter(Pe=>Pe.type.toLowerCase().includes(z)||Pe.payload.toLowerCase().includes(z))}return Z}function te(){return C!==""||v!==""}function X(){U=0,O=0,M=!1,se.style.display="none"}function He(Z){J.has(Z)?J.delete(Z):J.add(Z),fe=Z;let z=le.scrollTop,Pe=M;K=!0,M=!0,et(),le.scrollTop=z,M=Pe,K=!1}function Ve(){return le.scrollHeight-le.scrollTop-le.clientHeight<=50}function et(){S=Date.now(),N=!1,Ee();let Z=n.getEvictedCount();Z>0?(ft.textContent=`${Z.toLocaleString()} older events truncated`,ft.style.display=""):ft.style.display="none",m=Ke();let z=m.length,Pe=n.getSize()>0;ee&&(ee.textContent=String(n.getSize())),z===0&&Pe&&te()?(oe.textContent=v?`No events matching '${v}'`:"No events matching filter",oe.style.display="",le.style.display="none"):(oe.style.display="none",le.style.display=""),V&&(V.title=te()?`Copy Filtered (${z})`:"Copy All"),M&&z>U&&(O+=z-U,ne.textContent=`${O} new event${O===1?"":"s"}`,se.style.display=""),U=z;let Ce=n.getAll(),Ie=Ce.length>0?Ce[0].timestamp:0,Be=new Set(m.map(be=>be.id));for(let be of J)Be.has(be)||J.delete(be);let ut=C!==Le||v!==Ye,ye=pe.size===0&&m.length>0;if(ut||ye||m.length===0){le.innerHTML="",pe.clear();let be=document.createDocumentFragment();for(let $e=0;$e<m.length;$e++){let de=Bo(m[$e],$e,Ie,a,J,He,s,o);pe.set(m[$e].id,de),be.appendChild(de)}le.appendChild(be),Le=C,Ye=v,fe=null}else{if(fe!==null){let $e=pe.get(fe);if($e&&$e.parentNode===le){let de=m.findIndex(bt=>bt.id===fe);if(de>=0){let bt=Bo(m[de],de,Ie,a,J,He,s,o);le.insertBefore(bt,$e),$e.remove(),pe.set(fe,bt)}}fe=null}let be=new Set(m.map($e=>$e.id));for(let[$e,de]of pe)be.has($e)||(de.remove(),pe.delete($e));for(let $e=0;$e<m.length;$e++){let de=m[$e];if(!pe.has(de.id)){let bt=Bo(de,$e,Ie,a,J,He,s,o);pe.set(de.id,bt),le.appendChild(bt)}}}M||(le.scrollTop=le.scrollHeight)}function Vt(){if(Date.now()-S>=Ed){Q!==null&&(cancelAnimationFrame(Q),Q=null),et();return}N||(N=!0,Q=requestAnimationFrame(()=>{Q=null,et()}))}let Dt=(Z,z)=>{if(!V)return;V.innerHTML="";let Pe=ue(Z,"12px","currentColor",1.5);Pe&&V.appendChild(Pe);let Ce=f("span","persona-text-xs");Ce.textContent="Copy All",V.appendChild(Ce),setTimeout(()=>{V.innerHTML="";let Ie=ue("clipboard-copy","12px","currentColor",1.5);Ie&&V.appendChild(Ie);let Be=f("span","persona-text-xs");Be.textContent="Copy All",V.appendChild(Be),V.disabled=!1},z)},ie=async()=>{if(V){V.disabled=!0;try{let Z;te()?Z=m:t?(Z=await t(),Z.length===0&&(Z=n.getAll())):Z=n.getAll();let z=Z.map(Pe=>{try{return JSON.parse(Pe.payload)}catch{return Pe.payload}});await navigator.clipboard.writeText(JSON.stringify(z,null,2)),Dt("check",1500)}catch{Dt("x",1500)}}},Ue=()=>{Y&&(C=Y.value,X(),et())},Te=()=>{!j||!ce||(ce.style.display=j.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{v=j.value,X(),et()},150))},tt=()=>{!j||!ce||(j.value="",v="",ce.style.display="none",E&&clearTimeout(E),X(),et())},_e=()=>{if(K)return;let Z=le.scrollTop,z=Z>re;re=Z,Ve()&&z?(M=!1,O=0,se.style.display="none"):Ve()||(M=!0)},Xe=Z=>{Z.deltaY<0&&(M=!0)},Wt=()=>{le.scrollTop=le.scrollHeight,M=!1,O=0,se.style.display="none"},Rt=Z=>{let z=Z.target;if(!z||z.closest("button"))return;let Pe=z.closest("[data-event-id]");if(!Pe)return;let Ce=Pe.getAttribute("data-event-id");Ce&&He(Ce)},Mt=Z=>{if((Z.metaKey||Z.ctrlKey)&&Z.key==="f"){Z.preventDefault(),j==null||j.focus(),j==null||j.select();return}Z.key==="Escape"&&(j&&document.activeElement===j?(tt(),j.blur(),y.focus()):r&&r())};V&&V.addEventListener("click",ie),Y&&Y.addEventListener("change",Ue),j&&j.addEventListener("input",Te),ce&&ce.addEventListener("click",tt),le.addEventListener("scroll",_e),le.addEventListener("wheel",Xe,{passive:!0}),le.addEventListener("click",Rt),se.addEventListener("click",Wt),y.addEventListener("keydown",Mt);function H(){E&&clearTimeout(E),Q!==null&&(cancelAnimationFrame(Q),Q=null),N=!1,pe.clear(),V&&V.removeEventListener("click",ie),Y&&Y.removeEventListener("change",Ue),j&&j.removeEventListener("input",Te),ce&&ce.removeEventListener("click",tt),le.removeEventListener("scroll",_e),le.removeEventListener("wheel",Xe),le.removeEventListener("click",Rt),se.removeEventListener("click",Wt),y.removeEventListener("keydown",Mt)}return{element:y,update:Vt,destroy:H}}}var Kl=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",s=(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 ${s.toLowerCase()}...`,g.appendChild(y)}else g.textContent=s;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 $o=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)})}},Pn=new $o;Pn.register("PersonaArtifactCard",Kl);function Rd(e){var o;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((o=e.props)!=null?o:{},null,2),n.appendChild(t),n.appendChild(r),n}function ss(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 o=ue(e,16,"currentColor",2);return o&&r.appendChild(o),r}function os(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 o=ue(e,16,"currentColor",2);return o&&r.appendChild(o),r}function Yl(e){let n=f("button","persona-artifact-doc-copy-btn");n.type="button",n.setAttribute("aria-label","Copy"),n.title="Copy";let t=ue("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 Hd(){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=ue("chevron-down",14,"currentColor",2);return n&&e.appendChild(n),e}function Xl(e,n){var ft,It,le,se;let t=(It=(ft=e.features)==null?void 0:ft.artifacts)==null?void 0:It.layout,o=((le=t==null?void 0:t.toolbarPreset)!=null?le:"default")==="document",s=(se=t==null?void 0:t.panePadding)==null?void 0:se.trim(),a=e.markdown?Xn(e.markdown):null,i=q=>a?a(q):yr(q),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 q;c(),(q=n.onDismiss)==null||q.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");o&&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");o&&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 q;c(),(q=n.onDismiss)==null||q.call(n)});let C="rendered",v=f("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=o?os("eye","Rendered view","persona-artifact-view-btn"):ss("eye","Rendered view",""),x=o?os("code-2","Source","persona-artifact-code-btn"):ss("code-2","Source",""),k=f("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),U=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,M=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,O=t==null?void 0:t.documentToolbarCopyMenuItems,S=!!(M&&O&&O.length>0),N=null,Q,K=null,re=null;if(o&&(U||M)&&!S){if(Q=Yl(U),M){let q=ue("chevron-down",14,"currentColor",2);q&&Q.appendChild(q)}}else if(o&&S){N=f("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=Yl(U),K=Hd(),N.append(Q,K),re=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"),N.appendChild(re);for(let q of O){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=q.label,ne.dataset.copyMenuId=q.id,re.appendChild(ne)}}else o?Q=os("copy","Copy",""):Q=ss("copy","Copy","");let J=o?os("refresh-cw","Refresh",""):ss("refresh-cw","Refresh",""),pe=o?os("x","Close",""):ss("x","Close",""),Le=()=>{var Ke,te,X;let q=(Ke=j.find(He=>He.id===ce))!=null?Ke:j[j.length-1],ne=(te=q==null?void 0:q.id)!=null?te:null,oe=(q==null?void 0:q.artifactType)==="markdown"&&(X=q.markdown)!=null?X:"",Ee=q?JSON.stringify({component:q.component,props:q.props},null,2):"";return{markdown:oe,jsonPayload:Ee,id:ne}},Ye=async()=>{var Ke;let{markdown:q,jsonPayload:ne}=Le(),oe=(Ke=j.find(te=>te.id===ce))!=null?Ke:j[j.length-1],Ee=(oe==null?void 0:oe.artifactType)==="markdown"?q:oe?ne:"";try{await navigator.clipboard.writeText(Ee)}catch{}};if(Q.addEventListener("click",async()=>{let q=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(q&&S){let{markdown:ne,jsonPayload:oe,id:Ee}=Le();try{await q({actionId:"primary",artifactId:Ee,markdown:ne,jsonPayload:oe})}catch{}return}await Ye()}),K&&re){let q=()=>{re.classList.add("persona-hidden"),K.setAttribute("aria-expanded","false")};K.addEventListener("click",ne=>{ne.stopPropagation(),re.classList.contains("persona-hidden")?(re.classList.remove("persona-hidden"),K.setAttribute("aria-expanded","true")):q()}),typeof document!="undefined"&&document.addEventListener("click",q),re.addEventListener("click",async ne=>{let oe=ne.target.closest("button[data-copy-menu-id]");if(!(oe!=null&&oe.dataset.copyMenuId))return;ne.stopPropagation();let Ee=oe.dataset.copyMenuId,{markdown:Ke,jsonPayload:te,id:X}=Le(),He=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{He?await He({actionId:Ee,artifactId:X,markdown:Ke,jsonPayload:te}):Ee==="markdown"||Ee==="md"?await navigator.clipboard.writeText(Ke):Ee==="json"||Ee==="source"?await navigator.clipboard.writeText(te):await navigator.clipboard.writeText(Ke||te)}catch{}q()})}J.addEventListener("click",async()=>{var q;try{await((q=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:q.call(t))}catch{}mt()}),pe.addEventListener("click",()=>{var q;c(),(q=n.onDismiss)==null||q.call(n)});let fe=()=>{o&&(E.setAttribute("aria-pressed",C==="rendered"?"true":"false"),x.setAttribute("aria-pressed",C==="source"?"true":"false"))};E.addEventListener("click",()=>{C="rendered",fe(),mt()}),x.addEventListener("click",()=>{C="source",fe(),mt()});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");o?(p.replaceChildren(),v.append(E,x),N?k.append(N,J,pe):k.append(Q,J,pe),p.append(v,ee,k),fe()):(p.appendChild(y),p.appendChild(m)),s&&(p.style.paddingLeft=s,p.style.paddingRight=s);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"),V=f("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Y.style.paddingLeft=s,Y.style.paddingRight=s,V.style.padding=s),g.appendChild(p),g.appendChild(Y),g.appendChild(V);let j=[],ce=null,he=!1,mt=()=>{var Ee,Ke,te,X;let q=o&&j.length<=1;Y.classList.toggle("persona-hidden",q),Y.replaceChildren();for(let He of j){let Ve=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");Ve.type="button",Ve.textContent=He.title||He.id.slice(0,8),He.id===ce&&Ve.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ve.addEventListener("click",()=>n.onSelect(He.id)),Y.appendChild(Ve)}V.replaceChildren();let ne=ce&&j.find(He=>He.id===ce)||j[j.length-1];if(!ne)return;if(o){let He=ne.artifactType==="markdown"?"MD":(Ee=ne.component)!=null?Ee:"Component",et=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ee.textContent=`${et} \xB7 ${He}`}else y.textContent="Artifacts";if(ne.artifactType==="markdown"){if(o&&C==="source"){let Ve=f("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ve.textContent=(Ke=ne.markdown)!=null?Ke:"",V.appendChild(Ve);return}let He=f("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");He.innerHTML=i((te=ne.markdown)!=null?te:""),V.appendChild(He);return}let oe=ne.component?Pn.get(ne.component):void 0;if(oe){let Ve={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let et=oe((X=ne.props)!=null?X:{},Ve);if(et){V.appendChild(et);return}}catch{}}V.appendChild(Rd(ne))},lt=()=>{var ne;let q=j.length>0;if(g.classList.toggle("persona-hidden",!q),d){let oe=typeof g.closest=="function"?g.closest("#persona-root"):null,Ke=((ne=oe==null?void 0:oe.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;q&&Ke&&he?(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(q){var ne,oe,Ee;j=q.artifacts,ce=(Ee=(oe=q.selectedId)!=null?oe:(ne=q.artifacts[q.artifacts.length-1])==null?void 0:ne.id)!=null?Ee:null,j.length>0&&(he=!0),mt(),lt()},setMobileOpen(q){he=q,!q&&d?(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):lt()}}}function on(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 Gl(e,n){var s,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"),!on(n))return;let t=(a=(s=n.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(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)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function Bd(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 Js(e,n){var d,c,g,p,y,m,C,v,E,x;if(!on(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"),Bd(e),Gl(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 o=(C=t==null?void 0:t.panePadding)==null?void 0:C.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=t==null?void 0:t.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):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"),Gl(e,n)}var Zl=["panel","seamless"];function Ks(e,n){var i,d,c,g,p,y;for(let m of Zl)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"),!on(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",o=Zl.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(g=t==null?void 0:t.paneBorderRadius)==null?void 0:g.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);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())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Ql(e,n){var t,r,o;return!n||!on(e)?!1:((o=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function $d(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 Fd(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 Nd(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function Od(e,n,t,r){let o=e-r-2*n-t;return Math.max(0,o)}function ec(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function tc(e,n,t,r,o,s){let a=$d(o,200),i=Od(n,t,r,200);i=Math.max(a,i);let d=Fd(s);return d!==null&&(i=Math.min(i,d)),Nd(e,a,i)}var nc={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"}},Fo=(e,n,t,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var C,v,E;if(s.dataset.enhanced==="true")return;let a=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let i=(v=nc[a])!=null?v:nc.init;s.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 S,N;let k=f("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${n.id}-${a}-${x.name}`;let U=f("span","persona-text-xs persona-font-medium persona-text-persona-muted");U.textContent=x.label,k.appendChild(U);let M=(S=x.type)!=null?S:"text",O;M==="textarea"?(O=document.createElement("textarea"),O.rows=3):(O=document.createElement("input"),O.type=M),O.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",O.id=`${n.id}-${a}-${x.name}`,O.name=x.name,O.placeholder=(N=x.placeholder)!=null?N:"",x.required&&(O.required=!0),k.appendChild(O),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),s.replaceChildren(d,g),g.addEventListener("submit",async x=>{var O,S;x.preventDefault();let k=(O=t.formEndpoint)!=null?O:"/form",U=new FormData(g),M={};U.forEach((N,Q)=>{M[Q]=N}),M.type=a,m.disabled=!0,y.textContent="Submitting\u2026";try{let N=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!N.ok)throw new Error(`Form submission failed (${N.status})`);let Q=await N.json();y.textContent=(S=Q.message)!=null?S:"Thanks! We'll be in touch soon.",Q.success&&Q.nextPrompt&&await r.sendMessage(String(Q.nextPrompt))}catch(N){y.textContent=N instanceof Error?N.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var No=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,o;return((r=t.priority)!=null?r:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(s=>s.id));return[...t.filter(s=>!r.has(s.id)),...n].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},as=new No;var Oo={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"},Do={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"},gt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Oo,darkTheme:Do,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 Ys(e){var n,t,r,o,s,a,i,d,c,g,p,y,m,C,v,E,x,k,U,M,O;return e?{...gt,...e,theme:{...gt.theme,...e.theme},darkTheme:{...gt.darkTheme,...e.darkTheme},launcher:{...gt.launcher,...e.launcher,dock:{...(n=gt.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=gt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...gt.copy,...e.copy},sendButton:{...gt.sendButton,...e.sendButton},statusIndicator:{...gt.statusIndicator,...e.statusIndicator},voiceRecognition:{...gt.voiceRecognition,...e.voiceRecognition},features:(()=>{var K,re;let S=(K=gt.features)==null?void 0:K.artifacts,N=(re=e.features)==null?void 0:re.artifacts,Q=S===void 0&&N===void 0?void 0:{...S,...N,layout:{...S==null?void 0:S.layout,...N==null?void 0:N.layout}};return{...gt.features,...e.features,...Q!==void 0?{artifacts:Q}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:gt.suggestionChips,suggestionChipsConfig:{...gt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...gt.layout,...e.layout,header:{...(a=gt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=gt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(g=gt.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=gt.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=gt.layout)==null?void 0:k.slots,...(U=e.layout)==null?void 0:U.slots}},markdown:{...gt.markdown,...e.markdown,options:{...(M=gt.markdown)==null?void 0:M.options,...(O=e.markdown)==null?void 0:O.options}},messageActions:{...gt.messageActions,...e.messageActions}}:gt}var rc=()=>{let e=new Map,n=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>t(o,s)),t=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:n,off:t,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Dd=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},_d=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let o=t;o<n.length;o+=1){let s=n[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return n.slice(t,o+1)}return null},is=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Dd(e),t=_d(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},_o=e=>typeof e=="string"?e:e==null?"":String(e),sr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:_o(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let t=e.payload,r=_o(t.element);if(r&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:_o(t.text)}}},sc=e=>Array.isArray(e)?e.map(n=>String(n)):[],ls=e=>{let n=new Set(sc(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(sc(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.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:s.message}))||null,null):null;if(!i)return null;n.add(s.message.id),r();let d={action:i,message:s.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:s.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 jd=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}},Vd=e=>e.map(n=>({...n,streaming:!1})),Xs=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?jd(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let o={...t,messages:t.messages?Vd(t.messages):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},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 kr=require("partial-json");function qd(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Ud(e,n){if(!qd(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 Gs(){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 o=(0,kr.parse)(t,kr.STR|kr.OBJ),s=Ud(o,t);s&&(e=s)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function oc(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Zs(e,n){let{config:t,message:r,onPropsUpdate:o}=n,s=Pn.get(e.component);if(!s)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=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function ac(){let e=Gs();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Qs(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 eo(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 zd=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function to(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=zd}=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=o,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 S=1;S<=5;S++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-star-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${c[S-1]}`),N.title=c[S-1],N.dataset.rating=String(S),N.innerHTML=`
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=L,x.forEach((ue,z)=>{let V=z<L;ue.classList.toggle("selected",V),ue.setAttribute("aria-checked",z===L-1?"true":"false")})}),x.push(F),A.appendChild(F)}m.appendChild(A);let H=null;if(d){let L=document.createElement("div");L.className="tvw-feedback-comment-container",H=document.createElement("textarea"),H.className="tvw-feedback-comment",H.placeholder=s,H.rows=3,H.setAttribute("aria-label","Additional comments"),L.appendChild(H),m.appendChild(L)}let Y=document.createElement("div");Y.className="tvw-feedback-actions";let k=document.createElement("button");k.type="button",k.className="tvw-feedback-btn tvw-feedback-btn-skip",k.textContent=a,k.addEventListener("click",()=>{r==null||r(),v.remove()});let P=document.createElement("button");return P.type="button",P.className="tvw-feedback-btn tvw-feedback-btn-submit",P.textContent=i,P.addEventListener("click",async()=>{if(p===null){A.classList.add("tvw-feedback-shake"),setTimeout(()=>A.classList.remove("tvw-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let L=(H==null?void 0:H.value.trim())||void 0;await t(p,L),v.remove()}catch(L){P.disabled=!1,P.textContent=i,console.error("[CSAT Feedback] Failed to submit:",L)}}),Y.appendChild(k),Y.appendChild(P),m.appendChild(Y),v.appendChild(m),v}function wr(n){let{onSubmit:t,onDismiss:r,title:e="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:v="Very likely"}=n,p=document.createElement("div");p.className="tvw-feedback-container tvw-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let m=null,w=document.createElement("div");w.className="tvw-feedback-content";let C=document.createElement("div");C.className="tvw-feedback-header";let y=document.createElement("h3");y.className="tvw-feedback-title",y.textContent=e,C.appendChild(y);let A=document.createElement("p");A.className="tvw-feedback-subtitle",A.textContent=o,C.appendChild(A),w.appendChild(C);let x=document.createElement("div");x.className="tvw-feedback-rating tvw-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let H=document.createElement("div");H.className="tvw-feedback-labels";let Y=document.createElement("span");Y.className="tvw-feedback-label-low",Y.textContent=c;let k=document.createElement("span");k.className="tvw-feedback-label-high",k.textContent=v,H.appendChild(Y),H.appendChild(k);let P=document.createElement("div");P.className="tvw-feedback-numbers";let L=[];for(let X=0;X<=10;X++){let _=document.createElement("button");_.type="button",_.className="tvw-feedback-rating-btn tvw-feedback-number-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`Rating ${X} out of 10`),_.textContent=String(X),_.dataset.rating=String(X),X<=6?_.classList.add("tvw-feedback-detractor"):X<=8?_.classList.add("tvw-feedback-passive"):_.classList.add("tvw-feedback-promoter"),_.addEventListener("click",()=>{m=X,L.forEach((Ce,se)=>{Ce.classList.toggle("selected",se===X),Ce.setAttribute("aria-checked",se===X?"true":"false")})}),L.push(_),P.appendChild(_)}x.appendChild(H),x.appendChild(P),w.appendChild(x);let F=null;if(d){let X=document.createElement("div");X.className="tvw-feedback-comment-container",F=document.createElement("textarea"),F.className="tvw-feedback-comment",F.placeholder=s,F.rows=3,F.setAttribute("aria-label","Additional comments"),X.appendChild(F),w.appendChild(X)}let ue=document.createElement("div");ue.className="tvw-feedback-actions";let z=document.createElement("button");z.type="button",z.className="tvw-feedback-btn tvw-feedback-btn-skip",z.textContent=a,z.addEventListener("click",()=>{r==null||r(),p.remove()});let V=document.createElement("button");return V.type="button",V.className="tvw-feedback-btn tvw-feedback-btn-submit",V.textContent=i,V.addEventListener("click",async()=>{if(m===null){P.classList.add("tvw-feedback-shake"),setTimeout(()=>P.classList.remove("tvw-feedback-shake"),500);return}V.disabled=!0,V.textContent="Submitting...";try{let X=(F==null?void 0:F.value.trim())||void 0;await t(m,X),p.remove()}catch(X){V.disabled=!1,V.textContent=i,console.error("[NPS Feedback] Failed to submit:",X)}}),ue.appendChild(z),ue.appendChild(V),w.appendChild(ue),p.appendChild(w),p}var is="persona-chat-history",Nl=30*1e3,Ol={"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 Dl(n){var e,o,s;if(!n)return[];let t=[],r=Array.from((e=n.items)!=null?e:[]);for(let i of r){if(i.kind!=="file"||!i.type.startsWith("image/"))continue;let a=i.getAsFile();if(!a)continue;if(a.name){t.push(a);continue}let d=(o=Ol[a.type])!=null?o:"png";t.push(new File([a],`clipboard-image-${Date.now()}.${d}`,{type:a.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let i of Array.from((s=n.files)!=null?s:[]))i.type.startsWith("image/")&&t.push(i);return t}function jl(n){var t,r,e,o,s,i,a,d,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=n.storage)!=null?t:"session",keyPrefix:(r=n.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(e=n.persist)==null?void 0:e.openState)!=null?o:!0,voiceState:(i=(s=n.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(d=(a=n.persist)==null?void 0:a.focusInput)!=null?d:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function _l(n){try{let t=n==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Gr=n=>!n||typeof n!="object"?{}:{...n},Pa=n=>n.map(t=>({...t,streaming:!1})),Ra=(n,t,r)=>{let e=n!=null&&n.markdown?Ss(n.markdown):null;return o=>{var a,d,c;let s=(a=o.text)!=null?a:"",i=(d=o.message.rawContent)!=null?d:null;if(t){let v=t.process({text:s,raw:i!=null?i:s,message:o.message,streaming:o.streaming});v!==null&&(s=v.text,v.persist||(o.message.__skipPersist=!0),v.resubmit&&!o.streaming&&r&&r())}return n!=null&&n.postprocessMessage?n.postprocessMessage({...o,text:s,raw:(c=i!=null?i:o.text)!=null?c:""}):e?e(s):Ys(s)}},yr=(n,t,r)=>{var q,We,_e,dt,vt,Tt,at,f,Re,$,b,R,ae,Te,Ke,Wt,lt,St,wt,De,qe,ht,Ve,At,jt,Zt,to,no,so,ro,oo,io,ao,lo,co;n.id&&n.id!=="persona-root"&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.id="persona-root";let e=ur(t),o=Ls.getForInstance(e.plugins);e.components&&rs.registerAll(e.components);let s=ka(),i=(q=e.storageAdapter)!=null?q:pr(),a={},d=null,c=l=>{if(e.onStateLoaded)try{return e.onStateLoaded(l)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(i!=null&&i.load)try{let l=i.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&&(a=Gr(h.metadata)),(We=h.messages)!=null&&We.length&&(e={...e,initialMessages:h.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(e.onStateLoaded)try{let l=c({messages:[],metadata:{}});(_e=l.messages)!=null&&_e.length&&(e={...e,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let v=()=>a,p=l=>{var h;a=(h=l({...a}))!=null?h:{},ds()},m=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Ws],w=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Nn.message,Nn.messageAndClick],C=Ps({parsers:m,handlers:w,getSessionMetadata:v,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let y=(vt=(dt=e.launcher)==null?void 0:dt.enabled)!=null?vt:!0,A=(at=(Tt=e.launcher)==null?void 0:Tt.autoExpand)!=null?at:!1,x=(f=e.autoFocusInput)!=null?f:!1,H=A,Y=y,k=($=(Re=e.layout)==null?void 0:Re.header)==null?void 0:$.layout,P=y?A:!0,L=!1,F=null,ue=()=>{L=!0,F&&clearTimeout(F),F=setTimeout(()=>{L&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),L=!1)},1e4)},z=Ra(e,C,ue),V=(R=(b=e.features)==null?void 0:b.showReasoning)!=null?R:!0,X=(Te=(ae=e.features)==null?void 0:ae.showToolCalls)!=null?Te:!0,_=(Wt=(Ke=e.features)==null?void 0:Ke.showEventStreamToggle)!=null?Wt:!1,se=`${(St=typeof e.persistState=="object"?(lt=e.persistState)==null?void 0:lt.keyPrefix:void 0)!=null?St:"persona-"}event-stream`,G=_?new Is(se):null,U=(qe=(De=(wt=e.features)==null?void 0:wt.eventStream)==null?void 0:De.maxEvents)!=null?qe:2e3,N=_?new ks(U,G):null,ee=null,fe=!1,Fe=null,Mt=0;G==null||G.open().then(()=>N==null?void 0:N.restore()).catch(l=>{e.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let gt={onCopy:l=>{var u,h;s.emit("message:copy",l),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(l.id,"copy").catch(S=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",S)}),(h=(u=e.messageActions)==null?void 0:u.onCopy)==null||h.call(u,l)},onFeedback:l=>{var u,h;s.emit("message:feedback",l),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(l.messageId,l.type).catch(S=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",S)}),(h=(u=e.messageActions)==null?void 0:u.onFeedback)==null||h.call(u,l)}},ft=(ht=e.statusIndicator)!=null?ht:{},Ht=l=>{var u,h,S,W;return l==="idle"?(u=ft.idleText)!=null?u:Rt.idle:l==="connecting"?(h=ft.connectingText)!=null?h:Rt.connecting:l==="connected"?(S=ft.connectedText)!=null?S:Rt.connected:l==="error"?(W=ft.errorText)!=null?W:Rt.error:Rt[l]},{wrapper:je,panel:ne}=ya(e),xe=ba(e,y),{container:He,body:$e,messagesWrapper:ze,suggestions:Ot,textarea:he,sendButton:Z,sendButtonWrapper:ct,composerForm:bt,statusText:kt,introTitle:Ct,introSubtitle:Kt,closeButton:te,iconHolder:Pe,headerTitle:xt,headerSubtitle:ve,header:Se,footer:Je,actionsRow:Bt,leftActions:It,rightActions:qt}=xe,I=xe.micButton,nt=xe.micButtonWrapper,O=xe.attachmentButton,Q=xe.attachmentButtonWrapper,re=xe.attachmentInput,Ne=xe.attachmentPreviewsContainer,oe=null;(Ve=e.attachments)!=null&&Ve.enabled&&re&&Ne&&(oe=Bn.fromConfig(e.attachments),oe.setPreviewsContainer(Ne),re.addEventListener("change",l=>{let u=l.target;oe==null||oe.handleFileSelect(u.files),u.value=""}));let Xe=o.find(l=>l.renderHeader);if(Xe!=null&&Xe.renderHeader){let l=Xe.renderHeader({config:e,defaultRenderer:()=>{let u=mn({config:e,showClose:y});return Fn(He,u,e),u.header},onClose:()=>ot(!1,"user")});if(l){let u=He.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(l),Se=l)}}let Ge=()=>{var u,h,S,W;if(!N)return;if(fe=!0,!ee&&N&&(ee=Ta({buffer:N,getFullHistory:()=>N.getAllFromStore(),onClose:()=>pe(),config:e,plugins:o})),ee&&($e.style.display="none",(u=Je.parentNode)==null||u.insertBefore(ee.element,Je),ee.update()),D){D.classList.remove("tvw-text-cw-muted"),D.classList.add("tvw-text-cw-accent"),D.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let M=(W=(S=(h=e.features)==null?void 0:h.eventStream)==null?void 0:S.classNames)==null?void 0:W.toggleButtonActive;M&&M.split(/\s+/).forEach(j=>j&&D.classList.add(j))}let l=()=>{if(!fe)return;let M=Date.now();M-Mt>=200&&(ee==null||ee.update(),Mt=M),Fe=requestAnimationFrame(l)};Mt=0,Fe=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},pe=()=>{var l,u,h;if(fe){if(fe=!1,ee&&ee.element.remove(),$e.style.display="",D){D.classList.remove("tvw-text-cw-accent"),D.classList.add("tvw-text-cw-muted"),D.style.boxShadow="";let S=(h=(u=(l=e.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:h.toggleButtonActive;S&&S.split(/\s+/).forEach(W=>W&&D.classList.remove(W))}Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},D=null;if(_){let l=(jt=(At=e.features)==null?void 0:At.eventStream)==null?void 0:jt.classNames,u="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");D=g("button",u),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let h=ie("activity","18px","currentColor",1.5);h&&D.appendChild(h);let S=xe.clearChatButtonWrapper,W=xe.closeButtonWrapper,M=S||W;M&&M.parentNode===Se?Se.insertBefore(D,M):Se.appendChild(D),D.addEventListener("click",()=>{fe?pe():Ge()})}let Ee=o.find(l=>l.renderComposer);if(Ee!=null&&Ee.renderComposer){let l=Ee.renderComposer({config:e,defaultRenderer:()=>Qn({config:e}).footer,onSubmit:u=>{T&&!T.isStreaming()&&T.sendMessage(u)},disabled:!1});l&&(Je.replaceWith(l),Je=l)}(()=>{var S,W;let l=(W=(S=e.layout)==null?void 0:S.slots)!=null?W:{},u=M=>{switch(M){case"body-top":return He.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return ze;case"footer-top":return Ot;case"composer":return bt;case"footer-bottom":return kt;default:return null}},h=(M,j)=>{var le;switch(M){case"header-left":case"header-center":case"header-right":if(M==="header-left")Se.insertBefore(j,Se.firstChild);else if(M==="header-right")Se.appendChild(j);else{let de=Se.querySelector(".tvw-flex-col");de?(le=de.parentNode)==null||le.insertBefore(j,de.nextSibling):Se.appendChild(j)}break;case"body-top":{let de=$e.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");de?de.replaceWith(j):$e.insertBefore(j,$e.firstChild);break}case"body-bottom":$e.appendChild(j);break;case"footer-top":Ot.replaceWith(j);break;case"footer-bottom":kt.replaceWith(j);break;default:break}};for(let[M,j]of Object.entries(l))if(j)try{let le=j({config:e,defaultContent:()=>u(M)});le&&h(M,le)}catch(le){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${M}":`,le)}})();let rt=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 W=S.getAttribute("data-message-id");if(!W)return;let M=h.getAttribute("data-bubble-type");M==="reasoning"?(ts.has(W)?ts.delete(W):ts.add(W),Sa(W,S)):M==="tool"&&(ns.has(W)?ns.delete(W):ns.add(W),Aa(W,S,e))};ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),rt(l))}),ze.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),rt(l))});let Yt=new Map;ze.addEventListener("click",l=>{var j;let h=l.target.closest(".tvw-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let S=h.closest("[data-actions-for]");if(!S)return;let W=S.getAttribute("data-actions-for");if(!W)return;let M=h.getAttribute("data-action");if(M==="copy"){let de=T.getMessages().find(ye=>ye.id===W);if(de&&gt.onCopy){let ye=de.content||"";navigator.clipboard.writeText(ye).then(()=>{h.classList.add("tvw-message-action-success");let we=ie("check",14,"currentColor",2);we&&(h.innerHTML="",h.appendChild(we)),setTimeout(()=>{h.classList.remove("tvw-message-action-success");let Me=ie("copy",14,"currentColor",2);Me&&(h.innerHTML="",h.appendChild(Me))},2e3)}).catch(we=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",we)}),gt.onCopy(de)}}else if(M==="upvote"||M==="downvote")if(((j=Yt.get(W))!=null?j:null)===M)Yt.delete(W),h.classList.remove("tvw-message-action-active");else{let ye=M==="upvote"?"downvote":"upvote",we=S.querySelector(`[data-action="${ye}"]`);we&&we.classList.remove("tvw-message-action-active"),Yt.set(W,M),h.classList.add("tvw-message-action-active");let J=T.getMessages().find(E=>E.id===W);J&&gt.onFeedback&&gt.onFeedback({type:M,messageId:J.id,message:J})}}),ze.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 W=S.getAttribute("data-message-id");if(!W)return;let M=h.getAttribute("data-approval-action");if(!M)return;let j=M==="approve"?"approved":"denied",de=T.getMessages().find(we=>we.id===W);if(!(de!=null&&de.approval))return;let ye=S.querySelector("[data-approval-buttons]");ye&&ye.querySelectorAll("button").forEach(Me=>{Me.disabled=!0,Me.style.opacity="0.5",Me.style.cursor="not-allowed"}),T.resolveApproval(de.approval,j)}),ne.appendChild(He),n.appendChild(je);let Qt=()=>{var ce,ge,Oe,me,Ye,ut,K,Ue,on,_t,nn,In,zs,kr,Ir,mt;let l=(ge=(ce=e.launcher)==null?void 0:ce.sidebarMode)!=null?ge:!1,u=l||((me=(Oe=e.launcher)==null?void 0:Oe.fullHeight)!=null?me:!1),h=(Ye=e.theme)!=null?Ye:{},S=(K=(ut=e.launcher)==null?void 0:ut.position)!=null?K:"bottom-left",W=S==="bottom-left"||S==="top-left",M=l?"none":"1px solid var(--tvw-cw-border)",j=l?W?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",le=l?"0":"16px",de=(Ue=h.panelBorder)!=null?Ue:M,ye=(on=h.panelShadow)!=null?on:j,we=(_t=h.panelBorderRadius)!=null?_t:le;n.style.cssText="",je.style.cssText="",ne.style.cssText="",He.style.cssText="",$e.style.cssText="",Je.style.cssText="";let Me=(In=(nn=e==null?void 0:e.launcher)==null?void 0:nn.width)!=null?In:e==null?void 0:e.launcherWidth,J=Me!=null?Me:"min(400px, calc(100vw - 24px))";l||(ne.style.width=J,ne.style.maxWidth=J),ne.style.boxShadow=ye,ne.style.borderRadius=we,He.style.border=de,He.style.borderRadius=we;let E=((zs=e.launcher)==null?void 0:zs.enabled)===!1;if(u&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",je.style.display="flex",je.style.flexDirection="column",je.style.flex="1 1 0%",je.style.minHeight="0",je.style.maxHeight="100%",je.style.height="100%",E&&(je.style.overflow="hidden"),ne.style.display="flex",ne.style.flexDirection="column",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.maxHeight="100%",ne.style.height="100%",ne.style.overflow="hidden",He.style.display="flex",He.style.flexDirection="column",He.style.flex="1 1 0%",He.style.minHeight="0",He.style.maxHeight="100%",He.style.overflow="hidden",$e.style.flex="1 1 0%",$e.style.minHeight="0",$e.style.overflowY="auto",Je.style.flexShrink="0"),je.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!l&&!E&&((kr=sn[S])!=null?kr:sn["bottom-right"]).split(" ").forEach(Yn=>je.classList.add(Yn)),l){let Kn=(mt=(Ir=e.launcher)==null?void 0:Ir.sidebarWidth)!=null?mt:"420px";je.style.cssText=`
20
+ `,N.addEventListener("click",()=>{p=S,x.forEach((Q,K)=>{let re=K<S;Q.classList.toggle("selected",re),Q.setAttribute("aria-checked",K===S-1?"true":"false")})}),x.push(N),E.appendChild(N)}y.appendChild(E);let k=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),S.appendChild(k),y.appendChild(S)}let U=document.createElement("div");U.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 O=document.createElement("button");return O.type="button",O.className="persona-feedback-btn persona-feedback-btn-submit",O.textContent=a,O.addEventListener("click",async()=>{if(p===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let S=(k==null?void 0:k.value.trim())||void 0;await n(p,S),g.remove()}catch(S){O.disabled=!1,O.textContent=a,console.error("[CSAT Feedback] Failed to submit:",S)}}),U.appendChild(M),U.appendChild(O),y.appendChild(U),g.appendChild(y),g}function no(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="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=o,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 U=document.createElement("span");U.className="persona-feedback-label-low",U.textContent=c;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=g,k.appendChild(U),k.appendChild(M);let O=document.createElement("div");O.className="persona-feedback-numbers";let S=[];for(let J=0;J<=10;J++){let pe=document.createElement("button");pe.type="button",pe.className="persona-feedback-rating-btn persona-feedback-number-btn",pe.setAttribute("role","radio"),pe.setAttribute("aria-checked","false"),pe.setAttribute("aria-label",`Rating ${J} out of 10`),pe.textContent=String(J),pe.dataset.rating=String(J),J<=6?pe.classList.add("persona-feedback-detractor"):J<=8?pe.classList.add("persona-feedback-passive"):pe.classList.add("persona-feedback-promoter"),pe.addEventListener("click",()=>{y=J,S.forEach((Le,Ye)=>{Le.classList.toggle("selected",Ye===J),Le.setAttribute("aria-checked",Ye===J?"true":"false")})}),S.push(pe),O.appendChild(pe)}x.appendChild(k),x.appendChild(O),m.appendChild(x);let N=null;if(d){let J=document.createElement("div");J.className="persona-feedback-comment-container",N=document.createElement("textarea"),N.className="persona-feedback-comment",N.placeholder=s,N.rows=3,N.setAttribute("aria-label","Additional comments"),J.appendChild(N),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 re=document.createElement("button");return re.type="button",re.className="persona-feedback-btn persona-feedback-btn-submit",re.textContent=a,re.addEventListener("click",async()=>{if(y===null){O.classList.add("persona-feedback-shake"),setTimeout(()=>O.classList.remove("persona-feedback-shake"),500);return}re.disabled=!0,re.textContent="Submitting...";try{let J=(N==null?void 0:N.value.trim())||void 0;await n(y,J),p.remove()}catch(J){re.disabled=!1,re.textContent=a,console.error("[NPS Feedback] Failed to submit:",J)}}),Q.appendChild(K),Q.appendChild(re),m.appendChild(Q),p.appendChild(m),p}var Lr="persona-chat-history",Jd=30*1e3,Kd={"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 Yd(e){var r,o,s;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=(o=Kd[i.type])!=null?o:"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((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&n.push(a);return n}function Xd(e){var n,t,r,o,s,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:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.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 Gd(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var jo=e=>!e||typeof e!="object"?{}:{...e},ic=e=>e.map(n=>({...n,streaming:!1})),lc=(e,n,t)=>{let r=e!=null&&e.markdown?Xn(e.markdown):null;return o=>{var i,d,c;let s=(i=o.text)!=null?i:"",a=(d=o.message.rawContent)!=null?d:null;if(n){let g=n.process({text:s,raw:a!=null?a:s,message:o.message,streaming:o.streaming});g!==null&&(s=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&t&&t())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...o,text:s,raw:(c=a!=null?a:o.text)!=null?c:""}):r?r(s):yr(s)}},ro=(e,n,t)=>{var ae,Se,nt,kt,wt,Ht,Lt,rt,at,Et,it,Bt,Jt,rn,Zo,Qo,ea,ta,na,ra,sa,oa,aa,ia,la,ca,da,pa,ua,ga,ma,fa,ha,ya,ba,xa,va,Ca;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let r=Ys(n),o=as.getForInstance(r.plugins);r.components&&Pn.registerAll(r.components);let s=rc(),a=(ae=r.storageAdapter)!=null?ae:Xs(),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=jo(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:{}});(nt=l.messages)!=null&&nt.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:{},Nr()},y=r.actionParsers&&r.actionParsers.length?r.actionParsers:[is],m=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[sr.message,sr.messageAndClick],C=ls({parsers:y,handlers:m,getSessionMetadata:g,updateSessionMetadata:p,emit:s.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=(Ht=r.launcher)==null?void 0:Ht.autoExpand)!=null?Lt:!1,x=(rt=r.autoFocusInput)!=null?rt:!1,k=E,U=v,M=(Et=(at=r.layout)==null?void 0:at.header)==null?void 0:Et.layout,O=!1,S=v?E:!0,N=!1,Q=null,K=()=>{N=!0,Q&&clearTimeout(Q),Q=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},re=lc(r,C,K),J=(Bt=(it=r.features)==null?void 0:it.showReasoning)!=null?Bt:!0,pe=(rn=(Jt=r.features)==null?void 0:Jt.showToolCalls)!=null?rn:!0,Le=(Qo=(Zo=r.features)==null?void 0:Zo.showEventStreamToggle)!=null?Qo:!1,fe=`${(ta=typeof r.persistState=="object"?(ea=r.persistState)==null?void 0:ea.keyPrefix:void 0)!=null?ta:"persona-"}event-stream`,ee=Le?new rs(fe):null,Y=(sa=(ra=(na=r.features)==null?void 0:na.eventStream)==null?void 0:ra.maxEvents)!=null?sa:2e3,V=Le?new ns(Y,ee):null,j=null,ce=!1,he=null,mt=0;ee==null||ee.open().then(()=>V==null?void 0:V.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let lt={onCopy:l=>{var u,h;s.emit("message:copy",l),W!=null&&W.isClientTokenMode()&&W.submitMessageFeedback(l.id,"copy").catch(A=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(h=(u=r.messageActions)==null?void 0:u.onCopy)==null||h.call(u,l)},onFeedback:l=>{var u,h;s.emit("message:feedback",l),W!=null&&W.isClientTokenMode()&&W.submitMessageFeedback(l.messageId,l.type).catch(A=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(h=(u=r.messageActions)==null?void 0:u.onFeedback)==null||h.call(u,l)}},ft=(oa=r.statusIndicator)!=null?oa:{},It=l=>{var u,h,A,L;return l==="idle"?(u=ft.idleText)!=null?u:_t.idle:l==="connecting"?(h=ft.connectingText)!=null?h:_t.connecting:l==="connected"?(A=ft.connectedText)!=null?A:_t.connected:l==="error"?(L=ft.errorText)!=null?L:_t.error:_t[l]},{wrapper:le,panel:se}=Dl(r),q=_l(r,v),{container:ne,body:oe,messagesWrapper:Ee,suggestions:Ke,textarea:te,sendButton:X,sendButtonWrapper:He,composerForm:Ve,statusText:et,introTitle:Vt,introSubtitle:Dt,closeButton:ie,iconHolder:Ue,headerTitle:Te,headerSubtitle:tt,header:_e,footer:Xe,actionsRow:Wt,leftActions:Rt,rightActions:Mt}=q,H=q.micButton,Z=q.micButtonWrapper,z=q.attachmentButton,Pe=q.attachmentButtonWrapper,Ce=q.attachmentInput,Ie=q.attachmentPreviewsContainer,Be=null,ut=null,ye=o.find(l=>l.renderHeader);if(ye!=null&&ye.renderHeader){let l=ye.renderHeader({config:r,defaultRenderer:()=>{let u=Ln({config:r,showClose:v});return nr(ne,u,r),u.header},onClose:()=>ht(!1,"user")});if(l){let u=ne.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),_e=l)}}let be=()=>{var u,h,A,L;if(!V)return;if(ce=!0,!j&&V&&(j=Jl({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>$e(),config:r,plugins:o})),j&&(oe.style.display="none",(u=Xe.parentNode)==null||u.insertBefore(j.element,Xe),j.update()),de){de.classList.remove("persona-text-persona-muted"),de.classList.add("persona-text-persona-accent"),de.style.boxShadow="inset 0 0 0 1.5px var(--persona-accent, #3b82f6)";let $=(L=(A=(h=r.features)==null?void 0:h.eventStream)==null?void 0:A.classNames)==null?void 0:L.toggleButtonActive;$&&$.split(/\s+/).forEach(R=>R&&de.classList.add(R))}let l=()=>{if(!ce)return;let $=Date.now();$-mt>=200&&(j==null||j.update(),mt=$),he=requestAnimationFrame(l)};mt=0,he=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},$e=()=>{var l,u,h;if(ce){if(ce=!1,j&&j.element.remove(),oe.style.display="",de){de.classList.remove("persona-text-persona-accent"),de.classList.add("persona-text-persona-muted"),de.style.boxShadow="";let A=(h=(u=(l=r.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:h.toggleButtonActive;A&&A.split(/\s+/).forEach(L=>L&&de.classList.remove(L))}he!==null&&(cancelAnimationFrame(he),he=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},de=null;if(Le){let l=(ia=(aa=r.features)==null?void 0:aa.eventStream)==null?void 0:ia.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:"");de=f("button",u),de.style.width="28px",de.style.height="28px",de.type="button",de.setAttribute("aria-label","Event Stream"),de.title="Event Stream";let h=ue("activity","18px","currentColor",1.5);h&&de.appendChild(h);let A=q.clearChatButtonWrapper,L=q.closeButtonWrapper,$=A||L;$&&$.parentNode===_e?_e.insertBefore(de,$):_e.appendChild(de),de.addEventListener("click",()=>{ce?$e():be()})}let bt=l=>{var A,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 R=l.querySelector("[data-persona-composer-form]");R!=null&&R.parentNode?R.parentNode.insertBefore(h,R):l.insertBefore(h,l.firstChild)}if(!l.querySelector('input[type="file"]')){let R=f("input");R.type="file",R.accept=((A=u.allowedTypes)!=null?A:kn).join(","),R.multiple=((L=u.maxFiles)!=null?L:4)>1,R.style.display="none",R.setAttribute("aria-label",($=u.buttonTooltipText)!=null?$:"Attach files"),l.appendChild(R)}},Gt=o.find(l=>l.renderComposer);if(Gt!=null&&Gt.renderComposer){let l=r.composer,u=Gt.renderComposer({config:r,defaultRenderer:()=>Sr({config:r}).footer,onSubmit:h=>{W&&!W.isStreaming()&&W.sendMessage(h)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ce==null||Ce.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h}},onVoiceToggle:((la=r.voiceRecognition)==null?void 0:la.enabled)===!0?()=>{ut==null||ut()}:void 0});u&&(Xe.replaceWith(u),Xe=u)}let pn=l=>{let u=l.querySelector("[data-persona-composer-form]"),h=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),$=l.querySelector("[data-persona-composer-status]");u&&(Ve=u),h&&(te=h),A&&(X=A),L&&(H=L,Z=L.parentElement),$&&(et=$);let R=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");R&&(Ke=R);let D=l.querySelector(".persona-attachment-button");D&&(z=D,Pe=D.parentElement),Ce=l.querySelector('input[type="file"]'),Ie=l.querySelector(".persona-attachment-previews");let B=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");B&&(Wt=B)};bt(Xe),pn(Xe);let un=(ca=r.layout)==null?void 0:ca.contentMaxWidth;un&&Ve&&(Ve.style.maxWidth=un,Ve.style.marginLeft="auto",Ve.style.marginRight="auto"),(da=r.attachments)!=null&&da.enabled&&Ce&&Ie&&(Be=tr.fromConfig(r.attachments),Be.setPreviewsContainer(Ie),Ce.addEventListener("change",l=>{let u=l.target;Be==null||Be.handleFileSelect(u.files),u.value=""})),(()=>{var A,L;let l=(L=(A=r.layout)==null?void 0:A.slots)!=null?L:{},u=$=>{switch($){case"body-top":return ne.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ee;case"footer-top":return Ke;case"composer":return Ve;case"footer-bottom":return et;default:return null}},h=($,R)=>{var D;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")_e.insertBefore(R,_e.firstChild);else if($==="header-right")_e.appendChild(R);else{let B=_e.querySelector(".persona-flex-col");B?(D=B.parentNode)==null||D.insertBefore(R,B.nextSibling):_e.appendChild(R)}break;case"body-top":{let B=oe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(R):oe.insertBefore(R,oe.firstChild);break}case"body-bottom":oe.appendChild(R);break;case"footer-top":Ke.replaceWith(R);break;case"footer-bottom":et.replaceWith(R);break;default:break}};for(let[$,R]of Object.entries(l))if(R)try{let D=R({config:r,defaultContent:()=>u($)});D&&h($,D)}catch(D){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,D)}})();let Wn=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let A=h.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let $=h.getAttribute("data-bubble-type");$==="reasoning"?(Er.has(L)?Er.delete(L):Er.add(L),ql(L,A)):$==="tool"&&(Tr.has(L)?Tr.delete(L):Tr.add(L),Ul(L,A,r))};Ee.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Wn(l))}),Ee.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Wn(l))});let ar=new Map;Ee.addEventListener("click",l=>{var R;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let A=h.closest("[data-actions-for]");if(!A)return;let L=A.getAttribute("data-actions-for");if(!L)return;let $=h.getAttribute("data-action");if($==="copy"){let B=W.getMessages().find(me=>me.id===L);if(B&&lt.onCopy){let me=B.content||"";navigator.clipboard.writeText(me).then(()=>{h.classList.add("persona-message-action-success");let ge=ue("check",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Me=ue("copy",14,"currentColor",2);Me&&(h.innerHTML="",h.appendChild(Me))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),lt.onCopy(B)}}else if($==="upvote"||$==="downvote")if(((R=ar.get(L))!=null?R:null)===$)ar.delete(L),h.classList.remove("persona-message-action-active");else{let me=$==="upvote"?"downvote":"upvote",ge=A.querySelector(`[data-action="${me}"]`);ge&&ge.classList.remove("persona-message-action-active"),ar.set(L,$),h.classList.add("persona-message-action-active");let je=W.getMessages().find(xe=>xe.id===L);je&&lt.onFeedback&&lt.onFeedback({type:$,messageId:je.id,message:je})}}),Ee.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let A=h.closest(".vanilla-approval-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let $=h.getAttribute("data-approval-action");if(!$)return;let R=$==="approve"?"approved":"denied",B=W.getMessages().find(ge=>ge.id===L);if(!(B!=null&&B.approval))return;let me=A.querySelector("[data-approval-buttons]");me&&me.querySelectorAll("button").forEach(Me=>{Me.disabled=!0,Me.style.opacity="0.5",Me.style.cursor="not-allowed"}),W.resolveApproval(B.approval,R)});let Ge=null,gn=null,Rn={artifacts:[],selectedId:null},an=!1,Pr={current:null};Ee.addEventListener("click",l=>{var ge,Me;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let A=h.getAttribute("data-download-artifact");if(!A)return;let L=W.getArtifactById(A),$=L==null?void 0:L.markdown,R=(L==null?void 0:L.title)||"artifact";if(!$){let je=h.closest("[data-open-artifact]"),xe=je==null?void 0:je.closest("[data-message-id]"),P=xe==null?void 0:xe.getAttribute("data-message-id");if(P){let Ae=W.getMessages().find(F=>F.id===P);if(Ae!=null&&Ae.rawContent)try{let F=JSON.parse(Ae.rawContent);$=(ge=F==null?void 0:F.props)==null?void 0:ge.markdown,R=((Me=F==null?void 0:F.props)==null?void 0:Me.title)||R}catch{}}}if(!$)return;let D=new Blob([$],{type:"text/markdown"}),B=URL.createObjectURL(D),me=document.createElement("a");me.href=B,me.download=`${R}.md`,me.click(),URL.revokeObjectURL(B)}),Ee.addEventListener("click",l=>{let h=l.target.closest("[data-open-artifact]");if(!h)return;let A=h.getAttribute("data-open-artifact");A&&(l.preventDefault(),l.stopPropagation(),W.selectArtifact(A),fn())}),Ee.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;u.hasAttribute("data-open-artifact")&&(l.preventDefault(),u.click())});let mn=null,dt=null,tn=null,vn=null,Ir=()=>{};function ir(){vn==null||vn(),vn=null}let Wr=()=>{var R;if(!mn||!dt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((R=e.ownerDocument.defaultView)!=null?R: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 A=mn.firstElementChild;if(!A||A===dt)return;let L=10;dt.style.position="absolute",dt.style.top="0",dt.style.bottom="0",dt.style.width=`${L}px`,dt.style.zIndex="5";let $=A.offsetWidth-L/2;dt.style.left=`${Math.max(0,$)}px`},Dn=()=>{},fn=()=>{var h,A,L,$,R;if(!Ge||!on(r))return;Js(e,r),Ks(e,r),Dn();let l=($=(L=(A=(h=r.features)==null?void 0:h.artifacts)==null?void 0:A.layout)==null?void 0:L.narrowHostMaxWidth)!=null?$:520,u=se.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l),Ge.update(Rn),an?(Ge.setMobileOpen(!1),Ge.element.classList.add("persona-hidden"),(R=Ge.backdrop)==null||R.classList.add("persona-hidden")):Rn.artifacts.length>0&&(Ge.element.classList.remove("persona-hidden"),Ge.setMobileOpen(!0)),Ir()};if(on(r)){se.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),Ge=Xl(r,{onSelect:h=>{var A;return(A=Pr.current)==null?void 0:A.selectArtifact(h)},onDismiss:()=>{an=!0,fn()}}),Ge.element.classList.add("persona-hidden"),mn=u,u.appendChild(l),u.appendChild(Ge.element),Ge.backdrop&&se.appendChild(Ge.backdrop),se.appendChild(u),Ir=()=>{var A,L,$,R;if(!mn||!Ge)return;if(!((($=(L=(A=r.features)==null?void 0:A.artifacts)==null?void 0:L.layout)==null?void 0:$.resizable)===!0)){tn==null||tn(),tn=null,ir(),dt&&(dt.remove(),dt=null),Ge.element.style.removeProperty("width"),Ge.element.style.removeProperty("maxWidth");return}if(!dt){let D=f("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");D.setAttribute("role","separator"),D.setAttribute("aria-orientation","vertical"),D.setAttribute("aria-label","Resize artifacts panel"),D.tabIndex=0;let B=e.ownerDocument,me=(R=B.defaultView)!=null?R:window,ge=Me=>{var F,We;if(!Ge||Me.button!==0||e.classList.contains("persona-artifact-narrow-host")||me.innerWidth<=640)return;Me.preventDefault(),ir();let je=Me.clientX,xe=Ge.element.getBoundingClientRect().width,P=(We=(F=r.features)==null?void 0:F.artifacts)==null?void 0:We.layout,ke=st=>{let Ze=mn.getBoundingClientRect().width,St=e.classList.contains("persona-artifact-appearance-seamless"),ct=St?0:ec(mn,me),ot=St?0:D.getBoundingClientRect().width||6,Kt=xe-(st.clientX-je),ve=tc(Kt,Ze,ct,ot,P==null?void 0:P.resizableMinWidth,P==null?void 0:P.resizableMaxWidth);Ge.element.style.width=`${ve}px`,Ge.element.style.maxWidth="none",Wr()},Ae=()=>{B.removeEventListener("pointermove",ke),B.removeEventListener("pointerup",Ae),B.removeEventListener("pointercancel",Ae),vn=null;try{D.releasePointerCapture(Me.pointerId)}catch{}};vn=Ae,B.addEventListener("pointermove",ke),B.addEventListener("pointerup",Ae),B.addEventListener("pointercancel",Ae);try{D.setPointerCapture(Me.pointerId)}catch{}};D.addEventListener("pointerdown",ge),dt=D,mn.insertBefore(D,Ge.element),tn=()=>{D.removeEventListener("pointerdown",ge)}}if(dt){let D=Rn.artifacts.length>0&&!an;dt.classList.toggle("persona-hidden",!D),Wr()}},Dn=()=>{var me,ge,Me,je,xe,P,ke,Ae,F,We,st,Ze,St,ct;if(!v||!Ge||((ge=(me=r.launcher)==null?void 0:me.sidebarMode)!=null?ge:!1))return;let A=(Me=e.ownerDocument.defaultView)!=null?Me:window,L=(xe=(je=r.launcher)==null?void 0:je.mobileFullscreen)!=null?xe:!0,$=(ke=(P=r.launcher)==null?void 0:P.mobileBreakpoint)!=null?ke:640;if(L&&A.innerWidth<=$||!Ql(r,v))return;let R=(We=(F=(Ae=r.launcher)==null?void 0:Ae.width)!=null?F:r.launcherWidth)!=null?We:"min(400px, calc(100vw - 24px))",D=(ct=(St=(Ze=(st=r.features)==null?void 0:st.artifacts)==null?void 0:Ze.layout)==null?void 0:St.expandedPanelWidth)!=null?ct:"min(720px, calc(100vw - 24px))";Rn.artifacts.length>0&&!an?(se.style.width=D,se.style.maxWidth=D):(se.style.width=R,se.style.maxWidth=R)},typeof ResizeObserver!="undefined"&&(gn=new ResizeObserver(()=>{fn()}),gn.observe(se))}else se.appendChild(ne);e.appendChild(le);let _n=()=>{var Ze,St,ct,ot,Kt,ve,pt,$t,sn,Ss,As,Es,go,mo,Tt,Ts,qr,Ur,hr,Ms,Nn;let l=jt(r),u=(St=(Ze=r.launcher)==null?void 0:Ze.sidebarMode)!=null?St:!1,h=l||u||((ot=(ct=r.launcher)==null?void 0:ct.fullHeight)!=null?ot:!1),A=((Kt=r.launcher)==null?void 0:Kt.enabled)===!1,L=(ve=r.theme)!=null?ve:{},$=(pt=e.ownerDocument.defaultView)!=null?pt:window,R=(sn=($t=r.launcher)==null?void 0:$t.mobileFullscreen)!=null?sn:!0,D=(As=(Ss=r.launcher)==null?void 0:Ss.mobileBreakpoint)!=null?As:640,B=$.innerWidth<=D,me=R&&B&&v,ge=(go=(Es=r.launcher)==null?void 0:Es.position)!=null?go:"bottom-left",Me=ge==="bottom-left"||ge==="top-left",je=u||me?"none":"1px solid var(--persona-persona-border)",xe=me?"none":u?Me?"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))",P=u||me?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ke=(mo=L.panelBorder)!=null?mo:je,Ae=(Tt=L.panelShadow)!=null?Tt:xe,F=(Ts=L.panelBorderRadius)!=null?Ts:P;if(e.style.cssText="",le.style.cssText="",se.style.cssText="",ne.style.cssText="",oe.style.cssText="",Xe.style.cssText="",me){le.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"),le.style.cssText=`
21
+ position: fixed !important;
22
+ inset: 0 !important;
23
+ width: 100% !important;
24
+ height: 100% !important;
25
+ max-height: 100% !important;
26
+ margin: 0 !important;
27
+ padding: 0 !important;
28
+ display: flex !important;
29
+ flex-direction: column !important;
30
+ z-index: inherit !important;
31
+ `,se.style.cssText=`
32
+ position: relative !important;
33
+ display: flex !important;
34
+ flex-direction: column !important;
35
+ flex: 1 1 0% !important;
36
+ width: 100% !important;
37
+ max-width: 100% !important;
38
+ height: 100% !important;
39
+ min-height: 0 !important;
40
+ margin: 0 !important;
41
+ padding: 0 !important;
42
+ box-shadow: none !important;
43
+ border-radius: 0 !important;
44
+ `,ne.style.cssText=`
45
+ display: flex !important;
46
+ flex-direction: column !important;
47
+ flex: 1 1 0% !important;
48
+ width: 100% !important;
49
+ height: 100% !important;
50
+ min-height: 0 !important;
51
+ max-height: 100% !important;
52
+ overflow: hidden !important;
53
+ border-radius: 0 !important;
54
+ border: none !important;
55
+ `,oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",Xe.style.flexShrink="0",O=!0;return}let We=(Ur=(qr=r==null?void 0:r.launcher)==null?void 0:qr.width)!=null?Ur:r==null?void 0:r.launcherWidth,st=We!=null?We:"min(400px, calc(100vw - 24px))";if(!u&&!l?A&&h?(se.style.width="100%",se.style.maxWidth="100%"):(se.style.width=st,se.style.maxWidth=st):l&&(se.style.width="100%",se.style.maxWidth="100%"),Dn(),se.style.boxShadow=Ae,se.style.borderRadius=F,ne.style.border=ke,ne.style.borderRadius=F,h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",A&&(e.style.width="100%"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.height="100%",A&&(le.style.overflow="hidden"),se.style.display="flex",se.style.flexDirection="column",se.style.flex="1 1 0%",se.style.minHeight="0",se.style.maxHeight="100%",se.style.height="100%",se.style.overflow="hidden",ne.style.display="flex",ne.style.flexDirection="column",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.maxHeight="100%",ne.style.overflow="hidden",oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",Xe.style.flexShrink="0"),le.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&&!A&&!l&&((hr=dn[ge])!=null?hr:dn["bottom-right"]).split(" ").forEach(Yt=>le.classList.add(Yt)),u){let Tn=(Nn=(Ms=r.launcher)==null?void 0:Ms.sidebarWidth)!=null?Nn:"420px";le.style.cssText=`
21
56
  position: fixed !important;
22
57
  top: 0 !important;
23
58
  bottom: 0 !important;
24
- width: ${Kn} !important;
59
+ width: ${Tn} !important;
25
60
  height: 100vh !important;
26
61
  max-height: 100vh !important;
27
62
  margin: 0 !important;
28
63
  padding: 0 !important;
29
64
  display: flex !important;
30
65
  flex-direction: column !important;
31
- ${W?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
- `,ne.style.cssText=`
66
+ ${Me?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
67
+ `,se.style.cssText=`
33
68
  position: relative !important;
34
69
  display: flex !important;
35
70
  flex-direction: column !important;
@@ -40,9 +75,9 @@
40
75
  min-height: 0 !important;
41
76
  margin: 0 !important;
42
77
  padding: 0 !important;
43
- box-shadow: ${ye} !important;
44
- border-radius: ${we} !important;
45
- `,ne.style.setProperty("width","100%","important"),ne.style.setProperty("max-width","100%","important"),He.style.cssText=`
78
+ box-shadow: ${Ae} !important;
79
+ border-radius: ${F} !important;
80
+ `,se.style.setProperty("width","100%","important"),se.style.setProperty("max-width","100%","important"),ne.style.cssText=`
46
81
  display: flex !important;
47
82
  flex-direction: column !important;
48
83
  flex: 1 1 0% !important;
@@ -51,13 +86,29 @@
51
86
  min-height: 0 !important;
52
87
  max-height: 100% !important;
53
88
  overflow: hidden !important;
54
- border-radius: ${we} !important;
55
- border: ${de} !important;
56
- `,Je.style.cssText=`
89
+ border-radius: ${F} !important;
90
+ border: ${ke} !important;
91
+ `,Xe.style.cssText=`
57
92
  flex-shrink: 0 !important;
58
93
  border-top: none !important;
59
94
  padding: 8px 16px 12px 16px !important;
60
- `}if(!E){let Kn="max-height: -moz-available !important; max-height: stretch !important;",Yn=l?"":"padding-top: 1.25em !important;";je.style.cssText+=Kn+Yn}};Qt(),cr(n,e);let Ze=[];_&&Ze.push(()=>{Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),ee==null||ee.destroy(),ee=null,N==null||N.destroy(),N=null,G=null});let en=null,vn=()=>{en&&(en(),en=null),e.colorScheme==="auto"&&(en=fa(()=>{cr(n,e)}))};vn(),Ze.push(()=>{en&&(en(),en=null)});let wn=Ea(Ot),rn=null,T,yn=!1,ln=!0,Sn=0,as=0,cn=null,dn=!1,Dn=0,jn=!1,Rs=125,Hs=2e3,Bs=5,ls=50,_n=new Map,Ae={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},cs=(to=(Zt=e.voiceRecognition)==null?void 0:Zt.autoResume)!=null?to:!1,Xt=l=>{s.emit("voice:state",{active:Ae.active,source:l,timestamp:Date.now()})},Dt=()=>{p(l=>({...l,voiceState:{active:Ae.active,timestamp:Date.now(),manuallyDeactivated:Ae.manuallyDeactivated}}))},Fs=()=>{var S,W;if(((S=e.voiceRecognition)==null?void 0:S.enabled)===!1)return;let l=Gr(a.voiceState),u=!!l.active,h=Number((W=l.timestamp)!=null?W:0);Ae.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<Nl&&setTimeout(()=>{var M,j;Ae.active||(Ae.manuallyDeactivated=!1,((j=(M=e.voiceRecognition)==null?void 0:M.provider)==null?void 0:j.type)==="runtype"?T.toggleVoice().then(()=>{Ae.active=T.isVoiceActive(),Xt("restore"),T.isVoiceActive()&&bn()}):Mn("restore"))},1e3)},$s=()=>T?Pa(T.getMessages()).filter(l=>!l.__skipPersist):[];function ds(l){if(!(i!=null&&i.save))return;let h={messages:l?Pa(l):T?$s():[],metadata:a};try{let S=i.save(h);S instanceof Promise&&S.catch(W=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",W)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)}}let An=(l=!1)=>{if(!ln)return;let u=Date.now();dn&&u<Dn&&!l||(dn&&u>=Dn&&(dn=!1),!(!l&&!yn)&&(u-as<Rs||(as=u,cn&&cancelAnimationFrame(cn),cn=requestAnimationFrame(()=>{dn||!ln||(jn=!0,$e.scrollTop=$e.scrollHeight,Sn=$e.scrollTop,requestAnimationFrame(()=>{jn=!1}),cn=null)}))))},un=null,Ns=()=>je.querySelector("#persona-scroll-container")||$e,Os=(l,u=500)=>{let h=l.scrollTop,S=l.clientHeight,W=l.scrollHeight,M=W-h;if(h+S>=W-2||Math.abs(M)<5)return;un!==null&&(cancelAnimationFrame(un),un=null);let le=performance.now(),de=we=>1-Math.pow(1-we,3),ye=we=>{let Me=l.scrollHeight;Me!==W&&(W=Me,M=W-h);let J=we-le,E=Math.min(J/u,1),ce=de(E),ge=h+M*ce;l.scrollTop=ge,E<1?un=requestAnimationFrame(ye):(l.scrollTop=l.scrollHeight,un=null)};un=requestAnimationFrame(ye)},Ds=l=>{let u=new Map;l.forEach(h=>{let S=_n.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!S&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(S!=null&&S.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(S?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),_n.clear(),u.forEach((h,S)=>{_n.set(S,h)})},En=(l,u,h)=>{var ye,we,Me,J;let S=document.createElement("div"),M=(()=>{var ce;let E=o.find(ge=>ge.renderLoadingIndicator);if(E!=null&&E.renderLoadingIndicator)return E.renderLoadingIndicator;if((ce=e.loadingIndicator)!=null&&ce.render)return e.loadingIndicator.render})();u.forEach(E=>{var Ye,ut;let ce=null,ge=o.find(K=>!!(E.variant==="reasoning"&&K.renderReasoning||E.variant==="tool"&&K.renderToolCall||E.variant==="approval"&&K.renderApproval||!E.variant&&K.renderMessage)),Oe=(Ye=e.layout)==null?void 0:Ye.messages;if(ge)if(E.variant==="reasoning"&&E.reasoning&&ge.renderReasoning){if(!V)return;ce=ge.renderReasoning({message:E,defaultRenderer:()=>jr(E),config:e})}else if(E.variant==="tool"&&E.toolCall&&ge.renderToolCall){if(!X)return;ce=ge.renderToolCall({message:E,defaultRenderer:()=>_r(E,e),config:e})}else if(E.variant==="approval"&&E.approval&&ge.renderApproval){if(e.approval===!1)return;ce=ge.renderApproval({message:E,defaultRenderer:()=>Ur(E,e),config:e})}else ge.renderMessage&&(ce=ge.renderMessage({message:E,defaultRenderer:()=>{let K=es(E,h,Oe,e.messageActions,gt,{loadingIndicatorRenderer:M,widgetConfig:e});return E.role!=="user"&&Vr(K,E,e,T),K},config:e}));if(!ce&&E.role==="assistant"&&!E.variant&&e.enableComponentStreaming!==!1&&mr(E)){let Ue=fr(E);if(Ue){let on=hr(Ue,{config:e,message:E,transform:h});if(on){let _t=document.createElement("div");if(_t.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),_t.id=`bubble-${E.id}`,_t.setAttribute("data-message-id",E.id),E.content&&E.content.trim()){let nn=document.createElement("div");nn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",nn.innerHTML=h({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),_t.appendChild(nn)}_t.appendChild(on),ce=_t}}}if(!ce)if(E.variant==="reasoning"&&E.reasoning){if(!V)return;ce=jr(E)}else if(E.variant==="tool"&&E.toolCall){if(!X)return;ce=_r(E,e)}else if(E.variant==="approval"&&E.approval){if(e.approval===!1)return;ce=Ur(E,e)}else{let K=(ut=e.layout)==null?void 0:ut.messages;K!=null&&K.renderUserMessage&&E.role==="user"?ce=K.renderUserMessage({message:E,config:e,streaming:!!E.streaming}):K!=null&&K.renderAssistantMessage&&E.role==="assistant"?ce=K.renderAssistantMessage({message:E,config:e,streaming:!!E.streaming}):ce=es(E,h,K,e.messageActions,gt,{loadingIndicatorRenderer:M,widgetConfig:e}),E.role!=="user"&&ce&&Vr(ce,E,e,T)}let me=document.createElement("div");me.className="tvw-flex",me.id=`wrapper-${E.id}`,me.setAttribute("data-wrapper-id",E.id),E.role==="user"&&me.classList.add("tvw-justify-end"),me.appendChild(ce),S.appendChild(me)});let j=u.some(E=>E.role==="assistant"&&E.streaming),le=u[u.length-1],de=(le==null?void 0:le.role)==="assistant"&&!le.streaming&&le.variant!=="approval";if(yn&&u.some(E=>E.role==="user")&&!j&&!de){let E={config:e,streaming:!0,location:"standalone",defaultRenderer:$n},ce=o.find(Oe=>Oe.renderLoadingIndicator),ge=null;if(ce!=null&&ce.renderLoadingIndicator&&(ge=ce.renderLoadingIndicator(E)),ge===null&&((ye=e.loadingIndicator)!=null&&ye.render)&&(ge=e.loadingIndicator.render(E)),ge===null&&(ge=$n()),ge){let Oe=document.createElement("div"),me=((we=e.loadingIndicator)==null?void 0:we.showBubble)!==!1;Oe.className=me?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Oe.setAttribute("data-typing-indicator","true"),Oe.appendChild(ge);let Ye=document.createElement("div");Ye.className="tvw-flex",Ye.id="wrapper-typing-indicator",Ye.setAttribute("data-wrapper-id","typing-indicator"),Ye.appendChild(Oe),S.appendChild(Ye)}}if(!yn&&u.length>0){let E=u[u.length-1],ce={config:e,lastMessage:E,messageCount:u.length},ge=o.find(me=>me.renderIdleIndicator),Oe=null;if(ge!=null&&ge.renderIdleIndicator&&(Oe=ge.renderIdleIndicator(ce)),Oe===null&&((Me=e.loadingIndicator)!=null&&Me.renderIdle)&&(Oe=e.loadingIndicator.renderIdle(ce)),Oe){let me=document.createElement("div"),Ye=((J=e.loadingIndicator)==null?void 0:J.showBubble)!==!1;me.className=Ye?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),me.setAttribute("data-idle-indicator","true"),me.appendChild(Oe);let ut=document.createElement("div");ut.className="tvw-flex",ut.id="wrapper-idle-indicator",ut.setAttribute("data-wrapper-id","idle-indicator"),ut.appendChild(me),S.appendChild(ut)}}wa(l,S),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let E=Ns();Os(E)})})},Tn=()=>{y&&(P?(je.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),ne.classList.remove("tvw-scale-95","tvw-opacity-0"),ne.classList.add("tvw-scale-100","tvw-opacity-100"),Qe?Qe.element.style.display="none":et&&(et.style.display="none")):(je.classList.add("tvw-pointer-events-none","tvw-opacity-0"),ne.classList.remove("tvw-scale-100","tvw-opacity-100"),ne.classList.add("tvw-scale-95","tvw-opacity-0"),Qe?Qe.element.style.display="":et&&(et.style.display="")))},ot=(l,u="user")=>{if(!y||P===l)return;let h=P;P=l,Tn(),P&&(Cn(),An(!0));let S={open:P,source:u,timestamp:Date.now()};P&&!h?s.emit("widget:opened",S):!P&&h&&s.emit("widget:closed",S),s.emit("widget:state",{open:P,launcherEnabled:y,voiceActive:Ae.active,streaming:T.isStreaming()})},Un=l=>{Z.disabled=l,I&&(I.disabled=l),wn.buttons.forEach(u=>{u.disabled=l})},qn=()=>{Ae.active||he&&he.focus()};s.on("widget:opened",()=>{e.autoFocusInput&&setTimeout(()=>qn(),200)});let us=()=>{var W,M,j,le,de,ye,we,Me,J,E,ce,ge,Oe,me;Ct.textContent=(M=(W=e.copy)==null?void 0:W.welcomeTitle)!=null?M:"Hello \u{1F44B}",Kt.textContent=(le=(j=e.copy)==null?void 0:j.welcomeSubtitle)!=null?le:"Ask anything about your account or products.",he.placeholder=(ye=(de=e.copy)==null?void 0:de.inputPlaceholder)!=null?ye:"How can I help...",(Me=(we=e.sendButton)==null?void 0:we.useIcon)!=null&&Me||(Z.textContent=(E=(J=e.copy)==null?void 0:J.sendButtonLabel)!=null?E:"Send");let u=(ge=(ce=e.theme)==null?void 0:ce.inputFontFamily)!=null?ge:"sans-serif",h=(me=(Oe=e.theme)==null?void 0:Oe.inputFontWeight)!=null?me:"400",S=Ye=>{switch(Ye){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'}};he.style.fontFamily=S(u),he.style.fontWeight=h};if(e.clientToken&&(e={...e,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{p(u=>({...u,sessionId:l}))}}),T=new Gn(e,{onMessagesChanged(l){En(ze,l,z),T&&(l.some(W=>W.role==="user")?wn.render([],T,he,l):wn.render(e.suggestionChips,T,he,l,e.suggestionChipsConfig)),An(!yn),Ds(l);let u=[...l].reverse().find(S=>S.role==="user"),h=Ae.lastUserMessageId;u&&u.id!==h&&(Ae.lastUserMessageId=u.id,s.emit("user:message",u)),Ae.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),ds(l)},onStatusChanged(l){var S;let u=(S=e.statusIndicator)!=null?S:{},h=W=>{var M,j,le,de;return W==="idle"?(M=u.idleText)!=null?M:Rt.idle:W==="connecting"?(j=u.connectingText)!=null?j:Rt.connecting:W==="connected"?(le=u.connectedText)!=null?le:Rt.connected:W==="error"?(de=u.errorText)!=null?de:Rt.error:Rt[W]};kt.textContent=h(l)},onStreamingChanged(l){yn=l,Un(l),T&&En(ze,T.getMessages(),z),l||An(!0)},onVoiceStatusChanged(l){var u,h;if(((h=(u=e.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":break;case"processing":Gt(),_s();break;case"speaking":Gt(),Us();break;default:l==="idle"&&T.isBargeInActive()?(Gt(),bn(),I==null||I.setAttribute("aria-label","End voice session")):(Ae.active=!1,Gt(),Xt("system"),Dt());break}}}),((so=(no=e.voiceRecognition)==null?void 0:no.provider)==null?void 0:so.type)==="runtype")try{T.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}e.clientToken&&T.initClientSession().catch(l=>{e.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),N&&T.setSSEEventCallback((l,u)=>{N==null||N.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&&(a=Gr(l.metadata),C.syncFromMetadata()),(u=l.messages)!=null&&u.length&&T.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let ps=l=>{var W;l.preventDefault();let u=he.value.trim(),h=(W=oe==null?void 0:oe.hasAttachments())!=null?W:!1;if(!u&&!h)return;let S;h&&(S=[],S.push(...oe.getContentParts()),u&&S.push(sr(u))),he.value="",he.style.height="auto",T.sendMessage(u,{contentParts:S}),h&&oe.clearAttachments()},gs=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Z.click())},hs=async l=>{var h;if(((h=e.attachments)==null?void 0:h.enabled)!==!0||!oe)return;let u=Dl(l.clipboardData);u.length!==0&&(l.preventDefault(),await oe.handleFiles(u))},Ft=null,Vt=!1,pn=null,ke=null,ms=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Mn=(l="user")=>{var M,j,le,de,ye,we,Me,J;if(Vt||T.isStreaming())return;let u=ms();if(!u)return;Ft=new u;let S=(j=((M=e.voiceRecognition)!=null?M:{}).pauseDuration)!=null?j:2e3;Ft.continuous=!0,Ft.interimResults=!0,Ft.lang="en-US";let W=he.value;Ft.onresult=E=>{let ce="",ge="";for(let me=0;me<E.results.length;me++){let Ye=E.results[me],ut=Ye[0].transcript;Ye.isFinal?ce+=ut+" ":ge=ut}let Oe=W+ce+ge;he.value=Oe,pn&&clearTimeout(pn),(ce||ge)&&(pn=window.setTimeout(()=>{let me=he.value.trim();me&&Ft&&Vt&&(tn(),he.value="",he.style.height="auto",T.sendMessage(me,{viaVoice:!0}))},S))},Ft.onerror=E=>{E.error!=="no-speech"&&tn()},Ft.onend=()=>{if(Vt){let E=he.value.trim();E&&E!==W.trim()&&(he.value="",he.style.height="auto",T.sendMessage(E,{viaVoice:!0})),tn()}};try{if(Ft.start(),Vt=!0,Ae.active=!0,l!=="system"&&(Ae.manuallyDeactivated=!1),Xt(l),Dt(),I){let E=(le=e.voiceRecognition)!=null?le:{};ke={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor,iconName:(de=E.iconName)!=null?de:"mic",iconSize:parseFloat((Me=(we=E.iconSize)!=null?we:(ye=e.sendButton)==null?void 0:ye.size)!=null?Me:"40")||24};let ce=(J=E.recordingBackgroundColor)!=null?J:"#ef4444",ge=E.recordingIconColor,Oe=E.recordingBorderColor;if(I.classList.add("tvw-voice-recording"),I.style.backgroundColor=ce,ge){I.style.color=ge;let me=I.querySelector("svg");me&&me.setAttribute("stroke",ge)}Oe&&(I.style.borderColor=Oe),I.setAttribute("aria-label","Stop voice recognition")}}catch{tn("system")}},tn=(l="user")=>{if(Vt){if(Vt=!1,pn&&(clearTimeout(pn),pn=null),Ft){try{Ft.stop()}catch{}Ft=null}Ae.active=!1,Xt(l),Dt(),I&&Gt()}},js=(l,u)=>{var me,Ye,ut,K,Ue,on,_t,nn;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),S=((me=l==null?void 0:l.provider)==null?void 0:me.type)==="runtype";if(!(h||S))return null;let M=g("div","tvw-send-button-wrapper"),j=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");j.type="button",j.setAttribute("aria-label","Start voice recognition");let le=(Ye=l==null?void 0:l.iconName)!=null?Ye:"mic",de=(ut=u==null?void 0:u.size)!=null?ut:"40px",ye=(K=l==null?void 0:l.iconSize)!=null?K:de,we=parseFloat(ye)||24,Me=(Ue=l==null?void 0:l.backgroundColor)!=null?Ue:u==null?void 0:u.backgroundColor,J=(on=l==null?void 0:l.iconColor)!=null?on:u==null?void 0:u.textColor;j.style.width=ye,j.style.height=ye,j.style.minWidth=ye,j.style.minHeight=ye,j.style.fontSize="18px",j.style.lineHeight="1";let E=J||"currentColor",ce=ie(le,we,E,1.5);ce?(j.appendChild(ce),j.style.color=E):(j.textContent="\u{1F3A4}",j.style.color=E),Me?j.style.backgroundColor=Me:j.classList.add("tvw-bg-cw-primary"),J?j.style.color=J:!J&&!(u!=null&&u.textColor)&&j.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(j.style.borderWidth=l.borderWidth,j.style.borderStyle="solid"),l!=null&&l.borderColor&&(j.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(j.style.paddingLeft=l.paddingX,j.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(j.style.paddingTop=l.paddingY,j.style.paddingBottom=l.paddingY),M.appendChild(j);let ge=(_t=l==null?void 0:l.tooltipText)!=null?_t:"Start voice recognition";if(((nn=l==null?void 0:l.showTooltip)!=null?nn:!1)&&ge){let In=g("div","tvw-send-button-tooltip");In.textContent=ge,M.appendChild(In)}return{micButton:j,micButtonWrapper:M}},Vn=()=>{var u,h,S,W,M;if(!I||ke)return;let l=(u=e.voiceRecognition)!=null?u:{};ke={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((M=(W=l.iconSize)!=null?W:(S=e.sendButton)==null?void 0:S.size)!=null?M:"40")||24}},zn=(l,u)=>{var M,j,le,de,ye;if(!I)return;let h=I.querySelector("svg");h&&h.remove();let S=(ye=ke==null?void 0:ke.iconSize)!=null?ye:parseFloat((de=(le=(M=e.voiceRecognition)==null?void 0:M.iconSize)!=null?le:(j=e.sendButton)==null?void 0:j.size)!=null?de:"40")||24,W=ie(l,S,u,1.5);W&&I.appendChild(W)},kn=()=>{I&&I.classList.remove("tvw-voice-recording","tvw-voice-processing","tvw-voice-speaking")},bn=()=>{var W,M;if(!I)return;Vn();let l=(W=e.voiceRecognition)!=null?W:{},u=(M=l.recordingBackgroundColor)!=null?M:"#ef4444",h=l.recordingIconColor,S=l.recordingBorderColor;if(kn(),I.classList.add("tvw-voice-recording"),I.style.backgroundColor=u,h){I.style.color=h;let j=I.querySelector("svg");j&&j.setAttribute("stroke",h)}S&&(I.style.borderColor=S),I.setAttribute("aria-label","Stop voice recognition")},_s=()=>{var le,de,ye,we,Me,J,E,ce;if(!I)return;Vn();let l=(le=e.voiceRecognition)!=null?le:{},u=T.getVoiceInterruptionMode(),h=(de=l.processingIconName)!=null?de:"loader",S=(we=(ye=l.processingIconColor)!=null?ye:ke==null?void 0:ke.color)!=null?we:"",W=(J=(Me=l.processingBackgroundColor)!=null?Me:ke==null?void 0:ke.backgroundColor)!=null?J:"",M=(ce=(E=l.processingBorderColor)!=null?E:ke==null?void 0:ke.borderColor)!=null?ce:"";kn(),I.classList.add("tvw-voice-processing"),I.style.backgroundColor=W,I.style.borderColor=M;let j=S||"currentColor";I.style.color=j,zn(h,j),I.setAttribute("aria-label","Processing voice input"),u==="none"&&(I.style.cursor="default")},Us=()=>{var ye,we,Me,J,E,ce,ge,Oe,me,Ye,ut,K;if(!I)return;Vn();let l=(ye=e.voiceRecognition)!=null?ye:{},u=T.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",S=(we=l.speakingIconName)!=null?we:h,W=(ce=l.speakingIconColor)!=null?ce:u==="barge-in"?(J=(Me=l.recordingIconColor)!=null?Me:ke==null?void 0:ke.color)!=null?J:"":(E=ke==null?void 0:ke.color)!=null?E:"",M=(me=l.speakingBackgroundColor)!=null?me:u==="barge-in"?(ge=l.recordingBackgroundColor)!=null?ge:"#ef4444":(Oe=ke==null?void 0:ke.backgroundColor)!=null?Oe:"",j=(K=l.speakingBorderColor)!=null?K:u==="barge-in"?(Ye=l.recordingBorderColor)!=null?Ye:"":(ut=ke==null?void 0:ke.borderColor)!=null?ut:"";kn(),I.classList.add("tvw-voice-speaking"),I.style.backgroundColor=M,I.style.borderColor=j;let le=W||"currentColor";I.style.color=le,zn(S,le);let de=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";I.setAttribute("aria-label",de),u==="none"&&(I.style.cursor="default"),u==="barge-in"&&I.classList.add("tvw-voice-recording")},Gt=()=>{var l,u,h;I&&(kn(),ke&&(I.style.backgroundColor=(l=ke.backgroundColor)!=null?l:"",I.style.color=(u=ke.color)!=null?u:"",I.style.borderColor=(h=ke.borderColor)!=null?h:"",zn(ke.iconName,ke.color||"currentColor"),ke=null),I.style.cursor="",I.setAttribute("aria-label","Start voice recognition"))},Jn=()=>{var l,u;if(((u=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let h=T.getVoiceStatus(),S=T.getVoiceInterruptionMode();if(S==="none"&&(h==="processing"||h==="speaking"))return;if(S==="cancel"&&(h==="processing"||h==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{Ae.active=!1,Ae.manuallyDeactivated=!0,Dt(),Xt("user"),Gt()});return}T.toggleVoice().then(()=>{Ae.active=T.isVoiceActive(),Ae.manuallyDeactivated=!T.isVoiceActive(),Dt(),Xt("user"),T.isVoiceActive()?bn():Gt()});return}if(Vt){let h=he.value.trim();Ae.manuallyDeactivated=!0,Dt(),tn("user"),h&&(he.value="",he.style.height="auto",T.sendMessage(h))}else Ae.manuallyDeactivated=!1,Dt(),Mn("user")};I&&(I.addEventListener("click",Jn),Ze.push(()=>{var l,u;((u=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),Gt()):tn("system"),I&&I.removeEventListener("click",Jn)}));let qs=s.on("assistant:complete",()=>{cs&&(Ae.active||Ae.manuallyDeactivated||cs==="assistant"&&!Ae.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!Ae.active&&!Ae.manuallyDeactivated&&(((u=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?T.toggleVoice().then(()=>{Ae.active=T.isVoiceActive(),Xt("auto"),T.isVoiceActive()&&bn()}):Mn("auto"))},600))});Ze.push(qs);let Vs=s.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});Ze.push(Vs);let gn=()=>{ot(!P,"user")},Qe=null,et=null;if(y){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:e,defaultRenderer:()=>Ms(e,gn).element,onToggle:gn});u&&(et=u)}et||(Qe=Ms(e,gn))}Qe?n.appendChild(Qe.element):et&&n.appendChild(et),Tn(),wn.render(e.suggestionChips,T,he,void 0,e.suggestionChipsConfig),us(),Un(T.isStreaming()),An(!0),Fs(),x&&(y?P&&setTimeout(()=>qn(),200):setTimeout(()=>qn(),0));let Cn=()=>{var h,S,W,M,j,le,de,ye;let l=(S=(h=e.launcher)==null?void 0:h.sidebarMode)!=null?S:!1,u=l||((M=(W=e.launcher)==null?void 0:W.fullHeight)!=null?M:!1);if(!y){ne.style.height="",ne.style.width="";return}if(!l){let we=(le=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?le:e==null?void 0:e.launcherWidth,Me=we!=null?we:"min(400px, calc(100vw - 24px))";ne.style.width=Me,ne.style.maxWidth=Me}if(!u){let we=window.innerHeight,Me=64,J=(ye=(de=e.launcher)==null?void 0:de.heightOffset)!=null?ye:0,E=Math.max(200,we-Me),ce=Math.min(640,E),ge=Math.max(200,ce-J);ne.style.height=`${ge}px`}};Cn(),window.addEventListener("resize",Cn),Ze.push(()=>window.removeEventListener("resize",Cn)),Sn=$e.scrollTop;let fs=()=>{let l=$e.scrollTop,u=$e.scrollHeight,h=$e.clientHeight,S=u-l-h,W=Math.abs(l-Sn);if(Sn=l,!jn&&!(W<=Bs)){if(!ln&&S<ls){dn=!1,ln=!0;return}ln&&S>ls&&(dn=!0,Dn=Date.now()+Hs,ln=!1)}};$e.addEventListener("scroll",fs,{passive:!0}),Ze.push(()=>$e.removeEventListener("scroll",fs)),Ze.push(()=>{cn&&cancelAnimationFrame(cn)});let vs=()=>{te&&(rn&&(te.removeEventListener("click",rn),rn=null),y?(te.style.display="",rn=()=>{P=!1,Tn()},te.addEventListener("click",rn)):te.style.display="none")};vs(),(()=>{let{clearChatButton:l}=xe;l&&l.addEventListener("click",()=>{T.clearMessages();try{localStorage.removeItem(is),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${is}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==is)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.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),i!=null&&i.clear)try{let h=i.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)}a={},C.syncFromMetadata(),N==null||N.clear(),ee==null||ee.update()})})(),bt.addEventListener("submit",ps),he.addEventListener("keydown",gs),he.addEventListener("paste",hs),Ze.push(()=>{bt.removeEventListener("submit",ps),he.removeEventListener("keydown",gs),he.removeEventListener("paste",hs)}),Ze.push(()=>{T.cancel()}),Qe?Ze.push(()=>{Qe==null||Qe.destroy()}):et&&Ze.push(()=>{et==null||et.remove()});let Lt={update(l){var po,go,ho,mo,fo,vo,wo,yo,bo,Co,xo,So,Ao,Eo,To,Mo,ko,Io,Lo,Wo,Po,Ro,Ho,Bo,Fo,$o,No,Oo,Do,jo,_o,Uo,qo,Vo,zo,Jo,Ko,Yo,Xo,Go,Zo,Qo,ei,ti,ni,si,ri,oi,ii,ai,li,ci,di,ui,pi,gi,hi,mi,fi,vi,wi,yi,bi,Ci,xi,Si,Ai,Ei,Ti,Mi,ki,Ii,Li,Wi,Pi,Ri,Hi,Bi,Fi,$i,Ni,Oi,Di,ji,_i,Ui,qi,Vi,zi,Ji;let u=e.toolCall,h=e.colorScheme;e={...e,...l},Qt(),cr(n,e),e.colorScheme!==h&&vn();let S=Ls.getForInstance(e.plugins);o.length=0,o.push(...S),y=(go=(po=e.launcher)==null?void 0:po.enabled)!=null?go:!0,A=(mo=(ho=e.launcher)==null?void 0:ho.autoExpand)!=null?mo:!1,V=(vo=(fo=e.features)==null?void 0:fo.showReasoning)!=null?vo:!0,X=(yo=(wo=e.features)==null?void 0:wo.showToolCalls)!=null?yo:!0;let W=_;if(_=(Co=(bo=e.features)==null?void 0:bo.showEventStreamToggle)!=null?Co:!1,_&&!W){if(N||(G=new Is(se),N=new ks(U,G),G.open().then(()=>N==null?void 0:N.restore()).catch(()=>{}),T.setSSEEventCallback((B,Ie)=>{N.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:B,timestamp:Date.now(),payload:JSON.stringify(Ie)})})),!D&&Se){let B=(So=(xo=e.features)==null?void 0:xo.eventStream)==null?void 0:So.classNames,Ie="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(B!=null&&B.toggleButton?" "+B.toggleButton:"");D=g("button",Ie),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let tt=ie("activity","18px","currentColor",1.5);tt&&D.appendChild(tt);let be=xe.clearChatButtonWrapper,Be=xe.closeButtonWrapper,yt=be||Be;yt&&yt.parentNode===Se?Se.insertBefore(D,yt):Se.appendChild(D),D.addEventListener("click",()=>{fe?pe():Ge()})}}else!_&&W&&(pe(),D&&(D.remove(),D=null),N==null||N.clear(),G==null||G.destroy(),N=null,G=null);if(((Ao=e.launcher)==null?void 0:Ao.enabled)===!1&&Qe&&(Qe.destroy(),Qe=null),((Eo=e.launcher)==null?void 0:Eo.enabled)===!1&&et&&(et.remove(),et=null),((To=e.launcher)==null?void 0:To.enabled)!==!1&&!Qe&&!et){let B=o.find(Ie=>Ie.renderLauncher);if(B!=null&&B.renderLauncher){let Ie=B.renderLauncher({config:e,defaultRenderer:()=>Ms(e,gn).element,onToggle:gn});Ie&&(et=Ie,n.appendChild(et))}et||(Qe=Ms(e,gn),n.appendChild(Qe.element))}Qe&&Qe.update(e),xt&&((Mo=e.launcher)==null?void 0:Mo.title)!==void 0&&(xt.textContent=e.launcher.title),ve&&((ko=e.launcher)==null?void 0:ko.subtitle)!==void 0&&(ve.textContent=e.launcher.subtitle);let M=(Io=e.layout)==null?void 0:Io.header;if((M==null?void 0:M.layout)!==k&&Se){let B=M?Zn(e,M,{showClose:y,onClose:()=>ot(!1,"user")}):mn({config:e,showClose:y,onClose:()=>ot(!1,"user")});Se.replaceWith(B.header),Se=B.header,Pe=B.iconHolder,xt=B.headerTitle,ve=B.headerSubtitle,te=B.closeButton,k=M==null?void 0:M.layout}else if(M&&(Pe&&(Pe.style.display=M.showIcon===!1?"none":""),xt&&(xt.style.display=M.showTitle===!1?"none":""),ve&&(ve.style.display=M.showSubtitle===!1?"none":""),te&&(te.style.display=M.showCloseButton===!1?"none":""),xe.clearChatButtonWrapper)){let B=M.showClearChat;if(B!==void 0){xe.clearChatButtonWrapper.style.display=B?"":"none";let{closeButtonWrapper:Ie}=xe;Ie&&!Ie.classList.contains("tvw-absolute")&&(B?Ie.classList.remove("tvw-ml-auto"):Ie.classList.add("tvw-ml-auto"))}}let le=((Lo=e.layout)==null?void 0:Lo.showHeader)!==!1;Se&&(Se.style.display=le?"":"none");let de=((Wo=e.layout)==null?void 0:Wo.showFooter)!==!1;Je&&(Je.style.display=de?"":"none"),y!==Y?y?ot(A,"auto"):(P=!0,Tn()):A!==H&&ot(A,"auto"),H=A,Y=y,Cn(),vs(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&T&&En(ze,T.getMessages(),z);let J=(Po=e.launcher)!=null?Po:{},E=(Ro=J.headerIconHidden)!=null?Ro:!1,ce=(Bo=(Ho=e.layout)==null?void 0:Ho.header)==null?void 0:Bo.showIcon,ge=E||ce===!1,Oe=J.headerIconName,me=(Fo=J.headerIconSize)!=null?Fo:"48px";if(Pe){let B=He.querySelector(".tvw-border-b-cw-divider"),Ie=B==null?void 0:B.querySelector(".tvw-flex-col");if(ge)Pe.style.display="none",B&&Ie&&!B.contains(Ie)&&B.insertBefore(Ie,B.firstChild);else{if(Pe.style.display="",Pe.style.height=me,Pe.style.width=me,B&&Ie&&(B.contains(Pe)?Pe.nextSibling!==Ie&&(Pe.remove(),B.insertBefore(Pe,Ie)):B.insertBefore(Pe,Ie)),Oe){let be=parseFloat(me)||24,Be=ie(Oe,be*.6,"#ffffff",2);Be?Pe.replaceChildren(Be):Pe.textContent=($o=J.agentIconText)!=null?$o:"\u{1F4AC}"}else if(J.iconUrl){let be=Pe.querySelector("img");if(be)be.src=J.iconUrl,be.style.height=me,be.style.width=me;else{let Be=document.createElement("img");Be.src=J.iconUrl,Be.alt="",Be.className="tvw-rounded-xl tvw-object-cover",Be.style.height=me,Be.style.width=me,Pe.replaceChildren(Be)}}else{let be=Pe.querySelector("svg"),Be=Pe.querySelector("img");(be||Be)&&Pe.replaceChildren(),Pe.textContent=(No=J.agentIconText)!=null?No:"\u{1F4AC}"}let tt=Pe.querySelector("img");tt&&(tt.style.height=me,tt.style.width=me)}}let Ye=(Do=(Oo=e.layout)==null?void 0:Oo.header)==null?void 0:Do.showTitle,ut=(_o=(jo=e.layout)==null?void 0:jo.header)==null?void 0:_o.showSubtitle;if(xt&&(xt.style.display=Ye===!1?"none":""),ve&&(ve.style.display=ut===!1?"none":""),te){((qo=(Uo=e.layout)==null?void 0:Uo.header)==null?void 0:qo.showCloseButton)===!1?te.style.display="none":te.style.display="";let Ie=(Vo=J.closeButtonSize)!=null?Vo:"32px",tt=(zo=J.closeButtonPlacement)!=null?zo:"inline";te.style.height=Ie,te.style.width=Ie;let{closeButtonWrapper:be}=xe,Be=tt==="top-right",yt=be==null?void 0:be.classList.contains("tvw-absolute");if(be&&Be!==yt)if(be.remove(),Be)be.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",He.style.position="relative",He.appendChild(be);else{let Le=(Ko=(Jo=J.clearChat)==null?void 0:Jo.placement)!=null?Ko:"inline",Et=(Xo=(Yo=J.clearChat)==null?void 0:Yo.enabled)!=null?Xo:!0;be.className=Et&&Le==="inline"?"":"tvw-ml-auto";let Ut=He.querySelector(".tvw-border-b-cw-divider");Ut&&Ut.appendChild(be)}if(J.closeButtonColor?(te.style.color=J.closeButtonColor,te.classList.remove("tvw-text-cw-muted")):(te.style.color="",te.classList.add("tvw-text-cw-muted")),J.closeButtonBackgroundColor?(te.style.backgroundColor=J.closeButtonBackgroundColor,te.classList.remove("hover:tvw-bg-gray-100")):(te.style.backgroundColor="",te.classList.add("hover:tvw-bg-gray-100")),J.closeButtonBorderWidth||J.closeButtonBorderColor){let Le=J.closeButtonBorderWidth||"0px",Et=J.closeButtonBorderColor||"transparent";te.style.border=`${Le} solid ${Et}`,te.classList.remove("tvw-border-none")}else te.style.border="",te.classList.add("tvw-border-none");J.closeButtonBorderRadius?(te.style.borderRadius=J.closeButtonBorderRadius,te.classList.remove("tvw-rounded-full")):(te.style.borderRadius="",te.classList.add("tvw-rounded-full")),J.closeButtonPaddingX?(te.style.paddingLeft=J.closeButtonPaddingX,te.style.paddingRight=J.closeButtonPaddingX):(te.style.paddingLeft="",te.style.paddingRight=""),J.closeButtonPaddingY?(te.style.paddingTop=J.closeButtonPaddingY,te.style.paddingBottom=J.closeButtonPaddingY):(te.style.paddingTop="",te.style.paddingBottom="");let Pt=(Go=J.closeButtonIconName)!=null?Go:"x",zt=(Zo=J.closeButtonIconText)!=null?Zo:"\xD7";te.innerHTML="";let Nt=ie(Pt,"20px",J.closeButtonColor||"",2);Nt?te.appendChild(Nt):te.textContent=zt;let pt=(Qo=J.closeButtonTooltipText)!=null?Qo:"Close chat",Jt=(ei=J.closeButtonShowTooltip)!=null?ei:!0;if(te.setAttribute("aria-label",pt),be&&(be._cleanupTooltip&&(be._cleanupTooltip(),delete be._cleanupTooltip),Jt&&pt)){let Le=null,Et=()=>{if(Le||!te)return;Le=g("div","tvw-clear-chat-tooltip"),Le.textContent=pt;let Cs=g("div");Cs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(Cs);let Ln=te.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Ln.left+Ln.width/2}px`,Le.style.top=`${Ln.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Ut=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};be.addEventListener("mouseenter",Et),be.addEventListener("mouseleave",Ut),te.addEventListener("focus",Et),te.addEventListener("blur",Ut),be._cleanupTooltip=()=>{Ut(),be&&(be.removeEventListener("mouseenter",Et),be.removeEventListener("mouseleave",Ut)),te&&(te.removeEventListener("focus",Et),te.removeEventListener("blur",Ut))}}}let{clearChatButton:K,clearChatButtonWrapper:Ue}=xe;if(K){let B=(ti=J.clearChat)!=null?ti:{},Ie=(ni=B.enabled)!=null?ni:!0,tt=(ri=(si=e.layout)==null?void 0:si.header)==null?void 0:ri.showClearChat,be=tt!==void 0?tt:Ie,Be=(oi=B.placement)!=null?oi:"inline";if(Ue){Ue.style.display=be?"":"none";let{closeButtonWrapper:yt}=xe;yt&&!yt.classList.contains("tvw-absolute")&&(be?yt.classList.remove("tvw-ml-auto"):yt.classList.add("tvw-ml-auto"));let Pt=Be==="top-right",zt=Ue.classList.contains("tvw-absolute");if(Pt!==zt&&be){if(Ue.remove(),Pt)Ue.className="tvw-absolute tvw-top-4 tvw-z-50",Ue.style.right="48px",He.style.position="relative",He.appendChild(Ue);else{Ue.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Ue.style.right="";let pt=He.querySelector(".tvw-border-b-cw-divider"),Jt=xe.closeButtonWrapper;pt&&Jt&&Jt.parentElement===pt?pt.insertBefore(Ue,Jt):pt&&pt.appendChild(Ue)}let Nt=xe.closeButtonWrapper;Nt&&!Nt.classList.contains("tvw-absolute")&&(Pt?Nt.classList.add("tvw-ml-auto"):Nt.classList.remove("tvw-ml-auto"))}}if(be){let yt=(ii=B.size)!=null?ii:"32px";K.style.height=yt,K.style.width=yt;let Pt=(ai=B.iconName)!=null?ai:"refresh-cw",zt=(li=B.iconColor)!=null?li:"";K.innerHTML="";let Nt=ie(Pt,"20px",zt||"",2);if(Nt&&K.appendChild(Nt),zt?(K.style.color=zt,K.classList.remove("tvw-text-cw-muted")):(K.style.color="",K.classList.add("tvw-text-cw-muted")),B.backgroundColor?(K.style.backgroundColor=B.backgroundColor,K.classList.remove("hover:tvw-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:tvw-bg-gray-100")),B.borderWidth||B.borderColor){let Le=B.borderWidth||"0px",Et=B.borderColor||"transparent";K.style.border=`${Le} solid ${Et}`,K.classList.remove("tvw-border-none")}else K.style.border="",K.classList.add("tvw-border-none");B.borderRadius?(K.style.borderRadius=B.borderRadius,K.classList.remove("tvw-rounded-full")):(K.style.borderRadius="",K.classList.add("tvw-rounded-full")),B.paddingX?(K.style.paddingLeft=B.paddingX,K.style.paddingRight=B.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),B.paddingY?(K.style.paddingTop=B.paddingY,K.style.paddingBottom=B.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let pt=(ci=B.tooltipText)!=null?ci:"Clear chat",Jt=(di=B.showTooltip)!=null?di:!0;if(K.setAttribute("aria-label",pt),Ue&&(Ue._cleanupTooltip&&(Ue._cleanupTooltip(),delete Ue._cleanupTooltip),Jt&&pt)){let Le=null,Et=()=>{if(Le||!K)return;Le=g("div","tvw-clear-chat-tooltip"),Le.textContent=pt;let Cs=g("div");Cs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(Cs);let Ln=K.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Ln.left+Ln.width/2}px`,Le.style.top=`${Ln.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Ut=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};Ue.addEventListener("mouseenter",Et),Ue.addEventListener("mouseleave",Ut),K.addEventListener("focus",Et),K.addEventListener("blur",Ut),Ue._cleanupTooltip=()=>{Ut(),Ue&&(Ue.removeEventListener("mouseenter",Et),Ue.removeEventListener("mouseleave",Ut)),K&&(K.removeEventListener("focus",Et),K.removeEventListener("blur",Ut))}}}}let on=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Ws],_t=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Nn.message,Nn.messageAndClick];C=Ps({parsers:on,handlers:_t,getSessionMetadata:v,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),z=Ra(e,C,ue),T.updateConfig(e),En(ze,T.getMessages(),z),wn.render(e.suggestionChips,T,he,void 0,e.suggestionChipsConfig),us(),Un(T.isStreaming());let nn=((ui=e.voiceRecognition)==null?void 0:ui.enabled)===!0,In=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),zs=((gi=(pi=e.voiceRecognition)==null?void 0:pi.provider)==null?void 0:gi.type)==="runtype";if(nn&&(In||zs))if(!I||!nt){let B=js(e.voiceRecognition,e.sendButton);B&&(I=B.micButton,nt=B.micButtonWrapper,qt.insertBefore(nt,ct),I.addEventListener("click",Jn),I.disabled=T.isStreaming())}else{let B=(hi=e.voiceRecognition)!=null?hi:{},Ie=(mi=e.sendButton)!=null?mi:{},tt=(fi=B.iconName)!=null?fi:"mic",be=(vi=Ie.size)!=null?vi:"40px",Be=(wi=B.iconSize)!=null?wi:be,yt=parseFloat(Be)||24;I.style.width=Be,I.style.height=Be,I.style.minWidth=Be,I.style.minHeight=Be;let Pt=(bi=(yi=B.iconColor)!=null?yi:Ie.textColor)!=null?bi:"currentColor";I.innerHTML="";let zt=ie(tt,yt,Pt,2);zt?I.appendChild(zt):I.textContent="\u{1F3A4}";let Nt=(Ci=B.backgroundColor)!=null?Ci:Ie.backgroundColor;Nt?(I.style.backgroundColor=Nt,I.classList.remove("tvw-bg-cw-primary")):(I.style.backgroundColor="",I.classList.add("tvw-bg-cw-primary")),Pt?(I.style.color=Pt,I.classList.remove("tvw-text-white")):!Pt&&!Ie.textColor&&(I.style.color="",I.classList.add("tvw-text-white")),B.borderWidth?(I.style.borderWidth=B.borderWidth,I.style.borderStyle="solid"):(I.style.borderWidth="",I.style.borderStyle=""),B.borderColor?I.style.borderColor=B.borderColor:I.style.borderColor="",B.paddingX?(I.style.paddingLeft=B.paddingX,I.style.paddingRight=B.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),B.paddingY?(I.style.paddingTop=B.paddingY,I.style.paddingBottom=B.paddingY):(I.style.paddingTop="",I.style.paddingBottom="");let pt=nt==null?void 0:nt.querySelector(".tvw-send-button-tooltip"),Jt=(xi=B.tooltipText)!=null?xi:"Start voice recognition";if(((Si=B.showTooltip)!=null?Si:!1)&&Jt)if(pt)pt.textContent=Jt,pt.style.display="";else{let Et=document.createElement("div");Et.className="tvw-send-button-tooltip",Et.textContent=Jt,nt==null||nt.insertBefore(Et,I)}else pt&&(pt.style.display="none");nt.style.display="",I.disabled=T.isStreaming()}else I&&nt&&(nt.style.display="none",((Ei=(Ai=e.voiceRecognition)==null?void 0:Ai.provider)==null?void 0:Ei.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Vt&&tn());if(((Ti=e.attachments)==null?void 0:Ti.enabled)===!0)if(!Q||!O){let B=(Mi=e.attachments)!=null?Mi:{},tt=(Ii=((ki=e.sendButton)!=null?ki:{}).size)!=null?Ii:"40px";Ne||(Ne=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),Ne.style.display="none",bt.insertBefore(Ne,he)),re||(re=document.createElement("input"),re.type="file",re.accept=((Li=B.allowedTypes)!=null?Li:xn).join(","),re.multiple=((Wi=B.maxFiles)!=null?Wi:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),bt.insertBefore(re,he)),Q=g("div","tvw-send-button-wrapper"),O=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),O.type="button",O.setAttribute("aria-label",(Pi=B.buttonTooltipText)!=null?Pi:"Attach file");let be=(Ri=B.buttonIconName)!=null?Ri:"paperclip",Be=tt,yt=parseFloat(Be)||40,Pt=Math.round(yt*.6);O.style.width=Be,O.style.height=Be,O.style.minWidth=Be,O.style.minHeight=Be,O.style.fontSize="18px",O.style.lineHeight="1",O.style.backgroundColor="transparent",O.style.color="var(--cw-primary, #111827)",O.style.border="none",O.style.borderRadius="6px",O.style.transition="background-color 0.15s ease",O.addEventListener("mouseenter",()=>{O.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),O.addEventListener("mouseleave",()=>{O.style.backgroundColor="transparent"});let zt=ie(be,Pt,"currentColor",1.5);zt?O.appendChild(zt):O.textContent="\u{1F4CE}",O.addEventListener("click",Jt=>{Jt.preventDefault(),re==null||re.click()}),Q.appendChild(O);let Nt=(Hi=B.buttonTooltipText)!=null?Hi:"Attach file",pt=g("div","tvw-send-button-tooltip");pt.textContent=Nt,Q.appendChild(pt),It.append(Q),!oe&&re&&Ne&&(oe=Bn.fromConfig(B),oe.setPreviewsContainer(Ne),re.addEventListener("change",async()=>{oe&&(re!=null&&re.files)&&(await oe.handleFileSelect(re.files),re.value="")}))}else{Q.style.display="";let B=(Bi=e.attachments)!=null?Bi:{};re&&(re.accept=((Fi=B.allowedTypes)!=null?Fi:xn).join(","),re.multiple=(($i=B.maxFiles)!=null?$i:4)>1),oe&&oe.updateConfig({allowedTypes:B.allowedTypes,maxFileSize:B.maxFileSize,maxFiles:B.maxFiles})}else Q&&(Q.style.display="none"),oe&&oe.clearAttachments();let mt=(Ni=e.sendButton)!=null?Ni:{},Kn=(Oi=mt.useIcon)!=null?Oi:!1,Yn=(Di=mt.iconText)!=null?Di:"\u2191",uo=mt.iconName,Lr=(ji=mt.tooltipText)!=null?ji:"Send message",_a=(_i=mt.showTooltip)!=null?_i:!1,ws=(Ui=mt.size)!=null?Ui:"40px",Js=mt.backgroundColor,an=mt.textColor;if(Kn){if(Z.style.width=ws,Z.style.height=ws,Z.style.minWidth=ws,Z.style.minHeight=ws,Z.style.fontSize="18px",Z.style.lineHeight="1",Z.innerHTML="",uo){let B=parseFloat(ws)||24,Ie=an&&typeof an=="string"&&an.trim()?an.trim():"currentColor",tt=ie(uo,B,Ie,2);tt?(Z.appendChild(tt),Z.style.color=Ie):(Z.textContent=Yn,an?Z.style.color=an:Z.classList.add("tvw-text-white"))}else Z.textContent=Yn,an?Z.style.color=an:Z.classList.add("tvw-text-white");Z.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Js?(Z.style.backgroundColor=Js,Z.classList.remove("tvw-bg-cw-primary")):Z.classList.add("tvw-bg-cw-primary")}else Z.textContent=(Vi=(qi=e.copy)==null?void 0:qi.sendButtonLabel)!=null?Vi:"Send",Z.style.width="",Z.style.height="",Z.style.minWidth="",Z.style.minHeight="",Z.style.fontSize="",Z.style.lineHeight="",Z.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",Js?(Z.style.backgroundColor=Js,Z.classList.remove("tvw-bg-cw-accent")):Z.classList.add("tvw-bg-cw-accent"),an?Z.style.color=an:Z.classList.add("tvw-text-white");mt.borderWidth?(Z.style.borderWidth=mt.borderWidth,Z.style.borderStyle="solid"):(Z.style.borderWidth="",Z.style.borderStyle=""),mt.borderColor?Z.style.borderColor=mt.borderColor:Z.style.borderColor="",mt.paddingX?(Z.style.paddingLeft=mt.paddingX,Z.style.paddingRight=mt.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),mt.paddingY?(Z.style.paddingTop=mt.paddingY,Z.style.paddingBottom=mt.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let ys=ct==null?void 0:ct.querySelector(".tvw-send-button-tooltip");if(_a&&Lr)if(ys)ys.textContent=Lr,ys.style.display="";else{let B=document.createElement("div");B.className="tvw-send-button-tooltip",B.textContent=Lr,ct==null||ct.insertBefore(B,Z)}else ys&&(ys.style.display="none");let bs=(zi=e.statusIndicator)!=null?zi:{},Ua=(Ji=bs.visible)!=null?Ji:!0;if(kt.style.display=Ua?"":"none",T){let B=T.getStatus(),Ie=tt=>{var be,Be,yt,Pt;return tt==="idle"?(be=bs.idleText)!=null?be:Rt.idle:tt==="connecting"?(Be=bs.connectingText)!=null?Be:Rt.connecting:tt==="connected"?(yt=bs.connectedText)!=null?yt:Rt.connected:tt==="error"?(Pt=bs.errorText)!=null?Pt:Rt.error:Rt[tt]};kt.textContent=Ie(B)}},open(){y&&ot(!0,"api")},close(){y&&ot(!1,"api")},toggle(){y&&ot(!P,"api")},clearChat(){T.clearMessages();try{localStorage.removeItem(is),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${is}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==is)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.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),i!=null&&i.clear)try{let u=i.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)}a={},C.syncFromMetadata(),N==null||N.clear(),ee==null||ee.update()},setMessage(l){return!he||T.isStreaming()?!1:(!P&&y&&ot(!0,"system"),he.value=l,he.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(T.isStreaming())return!1;let u=(l==null?void 0:l.trim())||he.value.trim();return u?(!P&&y&&ot(!0,"system"),he.value="",he.style.height="auto",T.sendMessage(u),!0):!1},startVoiceRecognition(){var u,h;return T.isStreaming()?!1:((h=(u=e.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype"?(T.isVoiceActive()||(!P&&y&&ot(!0,"system"),Ae.manuallyDeactivated=!1,Dt(),T.toggleVoice().then(()=>{Ae.active=T.isVoiceActive(),Xt("user"),T.isVoiceActive()&&bn()})),!0):Vt?!0:ms()?(!P&&y&&ot(!0,"system"),Ae.manuallyDeactivated=!1,Dt(),Mn("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{Ae.active=!1,Ae.manuallyDeactivated=!0,Dt(),Xt("user"),Gt()}),!0):!1:Vt?(Ae.manuallyDeactivated=!0,Dt(),tn("user"),!0):!1},injectMessage(l){return!P&&y&&ot(!0,"system"),T.injectMessage(l)},injectAssistantMessage(l){!P&&y&&ot(!0,"system");let u=T.injectAssistantMessage(l);return L&&(L=!1,F&&(clearTimeout(F),F=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),u},injectUserMessage(l){return!P&&y&&ot(!0,"system"),T.injectUserMessage(l)},injectSystemMessage(l){return!P&&y&&ot(!0,"system"),T.injectSystemMessage(l)},injectMessageBatch(l){return!P&&y&&ot(!0,"system"),T.injectMessageBatch(l)},injectTestMessage(l){!P&&y&&ot(!0,"system"),T.injectTestEvent(l)},async connectStream(l,u){return T.connectStream(l,u)},__pushEventStreamEvent(l){N&&N.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!_||!N||Ge()},hideEventStream(){fe&&pe()},isEventStreamVisible(){return fe},focusInput(){return y&&!P||!he?!1:(he.focus(),!0)},async resolveApproval(l,u){let S=T.getMessages().find(W=>{var M;return W.variant==="approval"&&((M=W.approval)==null?void 0:M.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);return T.resolveApproval(S.approval,u)},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){p(l)},on(l,u){return s.on(l,u)},off(l,u){s.off(l,u)},isOpen(){return y&&P},isVoiceActive(){return Ae.active},getState(){return{open:y&&P,launcherEnabled:y,voiceActive:Ae.active,streaming:T.isStreaming()}},showCSATFeedback(l){!P&&y&&ot(!0,"system");let u=ze.querySelector(".tvw-feedback-container");u&&u.remove();let h=vr({onSubmit:async(S,W)=>{var M;T.isClientTokenMode()&&await T.submitCSATFeedback(S,W),(M=l==null?void 0:l.onSubmit)==null||M.call(l,S,W)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!P&&y&&ot(!0,"system");let u=ze.querySelector(".tvw-feedback-container");u&&u.remove();let h=wr({onSubmit:async(S,W)=>{var M;T.isClientTokenMode()&&await T.submitNPSFeedback(S,W),(M=l==null?void 0:l.onSubmit)==null||M.call(l,S,W)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return T.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return T.submitNPSFeedback(l,u)},destroy(){Ze.forEach(l=>l()),je.remove(),Qe==null||Qe.destroy(),et==null||et.remove(),rn&&te.removeEventListener("click",rn)}};if((((ro=r==null?void 0:r.debugTools)!=null?ro:!1)||!!e.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:h=>h?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Ze.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),u=h=>{let S=h.detail;(!(S!=null&&S.instanceId)||S.instanceId===l)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",u),Ze.push(()=>{window.removeEventListener("persona:focusInput",u)}),_){let h=W=>{let M=W.detail;(!(M!=null&&M.instanceId)||M.instanceId===l)&&Lt.showEventStream()},S=W=>{let M=W.detail;(!(M!=null&&M.instanceId)||M.instanceId===l)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",h),window.addEventListener("persona:hideEventStream",S),Ze.push(()=>{window.removeEventListener("persona:showEventStream",h),window.removeEventListener("persona:hideEventStream",S)})}}let $t=jl(e.persistState);if($t&&y){let l=_l($t.storage),u=`${$t.keyPrefix}widget-open`,h=`${$t.keyPrefix}widget-voice`,S=`${$t.keyPrefix}widget-voice-mode`;if(l){let W=((oo=$t.persist)==null?void 0:oo.openState)&&l.getItem(u)==="true",M=((io=$t.persist)==null?void 0:io.voiceState)&&l.getItem(h)==="true",j=((ao=$t.persist)==null?void 0:ao.voiceState)&&l.getItem(S)==="true";if(W&&setTimeout(()=>{Lt.open(),setTimeout(()=>{var le;if(M||j)Lt.startVoiceRecognition();else if((le=$t.persist)!=null&&le.focusInput){let de=n.querySelector("textarea");de&&de.focus()}},100)},0),(lo=$t.persist)!=null&&lo.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(co=$t.persist)!=null&&co.voiceState&&(s.on("voice:state",le=>{l.setItem(h,le.active?"true":"false")}),s.on("user:message",le=>{l.setItem(S,le.viaVoice?"true":"false")})),$t.clearOnChatClear){let le=()=>{l.removeItem(u),l.removeItem(h),l.removeItem(S)},de=()=>le();window.addEventListener("persona:clear-chat",de),Ze.push(()=>{window.removeEventListener("persona:clear-chat",de)})}}}return Lt};var Zr={},Ul=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let t=document.querySelector(n);if(!t)throw new Error(`Chat widget target "${n}" was not found`);return t}return n},ql=()=>{try{if(typeof Zr!="undefined"&&Zr.url)return new URL("../widget.css",Zr.url).href}catch{}return null},Ha=n=>{let t=ql(),r=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-persona]"))return;let e=document.head.querySelector("link[data-persona]");if(!e)return;let o=e.cloneNode(!0);n.insertBefore(o,n.firstChild)};if(n instanceof ShadowRoot)if(t){let e=document.createElement("link");e.rel="stylesheet",e.href=t,e.setAttribute("data-persona","true"),n.insertBefore(e,n.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&t){let o=document.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},Qr=n=>{var c,v,p,m;let t=Ul(n.target),r=document.createElement("div");r.className="persona-host";let e=(p=(v=(c=n.config)==null?void 0:c.launcher)==null?void 0:v.enabled)!=null?p:!0;e||(r.style.height="100%"),t.appendChild(r);let o=n.useShadowDom===!0,s,i;if(o){let w=r.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),Ha(w)}else i=r,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),Ha(r);t.id&&s.setAttribute("data-persona-instance",t.id);let a=yr(s,n.config,{debugTools:n.debugTools});(m=n.onReady)==null||m.call(n);let d={...a,host:r,destroy(){a.destroy(),r.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=d),d};var Ba={name:"@runtypelabs/persona",version:"1.48.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./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:{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"},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 On=Ba.version;function fn(n){if(n!==void 0)return typeof n=="string"?n:Array.isArray(n)?`[${n.map(t=>t.toString()).join(", ")}]`:n.toString()}function zl(n){if(n)return{getHeaders:fn(n.getHeaders),onFeedback:fn(n.onFeedback),onCopy:fn(n.onCopy),requestMiddleware:fn(n.requestMiddleware),actionHandlers:fn(n.actionHandlers),actionParsers:fn(n.actionParsers),postprocessMessage:fn(n.postprocessMessage),contextProviders:fn(n.contextProviders),streamParser:fn(n.streamParser)}}var Fa=`({ text, message }: any) => {
95
+ `}if(!A&&!l){let Tn="max-height: -moz-available !important; max-height: stretch !important;",Yt=u?"":"padding-top: 1.25em !important;";le.style.cssText+=Tn+Yt}};_n(),On(e,r),Js(e,r),Ks(e,r);let xt=[];gn&&xt.push(()=>{gn==null||gn.disconnect(),gn=null}),xt.push(()=>{tn==null||tn(),tn=null,ir(),dt&&(dt.remove(),dt=null),Ge==null||Ge.element.style.removeProperty("width"),Ge==null||Ge.element.style.removeProperty("maxWidth")}),Le&&xt.push(()=>{he!==null&&(cancelAnimationFrame(he),he=null),j==null||j.destroy(),j=null,V==null||V.destroy(),V=null,ee=null});let hn=null,Rr=()=>{hn&&(hn(),hn=null),r.colorScheme==="auto"&&(hn=Us(()=>{On(e,r)}))};Rr(),xt.push(()=>{hn&&(hn(),hn=null)});let Hn=zl(Ke),yn=null,W,Bn=!1,$n=$l(),Hr=0,Cn=!0,jn=0,Br=0,wn=null,Sn=!1,lr=0,cr=!1,ps=125,us=2e3,gs=5,$r=50,dr=new Map,qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Fr=(ua=(pa=r.voiceRecognition)==null?void 0:pa.autoResume)!=null?ua:!1,nn=l=>{s.emit("voice:state",{active:qe.active,source:l,timestamp:Date.now()})},zt=()=>{p(l=>({...l,voiceState:{active:qe.active,timestamp:Date.now(),manuallyDeactivated:qe.manuallyDeactivated}}))},ms=()=>{var A,L;if(((A=r.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=jo(i.voiceState),u=!!l.active,h=Number((L=l.timestamp)!=null?L:0);qe.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<Jd&&setTimeout(()=>{var $,R;qe.active||(qe.manuallyDeactivated=!1,((R=($=r.voiceRecognition)==null?void 0:$.provider)==null?void 0:R.type)==="runtype"?W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),nn("restore"),W.isVoiceActive()&&Fn()}):Un("restore"))},1e3)},fs=()=>W?ic(W.getMessages()).filter(l=>!l.__skipPersist):[];function Nr(l){if(!(a!=null&&a.save))return;let h={messages:l?ic(l):W?fs():[],metadata:i};try{let A=a.save(h);A instanceof Promise&&A.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let Vn=(l=!1)=>{if(!Cn)return;let u=Date.now();Sn&&u<lr&&!l||(Sn&&u>=lr&&(Sn=!1),!(!l&&!Bn)&&(u-Br<ps||(Br=u,wn&&cancelAnimationFrame(wn),wn=requestAnimationFrame(()=>{Sn||!Cn||(cr=!0,oe.scrollTop=oe.scrollHeight,jn=oe.scrollTop,requestAnimationFrame(()=>{cr=!1}),wn=null)}))))},An=null,hs=()=>le.querySelector("#persona-scroll-container")||oe,ys=(l,u=500)=>{let h=l.scrollTop,A=l.clientHeight,L=l.scrollHeight,$=L-h;if(h+A>=L-2||Math.abs($)<5)return;An!==null&&(cancelAnimationFrame(An),An=null);let D=performance.now(),B=ge=>1-Math.pow(1-ge,3),me=ge=>{let Me=l.scrollHeight;Me!==L&&(L=Me,$=L-h);let je=ge-D,xe=Math.min(je/u,1),P=B(xe),ke=h+$*P;l.scrollTop=ke,xe<1?An=requestAnimationFrame(me):(l.scrollTop=l.scrollHeight,An=null)};An=requestAnimationFrame(me)},bs=l=>{let u=new Map;l.forEach(h=>{let A=dr.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!A&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(A!=null&&A.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(A?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),dr.clear(),u.forEach((h,A)=>{dr.set(A,h)})},qn=(l,u,h)=>{var ge,Me,je,xe;let A=document.createElement("div"),$=(()=>{var ke;let P=o.find(Ae=>Ae.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((ke=r.loadingIndicator)!=null&&ke.render)return r.loadingIndicator.render})(),R=new Set;u.forEach(P=>{var St,ct;R.add(P.id);let ke=Bl(P,Hr),Ae=Fl($n,P.id,ke);if(Ae){A.appendChild(Ae.cloneNode(!0));return}let F=null,We=o.find(ot=>!!(P.variant==="reasoning"&&ot.renderReasoning||P.variant==="tool"&&ot.renderToolCall||P.variant==="approval"&&ot.renderApproval||!P.variant&&ot.renderMessage)),st=(St=r.layout)==null?void 0:St.messages;if(We)if(P.variant==="reasoning"&&P.reasoning&&We.renderReasoning){if(!J)return;F=We.renderReasoning({message:P,defaultRenderer:()=>Wo(P),config:r})}else if(P.variant==="tool"&&P.toolCall&&We.renderToolCall){if(!pe)return;F=We.renderToolCall({message:P,defaultRenderer:()=>Ro(P,r),config:r})}else if(P.variant==="approval"&&P.approval&&We.renderApproval){if(r.approval===!1)return;F=We.renderApproval({message:P,defaultRenderer:()=>Ho(P,r),config:r})}else We.renderMessage&&(F=We.renderMessage({message:P,defaultRenderer:()=>{let ot=Ar(P,h,st,r.messageActions,lt,{loadingIndicatorRenderer:$,widgetConfig:r});return P.role!=="user"&&Fo(ot,P,r,W),ot},config:r}));if(!F&&P.role==="assistant"&&!P.variant&&r.enableComponentStreaming!==!1&&Qs(P)){let Kt=eo(P);if(Kt){let ve=Zs(Kt,{config:r,message:P,transform:h});if(ve)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-${P.id}`,$t.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let sn=document.createElement("div");sn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",sn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),$t.appendChild(sn)}$t.appendChild(ve),F=$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-${P.id}`,$t.setAttribute("data-message-id",P.id),$t.setAttribute("data-persona-component-directive","true"),P.content&&P.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:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),$t.appendChild(sn)}$t.appendChild(ve),F=$t}}}if(!F)if(P.variant==="reasoning"&&P.reasoning){if(!J)return;F=Wo(P)}else if(P.variant==="tool"&&P.toolCall){if(!pe)return;F=Ro(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;F=Ho(P,r)}else{let ot=(ct=r.layout)==null?void 0:ct.messages;ot!=null&&ot.renderUserMessage&&P.role==="user"?F=ot.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):ot!=null&&ot.renderAssistantMessage&&P.role==="assistant"?F=ot.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):F=Ar(P,h,ot,r.messageActions,lt,{loadingIndicatorRenderer:$,widgetConfig:r}),P.role!=="user"&&F&&Fo(F,P,r,W)}let Ze=document.createElement("div");Ze.className="persona-flex",Ze.id=`wrapper-${P.id}`,Ze.setAttribute("data-wrapper-id",P.id),P.role==="user"&&Ze.classList.add("persona-justify-end"),(F==null?void 0:F.getAttribute("data-persona-component-directive"))==="true"&&Ze.classList.add("persona-w-full"),Ze.appendChild(F),Nl($n,P.id,ke,Ze),A.appendChild(Ze)}),Ol($n,R);let D=u.some(P=>P.role==="assistant"&&P.streaming),B=u[u.length-1],me=(B==null?void 0:B.role)==="assistant"&&!B.streaming&&B.variant!=="approval";if(Bn&&u.some(P=>P.role==="user")&&!D&&!me){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:rr},ke=o.find(F=>F.renderLoadingIndicator),Ae=null;if(ke!=null&&ke.renderLoadingIndicator&&(Ae=ke.renderLoadingIndicator(P)),Ae===null&&((ge=r.loadingIndicator)!=null&&ge.render)&&(Ae=r.loadingIndicator.render(P)),Ae===null&&(Ae=rr()),Ae){let F=document.createElement("div"),We=((Me=r.loadingIndicator)==null?void 0:Me.showBubble)!==!1;F.className=We?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-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(" "),F.setAttribute("data-typing-indicator","true"),F.appendChild(Ae);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-typing-indicator",st.setAttribute("data-wrapper-id","typing-indicator"),st.appendChild(F),A.appendChild(st)}}if(!Bn&&u.length>0){let P=u[u.length-1],ke={config:r,lastMessage:P,messageCount:u.length},Ae=o.find(We=>We.renderIdleIndicator),F=null;if(Ae!=null&&Ae.renderIdleIndicator&&(F=Ae.renderIdleIndicator(ke)),F===null&&((je=r.loadingIndicator)!=null&&je.renderIdle)&&(F=r.loadingIndicator.renderIdle(ke)),F){let We=document.createElement("div"),st=((xe=r.loadingIndicator)==null?void 0:xe.showBubble)!==!1;We.className=st?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),We.setAttribute("data-idle-indicator","true"),We.appendChild(F);let Ze=document.createElement("div");Ze.className="persona-flex",Ze.id="wrapper-idle-indicator",Ze.setAttribute("data-wrapper-id","idle-indicator"),Ze.appendChild(We),A.appendChild(Ze)}}Hl(l,A),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let P=hs();ys(P)})})},pr=()=>{if(!v)return;let l=jt(r);S?(le.style.display=l?"flex":"",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),se.classList.remove("persona-scale-95","persona-opacity-0"),se.classList.add("persona-scale-100","persona-opacity-100"),we?we.element.style.display="none":Ne&&(Ne.style.display="none")):(l?(le.style.display="none",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(le.style.display="",le.classList.add("persona-pointer-events-none","persona-opacity-0"),se.classList.remove("persona-scale-100","persona-opacity-100"),se.classList.add("persona-scale-95","persona-opacity-0")),we?we.element.style.display="":Ne&&(Ne.style.display=""))},ht=(l,u="user")=>{if(!v||S===l)return;let h=S;S=l,pr(),S&&(vt(),Vn(!0));let A={open:S,source:u,timestamp:Date.now()};S&&!h?s.emit("widget:opened",A):!S&&h&&s.emit("widget:closed",A),s.emit("widget:state",{open:S,launcherEnabled:v,voiceActive:qe.active,streaming:W.isStreaming()})},ur=l=>{X.disabled=l,H&&(H.disabled=l),Hn.buttons.forEach(u=>{u.disabled=l}),Xe.dataset.personaComposerStreaming=l?"true":"false",Xe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},gr=()=>{qe.active||te&&te.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>gr(),200)});let Or=()=>{var L,$,R,D,B,me,ge,Me,je,xe,P,ke,Ae,F;Vt.textContent=($=(L=r.copy)==null?void 0:L.welcomeTitle)!=null?$:"Hello \u{1F44B}",Dt.textContent=(D=(R=r.copy)==null?void 0:R.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",te.placeholder=(me=(B=r.copy)==null?void 0:B.inputPlaceholder)!=null?me:"How can I help...",(Me=(ge=r.sendButton)==null?void 0:ge.useIcon)!=null&&Me||(X.textContent=(xe=(je=r.copy)==null?void 0:je.sendButtonLabel)!=null?xe:"Send");let u=(ke=(P=r.theme)==null?void 0:P.inputFontFamily)!=null?ke:"sans-serif",h=(F=(Ae=r.theme)==null?void 0:Ae.inputFontWeight)!=null?F:"400",A=We=>{switch(We){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=A(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}))}}),W=new xr(r,{onMessagesChanged(l){qn(Ee,l,re),W&&(l.some(L=>L.role==="user")?Hn.render([],W,te,l):Hn.render(r.suggestionChips,W,te,l,r.suggestionChipsConfig)),Vn(!Bn),bs(l);let u=[...l].reverse().find(A=>A.role==="user"),h=qe.lastUserMessageId;u&&u.id!==h&&(qe.lastUserMessageId=u.id,s.emit("user:message",u)),qe.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Nr(l)},onStatusChanged(l){var A;let u=(A=r.statusIndicator)!=null?A:{},h=L=>{var $,R,D,B;return L==="idle"?($=u.idleText)!=null?$:_t.idle:L==="connecting"?(R=u.connectingText)!=null?R:_t.connecting:L==="connected"?(D=u.connectedText)!=null?D:_t.connected:L==="error"?(B=u.errorText)!=null?B:_t.error:_t[L]};et.textContent=h(l)},onStreamingChanged(l){Bn=l,ur(l),W&&qn(Ee,W.getMessages(),re),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":cn(),vs();break;case"speaking":cn(),Cs();break;default:l==="idle"&&W.isBargeInActive()?(cn(),Fn(),H==null||H.setAttribute("aria-label","End voice session")):(qe.active=!1,cn(),nn("system"),zt());break}},onArtifactsState(l){Rn=l,fn()}}),Pr.current=W,((ma=(ga=r.voiceRecognition)==null?void 0:ga.provider)==null?void 0:ma.type)==="runtype")try{W.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&W.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),V&&W.setSSEEventCallback((l,u)=>{V==null||V.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=jo(l.metadata),C.syncFromMetadata()),(u=l.messages)!=null&&u.length&&W.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Dr=l=>{var L;l.preventDefault();let u=te.value.trim(),h=(L=Be==null?void 0:Be.hasAttachments())!=null?L:!1;if(!u&&!h)return;let A;h&&(A=[],A.push(...Be.getContentParts()),u&&A.push($s(u))),te.value="",te.style.height="auto",W.sendMessage(u,{contentParts:A}),h&&Be.clearAttachments()},_r=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),X.click())},jr=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!Be)return;let u=Yd(l.clipboardData);u.length!==0&&(l.preventDefault(),await Be.handleFiles(u))},qt=null,Zt=!1,En=null,Re=null,Vr=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Un=(l="user")=>{var $,R,D,B,me,ge,Me,je;if(Zt||W.isStreaming())return;let u=Vr();if(!u)return;qt=new u;let A=(R=(($=r.voiceRecognition)!=null?$:{}).pauseDuration)!=null?R:2e3;qt.continuous=!0,qt.interimResults=!0,qt.lang="en-US";let L=te.value;qt.onresult=xe=>{let P="",ke="";for(let F=0;F<xe.results.length;F++){let We=xe.results[F],st=We[0].transcript;We.isFinal?P+=st+" ":ke=st}let Ae=L+P+ke;te.value=Ae,En&&clearTimeout(En),(P||ke)&&(En=window.setTimeout(()=>{let F=te.value.trim();F&&qt&&Zt&&(ln(),te.value="",te.style.height="auto",W.sendMessage(F,{viaVoice:!0}))},A))},qt.onerror=xe=>{xe.error!=="no-speech"&&ln()},qt.onend=()=>{if(Zt){let xe=te.value.trim();xe&&xe!==L.trim()&&(te.value="",te.style.height="auto",W.sendMessage(xe,{viaVoice:!0})),ln()}};try{if(qt.start(),Zt=!0,qe.active=!0,l!=="system"&&(qe.manuallyDeactivated=!1),nn(l),zt(),H){let xe=(D=r.voiceRecognition)!=null?D:{};Re={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(B=xe.iconName)!=null?B:"mic",iconSize:parseFloat((Me=(ge=xe.iconSize)!=null?ge:(me=r.sendButton)==null?void 0:me.size)!=null?Me:"40")||24};let P=(je=xe.recordingBackgroundColor)!=null?je:"#ef4444",ke=xe.recordingIconColor,Ae=xe.recordingBorderColor;if(H.classList.add("persona-voice-recording"),H.style.backgroundColor=P,ke){H.style.color=ke;let F=H.querySelector("svg");F&&F.setAttribute("stroke",ke)}Ae&&(H.style.borderColor=Ae),H.setAttribute("aria-label","Stop voice recognition")}}catch{ln("system")}},ln=(l="user")=>{if(Zt){if(Zt=!1,En&&(clearTimeout(En),En=null),qt){try{qt.stop()}catch{}qt=null}if(qe.active=!1,nn(l),zt(),H){if(H.classList.remove("persona-voice-recording"),Re){H.style.backgroundColor=Re.backgroundColor,H.style.color=Re.color,H.style.borderColor=Re.borderColor;let u=H.querySelector("svg");u&&u.setAttribute("stroke",Re.color||"currentColor"),Re=null}H.setAttribute("aria-label","Start voice recognition")}}},xs=(l,u)=>{var F,We,st,Ze,St,ct,ot,Kt;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((F=l==null?void 0:l.provider)==null?void 0:F.type)==="runtype";if(!(h||A))return null;let $=f("div","persona-send-button-wrapper"),R=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");R.type="button",R.setAttribute("aria-label","Start voice recognition");let D=(We=l==null?void 0:l.iconName)!=null?We:"mic",B=(st=u==null?void 0:u.size)!=null?st:"40px",me=(Ze=l==null?void 0:l.iconSize)!=null?Ze:B,ge=parseFloat(me)||24,Me=(St=l==null?void 0:l.backgroundColor)!=null?St:u==null?void 0:u.backgroundColor,je=(ct=l==null?void 0:l.iconColor)!=null?ct:u==null?void 0:u.textColor;R.style.width=me,R.style.height=me,R.style.minWidth=me,R.style.minHeight=me,R.style.fontSize="18px",R.style.lineHeight="1";let xe=je||"currentColor",P=ue(D,ge,xe,1.5);P?(R.appendChild(P),R.style.color=xe):(R.textContent="\u{1F3A4}",R.style.color=xe),Me?R.style.backgroundColor=Me:R.classList.add("persona-bg-persona-primary"),je?R.style.color=je:!je&&!(u!=null&&u.textColor)&&R.classList.add("persona-text-white"),l!=null&&l.borderWidth&&(R.style.borderWidth=l.borderWidth,R.style.borderStyle="solid"),l!=null&&l.borderColor&&(R.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(R.style.paddingLeft=l.paddingX,R.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(R.style.paddingTop=l.paddingY,R.style.paddingBottom=l.paddingY),$.appendChild(R);let ke=(ot=l==null?void 0:l.tooltipText)!=null?ot:"Start voice recognition";if(((Kt=l==null?void 0:l.showTooltip)!=null?Kt:!1)&&ke){let ve=f("div","persona-send-button-tooltip");ve.textContent=ke,$.appendChild(ve)}return{micButton:R,micButtonWrapper:$}},mr=()=>{var u,h,A,L,$;if(!H||Re)return;let l=(u=r.voiceRecognition)!=null?u:{};Re={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat(($=(L=l.iconSize)!=null?L:(A=r.sendButton)==null?void 0:A.size)!=null?$:"40")||24}},fr=(l,u)=>{var $,R,D,B,me;if(!H)return;let h=H.querySelector("svg");h&&h.remove();let A=(me=Re==null?void 0:Re.iconSize)!=null?me:parseFloat((B=(D=($=r.voiceRecognition)==null?void 0:$.iconSize)!=null?D:(R=r.sendButton)==null?void 0:R.size)!=null?B:"40")||24,L=ue(l,A,u,1.5);L&&H.appendChild(L)},zn=()=>{H&&H.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Fn=()=>{var L,$;if(!H)return;mr();let l=(L=r.voiceRecognition)!=null?L:{},u=($=l.recordingBackgroundColor)!=null?$:"#ef4444",h=l.recordingIconColor,A=l.recordingBorderColor;if(zn(),H.classList.add("persona-voice-recording"),H.style.backgroundColor=u,h){H.style.color=h;let R=H.querySelector("svg");R&&R.setAttribute("stroke",h)}A&&(H.style.borderColor=A),H.setAttribute("aria-label","Stop voice recognition")},vs=()=>{var D,B,me,ge,Me,je,xe,P;if(!H)return;mr();let l=(D=r.voiceRecognition)!=null?D:{},u=W.getVoiceInterruptionMode(),h=(B=l.processingIconName)!=null?B:"loader",A=(ge=(me=l.processingIconColor)!=null?me:Re==null?void 0:Re.color)!=null?ge:"",L=(je=(Me=l.processingBackgroundColor)!=null?Me:Re==null?void 0:Re.backgroundColor)!=null?je:"",$=(P=(xe=l.processingBorderColor)!=null?xe:Re==null?void 0:Re.borderColor)!=null?P:"";zn(),H.classList.add("persona-voice-processing"),H.style.backgroundColor=L,H.style.borderColor=$;let R=A||"currentColor";H.style.color=R,fr(h,R),H.setAttribute("aria-label","Processing voice input"),u==="none"&&(H.style.cursor="default")},Cs=()=>{var me,ge,Me,je,xe,P,ke,Ae,F,We,st,Ze;if(!H)return;mr();let l=(me=r.voiceRecognition)!=null?me:{},u=W.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",A=(ge=l.speakingIconName)!=null?ge:h,L=(P=l.speakingIconColor)!=null?P:u==="barge-in"?(je=(Me=l.recordingIconColor)!=null?Me:Re==null?void 0:Re.color)!=null?je:"":(xe=Re==null?void 0:Re.color)!=null?xe:"",$=(F=l.speakingBackgroundColor)!=null?F:u==="barge-in"?(ke=l.recordingBackgroundColor)!=null?ke:"#ef4444":(Ae=Re==null?void 0:Re.backgroundColor)!=null?Ae:"",R=(Ze=l.speakingBorderColor)!=null?Ze:u==="barge-in"?(We=l.recordingBorderColor)!=null?We:"":(st=Re==null?void 0:Re.borderColor)!=null?st:"";zn(),H.classList.add("persona-voice-speaking"),H.style.backgroundColor=$,H.style.borderColor=R;let D=L||"currentColor";H.style.color=D,fr(A,D);let B=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";H.setAttribute("aria-label",B),u==="none"&&(H.style.cursor="default"),u==="barge-in"&&H.classList.add("persona-voice-recording")},cn=()=>{var l,u,h;H&&(zn(),Re&&(H.style.backgroundColor=(l=Re.backgroundColor)!=null?l:"",H.style.color=(u=Re.color)!=null?u:"",H.style.borderColor=(h=Re.borderColor)!=null?h:"",fr(Re.iconName,Re.color||"currentColor"),Re=null),H.style.cursor="",H.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=W.getVoiceStatus(),A=W.getVoiceInterruptionMode();if(A==="none"&&(h==="processing"||h==="speaking"))return;if(A==="cancel"&&(h==="processing"||h==="speaking")){W.stopVoicePlayback();return}if(W.isBargeInActive()){W.stopVoicePlayback(),W.deactivateBargeIn().then(()=>{qe.active=!1,qe.manuallyDeactivated=!0,zt(),nn("user"),cn()});return}W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),qe.manuallyDeactivated=!W.isVoiceActive(),zt(),nn("user"),W.isVoiceActive()?Fn():cn()});return}if(Zt){let h=te.value.trim();qe.manuallyDeactivated=!0,zt(),ln("user"),h&&(te.value="",te.style.height="auto",W.sendMessage(h))}else qe.manuallyDeactivated=!1,zt(),Un("user")};ut=Jn,H&&(H.addEventListener("click",Jn),xt.push(()=>{var l,u;((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(W.isVoiceActive()&&W.toggleVoice(),cn()):ln("system"),H&&H.removeEventListener("click",Jn)}));let ws=s.on("assistant:complete",()=>{Fr&&(qe.active||qe.manuallyDeactivated||Fr==="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"?W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),nn("auto"),W.isVoiceActive()&&Fn()}):Un("auto"))},600))});xt.push(ws);let G=s.on("action:resubmit",()=>{setTimeout(()=>{W&&!W.isStreaming()&&W.continueConversation()},100)});xt.push(G);let Fe=()=>{ht(!S,"user")},we=null,Ne=null;if(v){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:r,defaultRenderer:()=>ts(r,Fe).element,onToggle:Fe});u&&(Ne=u)}Ne||(we=ts(r,Fe))}we?e.appendChild(we.element):Ne&&e.appendChild(Ne),pr(),Hn.render(r.suggestionChips,W,te,void 0,r.suggestionChipsConfig),Or(),ur(W.isStreaming()),Vn(!0),ms(),x&&(v?S&&setTimeout(()=>gr(),200):setTimeout(()=>gr(),0));let vt=()=>{var B,me,ge,Me,je,xe,P,ke,Ae,F,We,st,Ze;let l=jt(r),u=(me=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?me:!1,h=l||u||((Me=(ge=r.launcher)==null?void 0:ge.fullHeight)!=null?Me:!1),A=(je=e.ownerDocument.defaultView)!=null?je:window,L=(P=(xe=r.launcher)==null?void 0:xe.mobileFullscreen)!=null?P:!0,$=(Ae=(ke=r.launcher)==null?void 0:ke.mobileBreakpoint)!=null?Ae:640,R=A.innerWidth<=$;if(L&&R&&v){_n(),On(e,r);return}if(O&&(O=!1,_n(),On(e,r)),!v&&!l){se.style.height="",se.style.width="";return}if(!u&&!l){let St=(We=(F=r==null?void 0:r.launcher)==null?void 0:F.width)!=null?We:r==null?void 0:r.launcherWidth,ct=St!=null?St:"min(400px, calc(100vw - 24px))";se.style.width=ct,se.style.maxWidth=ct}if(Dn(),!h){let St=A.innerHeight,ct=64,ot=(Ze=(st=r.launcher)==null?void 0:st.heightOffset)!=null?Ze:0,Kt=Math.max(200,St-ct),ve=Math.min(640,Kt),pt=Math.max(200,ve-ot);se.style.height=`${pt}px`}};vt();let Nt=(fa=e.ownerDocument.defaultView)!=null?fa:window;Nt.addEventListener("resize",vt),xt.push(()=>Nt.removeEventListener("resize",vt)),jn=oe.scrollTop;let Ct=()=>{let l=oe.scrollTop,u=oe.scrollHeight,h=oe.clientHeight,A=u-l-h,L=Math.abs(l-jn);if(jn=l,!cr&&!(L<=gs)){if(!Cn&&A<$r){Sn=!1,Cn=!0;return}Cn&&A>$r&&(Sn=!0,lr=Date.now()+us,Cn=!1)}};oe.addEventListener("scroll",Ct,{passive:!0}),xt.push(()=>oe.removeEventListener("scroll",Ct)),xt.push(()=>{wn&&cancelAnimationFrame(wn)});let b=()=>{ie&&(yn&&(ie.removeEventListener("click",yn),yn=null),v?(ie.style.display="",yn=()=>{ht(!1,"user")},ie.addEventListener("click",yn)):ie.style.display="none")};b(),(()=>{let{clearChatButton:l}=q;l&&l.addEventListener("click",()=>{W.clearMessages(),$n.clear();try{localStorage.removeItem(Lr),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Lr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Lr)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(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}i={},C.syncFromMetadata(),V==null||V.clear(),j==null||j.update()})})(),Ve&&Ve.addEventListener("submit",Dr),te==null||te.addEventListener("keydown",_r),te==null||te.addEventListener("paste",jr),xt.push(()=>{Ve&&Ve.removeEventListener("submit",Dr),te==null||te.removeEventListener("keydown",_r),te==null||te.removeEventListener("paste",jr)}),xt.push(()=>{W.cancel()}),we?xt.push(()=>{we==null||we.destroy()}):Ne&&xt.push(()=>{Ne==null||Ne.remove()});let T={update(l){var wa,Sa,Aa,Ea,Ta,Ma,ka,La,Pa,Ia,Wa,Ra,Ha,Ba,$a,Fa,Na,Oa,Da,_a,ja,Va,qa,Ua,za,Ja,Ka,Ya,Xa,Ga,Za,Qa,ei,ti,ni,ri,si,oi,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,$i,Fi,Ni,Oi,Di,_i,ji,Vi,qi,Ui,zi,Ji,Ki,Yi,Xi,Gi,Zi,Qi,el,tl,nl,rl,sl,ol;let u=r.toolCall,h=r.messageActions,A=(wa=r.layout)==null?void 0:wa.messages,L=r.colorScheme;r={...r,...l},_n(),On(e,r),Js(e,r),Ks(e,r),fn(),r.colorScheme!==L&&Rr();let $=as.getForInstance(r.plugins);o.length=0,o.push(...$),v=(Aa=(Sa=r.launcher)==null?void 0:Sa.enabled)!=null?Aa:!0,E=(Ta=(Ea=r.launcher)==null?void 0:Ea.autoExpand)!=null?Ta:!1,J=(ka=(Ma=r.features)==null?void 0:Ma.showReasoning)!=null?ka:!0,pe=(Pa=(La=r.features)==null?void 0:La.showToolCalls)!=null?Pa:!0;let R=Le;if(Le=(Wa=(Ia=r.features)==null?void 0:Ia.showEventStreamToggle)!=null?Wa:!1,Le&&!R){if(V||(ee=new rs(fe),V=new ns(Y,ee),ee.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),W.setSSEEventCallback((_,ze)=>{V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:_,timestamp:Date.now(),payload:JSON.stringify(ze)})})),!de&&_e){let _=(Ha=(Ra=r.features)==null?void 0:Ra.eventStream)==null?void 0:Ha.classNames,ze="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"+(_!=null&&_.toggleButton?" "+_.toggleButton:"");de=f("button",ze),de.style.width="28px",de.style.height="28px",de.type="button",de.setAttribute("aria-label","Event Stream"),de.title="Event Stream";let yt=ue("activity","18px","currentColor",1.5);yt&&de.appendChild(yt);let Oe=q.clearChatButtonWrapper,Qe=q.closeButtonWrapper,Pt=Oe||Qe;Pt&&Pt.parentNode===_e?_e.insertBefore(de,Pt):_e.appendChild(de),de.addEventListener("click",()=>{ce?$e():be()})}}else!Le&&R&&($e(),de&&(de.remove(),de=null),V==null||V.clear(),ee==null||ee.destroy(),V=null,ee=null);if(((Ba=r.launcher)==null?void 0:Ba.enabled)===!1&&we&&(we.destroy(),we=null),(($a=r.launcher)==null?void 0:$a.enabled)===!1&&Ne&&(Ne.remove(),Ne=null),((Fa=r.launcher)==null?void 0:Fa.enabled)!==!1&&!we&&!Ne){let _=o.find(ze=>ze.renderLauncher);if(_!=null&&_.renderLauncher){let ze=_.renderLauncher({config:r,defaultRenderer:()=>ts(r,Fe).element,onToggle:Fe});ze&&(Ne=ze,e.appendChild(Ne))}Ne||(we=ts(r,Fe),e.appendChild(we.element))}we&&we.update(r),Te&&((Na=r.launcher)==null?void 0:Na.title)!==void 0&&(Te.textContent=r.launcher.title),tt&&((Oa=r.launcher)==null?void 0:Oa.subtitle)!==void 0&&(tt.textContent=r.launcher.subtitle);let D=(Da=r.layout)==null?void 0:Da.header;if((D==null?void 0:D.layout)!==M&&_e){let _=D?wr(r,D,{showClose:v,onClose:()=>ht(!1,"user")}):Ln({config:r,showClose:v,onClose:()=>ht(!1,"user")});_e.replaceWith(_.header),_e=_.header,Ue=_.iconHolder,Te=_.headerTitle,tt=_.headerSubtitle,ie=_.closeButton,M=D==null?void 0:D.layout}else if(D&&(Ue&&(Ue.style.display=D.showIcon===!1?"none":""),Te&&(Te.style.display=D.showTitle===!1?"none":""),tt&&(tt.style.display=D.showSubtitle===!1?"none":""),ie&&(ie.style.display=D.showCloseButton===!1?"none":""),q.clearChatButtonWrapper)){let _=D.showClearChat;if(_!==void 0){q.clearChatButtonWrapper.style.display=_?"":"none";let{closeButtonWrapper:ze}=q;ze&&!ze.classList.contains("persona-absolute")&&(_?ze.classList.remove("persona-ml-auto"):ze.classList.add("persona-ml-auto"))}}let me=((_a=r.layout)==null?void 0:_a.showHeader)!==!1;_e&&(_e.style.display=me?"":"none");let ge=((ja=r.layout)==null?void 0:ja.showFooter)!==!1;Xe&&(Xe.style.display=ge?"":"none"),v!==U?v?ht(E,"auto"):(S=!0,pr()):E!==k&&ht(E,"auto"),k=E,U=v,vt(),b();let xe=JSON.stringify(l.toolCall)!==JSON.stringify(u),P=JSON.stringify(r.messageActions)!==JSON.stringify(h),ke=JSON.stringify((Va=r.layout)==null?void 0:Va.messages)!==JSON.stringify(A);(xe||P||ke)&&W&&(Hr++,qn(Ee,W.getMessages(),re));let F=(qa=r.launcher)!=null?qa:{},We=(Ua=F.headerIconHidden)!=null?Ua:!1,st=(Ja=(za=r.layout)==null?void 0:za.header)==null?void 0:Ja.showIcon,Ze=We||st===!1,St=F.headerIconName,ct=(Ka=F.headerIconSize)!=null?Ka:"48px";if(Ue){let _=ne.querySelector(".persona-border-b-persona-divider"),ze=_==null?void 0:_.querySelector(".persona-flex-col");if(Ze)Ue.style.display="none",_&&ze&&!_.contains(ze)&&_.insertBefore(ze,_.firstChild);else{if(Ue.style.display="",Ue.style.height=ct,Ue.style.width=ct,_&&ze&&(_.contains(Ue)?Ue.nextSibling!==ze&&(Ue.remove(),_.insertBefore(Ue,ze)):_.insertBefore(Ue,ze)),St){let Oe=parseFloat(ct)||24,Qe=ue(St,Oe*.6,"#ffffff",2);Qe?Ue.replaceChildren(Qe):Ue.textContent=(Ya=F.agentIconText)!=null?Ya:"\u{1F4AC}"}else if(F.iconUrl){let Oe=Ue.querySelector("img");if(Oe)Oe.src=F.iconUrl,Oe.style.height=ct,Oe.style.width=ct;else{let Qe=document.createElement("img");Qe.src=F.iconUrl,Qe.alt="",Qe.className="persona-rounded-xl persona-object-cover",Qe.style.height=ct,Qe.style.width=ct,Ue.replaceChildren(Qe)}}else{let Oe=Ue.querySelector("svg"),Qe=Ue.querySelector("img");(Oe||Qe)&&Ue.replaceChildren(),Ue.textContent=(Xa=F.agentIconText)!=null?Xa:"\u{1F4AC}"}let yt=Ue.querySelector("img");yt&&(yt.style.height=ct,yt.style.width=ct)}}let ot=(Za=(Ga=r.layout)==null?void 0:Ga.header)==null?void 0:Za.showTitle,Kt=(ei=(Qa=r.layout)==null?void 0:Qa.header)==null?void 0:ei.showSubtitle;if(Te&&(Te.style.display=ot===!1?"none":""),tt&&(tt.style.display=Kt===!1?"none":""),ie){((ni=(ti=r.layout)==null?void 0:ti.header)==null?void 0:ni.showCloseButton)===!1?ie.style.display="none":ie.style.display="";let ze=(ri=F.closeButtonSize)!=null?ri:"32px",yt=(si=F.closeButtonPlacement)!=null?si:"inline";ie.style.height=ze,ie.style.width=ze;let{closeButtonWrapper:Oe}=q,Qe=yt==="top-right",Pt=Oe==null?void 0:Oe.classList.contains("persona-absolute");if(Oe&&Qe!==Pt)if(Oe.remove(),Qe)Oe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ne.style.position="relative",ne.appendChild(Oe);else{let Je=(ai=(oi=F.clearChat)==null?void 0:oi.placement)!=null?ai:"inline",Ft=(li=(ii=F.clearChat)==null?void 0:ii.enabled)!=null?li:!0;Oe.className=Ft&&Je==="inline"?"":"persona-ml-auto";let Xt=ne.querySelector(".persona-border-b-persona-divider");Xt&&Xt.appendChild(Oe)}if(F.closeButtonColor?(ie.style.color=F.closeButtonColor,ie.classList.remove("persona-text-persona-muted")):(ie.style.color="",ie.classList.add("persona-text-persona-muted")),F.closeButtonBackgroundColor?(ie.style.backgroundColor=F.closeButtonBackgroundColor,ie.classList.remove("hover:persona-bg-gray-100")):(ie.style.backgroundColor="",ie.classList.add("hover:persona-bg-gray-100")),F.closeButtonBorderWidth||F.closeButtonBorderColor){let Je=F.closeButtonBorderWidth||"0px",Ft=F.closeButtonBorderColor||"transparent";ie.style.border=`${Je} solid ${Ft}`,ie.classList.remove("persona-border-none")}else ie.style.border="",ie.classList.add("persona-border-none");F.closeButtonBorderRadius?(ie.style.borderRadius=F.closeButtonBorderRadius,ie.classList.remove("persona-rounded-full")):(ie.style.borderRadius="",ie.classList.add("persona-rounded-full")),F.closeButtonPaddingX?(ie.style.paddingLeft=F.closeButtonPaddingX,ie.style.paddingRight=F.closeButtonPaddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),F.closeButtonPaddingY?(ie.style.paddingTop=F.closeButtonPaddingY,ie.style.paddingBottom=F.closeButtonPaddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let Ot=(ci=F.closeButtonIconName)!=null?ci:"x",Qt=(di=F.closeButtonIconText)!=null?di:"\xD7";ie.innerHTML="";let Ut=ue(Ot,"20px",F.closeButtonColor||"",2);Ut?ie.appendChild(Ut):ie.textContent=Qt;let At=(pi=F.closeButtonTooltipText)!=null?pi:"Close chat",en=(ui=F.closeButtonShowTooltip)!=null?ui:!0;if(ie.setAttribute("aria-label",At),Oe&&(Oe._cleanupTooltip&&(Oe._cleanupTooltip(),delete Oe._cleanupTooltip),en&&At)){let Je=null,Ft=()=>{if(Je||!ie)return;let Kn=ie.ownerDocument,Kr=Kn.body;if(!Kr)return;Je=bn(Kn,"div","persona-clear-chat-tooltip"),Je.textContent=At;let Yr=bn(Kn,"div");Yr.className="persona-clear-chat-tooltip-arrow",Je.appendChild(Yr);let Yn=ie.getBoundingClientRect();Je.style.position="fixed",Je.style.left=`${Yn.left+Yn.width/2}px`,Je.style.top=`${Yn.top-8}px`,Je.style.transform="translate(-50%, -100%)",Kr.appendChild(Je)},Xt=()=>{Je&&Je.parentNode&&(Je.parentNode.removeChild(Je),Je=null)};Oe.addEventListener("mouseenter",Ft),Oe.addEventListener("mouseleave",Xt),ie.addEventListener("focus",Ft),ie.addEventListener("blur",Xt),Oe._cleanupTooltip=()=>{Xt(),Oe&&(Oe.removeEventListener("mouseenter",Ft),Oe.removeEventListener("mouseleave",Xt)),ie&&(ie.removeEventListener("focus",Ft),ie.removeEventListener("blur",Xt))}}}let{clearChatButton:ve,clearChatButtonWrapper:pt}=q;if(ve){let _=(gi=F.clearChat)!=null?gi:{},ze=(mi=_.enabled)!=null?mi:!0,yt=(hi=(fi=r.layout)==null?void 0:fi.header)==null?void 0:hi.showClearChat,Oe=yt!==void 0?yt:ze,Qe=(yi=_.placement)!=null?yi:"inline";if(pt){pt.style.display=Oe?"":"none";let{closeButtonWrapper:Pt}=q;Pt&&!Pt.classList.contains("persona-absolute")&&(Oe?Pt.classList.remove("persona-ml-auto"):Pt.classList.add("persona-ml-auto"));let Ot=Qe==="top-right",Qt=pt.classList.contains("persona-absolute");if(Ot!==Qt&&Oe){if(pt.remove(),Ot)pt.className="persona-absolute persona-top-4 persona-z-50",pt.style.right="48px",ne.style.position="relative",ne.appendChild(pt);else{pt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",pt.style.right="";let At=ne.querySelector(".persona-border-b-persona-divider"),en=q.closeButtonWrapper;At&&en&&en.parentElement===At?At.insertBefore(pt,en):At&&At.appendChild(pt)}let Ut=q.closeButtonWrapper;Ut&&!Ut.classList.contains("persona-absolute")&&(Ot?Ut.classList.add("persona-ml-auto"):Ut.classList.remove("persona-ml-auto"))}}if(Oe){let Pt=(bi=_.size)!=null?bi:"32px";ve.style.height=Pt,ve.style.width=Pt;let Ot=(xi=_.iconName)!=null?xi:"refresh-cw",Qt=(vi=_.iconColor)!=null?vi:"";ve.innerHTML="";let Ut=ue(Ot,"20px",Qt||"",2);if(Ut&&ve.appendChild(Ut),Qt?(ve.style.color=Qt,ve.classList.remove("persona-text-persona-muted")):(ve.style.color="",ve.classList.add("persona-text-persona-muted")),_.backgroundColor?(ve.style.backgroundColor=_.backgroundColor,ve.classList.remove("hover:persona-bg-gray-100")):(ve.style.backgroundColor="",ve.classList.add("hover:persona-bg-gray-100")),_.borderWidth||_.borderColor){let Je=_.borderWidth||"0px",Ft=_.borderColor||"transparent";ve.style.border=`${Je} solid ${Ft}`,ve.classList.remove("persona-border-none")}else ve.style.border="",ve.classList.add("persona-border-none");_.borderRadius?(ve.style.borderRadius=_.borderRadius,ve.classList.remove("persona-rounded-full")):(ve.style.borderRadius="",ve.classList.add("persona-rounded-full")),_.paddingX?(ve.style.paddingLeft=_.paddingX,ve.style.paddingRight=_.paddingX):(ve.style.paddingLeft="",ve.style.paddingRight=""),_.paddingY?(ve.style.paddingTop=_.paddingY,ve.style.paddingBottom=_.paddingY):(ve.style.paddingTop="",ve.style.paddingBottom="");let At=(Ci=_.tooltipText)!=null?Ci:"Clear chat",en=(wi=_.showTooltip)!=null?wi:!0;if(ve.setAttribute("aria-label",At),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),en&&At)){let Je=null,Ft=()=>{if(Je||!ve)return;let Kn=ve.ownerDocument,Kr=Kn.body;if(!Kr)return;Je=bn(Kn,"div","persona-clear-chat-tooltip"),Je.textContent=At;let Yr=bn(Kn,"div");Yr.className="persona-clear-chat-tooltip-arrow",Je.appendChild(Yr);let Yn=ve.getBoundingClientRect();Je.style.position="fixed",Je.style.left=`${Yn.left+Yn.width/2}px`,Je.style.top=`${Yn.top-8}px`,Je.style.transform="translate(-50%, -100%)",Kr.appendChild(Je)},Xt=()=>{Je&&Je.parentNode&&(Je.parentNode.removeChild(Je),Je=null)};pt.addEventListener("mouseenter",Ft),pt.addEventListener("mouseleave",Xt),ve.addEventListener("focus",Ft),ve.addEventListener("blur",Xt),pt._cleanupTooltip=()=>{Xt(),pt&&(pt.removeEventListener("mouseenter",Ft),pt.removeEventListener("mouseleave",Xt)),ve&&(ve.removeEventListener("focus",Ft),ve.removeEventListener("blur",Xt))}}}}let $t=r.actionParsers&&r.actionParsers.length?r.actionParsers:[is],sn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[sr.message,sr.messageAndClick];C=ls({parsers:$t,handlers:sn,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),re=lc(r,C,K),W.updateConfig(r),qn(Ee,W.getMessages(),re),Hn.render(r.suggestionChips,W,te,void 0,r.suggestionChipsConfig),Or(),ur(W.isStreaming());let Ss=((Si=r.voiceRecognition)==null?void 0:Si.enabled)===!0,As=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Es=((Ei=(Ai=r.voiceRecognition)==null?void 0:Ai.provider)==null?void 0:Ei.type)==="runtype";if(Ss&&(As||Es))if(!H||!Z){let _=xs(r.voiceRecognition,r.sendButton);_&&(H=_.micButton,Z=_.micButtonWrapper,Mt.insertBefore(Z,He),H.addEventListener("click",Jn),H.disabled=W.isStreaming())}else{let _=(Ti=r.voiceRecognition)!=null?Ti:{},ze=(Mi=r.sendButton)!=null?Mi:{},yt=(ki=_.iconName)!=null?ki:"mic",Oe=(Li=ze.size)!=null?Li:"40px",Qe=(Pi=_.iconSize)!=null?Pi:Oe,Pt=parseFloat(Qe)||24;H.style.width=Qe,H.style.height=Qe,H.style.minWidth=Qe,H.style.minHeight=Qe;let Ot=(Wi=(Ii=_.iconColor)!=null?Ii:ze.textColor)!=null?Wi:"currentColor";H.innerHTML="";let Qt=ue(yt,Pt,Ot,2);Qt?H.appendChild(Qt):H.textContent="\u{1F3A4}";let Ut=(Ri=_.backgroundColor)!=null?Ri:ze.backgroundColor;Ut?(H.style.backgroundColor=Ut,H.classList.remove("persona-bg-persona-primary")):(H.style.backgroundColor="",H.classList.add("persona-bg-persona-primary")),Ot?(H.style.color=Ot,H.classList.remove("persona-text-white")):!Ot&&!ze.textColor&&(H.style.color="",H.classList.add("persona-text-white")),_.borderWidth?(H.style.borderWidth=_.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),_.borderColor?H.style.borderColor=_.borderColor:H.style.borderColor="",_.paddingX?(H.style.paddingLeft=_.paddingX,H.style.paddingRight=_.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),_.paddingY?(H.style.paddingTop=_.paddingY,H.style.paddingBottom=_.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let At=Z==null?void 0:Z.querySelector(".persona-send-button-tooltip"),en=(Hi=_.tooltipText)!=null?Hi:"Start voice recognition";if(((Bi=_.showTooltip)!=null?Bi:!1)&&en)if(At)At.textContent=en,At.style.display="";else{let Ft=document.createElement("div");Ft.className="persona-send-button-tooltip",Ft.textContent=en,Z==null||Z.insertBefore(Ft,H)}else At&&(At.style.display="none");Z.style.display="",H.disabled=W.isStreaming()}else H&&Z&&(Z.style.display="none",((Fi=($i=r.voiceRecognition)==null?void 0:$i.provider)==null?void 0:Fi.type)==="runtype"?W.isVoiceActive()&&W.toggleVoice():Zt&&ln());if(((Ni=r.attachments)==null?void 0:Ni.enabled)===!0)if(!Pe||!z){let _=(Oi=r.attachments)!=null?Oi:{},yt=(_i=((Di=r.sendButton)!=null?Di:{}).size)!=null?_i:"40px";Ie||(Ie=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ie.style.display="none",Ve.insertBefore(Ie,te)),Ce||(Ce=document.createElement("input"),Ce.type="file",Ce.accept=((ji=_.allowedTypes)!=null?ji:kn).join(","),Ce.multiple=((Vi=_.maxFiles)!=null?Vi:4)>1,Ce.style.display="none",Ce.setAttribute("aria-label","Attach files"),Ve.insertBefore(Ce,te)),Pe=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",(qi=_.buttonTooltipText)!=null?qi:"Attach file");let Oe=(Ui=_.buttonIconName)!=null?Ui:"paperclip",Qe=yt,Pt=parseFloat(Qe)||40,Ot=Math.round(Pt*.6);z.style.width=Qe,z.style.height=Qe,z.style.minWidth=Qe,z.style.minHeight=Qe,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 Qt=ue(Oe,Ot,"currentColor",1.5);Qt?z.appendChild(Qt):z.textContent="\u{1F4CE}",z.addEventListener("click",en=>{en.preventDefault(),Ce==null||Ce.click()}),Pe.appendChild(z);let Ut=(zi=_.buttonTooltipText)!=null?zi:"Attach file",At=f("div","persona-send-button-tooltip");At.textContent=Ut,Pe.appendChild(At),Rt.append(Pe),!Be&&Ce&&Ie&&(Be=tr.fromConfig(_),Be.setPreviewsContainer(Ie),Ce.addEventListener("change",async()=>{Be&&(Ce!=null&&Ce.files)&&(await Be.handleFileSelect(Ce.files),Ce.value="")}))}else{Pe.style.display="";let _=(Ji=r.attachments)!=null?Ji:{};Ce&&(Ce.accept=((Ki=_.allowedTypes)!=null?Ki:kn).join(","),Ce.multiple=((Yi=_.maxFiles)!=null?Yi:4)>1),Be&&Be.updateConfig({allowedTypes:_.allowedTypes,maxFileSize:_.maxFileSize,maxFiles:_.maxFiles})}else Pe&&(Pe.style.display="none"),Be&&Be.clearAttachments();let Tt=(Xi=r.sendButton)!=null?Xi:{},Ts=(Gi=Tt.useIcon)!=null?Gi:!1,qr=(Zi=Tt.iconText)!=null?Zi:"\u2191",Ur=Tt.iconName,hr=(Qi=Tt.tooltipText)!=null?Qi:"Send message",Ms=(el=Tt.showTooltip)!=null?el:!1,Nn=(tl=Tt.size)!=null?tl:"40px",Tn=Tt.backgroundColor,Yt=Tt.textColor;if(Ts){if(X.style.width=Nn,X.style.height=Nn,X.style.minWidth=Nn,X.style.minHeight=Nn,X.style.fontSize="18px",X.style.lineHeight="1",X.innerHTML="",Ur){let _=parseFloat(Nn)||24,ze=Yt&&typeof Yt=="string"&&Yt.trim()?Yt.trim():"currentColor",yt=ue(Ur,_,ze,2);yt?(X.appendChild(yt),X.style.color=ze):(X.textContent=qr,Yt?X.style.color=Yt:X.classList.add("persona-text-white"))}else X.textContent=qr,Yt?X.style.color=Yt: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",Tn?(X.style.backgroundColor=Tn,X.classList.remove("persona-bg-persona-primary")):X.classList.add("persona-bg-persona-primary")}else X.textContent=(rl=(nl=r.copy)==null?void 0:nl.sendButtonLabel)!=null?rl:"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",Tn?(X.style.backgroundColor=Tn,X.classList.remove("persona-bg-persona-accent")):X.classList.add("persona-bg-persona-accent"),Yt?X.style.color=Yt:X.classList.add("persona-text-white");Tt.borderWidth?(X.style.borderWidth=Tt.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),Tt.borderColor?X.style.borderColor=Tt.borderColor:X.style.borderColor="",Tt.paddingX?(X.style.paddingLeft=Tt.paddingX,X.style.paddingRight=Tt.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),Tt.paddingY?(X.style.paddingTop=Tt.paddingY,X.style.paddingBottom=Tt.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let zr=He==null?void 0:He.querySelector(".persona-send-button-tooltip");if(Ms&&hr)if(zr)zr.textContent=hr,zr.style.display="";else{let _=document.createElement("div");_.className="persona-send-button-tooltip",_.textContent=hr,He==null||He.insertBefore(_,X)}else zr&&(zr.style.display="none");let Jr=(sl=r.statusIndicator)!=null?sl:{},Fc=(ol=Jr.visible)!=null?ol:!0;if(et.style.display=Fc?"":"none",W){let _=W.getStatus(),ze=yt=>{var Oe,Qe,Pt,Ot;return yt==="idle"?(Oe=Jr.idleText)!=null?Oe:_t.idle:yt==="connecting"?(Qe=Jr.connectingText)!=null?Qe:_t.connecting:yt==="connected"?(Pt=Jr.connectedText)!=null?Pt:_t.connected:yt==="error"?(Ot=Jr.errorText)!=null?Ot:_t.error:_t[yt]};et.textContent=ze(_)}},open(){v&&ht(!0,"api")},close(){v&&ht(!1,"api")},toggle(){v&&ht(!S,"api")},clearChat(){an=!1,W.clearMessages(),$n.clear();try{localStorage.removeItem(Lr),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Lr}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Lr)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(),V==null||V.clear(),j==null||j.update()},setMessage(l){return!te||W.isStreaming()?!1:(!S&&v&&ht(!0,"system"),te.value=l,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(W.isStreaming())return!1;let u=(l==null?void 0:l.trim())||te.value.trim();return u?(!S&&v&&ht(!0,"system"),te.value="",te.style.height="auto",W.sendMessage(u),!0):!1},startVoiceRecognition(){var u,h;return W.isStreaming()?!1:((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype"?(W.isVoiceActive()||(!S&&v&&ht(!0,"system"),qe.manuallyDeactivated=!1,zt(),W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),nn("user"),W.isVoiceActive()&&Fn()})),!0):Zt?!0:Vr()?(!S&&v&&ht(!0,"system"),qe.manuallyDeactivated=!1,zt(),Un("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?W.isVoiceActive()?(W.toggleVoice().then(()=>{qe.active=!1,qe.manuallyDeactivated=!0,zt(),nn("user"),cn()}),!0):!1:Zt?(qe.manuallyDeactivated=!0,zt(),ln("user"),!0):!1},injectMessage(l){return!S&&v&&ht(!0,"system"),W.injectMessage(l)},injectAssistantMessage(l){!S&&v&&ht(!0,"system");let u=W.injectAssistantMessage(l);return N&&(N=!1,Q&&(clearTimeout(Q),Q=null),setTimeout(()=>{W&&!W.isStreaming()&&W.continueConversation()},100)),u},injectUserMessage(l){return!S&&v&&ht(!0,"system"),W.injectUserMessage(l)},injectSystemMessage(l){return!S&&v&&ht(!0,"system"),W.injectSystemMessage(l)},injectMessageBatch(l){return!S&&v&&ht(!0,"system"),W.injectMessageBatch(l)},injectTestMessage(l){!S&&v&&ht(!0,"system"),W.injectTestEvent(l)},async connectStream(l,u){return W.connectStream(l,u)},__pushEventStreamEvent(l){V&&V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!Le||!V||be()},hideEventStream(){ce&&$e()},isEventStreamVisible(){return ce},showArtifacts(){on(r)&&(an=!1,fn(),Ge==null||Ge.setMobileOpen(!0))},hideArtifacts(){on(r)&&(an=!0,fn())},upsertArtifact(l){return on(r)?(an=!1,W.upsertArtifact(l)):null},selectArtifact(l){on(r)&&W.selectArtifact(l)},clearArtifacts(){on(r)&&W.clearArtifacts()},focusInput(){return v&&!S||!te?!1:(te.focus(),!0)},async resolveApproval(l,u){let A=W.getMessages().find(L=>{var $;return L.variant==="approval"&&(($=L.approval)==null?void 0:$.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return W.resolveApproval(A.approval,u)},getMessages(){return W.getMessages()},getStatus(){return W.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){p(l)},on(l,u){return s.on(l,u)},off(l,u){s.off(l,u)},isOpen(){return v&&S},isVoiceActive(){return qe.active},getState(){return{open:v&&S,launcherEnabled:v,voiceActive:qe.active,streaming:W.isStreaming()}},showCSATFeedback(l){!S&&v&&ht(!0,"system");let u=Ee.querySelector(".persona-feedback-container");u&&u.remove();let h=to({onSubmit:async(A,L)=>{var $;W.isClientTokenMode()&&await W.submitCSATFeedback(A,L),($=l==null?void 0:l.onSubmit)==null||$.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Ee.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!S&&v&&ht(!0,"system");let u=Ee.querySelector(".persona-feedback-container");u&&u.remove();let h=no({onSubmit:async(A,L)=>{var $;W.isClientTokenMode()&&await W.submitNPSFeedback(A,L),($=l==null?void 0:l.onSubmit)==null||$.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Ee.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return W.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return W.submitNPSFeedback(l,u)},destroy(){xt.forEach(l=>l()),le.remove(),we==null||we.destroy(),Ne==null||Ne.remove(),yn&&ie.removeEventListener("click",yn)}};if((((ha=t==null?void 0:t.debugTools)!=null?ha:!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=D=>{let B=D.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&T.focusInput()};if(window.addEventListener("persona:focusInput",u),xt.push(()=>{window.removeEventListener("persona:focusInput",u)}),Le){let D=me=>{let ge=me.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===l)&&T.showEventStream()},B=me=>{let ge=me.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===l)&&T.hideEventStream()};window.addEventListener("persona:showEventStream",D),window.addEventListener("persona:hideEventStream",B),xt.push(()=>{window.removeEventListener("persona:showEventStream",D),window.removeEventListener("persona:hideEventStream",B)})}let h=D=>{let B=D.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&T.showArtifacts()},A=D=>{let B=D.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&T.hideArtifacts()},L=D=>{let B=D.detail;B!=null&&B.instanceId&&B.instanceId!==l||B!=null&&B.artifact&&T.upsertArtifact(B.artifact)},$=D=>{let B=D.detail;B!=null&&B.instanceId&&B.instanceId!==l||typeof(B==null?void 0:B.id)=="string"&&T.selectArtifact(B.id)},R=D=>{let B=D.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&T.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",R),xt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",R)})}let I=Xd(r.persistState);if(I&&v){let l=Gd(I.storage),u=`${I.keyPrefix}widget-open`,h=`${I.keyPrefix}widget-voice`,A=`${I.keyPrefix}widget-voice-mode`;if(l){let L=((ya=I.persist)==null?void 0:ya.openState)&&l.getItem(u)==="true",$=((ba=I.persist)==null?void 0:ba.voiceState)&&l.getItem(h)==="true",R=((xa=I.persist)==null?void 0:xa.voiceState)&&l.getItem(A)==="true";if(L&&setTimeout(()=>{T.open(),setTimeout(()=>{var D;if($||R)T.startVoiceRecognition();else if((D=I.persist)!=null&&D.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(va=I.persist)!=null&&va.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(Ca=I.persist)!=null&&Ca.voiceState&&(s.on("voice:state",D=>{l.setItem(h,D.active?"true":"false")}),s.on("user:message",D=>{l.setItem(A,D.viaVoice?"true":"false")})),I.clearOnChatClear){let D=()=>{l.removeItem(u),l.removeItem(h),l.removeItem(A)},B=()=>D();window.addEventListener("persona:clear-chat",B),xt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return T};var cc=(e,n)=>{var r,o;let t=(o=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?o:!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"},Vo=(e,n,t,r,o,s)=>{let a=Cr(o),i=s?a.width:a.collapsedWidth;e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=a.side,e.dataset.personaDockOpen=s?"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)},Zd=(e,n)=>{let t=e.ownerDocument.createElement("div");return cc(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){cc(t,r)},destroy(){t.remove()}}},Qd=(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 o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=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),Vo(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,Vo(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),Vo(a,i,d,c,n,g)},destroy(){r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},cs=(e,n)=>jt(n)?Qd(e,n):Zd(e,n);var qo={},ep=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},tp=()=>{try{if(typeof qo!="undefined"&&qo.url)return new URL("../widget.css",qo.url).href}catch{}return null},dc=(e,n)=>{let t=tp(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=n.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),n.head.appendChild(s)}},Uo=e=>{var E;let n=ep(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,o=e.config,s=cs(n,o),a,i=[],d=(x,k)=>{var S,N;let M=!((N=(S=k==null?void 0:k.launcher)==null?void 0:S.enabled)!=null?N:!0)||jt(k),O=r.createElement("div");if(O.id="persona-root",M&&(O.style.height="100%",O.style.display="flex",O.style.flexDirection="column",O.style.flex="1",O.style.minHeight="0"),t){let Q=x.attachShadow({mode:"open"});Q.appendChild(O),dc(Q,r)}else x.appendChild(O),dc(x,r);return n.id&&O.setAttribute("data-persona-instance",n.id),O},c=()=>{s.syncWidgetState(a.getState())},g=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let x=d(s.host,o);a=ro(x,o,{debugTools:e.debugTools}),g()},y=()=>{i.forEach(x=>x()),i=[],a.destroy()};p(),(E=e.onReady)==null||E.call(e);let m=x=>{y(),s.destroy(),s=cs(n,x),o=x,p()},C={update(x){var O,S,N,Q,K,re;let k={...o,...x,launcher:{...(O=o==null?void 0:o.launcher)!=null?O:{},...(S=x==null?void 0:x.launcher)!=null?S:{},dock:{...(Q=(N=o==null?void 0:o.launcher)==null?void 0:N.dock)!=null?Q:{},...(re=(K=x==null?void 0:x.launcher)==null?void 0:K.dock)!=null?re:{}}}},U=jt(o),M=jt(k);if(U!==M){m(k);return}o=k,s.updateConfig(o),a.update(x),c()},destroy(){y(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(C,{get(x,k,U){if(k==="host")return s.host;if(k in x)return Reflect.get(x,k,U);let M=a[k];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var fc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),np=new Set(["button","a","input","select","textarea","details","summary"]),rp=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),zo=/\b(product|card|item|listing|result)\b/i,Ko=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,sp=3e3,op=100;function hc(e){let n=typeof e.className=="string"?e.className:"";if(zo.test(n)||e.id&&zo.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&zo.test(r.value))return!0}return!1}function yc(e){var n;return Ko.test(((n=e.textContent)!=null?n:"").trim())}function bc(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let o=(t=n[r].getAttribute("href"))!=null?t:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function ap(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function pc(e){let n=e.match(Ko);return n?n[0]:null}function uc(e){var r,o,s;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&&((o=n.textContent)!=null&&o.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(s=t==null?void 0:t.textContent)!=null&&s.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function ip(e){let n=[],t=r=>{let o=r.trim();o&&!n.includes(o)&&n.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return t((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return t((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;t((o=r.value)!=null?o:"")}),n.slice(0,6)}var lp="commerce-card",cp="result-card";function gc(e){return!hc(e)||!yc(e)||!bc(e)&&!ap(e)?0:5200}function mc(e){var r;return!hc(e)||yc(e)||!bc(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 Yo=[{id:lp,scoreElement(e){return gc(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||Ko.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,c,g;if(gc(e)===0)return null;let{title:t,href:r}=uc(e),o=(g=(c=pc(((d=e.textContent)!=null?d:"").trim()))!=null?c:pc(n.text))!=null?g:"",s=ip(e);return[r&&t?`[${t}](${r})${o?` \u2014 ${o}`:""}`:t?`${t}${o?` \u2014 ${o}`:""}`:o||n.text.trim().slice(0,120),`selector: ${n.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
96
+ `)}},{id:cp,scoreElement(e){return mc(e)},formatSummary(e,n){if(mc(e)===0)return null;let{title:t,href:r}=uc(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
97
+ `)}}];function dp(){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,y,m,C,v,E,x,k,U,M,O,S;let n=(g=e.options)!=null?g:{},t=(y=(p=n.maxElements)!=null?p:e.maxElements)!=null?y:80,r=(C=(m=n.excludeSelector)!=null?m:e.excludeSelector)!=null?C:".persona-host",o=(E=(v=n.maxTextLength)!=null?v:e.maxTextLength)!=null?E:200,s=(k=(x=n.visibleOnly)!=null?x:e.visibleOnly)!=null?k:!0,a=(U=n.root)!=null?U:e.root,i=(M=n.mode)!=null?M:"structured",d=(O=n.maxCandidates)!=null?O:Math.max(500,t*10),c=(S=e.rules)!=null?S:Yo;return i==="simple"&&e.rules&&e.rules.length>0?(dp(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:c}}function Jo(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var up=["data-testid","data-product","data-action","data-id","data-name","data-type"];function gp(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"||np.has(n)||t&&rp.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function xc(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 mp(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let o=e.getAttribute("aria-label");o&&(n["aria-label"]=o);let s=e.getAttribute("type");s&&(n.type=s);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 Xo(e){let n=e.tagName.toLowerCase();if(e.id){let o=`#${Jo(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of up){let s=e.getAttribute(o);if(s){let a=`${n}[${o}="${Jo(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(t.length>0){let o=`${n}.${t.map(a=>Jo(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(s>=0)return`${n}:nth-of-type(${s+1})`}return n}function fp(e){return e==="static"?op:sp}function vc(e,n){var o;let t=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,n);return{selector:Xo(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:gp(e),attributes:mp(e)}}function hp(e,n,t,r){let o=fp(n.interactivity),s=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function yp(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 bp(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,g=c.tagName.toLowerCase();if(fc.has(g)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!xc(c)){i=a.nextNode();continue}let p=vc(c,e.maxTextLength),y=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(E=>E==="role");if(!y&&!m){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:C,formattingRule:v}=hp(c,p,e.rules,t);o.push({el:c,domIndex:s,enriched:p,score:C,formattingRule:v}),s+=1}i=a.nextNode()}o.sort((c,g)=>{let p=c.enriched.interactivity==="static"?1:0,y=g.enriched.interactivity==="static"?1:0;return p!==y?p-y:g.score!==c.score?g.score-c.score:c.domIndex-g.domIndex});let d=[];for(let c of o){if(d.length>=e.maxElements)break;yp(d,c)||d.push(c)}return d.sort((c,g)=>{let p=c.enriched.interactivity==="static"?1:0,y=g.enriched.interactivity==="static"?1:0;return p!==y?p-y:p===1&&g.score!==c.score?g.score-c.score:c.domIndex-g.domIndex}),d.map(c=>{var y;let g;if((y=c.formattingRule)!=null&&y.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 xp(e,n){let t=[],r=new Set,o=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&t.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,c=d.tagName.toLowerCase();if(fc.has(c)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!xc(d)){s=o.nextNode();continue}let g=vc(d,e.maxTextLength),p=g.text.length>0,y=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(m=>m==="role");if(!p&&!y){s=o.nextNode();continue}r.has(g.selector)||(r.add(g.selector),t.push(g))}s=o.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 Cc(e={}){var r;let n=pp(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?xp(n,t):bp(n,t):[]}var so=100;function wc(e,n={}){var s;if(e.length===0)return"No page elements found.";let t=(s=n.mode)!=null?s:"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
+ ${a.map(i=>`- ${i.split(`
99
+ `).join(`
100
+ `)}`).join(`
101
+ `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,so)}" (clickable)`);r.push(`Interactive elements:
102
+ ${a.join(`
103
+ `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,so)}" (navigable)`);r.push(`Navigation links:
104
+ ${a.join(`
105
+ `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,so)}" (input)`);r.push(`Form inputs:
106
+ ${a.join(`
107
+ `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,so)}"`);r.push(`Content:
108
+ ${a.join(`
109
+ `)}`)}return r.join(`
110
+
111
+ `)}var Sc={name:"@runtypelabs/persona",version:"2.1.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./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:{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"},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 or=Sc.version;function In(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function Cp(e){if(e)return{getHeaders:In(e.getHeaders),onFeedback:In(e.onFeedback),onCopy:In(e.onCopy),requestMiddleware:In(e.requestMiddleware),actionHandlers:In(e.actionHandlers),actionParsers:In(e.actionParsers),postprocessMessage:In(e.postprocessMessage),contextProviders:In(e.contextProviders),streamParser:In(e.streamParser)}}var Ac=`({ text, message }: any) => {
61
112
  const jsonSource = (message as any).rawContent || text || message.content;
62
113
  if (!jsonSource || typeof jsonSource !== 'string') return null;
63
114
  let cleanJson = jsonSource
@@ -70,7 +121,7 @@
70
121
  if (parsed.action) return { type: parsed.action, payload: parsed };
71
122
  } catch (e) { return null; }
72
123
  return null;
73
- }`,$a=`function(ctx) {
124
+ }`,Ec=`function(ctx) {
74
125
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
75
126
  if (!jsonSource || typeof jsonSource !== 'string') return null;
76
127
  var cleanJson = jsonSource
@@ -83,7 +134,7 @@
83
134
  if (parsed.action) return { type: parsed.action, payload: parsed };
84
135
  } catch (e) { return null; }
85
136
  return null;
86
- }`,Na=`(action: any, context: any) => {
137
+ }`,Tc=`(action: any, context: any) => {
87
138
  if (action.type !== 'nav_then_click') return;
88
139
  const payload = action.payload || action.raw || {};
89
140
  const url = payload?.page;
@@ -100,7 +151,7 @@
100
151
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
101
152
  window.location.href = targetUrl;
102
153
  return { handled: true, displayText: text };
103
- }`,Oa=`function(action, context) {
154
+ }`,Mc=`function(action, context) {
104
155
  if (action.type !== 'nav_then_click') return;
105
156
  var payload = action.payload || action.raw || {};
106
157
  var url = payload.page;
@@ -117,24 +168,24 @@
117
168
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
118
169
  window.location.href = targetUrl;
119
170
  return { handled: true, displayText: text };
120
- }`,Jl=`(parsed: any) => {
171
+ }`,wp=`(parsed: any) => {
121
172
  if (!parsed || typeof parsed !== 'object') return null;
122
173
  if (parsed.action === 'nav_then_click') return 'Navigating...';
123
174
  if (parsed.action === 'message') return parsed.text || '';
124
175
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
125
176
  return parsed.text || null;
126
- }`,Kl=`function(parsed) {
177
+ }`,Sp=`function(parsed) {
127
178
  if (!parsed || typeof parsed !== 'object') return null;
128
179
  if (parsed.action === 'nav_then_click') return 'Navigating...';
129
180
  if (parsed.action === 'message') return parsed.text || '';
130
181
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
131
182
  return parsed.text || null;
132
- }`;function Yl(n){if(!n)return null;let t=n.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function br(n){var t,r;return(r=(t=n.parserType)!=null?t:Yl(n.streamParser))!=null?r:"plain"}function Cr(n,t){let r=[];return n.toolCall&&(r.push(`${t}toolCall: {`),Object.entries(n.toolCall).forEach(([e,o])=>{typeof o=="string"&&r.push(`${t} ${e}: "${o}",`)}),r.push(`${t}},`)),r}function xr(n,t,r){let e=[],o=n.messageActions&&Object.entries(n.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),s=(r==null?void 0:r.onFeedback)||(r==null?void 0:r.onCopy);return(o||s)&&(e.push(`${t}messageActions: {`),n.messageActions&&Object.entries(n.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?e.push(`${t} ${i}: "${a}",`):typeof a=="boolean"&&e.push(`${t} ${i}: ${a},`))}),r!=null&&r.onFeedback&&e.push(`${t} onFeedback: ${r.onFeedback},`),r!=null&&r.onCopy&&e.push(`${t} onCopy: ${r.onCopy},`),e.push(`${t}},`)),e}function Sr(n,t){let r=[];if(n.markdown){let e=n.markdown.options&&Object.keys(n.markdown.options).length>0,o=n.markdown.disableDefaultStyles!==void 0;(e||o)&&(r.push(`${t}markdown: {`),e&&(r.push(`${t} options: {`),Object.entries(n.markdown.options).forEach(([s,i])=>{typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`)}),r.push(`${t} },`)),o&&r.push(`${t} disableDefaultStyles: ${n.markdown.disableDefaultStyles},`),r.push(`${t}},`))}return r}function Ar(n,t){let r=[];if(n.layout){let e=n.layout.header&&Object.keys(n.layout.header).some(s=>s!=="render"),o=n.layout.messages&&Object.keys(n.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(e||o)&&(r.push(`${t}layout: {`),e&&(r.push(`${t} header: {`),Object.entries(n.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`))}),r.push(`${t} },`)),o&&(r.push(`${t} messages: {`),Object.entries(n.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(r.push(`${t} avatar: {`),Object.entries(i).forEach(([a,d])=>{typeof d=="string"?r.push(`${t} ${a}: "${d}",`):typeof d=="boolean"&&r.push(`${t} ${a}: ${d},`)}),r.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(r.push(`${t} timestamp: {`),Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?r.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&r.push(`${t} ${d}: ${c},`))}),r.push(`${t} },`)):typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`))}),r.push(`${t} },`)),r.push(`${t}},`))}return r}function eo(n,t){let r=[];return n&&(n.getHeaders&&r.push(`${t}getHeaders: ${n.getHeaders},`),n.requestMiddleware&&r.push(`${t}requestMiddleware: ${n.requestMiddleware},`),n.actionParsers&&r.push(`${t}actionParsers: ${n.actionParsers},`),n.actionHandlers&&r.push(`${t}actionHandlers: ${n.actionHandlers},`),n.contextProviders&&r.push(`${t}contextProviders: ${n.contextProviders},`),n.streamParser&&r.push(`${t}streamParser: ${n.streamParser},`)),r}function Da(n,t="esm",r){let e={...n};delete e.postprocessMessage,delete e.initialMessages;let o=r?{...r,hooks:zl(r.hooks)}:void 0;return t==="esm"?Xl(e,o):t==="script-installer"?Ql(e):t==="script-advanced"?tc(e,o):t==="react-component"?Gl(e,o):t==="react-advanced"?Zl(e,o):ec(e,o)}function Xl(n,t){let r=t==null?void 0:t.hooks,e=br(n),o=e!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Cr(n," ")),s.push(...xr(n," ",r)),s.push(...Sr(n," ")),s.push(...Ar(n," ")),s.push(...eo(r," ")),n.debug&&s.push(` debug: ${n.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
133
- `)}function Gl(n,t){let r=t==null?void 0:t.hooks,e=br(n),o=e!=="plain",s=["// 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 n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Cr(n," ")),s.push(...xr(n," ",r)),s.push(...Sr(n," ")),s.push(...Ar(n," ")),s.push(...eo(r," ")),n.debug&&s.push(` debug: ${n.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
134
- `)}function Zl(n,t){let r=t==null?void 0:t.hooks,e=["// 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 n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&e.push(` clientToken: "${n.clientToken}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"?e.push(` ${o}: ${s},`):typeof s=="number"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{e.push(` ${o}: ${s},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),e.push(...Cr(n," ")),e.push(...xr(n," ",r)),e.push(...Sr(n," ")),e.push(...Ar(n," ")),r!=null&&r.getHeaders&&e.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&e.push(` contextProviders: ${r.contextProviders},`),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?e.push(` streamParser: ${r.streamParser},`):(e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(` streamParser: () => createFlexibleJsonStreamParser(${Jl}),`)),r!=null&&r.actionParsers?(e.push(" // Action parsers (custom merged with defaults)"),e.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),e.push(" // Built-in parser for markdown-wrapped JSON"),e.push(` ${Fa}`),e.push(" ],")):(e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Parser for markdown-wrapped JSON"),e.push(` ${Fa}`),e.push(" ],")),r!=null&&r.actionHandlers?(e.push(" // Action handlers (custom merged with defaults)"),e.push(` actionHandlers: [...(${r.actionHandlers}),`),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Built-in handler for nav_then_click action"),e.push(` ${Na}`),e.push(" ],")):(e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(` ${Na}`),e.push(" ],")),r!=null&&r.postprocessMessage?e.push(` postprocessMessage: ${r.postprocessMessage},`):e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(e.push(" // Request middleware (custom merged with DOM context)"),e.push(" requestMiddleware: ({ payload, config }) => {"),e.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),e.push(" const merged = customResult || payload;"),e.push(" return {"),e.push(" ...merged,"),e.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),e.push(" };"),e.push(" }")):(e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }")),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('persona:message', handleMessage);"),e.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('persona:message', handleMessage);"),e.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
135
- `)}function ja(n){var o;let t=br(n),r=t!=="plain",e={};if(n.apiUrl&&(e.apiUrl=n.apiUrl),n.clientToken&&(e.clientToken=n.clientToken),n.flowId&&(e.flowId=n.flowId),r&&(e.parserType=t),n.theme&&(e.theme=n.theme),n.launcher&&(e.launcher=n.launcher),n.copy&&(e.copy=n.copy),n.sendButton&&(e.sendButton=n.sendButton),n.voiceRecognition&&(e.voiceRecognition=n.voiceRecognition),n.statusIndicator&&(e.statusIndicator=n.statusIndicator),n.features&&(e.features=n.features),((o=n.suggestionChips)==null?void 0:o.length)>0&&(e.suggestionChips=n.suggestionChips),n.suggestionChipsConfig&&(e.suggestionChipsConfig=n.suggestionChipsConfig),n.debug&&(e.debug=n.debug),n.toolCall){let s={};Object.entries(n.toolCall).forEach(([i,a])=>{typeof a=="string"&&(s[i]=a)}),Object.keys(s).length>0&&(e.toolCall=s)}if(n.messageActions){let s={};Object.entries(n.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[i]=a)}),Object.keys(s).length>0&&(e.messageActions=s)}if(n.markdown){let s={};n.markdown.options&&(s.options=n.markdown.options),n.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=n.markdown.disableDefaultStyles),Object.keys(s).length>0&&(e.markdown=s)}if(n.layout){let s={};if(n.layout.header){let i={};Object.entries(n.layout.header).forEach(([a,d])=>{a!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(s.header=i)}if(n.layout.messages){let i={};Object.entries(n.layout.messages).forEach(([a,d])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof d=="object"&&d!==null)i.avatar=d;else if(a==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([v,p])=>{v!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(c[v]=p)}),Object.keys(c).length>0&&(i.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(e.layout=s)}return e}function Ql(n){let t=ja(n),r=JSON.stringify(t,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${On}/dist/install.global.js" data-config='${r}'></script>`}function ec(n,t){let r=t==null?void 0:t.hooks,e=br(n),o=e!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${On}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${On}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"?s.push(` ${i}: ${a},`):typeof a=="number"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Cr(n," ")),s.push(...xr(n," ",r)),s.push(...Sr(n," ")),s.push(...Ar(n," ")),s.push(...eo(r," ")),n.debug&&s.push(` debug: ${n.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
136
- `)}function tc(n,t){let r=t==null?void 0:t.hooks,e=ja(n),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(e,null,2).split(`
137
- `).map((i,a)=>a===0?i:" "+i).join(`
138
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${On}/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 r!=null&&r.getHeaders&&(s.push(` widgetConfig.getHeaders = ${r.getHeaders};`),s.push("")),r!=null&&r.contextProviders&&(s.push(` widgetConfig.contextProviders = ${r.contextProviders};`),s.push("")),r!=null&&r.streamParser?s.push(` widgetConfig.streamParser = ${r.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${Kl});`),s.push(" };")),s.push(""),r!=null&&r.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${r.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${$a}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${$a}`),s.push(" ];")),s.push(""),r!=null&&r.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${r.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Oa}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Oa}`),s.push(" ];")),s.push(""),r!=null&&r.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${r.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),r!=null&&r.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(r!=null&&r.onFeedback||r!=null&&r.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r!=null&&r.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r!=null&&r.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${r.onCopy};`),s.push("")),s.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>"),s.join(`
139
- `)}var nc=Qr;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_WIDGET_CONFIG,VERSION,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTextPart,createTypingIndicator,createVoiceProvider,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getDisplayText,getHeaderLayout,getImageParts,hasComponentDirective,hasImages,headerLayouts,initAgentWidget,isComponentDirectiveType,isVoiceSupported,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,renderComponentDirective,renderLoadingIndicatorWithFallback,validateImageFile});
183
+ }`;function Ap(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 oo(e){var n,t;return(t=(n=e.parserType)!=null?n:Ap(e.streamParser))!=null?t:"plain"}function ao(e,n){let t=[];return e.toolCall&&(t.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&t.push(`${n} ${r}: "${o}",`)}),t.push(`${n}},`)),t}function io(e,n,t){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(o||s)&&(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 lo(e,n){let t=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(t.push(`${n}markdown: {`),r&&(t.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?t.push(`${n} ${s}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${s}: ${a},`)}),t.push(`${n} },`)),o&&t.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${n}},`))}return t}function co(e,n){let t=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(t.push(`${n}layout: {`),r&&(t.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?t.push(`${n} ${s}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${s}: ${a},`))}),t.push(`${n} },`)),o&&(t.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="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} },`)):s==="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} ${s}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${s}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function Go(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 kc(e,n,t){Object.entries(n).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${t}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${t}${r}: {`),kc(e,o,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(o)},`)}})}function po(e,n,t,r){t&&(e.push(`${r}${n}: {`),kc(e,t,`${r} `),e.push(`${r}},`))}function Lc(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=t?{...t,hooks:Cp(t.hooks)}:void 0;return n==="esm"?Ep(r,o):n==="script-installer"?kp(r):n==="script-advanced"?Pp(r,o):n==="react-component"?Tp(r,o):n==="react-advanced"?Mp(r,o):Lp(r,o)}function Ep(e,n){let t=n==null?void 0:n.hooks,r=oo(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.launcher&&po(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...ao(e," ")),s.push(...io(e," ",t)),s.push(...lo(e," ")),s.push(...co(e," ")),s.push(...Go(t," ")),e.debug&&s.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?s.push(` postprocessMessage: ${t.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
184
+ `)}function Tp(e,n){let t=n==null?void 0:n.hooks,r=oo(e),o=r!=="plain",s=["// 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&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.launcher&&po(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...ao(e," ")),s.push(...io(e," ",t)),s.push(...lo(e," ")),s.push(...co(e," ")),s.push(...Go(t," ")),e.debug&&s.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?s.push(` postprocessMessage: ${t.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
185
+ `)}function Mp(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(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.launcher&&po(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),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(...ao(e," ")),r.push(...io(e," ",t)),r.push(...lo(e," ")),r.push(...co(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(${wp}),`)),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(` ${Ac}`),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(` ${Ac}`),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(` ${Tc}`),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(` ${Tc}`),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 Pc(e){var o;let n=oo(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),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(r.markdown=s)}if(e.layout){let s={};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&&(s.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&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function kp(e){let n=Pc(e),t=JSON.stringify(n,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${or}/dist/install.global.js" data-config='${t}'></script>`}function Lp(e,n){let t=n==null?void 0:n.hooks,r=oo(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${or}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${or}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.launcher&&po(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...ao(e," ")),s.push(...io(e," ",t)),s.push(...lo(e," ")),s.push(...co(e," ")),s.push(...Go(t," ")),e.debug&&s.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?s.push(` postprocessMessage: ${t.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
187
+ `)}function Pp(e,n){let t=n==null?void 0:n.hooks,r=Pc(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
188
+ `).map((a,i)=>i===0?a:" "+a).join(`
189
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${or}/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&&(s.push(` widgetConfig.getHeaders = ${t.getHeaders};`),s.push("")),t!=null&&t.contextProviders&&(s.push(` widgetConfig.contextProviders = ${t.contextProviders};`),s.push("")),t!=null&&t.streamParser?s.push(` widgetConfig.streamParser = ${t.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${Sp});`),s.push(" };")),s.push(""),t!=null&&t.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${t.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Ec}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Ec}`),s.push(" ];")),s.push(""),t!=null&&t.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${t.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Mc}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Mc}`),s.push(" ];")),s.push(""),t!=null&&t.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${t.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),t!=null&&t.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),s.push("")),s.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>"),s.join(`
190
+ `)}function Ic(){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 Wc(){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 Rc(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:xn(e.colors.primary,.95),100:xn(e.colors.primary,.9),200:xn(e.colors.primary,.8),300:xn(e.colors.primary,.7),400:xn(e.colors.primary,.6),500:e.colors.primary,600:xn(e.colors.primary,.8),700:xn(e.colors.primary,.7),800:xn(e.colors.primary,.6),900:xn(e.colors.primary,.5),950:xn(e.colors.primary,.45)}}),{...n,palette:t}}}}function Hc(){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 Bc(){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 xn(e,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(o+(255-o)*(1-n));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function $c(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Ip=Uo;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_COMPONENTS,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,VERSION,accessibilityPlugin,animationsPlugin,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,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,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isComponentDirectiveType,isDockedMountMode,isVoiceSupported,markdownPostprocessor,mergeWithDefaults,migrateV1Theme,normalizeContent,pluginRegistry,reducedMotionPlugin,renderComponentDirective,renderLoadingIndicatorWithFallback,resolveDockConfig,resolveTokens,themeToCssVariables,validateImageFile,validateTheme,validateV1Theme});
140
191
  //# sourceMappingURL=index.cjs.map