@runtypelabs/persona 1.48.0 → 2.0.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 +1055 -24
  5. package/dist/index.d.ts +1055 -24
  6. package/dist/index.global.js +111 -60
  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 +836 -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 +836 -513
  46. package/src/types/theme.ts +354 -0
  47. package/src/types.ts +314 -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 +179 -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 +125 -0
  68. package/src/utils/theme.ts +216 -60
  69. package/src/utils/tokens.ts +682 -0
package/dist/index.js CHANGED
@@ -1,35 +1,70 @@
1
- import{Marked as Ta}from"marked";var Ma=n=>{if(n)return n},Ds=n=>{var o,s;let t=n==null?void 0:n.markedOptions,r=new Ta({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=Ma(n==null?void 0:n.renderer);return e&&r.use({renderer:e}),i=>r.parse(i)},js=n=>n?Ds({markedOptions:n.options,renderer:n.renderer}):Ds(),ka=Ds(),Fi=n=>ka(n),ur=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),$i=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Bi=n=>`%%FORM_PLACEHOLDER_${n}%%`,Ni=(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=Bi(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=Bi(t.length);return t.push({token:s,type:o}),s}),r},Ia=n=>{let t=js(n);return r=>{let e=[],o=Ni(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="${$i(a)}"></div>`;s=s.replace(d,v)}),s}},La=n=>{let t=[],r=Ni(n,t),e=Fi(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="${$i(s)}"></div>`;e=e.replace(i,d)}),e};import{parse as Oi,STR as Di,OBJ as ji}from"partial-json";var _s=n=>n.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),hs=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)}},Wa=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`},_i=n=>n.status==="complete"?Wa(n):n.status==="pending"?"Waiting":"",Pa=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 Ui=n=>n.status==="complete"?Pa(n):"Using tool...",Ra=()=>{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()=>{}}},Us=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},pr=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},gr=()=>{var t;let n=Ra();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)}},hr=()=>{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=Oi(r,Di|ji);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?_s(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=_s(o.text)))}catch{}return t=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},Ha=n=>{let t=null,r=0,o=n||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?_s(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?_s(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=Oi(s,Di|ji),d=o(a);d!==null&&(t=d)}catch{}return r=s.length,{text:t||"",raw:s}},close:()=>{}}},mr=()=>{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 Ba="https://api.runtype.com/v1/dispatch",fr="https://api.runtype.com",vr=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 Fa(n){switch(n){case"json":return hr;case"regex-json":return gr;case"xml":return mr;default:return pr}}var jn=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var r,e,o;this.apiUrl=(r=t.apiUrl)!=null?r:Ba,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(e=t.streamParser)!=null?e:Fa(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$/,""))||fr;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$/,""))||fr}/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(vr).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$/,""))||fr}/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(vr).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(vr).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,mn,fn,rn,T,vn,ln,xn,Qn,cn,dn,Wn,Pn,Es,Ts,Ms,es,Rn,Ae,ts,Xt,Dt,ks,Is,ns,Sn,un,Ls,Ws,Ps,or,An,En,ot,Hn,Bn,ss,rs,os,is,Ft,Vt,pn,ke,as,Tn,tn,Rs,Fn,$n,Mn,wn,Hs,Bs,Gt,Nn,Fs,$s,gn,Qe,et,yn,ls,cs,ir,Lt,ar,$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,it,f;return H((f=(it=(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?it: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 it=String(_e);return L(dt,it),it}if(dt){let it=A.byStep.get(dt);if(it)return A.lastId=it,it}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 it=String(_e);return z(dt,it),it}if(dt){let it=x.byCall.get(dt);if(it)return x.lastId=it,it}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
+ import{Marked as pc}from"marked";var uc=e=>{if(e)return e},xs=e=>{var o,s;let t=e==null?void 0:e.markedOptions,n=new pc({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}),r=uc(e==null?void 0:e.renderer);return r&&n.use({renderer:r}),a=>n.parse(a)},ir=e=>e?xs({markedOptions:e.options,renderer:e.renderer}):xs(),gc=xs(),_i=e=>gc(e),Dr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),ji=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Di=e=>`%%FORM_PLACEHOLDER_${e}%%`,Vi=(e,t)=>{let n=e;return n=n.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=Di(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Di(t.length);return t.push({token:s,type:o}),s}),n},mc=e=>{let t=ir(e);return n=>{let r=[],o=Vi(n,r),s=t(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="${ji(i)}"></div>`;s=s.replace(d,g)}),s}},fc=e=>{let t=[],n=Vi(e,t),r=_i(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${ji(s)}"></div>`;r=r.replace(a,d)}),r};import{parse as qi,STR as Ui,OBJ as zi}from"partial-json";var vs=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),_r=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)}},hc=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Ji=e=>e.status==="complete"?hc(e):e.status==="pending"?"Waiting":"",yc=e=>{var o,s,a;let n=(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 n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Ki=e=>e.status==="complete"?yc(e):"Using tool...",bc=()=>{let e=null,t=0,n=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<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Cs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Us=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},zs=()=>{var t;let e=bc();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Js=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=qi(n,Ui|zi);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?vs(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=vs(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},xc=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?vs(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?vs(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:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=qi(s,Ui|zi),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Ks=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var vc="https://api.runtype.com/v1/dispatch",Ys="https://api.runtype.com",Xs=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 Cc(e){switch(e){case"json":return Js;case"regex-json":return zs;case"xml":return Ks;default:return Us}}var lr=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var n,r,o;this.apiUrl=(n=t.apiUrl)!=null?n:vc,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Cc(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 r;let n=((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ys;return t==="init"?`${n}/v1/client/init`:`${n}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var t,n;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,(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});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 n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ys}/v1/client/feedback`}async sendFeedback(t){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(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 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(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){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:t,comment:n})}async submitNPSFeedback(t,n){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:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({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 n({type:"error",error:m}),m}let c=await this.buildPayload(t.messages),g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(Xs).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}}),...t.assistantMessageId&&{assistantMessageId:t.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 n({type:"error",error:v}),v}if(y.status===429){let v=new Error(m.hint||"Message limit reached for this session.");throw n({type:"error",error:v}),v}let C=new Error(m.error||"Failed to send message");throw n({type:"error",error:C}),C}if(!y.body){let m=new Error("No response body received");throw n({type:"error",error:m}),m}n({type:"status",status:"connected"});try{await this.streamResponse(y.body,n,t.assistantMessageId)}finally{n({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")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({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 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 n({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 n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({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 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 n({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 n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ys}/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:n,streamResponse:!0})})}async buildAgentPayload(t){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Xs).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:n,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:t,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(t){let r={messages:t.slice().filter(Xs).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:t,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(t,n,r,o,s){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(t);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)),n({type:"status",status:"idle"})),a.error&&n({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(t,n,r){var mt,Pt,le,se,q,ne,oe,Ee,Ke,ee,X,He,Ve,et,jt,Dt,ie,Ue,Te,tt,_e,Xe,$t,Ft,It,H,te,J,We,Ce,Pe,Be,ut,ye,be,$e,de,bt,Gt,pn,un,ts,Ln,Xn,Ge,gn,Pn,an,vr,mn,dt,tn,vn,Cr,Gn,wr,Nn,fn,On,xt,hn,Sr,In,yn,W,Wn,Rn,Ar,Cn,Dn,Er,wn,Sn,Zn,Qn,ns,rs,ss,Tr,er,qe,Mr,nn,zt,os,as,kr,_n,An,is,ls,cs,js,jn,tr,ft,nr,rr,Lr,Pr,Ir,Wr,Vt,Zt,En,Re,Rr,Vn,ln,ds,sr,or,qn,Hn,ps,us,cn,Un,gs;let o=t.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=>{n({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},Z=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,z=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},Q=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,gt=new Map,lt=(mt=this.config.iterationDisplay)!=null?mt:"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",it="";for(let $ of vt)$.startsWith("event:")?Tt=$.replace("event:","").trim():$.startsWith("data:")&&(it+=$.replace("data:","").trim());if(!it)continue;let f;try{f=JSON.parse(it)}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=(mn=f.duration)!=null?mn:f.executionTime;if(typeof ae=="number")R.durationMs=ae;else{let Wt=(fn=R.startedAt)!=null?fn: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:(vn=Te==null?void 0:Te.iteration)!=null?vn: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=(Qn=(xn=f.text)!=null?xn:f.delta)!=null?Qn:f.content)!=null?cn:f.chunk)!=null?dn:"";if(ae){let Ke=((Wn=G.get(R.id))!=null?Wn:"")+ae;R.rawContent=Ke,se.has(R.id)||se.set(R.id,this.createStreamParser());let Wt=se.get(R.id),at=Ke.trim().startsWith("{")||Ke.trim().startsWith("[");if(at&&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(!at&&!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:(Pn=wt==null?void 0:wt.text)!=null?Pn:null;De!==null&&De.trim()!==""?(R.content=De,p(R)):!at&&!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=(Ts=(Es=f.result)==null?void 0:Es.response)!=null?Ts:R.content;if(Te){let Ke=G.get(R.id),Wt=Ke!=null?Ke:Ce(Te);R.rawContent=Wt;let at=se.get(R.id),St=null,wt=!1;if(at&&(St=at.getExtractedText(),St===null&&(St=Us(Wt)),St===null)){let De=at.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:(Ms=De==null?void 0:De.text)!=null?Ms: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=(es=De.close)==null?void 0:es.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=(Rn=f.result)==null?void 0:Rn.response,ae=P();if(R!=null){let Te=se.get(ae.id),Ke=!1,Wt=!1;if(Te){let at=Te.getExtractedText(),St=G.get(ae.id),wt=St!=null?St:Ce(R);if(ae.rawContent=wt,at!==null&&at.trim()!=="")ae.content=at,Ke=!0;else{let De=Us(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 at=G.get(ae.id);ae.rawContent=at!=null?at:Ce(R)}if(!Ke&&!G.has(ae.id)&&(ae.content=Ce(R)),Te){let at=(ts=Te.close)==null?void 0:ts.call(Te);at instanceof Promise&&at.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=Us(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,at=b.streaming!==!1;Wt&&(b.content=Te),b.streaming=!1,(Wt||at)&&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:(ks=f.agentName)!=null?ks:"",status:"running",currentIteration:0,maxIterations:(Is=f.maxIterations)!=null?Is: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+=(ns=f.delta)!=null?ns:"",$.agentMetadata={executionId:f.executionId,iteration:f.iteration,turnId:f.turnId,agentName:U==null?void 0:U.agentName},p($)}else if(f.contentType==="thinking"){let $=(Sn=f.turnId)!=null?Sn:`agent-think-${f.iteration}`,b=ue($);b.reasoning=(un=b.reasoning)!=null?un:{id:$,status:"streaming",chunks:[]},b.reasoning.chunks.push((Ls=f.delta)!=null?Ls:""),b.agentMetadata={executionId:f.executionId,iteration:f.iteration,turnId:f.turnId},p(b)}else if(f.contentType==="tool_input"){let $=(Ws=f.toolCallId)!=null?Ws:x.lastId;if($){let b=y.get($);b!=null&&b.toolCall&&(b.toolCall.chunks=(Ps=b.toolCall.chunks)!=null?Ps:[],b.toolCall.chunks.push((or=f.delta)!=null?or:""),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=(An=b.reasoning.startedAt)!=null?An:Date.now();b.reasoning.durationMs=Math.max(0,((En=b.reasoning.completedAt)!=null?En: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=(Hn=b.toolCall)!=null?Hn:{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=(Bn=f.toolName)!=null?Bn:R.name,R.status="running",f.parameters!==void 0&&(R.args=f.parameters),R.startedAt=_((ss=f.startedAt)!=null?ss: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 $=(rs=f.toolCallId)!=null?rs:x.lastId;if($){let b=(os=y.get($))!=null?os:X($);b.toolCall&&(b.toolCall.chunks=(is=b.toolCall.chunks)!=null?is:[],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:(as=f.reflection)!=null?as:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(Tn=f.reflection)!=null?Tn:""]},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:(Rs=(tn=f.error)==null?void 0:tn.message)!=null?Rs:"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 $=(Fn=f.approvalId)!=null?Fn:`approval-${c()}`,b={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:($n=U==null?void 0:U.agentId)!=null?$n:"virtual",executionId:(wn=(Mn=f.executionId)!=null?Mn:U==null?void 0:U.executionId)!=null?wn:"",toolName:(Hs=f.toolName)!=null?Hs:"",toolType:f.toolType,description:(Gt=f.description)!=null?Gt:`Execute ${(Bs=f.toolName)!=null?Bs:"tool"}`,parameters:f.parameters}};p(b)}else if(Re==="step_await"&&f.awaitReason==="approval_required"){let $=(Nn=f.approvalId)!=null?Nn:`approval-${c()}`,b={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Fs=U==null?void 0:U.agentId)!=null?Fs:"virtual",executionId:(gn=($s=f.executionId)!=null?$s:U==null?void 0:U.executionId)!=null?gn:"",toolName:(Qe=f.toolName)!=null?Qe:"",toolType:f.toolType,description:(yn=f.description)!=null?yn:`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:(ls=f.decision)!=null?ls:"approved",agentId:(cs=U==null?void 0:U.agentId)!=null?cs:"virtual",executionId:(Lt=(ir=f.executionId)!=null?ir:U==null?void 0:U.executionId)!=null?Lt:"",toolName:(ar=f.toolName)!=null?ar:"",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 $a(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${n}_${t}`}function ms(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function _n(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var qs="[Image]";function Na(n){return typeof n=="string"?[{type:"text",text:n}]:n}function Oa(n){return typeof n=="string"?n:n.filter(t=>t.type==="text").map(t=>t.text).join("")}function Da(n){return typeof n=="string"?!1:n.some(t=>t.type==="image")}function ja(n){return typeof n=="string"?[]:n.filter(t=>t.type==="image")}function wr(n){return{type:"text",text:n}}function _a(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 Ua(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 qa(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 qi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Va=["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"],bn=[...qi,...Va];function za(n){return qi.includes(n)||n.startsWith("image/")}function Vs(n){return za(n.type)}async function Vi(n){return new Promise((t,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;Vs(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 zi(n,t=bn,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 Ja(n){let t=n.split(".");return t.length>1?t.pop().toLowerCase():""}function Ji(n,t){let r=Ja(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 zs=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 Js=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 fs=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 Js;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 zs(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 Ln=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 Un(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new fs(n.runtype);case"browser":if(!Ln.isSupported())throw new Error("Browser speech recognition not supported");return new Ln(n.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function yr(n){if((n==null?void 0:n.type)==="runtype"&&n.runtype)return Un({type:"runtype",runtype:n.runtype});if(Ln.isSupported())return Un({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ks(n){try{return yr(n),!0}catch{return!1}}var vs=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 jn(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 Ks((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=Un(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 jn(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"?ms():r==="assistant"?_n():`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"?ms():o==="assistant"?_n():`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=ms(),s=_n(),i={id:o,role:"user",content:e||qs,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=_n();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};import*as Ka from"lucide";var ie=(n,t=24,r="currentColor",e=2)=>{try{let o=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ka[o];return s?Ya(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 Ya(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 Ys={allowedTypes:bn,maxFileSize:10*1024*1024,maxFiles:4};function Xa(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ga(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 qn=class n{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,e,o;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Ys.allowedTypes,maxFileSize:(e=t.maxFileSize)!=null?e:Ys.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ys.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:Ys.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=zi(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 Vi(c),m=Vs(c)?URL.createObjectURL(c):null,w={id:Xa(),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=Vs(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=Ga(t.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let c=g("span");c.textContent=Ji(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 br=()=>{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"},Za=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"||br()==="dark"?e:r},Ki=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{n(br())});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(br());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())}},Xs=(n,t)=>{let r=Za(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))})};import{Idiomorph as Qa}from"idiomorph";var Yi=(n,t,r={})=>{let{preserveTypingAnimation:e=!0}=r;Qa.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 ws=(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=(Pt=we.pop())!=null?Pt:"";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){n({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,n,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=Z(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=(ee=(Ke=N(b,!1))!=null?Ke:N(b,!0))!=null?ee:`reason-${c()}`,w=Z(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=(jt=(et=b.reasoningText)!=null?et:b.text)!=null?jt: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=($t=w.reasoning.startedAt)!=null?$t:Date.now();w.reasoning.durationMs=Math.max(0,((Ft=w.reasoning.completedAt)!=null?Ft:Date.now())-ae),w.streaming=!1,p(w)}let I=U(b);I&&E.byStep.delete(I)}else if(De==="tool_start"){let T=(It=fe(b,!0))!=null?It:`tool-${c()}`,w=(H=b.toolName)!=null?H:b.name;if(Ye(w)){re.add(T);continue}let I=Q(T),ae=(te=I.toolCall)!=null?te:{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=(We=ae.startedAt)!=null?We:Y((J=b.startedAt)!=null?J: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:(Pe=Se==null?void 0:Se.iteration)!=null?Pe: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=Q(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=(Ln=w.agentMetadata)!=null?Ln:{executionId:(un=Se==null?void 0:Se.executionId)!=null?un:b.executionId,iteration:(ts=Se==null?void 0:Se.iteration)!=null?ts:b.iteration}),p(w)}else if(De==="tool_complete"){let T=(Ge=(Xn=fe(b,!1))!=null?Xn:fe(b,!0))!=null?Ge:`tool-${c()}`;if(re.has(T)){re.delete(T);continue}let w=Q(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((Pn=b.completedAt)!=null?Pn:b.timestamp);let ae=(an=b.duration)!=null?an:b.executionTime;if(typeof ae=="number")I.durationMs=ae;else{let Mt=(vr=I.startedAt)!=null?vr:Date.now();I.durationMs=Math.max(0,((mn=I.completedAt)!=null?mn:Date.now())-Mt)}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=(Nn=(wr=(Gn=(Cr=b.text)!=null?Cr:b.delta)!=null?Gn:b.content)!=null?wr:b.chunk)!=null?Nn:"";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 Mt=j.get(I.id),wt=nt.trim().startsWith("{")||nt.trim().startsWith("[");if(wt&&ce.set(I.id,nt),Mt.__isPlainTextParser===!0){I.content+=ae,ce.delete(I.id),j.delete(I.id),I.rawContent=void 0,p(I);continue}let kt=Mt.processChunk(nt);if(kt instanceof Promise)kt.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 kt=="string"?kt:(On=kt==null?void 0:kt.text)!=null?On: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),Mt=nt!=null?nt:V(Se);I.rawContent=Mt;let wt=j.get(I.id),Wt=null,kt=!1;if(wt&&(Wt=wt.getExtractedText(),Wt===null&&(Wt=Cs(Mt)),Wt===null)){let rt=wt.processChunk(Mt);rt instanceof Promise?(kt=!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 Rt=y;Rt&&Rt.id===I.id&&(Rt.content=Et,Rt.streaming=!1,j.delete(Rt.id),ce.delete(Rt.id),p(Rt))}})):Wt=typeof rt=="string"?rt:(Sr=rt==null?void 0:rt.text)!=null?Sr:null}if(!kt){Wt!==null&&Wt.trim()!==""?I.content=Wt:ce.has(I.id)||(I.content=V(Se));let rt=j.get(I.id);if(rt){let at=(In=rt.close)==null?void 0:In.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,Mt=!1;if(Se){let wt=Se.getExtractedText(),Wt=ce.get(ae.id),kt=Wt!=null?Wt:V(I);if(ae.rawContent=kt,wt!==null&&wt.trim()!=="")ae.content=wt,nt=!0;else{let rt=Cs(kt);if(rt!==null)ae.content=rt,nt=!0;else{let at=Se.processChunk(kt);if(at instanceof Promise)Mt=!0,at.then(Et=>{var Rt;let it=typeof Et=="string"?Et:(Rt=Et==null?void 0:Et.text)!=null?Rt: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(!Mt){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=(Wn=Se.close)==null?void 0:Wn.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=(Rn=b.result)==null?void 0:Rn.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 Wt=Cs(ae);if(Wt!==null)Se=Wt;else{let kt=nt.processChunk(ae);kt instanceof Promise&&kt.then(at=>{var it;let Et=typeof at=="string"?at:(it=at==null?void 0:at.text)!=null?it:null;if(Et!==null){let Rt=y;Rt&&Rt.id===w.id&&(Rt.content=Et,Rt.streaming=!1,p(Rt))}});let rt=nt.getExtractedText();rt!==null&&(Se=rt)}}j.delete(w.id),ce.delete(w.id);let Mt=Se!==w.content,wt=w.streaming!==!1;Mt&&(w.content=Se),w.streaming=!1,(Mt||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))}n({type:"status",status:"idle"})}else if(De==="agent_start")he={executionId:b.executionId,agentId:(Ar=b.agentId)!=null?Ar:"virtual",agentName:(Cn=b.agentName)!=null?Cn:"",status:"running",currentIteration:0,maxTurns:(Dn=b.maxTurns)!=null?Dn: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),gt.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+=(Er=b.delta)!=null?Er:"",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=Z(T);w.reasoning=(Sn=w.reasoning)!=null?Sn:{id:T,status:"streaming",chunks:[]},w.reasoning.chunks.push((Zn=b.delta)!=null?Zn:""),w.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},p(w)}else if(b.contentType==="tool_input"){let T=(Qn=b.toolCallId)!=null?Qn:x.lastId;if(T){let w=v.get(T);w!=null&&w.toolCall&&(w.toolCall.chunks=(ns=w.toolCall.chunks)!=null?ns:[],w.toolCall.chunks.push((rs=b.delta)!=null?rs:""),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=(ss=w.reasoning.startedAt)!=null?ss:Date.now();w.reasoning.durationMs=Math.max(0,((Tr=w.reasoning.completedAt)!=null?Tr:Date.now())-I),w.streaming=!1,p(w)}}}else if(De==="agent_tool_start"){let T=(er=b.toolCallId)!=null?er:`agent-tool-${c()}`;K(M(b),T);let w=Q(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=(Mr=b.toolName)!=null?Mr: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=(os=b.toolCallId)!=null?os:x.lastId;if(T){let w=(as=v.get(T))!=null?as:Q(T);w.toolCall&&(w.toolCall.chunks=(kr=w.toolCall.chunks)!=null?kr:[],w.toolCall.chunks.push((_n=b.delta)!=null?_n:""),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=(is=v.get(T))!=null?is:Q(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((ls=b.completedAt)!=null?ls: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:(cs=b.reflection)!=null?cs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"complete",chunks:[(js=b.reflection)!=null?js:""]},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)),n({type:"status",status:"idle"})}else if(De==="agent_error"){let T=typeof b.error=="string"?b.error:(tr=(jn=b.error)==null?void 0:jn.message)!=null?tr:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",T):n({type:"error",error:new Error(T)})}else if(De!=="agent_ping")if(De==="agent_approval_start"){let T=(ft=b.approvalId)!=null?ft:`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:(nr=he==null?void 0:he.agentId)!=null?nr:"virtual",executionId:(Lr=(rr=b.executionId)!=null?rr:he==null?void 0:he.executionId)!=null?Lr:"",toolName:(Pr=b.toolName)!=null?Pr:"",toolType:b.toolType,description:(Wr=b.description)!=null?Wr:`Execute ${(Ir=b.toolName)!=null?Ir:"tool"}`,parameters:b.parameters}};p(w)}else if(De==="step_await"&&b.awaitReason==="approval_required"){let T=(Vt=b.approvalId)!=null?Vt:`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:(Rr=b.toolName)!=null?Rr:"",toolType:b.toolType,description:(ln=b.description)!=null?ln:`Execute ${(Vn=b.toolName)!=null?Vn:"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:(ds=b.decision)!=null?ds:"approved",agentId:(sr=he==null?void 0:he.agentId)!=null?sr:"virtual",executionId:(qn=(or=b.executionId)!=null?or:he==null?void 0:he.executionId)!=null?qn:"",toolName:(Hn=b.toolName)!=null?Hn:"",description:(ps=b.description)!=null?ps:"",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(n({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"}})};z.set(w,ae),p(ae)}}else if(De==="artifact_delta"){let T=String(b.id),w=typeof b.delta=="string"?b.delta:String((us=b.delta)!=null?us:"");n({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:{};n({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);n({type:"artifact_complete",id:T});let w=z.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),z.delete(T)}}}else if(De==="transcript_insert"){let T=b.message;if(!T||typeof T!="object")continue;let w=String((Un=T.id)!=null?Un:`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),Mt=(gs=nt==null?void 0:nt.props)==null?void 0:gs.artifactId;typeof Mt=="string"&&pe.add(Mt)}catch{}y=null,m.current=null,j.delete(w),ce.delete(w)}else De==="error"&&b.error&&n({type:"error",error:b.error instanceof Error?b.error:new Error(String(b.error))})}}}}}};function wc(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function jr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function cr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ws="[Image]";function Sc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ac(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ec(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Tc(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Gs(e){return{type:"text",text:e}}function Mc(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function kc(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Lc(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Yi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Pc=["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"],Mn=[...Yi,...Pc];function Ic(e){return Yi.includes(e)||e.startsWith("image/")}function Ss(e){return Ic(e.type)}async function Xi(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ss(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Gi(e,t=Mn,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Wc(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Zi(e,t){let n=Wc(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"}[e]||n||"FILE"}var As=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 n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.ensureContext(),o=this.pcmToFloat32(n),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 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 n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}};var Es=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,o,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.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 Vr=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 Es;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,n,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=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.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(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,r;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"})),(n=t.response.audio)!=null&&n.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)))))):(r=t.response.audio)!=null&&r.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 As(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("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,n,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=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n: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(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,a;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 n=this.audioContext,r=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(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 n;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(t),o=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:o,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(r){this.errorCallbacks.forEach(o=>o(r)),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((n,r)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];n(a)},o.onerror=r,o.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),r=new Uint8Array(n.length);for(let c=0;c<n.length;c++)r[c]=n.charCodeAt(c);let o=t.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(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 Kn=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,n;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=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.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(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 dr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Vr(e.runtype);case"browser":if(!Kn.isSupported())throw new Error("Browser speech recognition not supported");return new Kn(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Zs(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return dr({type:"runtype",runtype:e.runtype});if(Kn.isSupported())return dr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ts(e){try{return Zs(e),!0}catch{return!1}}var qr=class e{constructor(t={},n){this.config=t;this.callbacks=n;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=t=>{var n,r,o,s,a,i,d;t.type==="message"?(this.upsertMessage(t.message),(n=t.message.agentMetadata)!=null&&n.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:(r=t.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxTurns: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,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r;this.messages=[...(r=t.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 lr(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,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,r,o;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=dr(s);let a=(n=this.config.voiceRecognition)!=null?n:{},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(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 n,r,o,s,a,i,d,c,g;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:((o=t.runtype)==null?void 0:o.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.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:(g=t.browser)==null?void 0:g.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}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,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new lr(this.config),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:g}=t,y={id:a!=null?a:n==="user"?jr():n==="assistant"?cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,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(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 n=[];for(let r of t){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"?jr():o==="assistant"?cr():`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}};n.push(m)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}async sendMessage(t,n){var c,g,p,y,m;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let o=jr(),s=cr(),a={id:o,role:"user",content:r||ws,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.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 t=cr();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(c){let g={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(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(t,n){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(t,this.handleEvent,n==null?void 0:n.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(t,n){var d,c,g;let r=`approval-${t.id}`,o={...t,status:n,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:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),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):n==="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){(g=(c=this.callbacks).onError)==null||g.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.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=this.sortMessages(t.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(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!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 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,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t),s=r.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(o.rate=n.rate),n.pitch!==void 0&&(o.pitch=n.pitch),setTimeout(()=>r.speak(o),50)}static pickBestVoice(t){var r;let n=["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 n){let s=t.find(a=>a.name===o);if(s)return s}return(r=t.find(o=>o.lang.startsWith("en")))!=null?r:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>s===r?{...o,...n}: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((n,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var f=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},bn=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};import*as Rc from"lucide";var ue=(e,t=24,n="currentColor",r=2)=>{try{let o=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),s=Rc[o];return s?Hc(s,t,n,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 Hc(e,t,n,r){if(!e||!Array.isArray(e))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",n),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 Ms={allowedTypes:Mn,maxFileSize:10*1024*1024,maxFiles:4};function Bc(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $c(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 pr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ms.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ms.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ms.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:Ms.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 n,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let g=Gi(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 Xi(c),y=Ss(c)?URL.createObjectURL(c):null,m={id:Bc(),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(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ss(t.file),r=f("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=f("img");a.src=t.previewUrl,a.alt=t.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=$c(t.file.type),d=ue(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=f("span");c.textContent=Zi(t.file.type,t.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(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({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:n})}};var Qi={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"}},el={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"}},tl={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"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"}},markdown:{inlineCode:{background:"semantic.colors.container",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},prose:{fontFamily:"inherit"}},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}}};function nl(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?nl(e,r):r}function Qs(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=nl(e,a);d!==void 0&&(t[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&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function rl(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function sl(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=sl(s,o):n[r]=o}return n}function Fc(e,t){return t?sl(e,t):e}function Ur(e,t={}){var o,s,a,i,d,c,g,p,y,m,C,v,E;let n={palette:Qi,semantic:el,components:tl},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(g=e==null?void 0:e.semantic)==null?void 0:g.colors,interactive:{...n.semantic.colors.interactive,...(y=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:y.interactive},feedback:{...n.semantic.colors.feedback,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:C.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:Fc(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let x=rl(r);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(k=>k.message).join(", ")}`)}if(t.plugins)for(let x of t.plugins)r=x.transform(r);return r}function eo(e){var d,c,g,p,y,m,C,v,E,x,k,U,M,O,S,N,Z,K,re,z,pe,Le,Ye,fe,Q,Y,V,j,ce,he,gt,lt,mt,Pt,le,se,q,ne,oe,Ee,Ke,ee,X,He,Ve,et,jt,Dt,ie,Ue,Te,tt,_e,Xe;let t=Qs(e),n={};for(let[$t,Ft]of Object.entries(t)){let It=$t.replace(/\./g,"-");n[`--persona-${It}`]=Ft.value}n["--persona-primary"]=(d=n["--persona-semantic-colors-primary"])!=null?d:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(c=n["--persona-semantic-colors-secondary"])!=null?c:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(g=n["--persona-semantic-colors-accent"])!=null?g:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(p=n["--persona-semantic-colors-surface"])!=null?p:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(y=n["--persona-semantic-colors-background"])!=null?y:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(m=n["--persona-semantic-colors-container"])!=null?m:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(C=n["--persona-semantic-colors-text"])!=null?C:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(v=n["--persona-semantic-colors-text-muted"])!=null?v:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(E=n["--persona-semantic-colors-text-inverse"])!=null?E:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(x=n["--persona-semantic-colors-border"])!=null?x:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(k=n["--persona-semantic-colors-divider"])!=null?k:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(U=n["--persona-components-voice-recording-indicator"])!=null?U:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(M=n["--persona-components-voice-recording-background"])!=null?M:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(O=n["--persona-components-voice-processing-icon"])!=null?O:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(S=n["--persona-components-voice-speaking-icon"])!=null?S:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(N=n["--persona-components-approval-requested-background"])!=null?N:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Z=n["--persona-components-approval-requested-border"])!=null?Z:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(K=n["--persona-components-approval-requested-text"])!=null?K:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(re=n["--persona-components-approval-approve-background"])!=null?re:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(z=n["--persona-components-approval-deny-background"])!=null?z:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(pe=n["--persona-components-attachment-image-background"])!=null?pe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(Le=n["--persona-components-attachment-image-border"])!=null?Le:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(Ye=n["--persona-semantic-typography-fontFamily"])!=null?Ye:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(fe=n["--persona-semantic-typography-fontSize"])!=null?fe:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(Q=n["--persona-semantic-typography-fontWeight"])!=null?Q:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Y=n["--persona-semantic-typography-lineHeight"])!=null?Y:n["--persona-palette-typography-lineHeight-normal"],n["--persona-radius-sm"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(j=n["--persona-palette-radius-md"])!=null?j:"0.375rem",n["--persona-radius-lg"]=(ce=n["--persona-palette-radius-lg"])!=null?ce:"0.5rem",n["--persona-radius-xl"]=(he=n["--persona-palette-radius-xl"])!=null?he:"0.75rem",n["--persona-launcher-radius"]=(lt=(gt=n["--persona-components-launcher-borderRadius"])!=null?gt:n["--persona-palette-radius-full"])!=null?lt:"9999px",n["--persona-button-radius"]=(Pt=(mt=n["--persona-components-button-primary-borderRadius"])!=null?mt:n["--persona-palette-radius-full"])!=null?Pt:"9999px",n["--persona-panel-radius"]=(se=(le=n["--persona-components-panel-borderRadius"])!=null?le:n["--persona-radius-xl"])!=null?se:"0.75rem",n["--persona-input-radius"]=(ne=(q=n["--persona-components-input-borderRadius"])!=null?q:n["--persona-radius-lg"])!=null?ne:"0.5rem",n["--persona-message-user-radius"]=(Ee=(oe=n["--persona-components-message-user-borderRadius"])!=null?oe:n["--persona-radius-lg"])!=null?Ee:"0.5rem",n["--persona-message-assistant-radius"]=(ee=(Ke=n["--persona-components-message-assistant-borderRadius"])!=null?Ke:n["--persona-radius-lg"])!=null?ee:"0.5rem",n["--persona-header-bg"]=(X=n["--persona-components-header-background"])!=null?X:n["--persona-surface"],n["--persona-header-border"]=(He=n["--persona-components-header-border"])!=null?He:n["--persona-divider"],n["--persona-message-user-bg"]=(Ve=n["--persona-components-message-user-background"])!=null?Ve:n["--persona-accent"],n["--persona-message-user-text"]=(et=n["--persona-components-message-user-text"])!=null?et:n["--persona-text-inverse"],n["--persona-message-assistant-bg"]=(jt=n["--persona-components-message-assistant-background"])!=null?jt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Dt=n["--persona-components-message-assistant-text"])!=null?Dt:n["--persona-text"],n["--persona-message-assistant-border"]=(ie=n["--persona-components-message-assistant-border"])!=null?ie:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Ue=n["--persona-components-message-assistant-shadow"])!=null?Ue:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-md-inline-code-bg"]=(Te=n["--persona-components-markdown-inlineCode-background"])!=null?Te:n["--persona-container"],n["--persona-md-inline-code-color"]=(tt=n["--persona-components-markdown-inlineCode-foreground"])!=null?tt:n["--persona-text"],n["--persona-md-link-color"]=(Xe=(_e=n["--persona-components-markdown-link-foreground"])!=null?_e:n["--persona-accent"])!=null?Xe:"#3b82f6";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let o=n["--persona-components-markdown-heading-h1-fontWeight"];o&&(n["--persona-md-h1-weight"]=o);let s=n["--persona-components-markdown-heading-h2-fontSize"];s&&(n["--persona-md-h2-size"]=s);let a=n["--persona-components-markdown-heading-h2-fontWeight"];a&&(n["--persona-md-h2-weight"]=a);let i=n["--persona-components-markdown-prose-fontFamily"];return i&&i!=="inherit"&&(n["--persona-md-prose-font-family"]=i),n}var to={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"},ol={radiusSm:"palette.radius.md",radiusMd:"palette.radius.lg",radiusLg:"palette.radius.xl",launcherRadius:"palette.radius.full",buttonRadius:"palette.radius.full"};function no(e,t={}){if(!e)return{};let n={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 to){let s=to[r],[a,i,d,c]=s.split(".");if(a==="palette"&&i==="colors"){let g=d;n.palette.colors[g]&&(n.palette.colors[g][c||"500"]=o)}else if(a==="semantic"){let g=s.replace("semantic.colors.","").split(".");g.length===1?n.semantic.colors[g[0]]=o:n.semantic.colors[g[0]]={...n.semantic.colors[g[0]],[g[1]]:o}}}else if(r in ol){n.palette.radius||(n.palette.radius={});let s=r.replace("radius","").toLowerCase();n.palette.radius[s||"md"]=o}else r==="inputFontFamily"?(n.palette.typography||(n.palette.typography={fontFamily:{}}),n.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"?(n.palette.typography||(n.palette.typography={fontWeight:{}}),n.palette.typography.fontWeight={normal:o}):r==="panelBorder"?(n.components||(n.components={}),n.components.panel||(n.components.panel={}),n.components.panel.border=o):r==="panelShadow"?(n.components||(n.components={}),n.components.panel||(n.components.panel={}),n.components.panel.shadow=o):r==="panelBorderRadius"&&(n.components||(n.components={}),n.components.panel||(n.components.panel={}),n.components.panel.borderRadius=o);return t.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."),n}function Nc(e){let t=[],n=e;if(!n)return{valid:!0,warnings:[]};let r=Object.keys(n).filter(o=>!(o in to||o in ol||o==="inputFontFamily"||o==="inputFontWeight"||o.startsWith("panel")));return r.length>0&&t.push(`The following v1 theme properties have no v2 equivalent and will be ignored: ${r.join(", ")}`),{valid:!0,warnings:t}}var Oc={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"}}},ro=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),so=(e,t)=>{if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];ro(s)&&ro(o)?n[r]=so(s,o):n[r]=o}return n},Dc=e=>ro(e)&&("palette"in e||"semantic"in e||"components"in e),al=e=>{if(!e)return;let t=no(e,{warn:!1});return Dc(e)?so(t,e):t},ks=()=>{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"},_c=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ks()},il=e=>_c(e),jc=e=>Ur(e),Vc=e=>{var n;let t=Ur(void 0,{validate:!1});return Ur({...e,palette:{...t.palette,colors:{...Oc.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ll=e=>{let t=il(e),n=al(e==null?void 0:e.theme),r=al(e==null?void 0:e.darkTheme);return t==="dark"?Vc(so(n,r)):jc(n)},qc=e=>eo(e),Yn=(e,t)=>{let n=ll(t),r=qc(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},oo=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ks())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(ks());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as Uc}from"idiomorph";var cl=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Uc.morph(e,t.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 dl(e,t){var n,r,o,s,a,i,d,c,g,p,y,m,C,v,E,x,k,U;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.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,t].join("\0")}function pl(){return new Map}function ul(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function gl(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function ml(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}var _t={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var zc={side:"right",width:"420px",collapsedWidth:"72px"},Ut=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},zr=e=>{var t,n;return{...zc,...(n=(t=e==null?void 0:e.launcher)==null?void 0:t.dock)!=null?n:{}}};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 Jr=(e,t)=>{let n=f("button");n.type="button",n.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 Cn=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}},Vn=(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 Xi=n=>Cn({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Gi=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}},Zi=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}},Cr={default:Xi,minimal:Gi,expanded:Zi},Qi=n=>{var t;return(t=Cr[n])!=null?t:Cr.default},ys=(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=Qi(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 el=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'}},bs=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=el(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 mn=g("div","tvw-send-button-tooltip");mn.textContent=Ze,V.appendChild(mn)}}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:bn).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 ea=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}},ta=(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?ys(n,e,{showClose:t}):Cn({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=bs({config:n}),m=((Y=n==null?void 0:n.layout)==null?void 0:Y.showFooter)!==!1;return o?Vn(r,s,n):(s.header.style.display="none",Vn(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 tl=320,nl=320,sl=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),rl=(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=`${tl}px`,c.style.maxHeight=`${nl}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}},zn=()=>{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},sa=(n,t,r)=>{let e={config:r!=null?r:{},streaming:!0,location:n,defaultRenderer:zn};if(t){let o=t(e);if(o!==null)return o}return zn()},ol=(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},na=(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},il=(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},ra=(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},Cs=(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=il(n.role,a),y=g("div",C.join(" "));y.id=`bubble-${n.id}`,y.setAttribute("data-message-id",n.id);let A=sl(n),x=(U=(G=n.content)==null?void 0:G.trim())!=null?U:"",Y=A.length>0&&x===qs,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=na(n,c);N.classList.add("tvw-ml-2","tvw-inline"),k.appendChild(N)}if(A.length>0){let N=rl(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=na(n,c);N.classList.add("tvw-mt-1"),y.appendChild(N)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let N=sa("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=ra(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=ol(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},al=(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}):Cs(n,t,r,e,o,s)};var Jn=new Set,oa=(n,t)=>{let r=Jn.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"},xr=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=Jn.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=_i(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 Kn=new Set,ia=(n,t,r)=>{var c;let e=Kn.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"},Sr=(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=Kn.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=Ui(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=hs(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=hs(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 Ar=(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=hs(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 aa=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 xs=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 Ss=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 Yn(n,t){t&&t.split(/\s+/).forEach(r=>r&&n.classList.add(r))}var ll={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"},dl=["flowName","stepName","reasoningText","text","name","tool","toolName"],ul=100;function pl(n,t){let r={...ll,...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 gl(n,t){return`+${((n-t)/1e3).toFixed(3)}s`}function hl(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 fl(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 vl(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 wl(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 Er(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");Yn(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"?gl(n.timestamp,r):hl(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=pl(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:dl,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 fl(vl(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(wl(n,i,a)),w}}function la(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");Yn(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");Yn(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");Yn(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"),Yn(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");Yn(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=Er(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=Er(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=Er(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>=ul){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 ca={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"}},Tr=(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=ca[i])!=null?y:ca.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 Mr=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()}},Gs=new Mr;var da={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"},ua={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"},lt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:da,darkTheme:ua,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 kr(n){var t,r,e,o,s,i,a,d,c,v,p,m,w,C,y,A,x,H,Y;return n?{...lt,...n,theme:{...lt.theme,...n.theme},darkTheme:{...lt.darkTheme,...n.darkTheme},launcher:{...lt.launcher,...n.launcher,clearChat:{...(t=lt.launcher)==null?void 0:t.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...lt.copy,...n.copy},sendButton:{...lt.sendButton,...n.sendButton},statusIndicator:{...lt.statusIndicator,...n.statusIndicator},voiceRecognition:{...lt.voiceRecognition,...n.voiceRecognition},features:{...lt.features,...n.features},suggestionChips:(e=n.suggestionChips)!=null?e:lt.suggestionChips,suggestionChipsConfig:{...lt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...lt.layout,...n.layout,header:{...(o=lt.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=lt.layout)==null?void 0:i.messages,...(a=n.layout)==null?void 0:a.messages,avatar:{...(c=(d=lt.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=lt.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=lt.layout)==null?void 0:A.slots,...(x=n.layout)==null?void 0:x.slots}},markdown:{...lt.markdown,...n.markdown,options:{...(H=lt.markdown)==null?void 0:H.options,...(Y=n.markdown)==null?void 0:Y.options}},messageActions:{...lt.messageActions,...n.messageActions}}:lt}var pa=()=>{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 yl=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},bl=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},Zs=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=yl(n),r=bl(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}},Ir=n=>typeof n=="string"?n:n==null?"":String(n),Xn={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Ir(n.payload.text)},messageAndClick:(n,t)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,e=Ir(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:Ir(r.text)}}},ga=n=>Array.isArray(n)?n.map(t=>String(t)):[],Qs=n=>{let t=new Set(ga(n.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(ga(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 Cl=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}},xl=n=>n.map(t=>({...t,streaming:!1})),Lr=(n="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?Cl(r.getItem(n)):null},save:r=>{let e=t();if(e)try{let o={...r,messages:r.messages?xl(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 Wr=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)})}},As=new Wr;import{parse as Sl,STR as Al,OBJ as El}from"partial-json";function Tl(n){if(!n||typeof n!="object"||!("component"in n))return!1;let t=n.component;return typeof t=="string"&&t.length>0}function Ml(n,t){if(!Tl(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 Pr(){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=Sl(r,Al|El),s=Ml(o,r);s&&(n=s)}catch{}return t=r.length,n},reset:()=>{n=null,t=0}}}function kl(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function Rr(n,t){let{config:r,message:e,onPropsUpdate:o}=t,s=As.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 Il(){let n=Pr();return{processChunk:t=>n.processChunk(t),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Hr(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 Br(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 Ll=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Fr(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=Ll}=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
+ `,n.addEventListener("click",t);let r=s=>{var U,M,O,S,N,Z,K,re,z,pe,Le,Ye;let a=(U=s.launcher)!=null?U:{},i=Ut(s),d=n.querySelector("[data-role='launcher-title']");d&&(d.textContent=(M=a.title)!=null?M:"Chat Assistant");let c=n.querySelector("[data-role='launcher-subtitle']");c&&(c.textContent=(O=a.subtitle)!=null?O:"Get answers fast");let g=n.querySelector(".persona-flex-col");g&&(a.textHidden||i?g.style.display="none":g.style.display="");let p=n.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 Q=parseFloat(fe)||24,Y=ue(a.agentIconName,Q*.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=(Z=a.agentIconText)!=null?Z:"\u{1F4AC}",p.style.display="")}let y=n.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=n.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 Q=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Q=(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-Q,8),j=ue(a.callToActionIconName,V,"currentColor",2);j?m.appendChild(j):m.textContent=(z=a.callToActionIconText)!=null?z:"\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";n.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(n.style.border=(Le=a.border)!=null?Le:x,n.style.boxShadow=(Ye=a.shadow)!=null?Ye:k,i){let fe=zr(s);n.style.width=`calc(${fe.collapsedWidth} - 16px)`,n.style.minWidth="40px",n.style.maxWidth=`calc(${fe.collapsedWidth} - 16px)`,n.style.justifyContent="center",n.style.padding="12px 0"}else n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.justifyContent="",n.style.padding=""},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var $n=e=>{var re,z,pe,Le,Ye,fe,Q,Y,V,j,ce,he,gt,lt,mt,Pt,le,se,q,ne,oe,Ee,Ke,ee,X,He,Ve,et,jt,Dt,ie,Ue;let{config:t,showClose:n=!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=t==null?void 0:t.launcher)!=null?re:{},s=(z=o.headerIconSize)!=null?z:"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=(Q=(fe=t==null?void 0:t.launcher)==null?void 0:fe.agentIconText)!=null?Q:"\u{1F4AC}"}else if((Y=t==null?void 0:t.launcher)!=null&&Y.iconUrl){let Te=f("img");Te.src=t.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=t==null?void 0:t.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=t==null?void 0:t.launcher)==null?void 0:ce.title)!=null?he:"Chat Assistant";let m=f("span","persona-text-xs persona-text-persona-muted");m.textContent=(lt=(gt=t==null?void 0:t.launcher)==null?void 0:gt.subtitle)!=null?lt:"Here to help you get answers fast",p.append(y,m),d?r.append(p):r.append(g,p);let C=(mt=o.clearChat)!=null?mt:{},v=(Pt=C.enabled)!=null?Pt:!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:"",$t=(Ee=C.borderWidth)!=null?Ee:"",Ft=(Ke=C.borderColor)!=null?Ke:"",It=(ee=C.borderRadius)!=null?ee:"",H=(X=C.paddingX)!=null?X:"",te=(He=C.paddingY)!=null?He:"",J=(Ve=C.tooltipText)!=null?Ve:"Clear chat",We=(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",J);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")),$t||Ft){let Pe=$t||"0px",Be=Ft||"transparent";x.style.border=`${Pe} solid ${Be}`,x.classList.remove("persona-border-none")}if(It&&(x.style.borderRadius=It,x.classList.remove("persona-rounded-full")),H?(x.style.paddingLeft=H,x.style.paddingRight=H):(x.style.paddingLeft="",x.style.paddingRight=""),te?(x.style.paddingTop=te,x.style.paddingBottom=te):(x.style.paddingTop="",x.style.paddingBottom=""),k.appendChild(x),We&&J&&x&&k){let Pe=null,Be=()=>{if(Pe||!x)return;let ye=x.ownerDocument,be=ye.body;if(!be)return;Pe=bn(ye,"div","persona-clear-chat-tooltip"),Pe.textContent=J;let $e=bn(ye,"div");$e.className="persona-clear-chat-tooltip-arrow",Pe.appendChild($e);let de=x.getBoundingClientRect();Pe.style.position="fixed",Pe.style.left=`${de.left+de.width/2}px`,Pe.style.top=`${de.top-8}px`,Pe.style.transform="translate(-50%, -100%)",be.appendChild(Pe)},ut=()=>{Pe&&Pe.parentNode&&(Pe.parentNode.removeChild(Pe),Pe=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=(jt=o.closeButtonTooltipText)!=null?jt:"Close chat",S=(Dt=o.closeButtonShowTooltip)!=null?Dt:!0;M.setAttribute("aria-label",O),M.style.display=n?"":"none";let N=(ie=o.closeButtonIconName)!=null?ie:"x",Z=(Ue=o.closeButtonIconText)!=null?Ue:"\xD7",K=ue(N,"20px",o.closeButtonColor||"",1);if(K?M.appendChild(K):M.textContent=Z,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,$t=Xe.body;if(!$t)return;Te=bn(Xe,"div","persona-clear-chat-tooltip"),Te.textContent=O;let Ft=bn(Xe,"div");Ft.className="persona-clear-chat-tooltip-arrow",Te.appendChild(Ft);let It=M.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${It.left+It.width/2}px`,Te.style.top=`${It.top-8}px`,Te.style.transform="translate(-50%, -100%)",$t.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}},ur=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.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(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var fl=e=>$n({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat});function Jc(e,t,n){var r,o;if(t!=null&&t.length)for(let s of t){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",()=>n==null?void 0:n(s.id)),e.appendChild(a)}}var hl=e=>{var x,k,U,M,O;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(x=t==null?void 0:t.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),Jc(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=n?"":"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}},ao={default:fl,minimal:hl},yl=e=>{var t;return(t=ao[e])!=null?t:ao.default},Kr=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.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=t==null?void 0:t.layout)!=null?a:"default",s=yl(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});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 Kc=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'}},Yr=e=>{var le,se,q,ne,oe,Ee,Ke,ee,X,He,Ve,et,jt,Dt,ie,Ue,Te,tt,_e,Xe,$t,Ft,It,H,te,J,We,Ce,Pe,Be,ut;let{config:t}=e,n=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=t==null?void 0:t.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=t==null?void 0:t.theme)==null?void 0:q.inputFontFamily)!=null?ne:"sans-serif",i=(Ee=(oe=t==null?void 0:t.theme)==null?void 0:oe.inputFontWeight)!=null?Ee:"400";s.style.fontFamily=Kc(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=t==null?void 0:t.sendButton)!=null?Ke:{},m=(ee=y.useIcon)!=null?ee:!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=(jt=t==null?void 0:t.copy)==null?void 0:jt.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=t==null?void 0:t.voiceRecognition)!=null?ie:{},Z=N.enabled===!0,K=null,re=null,z=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),pe=((Ue=N.provider)==null?void 0:Ue.type)==="runtype";if(Z&&(z||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=($t=N.tooltipText)!=null?$t:"Start voice recognition";if(((Ft=N.showTooltip)!=null?Ft:!1)&&un){let Ln=f("div","persona-send-button-tooltip");Ln.textContent=un,re.appendChild(Ln)}}let Ye=(It=t==null?void 0:t.attachments)!=null?It:{},fe=Ye.enabled===!0,Q=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:Mn).join(","),V.multiple=((te=Ye.maxFiles)!=null?te:4)>1,V.style.display="none",V.setAttribute("aria-label","Attach files"),Y=f("div","persona-send-button-wrapper"),Q=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Q.type="button",Q.setAttribute("aria-label",(J=Ye.buttonTooltipText)!=null?J:"Attach file");let ye=(We=Ye.buttonIconName)!=null?We:"paperclip",be=k,$e=parseFloat(be)||40,de=Math.round($e*.6);Q.style.width=be,Q.style.height=be,Q.style.minWidth=be,Q.style.minHeight=be,Q.style.fontSize="18px",Q.style.lineHeight="1",Q.style.backgroundColor="transparent",Q.style.color="var(--persona-primary, #111827)",Q.style.border="none",Q.style.borderRadius="6px",Q.style.transition="background-color 0.15s ease",Q.addEventListener("mouseenter",()=>{Q.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Q.addEventListener("mouseleave",()=>{Q.style.backgroundColor="transparent"});let bt=ue(ye,de,"currentColor",1.5);bt?Q.appendChild(bt):Q.textContent="\u{1F4CE}",Q.addEventListener("click",un=>{un.preventDefault(),V==null||V.click()}),Y.appendChild(Q);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!==Q&&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 gt=f("div","persona-flex persona-items-center persona-gap-1");re&&gt.append(re),gt.append(O),ce.append(he,gt),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 mt=(Pe=t==null?void 0:t.statusIndicator)!=null?Pe:{},Pt=(Be=mt.visible)!=null?Be:!0;return lt.style.display=Pt?"":"none",lt.textContent=(ut=mt.idleText)!=null?ut:"Online",n.append(r,o,lt),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:S,sendButtonWrapper:O,micButton:K,micButtonWrapper:re,statusText:lt,attachmentButton:Q,attachmentButtonWrapper:Y,attachmentInput:V,attachmentPreviewsContainer:j,actionsRow:ce,leftActions:he,rightActions:gt}};var bl=e=>{var c,g,p,y,m,C,v;let t=(g=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?g:!0;if(Ut(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(!t){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}},xl=(e,t=!0)=>{var v,E,x,k,U,M,O,S,N;let n=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?Kr(e,r,{showClose:t}):$n({config:e,showClose:t}),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=Yr({config:e}),C=((N=e==null?void 0:e.layout)==null?void 0:N.showFooter)!==!1;return o?ur(n,s,e):(s.header.style.display="none",ur(n,s,e)),n.append(a),C||(m.footer.style.display="none"),n.append(m.footer),{container:n,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 Yc=320,Xc=320,Gc=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Zc=(e,t,n)=>{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"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};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=`${Yc}px`,c.style.maxHeight=`${Xc}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 n==null||n(),null}},gr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";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="0ms";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="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(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},Cl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:gr};if(t){let o=t(r);if(o!==null)return o}return gr()},Qc=(e,t)=>{let n=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=t==="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=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},vl=(e,t)=>{let n=f("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},ed=(e,t="bubble")=>{let n=["vanilla-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("vanilla-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("vanilla-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.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 n},wl=(e,t,n)=>{var m,C,v,E,x,k;let r=(m=t.showCopy)!=null?m:!0,o=(C=t.showUpvote)!=null?C:!0,s=(v=t.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=t.visibility)!=null?E:"hover",i=(x=t.align)!=null?x:"right",d=(k=t.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},Xr=(e,t,n,r,o,s)=>{var re,z,pe,Le,Ye,fe,Q;let a=n!=null?n:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,g=(z=d==null?void 0:d.show)!=null?z:!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=ed(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=Gc(e),x=(Q=(fe=e.content)==null?void 0:fe.trim())!=null?Q:"",U=E.length>0&&x===ws,M=document.createElement("div");M.classList.add("persona-message-content");let O=t({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=vl(e,c);Y.classList.add("persona-ml-2","persona-inline"),M.appendChild(Y)}if(E.length>0){let Y=Zc(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=vl(e,c);Y.classList.add("persona-mt-1"),v.appendChild(Y)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let Y=Cl("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=wl(e,r,o);v.appendChild(Y)}if(!g||e.role==="system")return v;let Z=f("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),K=Qc(d,e.role);return y==="right"||y==="left"&&e.role==="user"?Z.append(v,K):Z.append(K,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Z},td=(e,t,n,r,o,s)=>{let a=n!=null?n:{};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}):Xr(e,t,n,r,o,s)};var mr=new Set,Sl=(e,t)=>{let n=mr.has(e),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t");if(!r||!o)return;r.setAttribute("aria-expanded",n?"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(n?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=n?"Hide":"Show"}o.style.display=n?"":"none"},io=e=>{let t=e.reasoning,n=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(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),!t)return n;let r=mr.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=Ji(t),s.appendChild(i),t.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=t.chunks.join(""),C=f("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return C.textContent=m||(t.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"})(),n.append(o,y),n};var fr=new Set,Al=(e,t,n)=>{var c;let r=fr.has(e),o=(c=n==null?void 0:n.toolCall)!=null?c:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.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"},lo=(e,t)=>{var v;let n=e.toolCall,r=(v=t==null?void 0:t.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),!n)return o;let s=fr.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=Ki(n),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),n.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=n.name,m.appendChild(E)}if(n.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=_r(n.args),E.append(x,k),m.appendChild(E)}if(n.chunks&&n.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=n.chunks.join(`
16
+ `),E.append(x,k),m.appendChild(E)}if(n.status==="complete"&&n.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=_r(n.result),E.append(x,k),m.appendChild(E)}if(n.status==="complete"&&typeof n.duration=="number"){let E=f("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(E.style.color=r.contentTextColor),E.textContent=`Duration: ${n.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 co=(e,t)=>{var v,E,x,k,U,M,O,S,N,Z,K,re;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.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)",!n)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=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.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 z=f("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");z.setAttribute("data-approval-status",n.status),n.status==="approved"?(z.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",z.style.color="var(--persona-palette-colors-success-700, #15803d)",z.textContent="Approved"):n.status==="denied"?(z.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",z.style.color="var(--persona-palette-colors-error-700, #b91c1c)",z.textContent="Denied"):n.status==="timeout"&&(z.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",z.style.color="var(--persona-palette-colors-warning-700, #b45309)",z.textContent="Timeout"),y.appendChild(z)}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=n.description,p.appendChild(C),n.parameters){let z=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&&(z.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(z.style.color=r.parameterTextColor),z.style.fontSize="0.75rem",z.style.lineHeight="1rem",z.textContent=_r(n.parameters),p.appendChild(z)}if(o){let z=f("div","persona-flex persona-gap-2 persona-mt-2");z.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=(Z=r==null?void 0:r.denyButtonTextColor)!=null?Z:"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 Q=ue("shield-x",14,(K=r==null?void 0:r.denyButtonTextColor)!=null?K:"var(--persona-feedback-error, #dc2626)",2);Q&&(Q.style.marginRight="4px",fe.appendChild(Q));let Y=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");fe.appendChild(Y),z.append(pe,fe),p.appendChild(z)}return a.append(i,p),s.appendChild(a),s};var El=e=>{let t=[];return{buttons:t,render:(r,o,s,a,i)=>{if(e.innerHTML="",t.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),t.push(C)}),e.appendChild(g)}}};var Gr=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;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),(n=this.store)==null||n.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 n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)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=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.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 Zr=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{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,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}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 r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{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=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{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=()=>{n(s.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};function hr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var nd={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)"}},rd={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},sd=["flowName","stepName","reasoningText","text","name","tool","toolName"],od=100;function ad(e,t){let n={...nd,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return rd}function id(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function ld(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function cd(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;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 dd(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{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),n()})}function pd(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function ud(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,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 po(e,t,n,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");hr(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:t,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"?id(e.timestamp,n):ld(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(t+1));let M=ad(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:sd,N=cd(e.payload,S),Z=null;N&&(Z=f("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Z.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"),z=ue("clipboard","12px","currentColor",1.5);return z&&re.appendChild(z),re.addEventListener("click",async Ye=>{Ye.stopPropagation(),await dd(pd(e)),re.innerHTML="";let fe=ue("check","12px","currentColor",1.5);fe&&re.appendChild(fe),setTimeout(()=>{re.innerHTML="";let Q=ue("clipboard","12px","currentColor",1.5);Q&&re.appendChild(Q)},1500)}),C.appendChild(v),C.appendChild(x),U&&C.appendChild(U),C.appendChild(O),Z&&C.appendChild(Z),C.appendChild(K),C.appendChild(re),m.appendChild(C),d&&m.appendChild(ud(e,a,i)),m}}function Tl(e){var c,g;let{buffer:t,getFullHistory:n,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:t.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");hr(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,Z=null,K=!1,re=0,z=new Set,pe=new Map,Le="",Ye="",fe=null,Q,Y,V,j,ce;function he(){let te=f("div","persona-flex persona-flex-col persona-flex-shrink-0"),J=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");hr(J,p==null?void 0:p.headerBar);let We=f("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");We.textContent="Events",Q=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"),Q.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 Pe=f("option","");Pe.value="",Pe.textContent="All events",Y.appendChild(Pe),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),J.appendChild(We),J.appendChild(Q),J.appendChild(Ce),J.appendChild(Y),J.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");hr(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"),hr(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),te.appendChild(J),te.appendChild(be),te}let gt,lt=s.find(te=>te.renderEventStreamToolbar);if(lt!=null&&lt.renderEventStreamToolbar&&o){let te=lt.renderEventStreamToolbar({config:o,defaultRenderer:()=>he(),eventCount:t.getSize(),filteredCount:0,onFilterChange:J=>{C=J,X(),et()},onSearchChange:J=>{v=J,X(),et()}});gt=te!=null?te:he()}else gt=he();let mt=f("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");mt.style.display="none";let Pt=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");hr(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",Pt.appendChild(le),Pt.appendChild(oe),Pt.appendChild(se),y.setAttribute("tabindex","0"),y.appendChild(gt),y.appendChild(mt),y.appendChild(Pt);function Ee(){let te=t.getAll(),J={};for(let ye of te)J[ye.type]=(J[ye.type]||0)+1;let We=Object.keys(J).sort(),Ce=We.length!==x.length||!We.every((ye,be)=>ye===x[be]),Pe=!Ce&&We.some(ye=>J[ye]!==k[ye]),Be=te.length!==Object.values(k).reduce((ye,be)=>ye+be,0);if(!Ce&&!Pe&&!Be||(x=We,k=J,!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 We){let be=f("option","");be.value=ye,be.textContent=`${ye} (${J[ye]||0})`,Y.appendChild(be)}ut&&We.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} (${J[be.value]||0})`}}function Ke(){let te=t.getAll();if(C&&(te=te.filter(J=>J.type===C)),v){let J=v.toLowerCase();te=te.filter(We=>We.type.toLowerCase().includes(J)||We.payload.toLowerCase().includes(J))}return te}function ee(){return C!==""||v!==""}function X(){U=0,O=0,M=!1,se.style.display="none"}function He(te){z.has(te)?z.delete(te):z.add(te),fe=te;let J=le.scrollTop,We=M;K=!0,M=!0,et(),le.scrollTop=J,M=We,K=!1}function Ve(){return le.scrollHeight-le.scrollTop-le.clientHeight<=50}function et(){S=Date.now(),N=!1,Ee();let te=t.getEvictedCount();te>0?(mt.textContent=`${te.toLocaleString()} older events truncated`,mt.style.display=""):mt.style.display="none",m=Ke();let J=m.length,We=t.getSize()>0;Q&&(Q.textContent=String(t.getSize())),J===0&&We&&ee()?(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=ee()?`Copy Filtered (${J})`:"Copy All"),M&&J>U&&(O+=J-U,ne.textContent=`${O} new event${O===1?"":"s"}`,se.style.display=""),U=J;let Ce=t.getAll(),Pe=Ce.length>0?Ce[0].timestamp:0,Be=new Set(m.map(be=>be.id));for(let be of z)Be.has(be)||z.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=po(m[$e],$e,Pe,a,z,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=po(m[de],de,Pe,a,z,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=po(de,$e,Pe,a,z,He,s,o);pe.set(de.id,bt),le.appendChild(bt)}}}M||(le.scrollTop=le.scrollHeight)}function jt(){if(Date.now()-S>=od){Z!==null&&(cancelAnimationFrame(Z),Z=null),et();return}N||(N=!0,Z=requestAnimationFrame(()=>{Z=null,et()}))}let Dt=(te,J)=>{if(!V)return;V.innerHTML="";let We=ue(te,"12px","currentColor",1.5);We&&V.appendChild(We);let Ce=f("span","persona-text-xs");Ce.textContent="Copy All",V.appendChild(Ce),setTimeout(()=>{V.innerHTML="";let Pe=ue("clipboard-copy","12px","currentColor",1.5);Pe&&V.appendChild(Pe);let Be=f("span","persona-text-xs");Be.textContent="Copy All",V.appendChild(Be),V.disabled=!1},J)},ie=async()=>{if(V){V.disabled=!0;try{let te;ee()?te=m:n?(te=await n(),te.length===0&&(te=t.getAll())):te=t.getAll();let J=te.map(We=>{try{return JSON.parse(We.payload)}catch{return We.payload}});await navigator.clipboard.writeText(JSON.stringify(J,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 te=le.scrollTop,J=te>re;re=te,Ve()&&J?(M=!1,O=0,se.style.display="none"):Ve()||(M=!0)},Xe=te=>{te.deltaY<0&&(M=!0)},$t=()=>{le.scrollTop=le.scrollHeight,M=!1,O=0,se.style.display="none"},Ft=te=>{let J=te.target;if(!J||J.closest("button"))return;let We=J.closest("[data-event-id]");if(!We)return;let Ce=We.getAttribute("data-event-id");Ce&&He(Ce)},It=te=>{if((te.metaKey||te.ctrlKey)&&te.key==="f"){te.preventDefault(),j==null||j.focus(),j==null||j.select();return}te.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",Ft),se.addEventListener("click",$t),y.addEventListener("keydown",It);function H(){E&&clearTimeout(E),Z!==null&&(cancelAnimationFrame(Z),Z=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",Ft),se.removeEventListener("click",$t),y.removeEventListener("keydown",It)}return{element:y,update:jt,destroy:H}}}var Ml=e=>{let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=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 ${t} in artifact panel`),n&&a.setAttribute("data-open-artifact",n);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=t;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 ${t}`,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",n),a.append(p)}return a};var uo=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}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(([n,r])=>{this.register(n,r)})}},Fn=new uo;Fn.register("PersonaArtifactCard",Ml);function gd(e){var o;let t=f("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=f("div","persona-font-semibold persona-text-sm persona-mb-2");n.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),t.appendChild(n),t.appendChild(r),t}function Qr(e,t,n=""){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 ${n}`);r.type="button",r.setAttribute("aria-label",t),r.title=t;let o=ue(e,16,"currentColor",2);return o&&r.appendChild(o),r}function es(e,t,n){let r=f("button",`persona-artifact-doc-icon-btn ${n}`.trim());r.type="button",r.setAttribute("aria-label",t),r.title=t;let o=ue(e,16,"currentColor",2);return o&&r.appendChild(o),r}function kl(e){let t=f("button","persona-artifact-doc-copy-btn");t.type="button",t.setAttribute("aria-label","Copy"),t.title="Copy";let n=ue("copy",e?14:16,"currentColor",2);if(n&&t.appendChild(n),e){let r=f("span","persona-artifact-doc-copy-label");r.textContent="Copy",t.appendChild(r)}return t}function md(){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 t=ue("chevron-down",14,"currentColor",2);return t&&e.appendChild(t),e}function Ll(e,t){var mt,Pt,le,se;let n=(Pt=(mt=e.features)==null?void 0:mt.artifacts)==null?void 0:Pt.layout,o=((le=n==null?void 0:n.toolbarPreset)!=null?le:"default")==="document",s=(se=n==null?void 0:n.panePadding)==null?void 0:se.trim(),a=e.markdown?ir(e.markdown):null,i=q=>a?a(q):Dr(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=t.onDismiss)==null||q.call(t)});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=t.onDismiss)==null||q.call(t)});let C="rendered",v=f("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=o?es("eye","Rendered view","persona-artifact-view-btn"):Qr("eye","Rendered view",""),x=o?es("code-2","Source","persona-artifact-code-btn"):Qr("code-2","Source",""),k=f("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),U=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,M=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,O=n==null?void 0:n.documentToolbarCopyMenuItems,S=!!(M&&O&&O.length>0),N=null,Z,K=null,re=null;if(o&&(U||M)&&!S){if(Z=kl(U),M){let q=ue("chevron-down",14,"currentColor",2);q&&Z.appendChild(q)}}else if(o&&S){N=f("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Z=kl(U),K=md(),N.append(Z,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?Z=es("copy","Copy",""):Z=Qr("copy","Copy","");let z=o?es("refresh-cw","Refresh",""):Qr("refresh-cw","Refresh",""),pe=o?es("x","Close",""):Qr("x","Close",""),Le=()=>{var Ke,ee,X;let q=(Ke=j.find(He=>He.id===ce))!=null?Ke:j[j.length-1],ne=(ee=q==null?void 0:q.id)!=null?ee: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(ee=>ee.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(Z.addEventListener("click",async()=>{let q=n==null?void 0:n.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:ee,id:X}=Le(),He=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{He?await He({actionId:Ee,artifactId:X,markdown:Ke,jsonPayload:ee}):Ee==="markdown"||Ee==="md"?await navigator.clipboard.writeText(Ke):Ee==="json"||Ee==="source"?await navigator.clipboard.writeText(ee):await navigator.clipboard.writeText(Ke||ee)}catch{}q()})}z.addEventListener("click",async()=>{var q;try{await((q=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:q.call(n))}catch{}gt()}),pe.addEventListener("click",()=>{var q;c(),(q=t.onDismiss)==null||q.call(t)});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(),gt()}),x.addEventListener("click",()=>{C="source",fe(),gt()});let Q=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,z,pe):k.append(Z,z,pe),p.append(v,Q,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,gt=()=>{var Ee,Ke,ee,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",()=>t.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";Q.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((ee=ne.markdown)!=null?ee:""),V.appendChild(He);return}let oe=ne.component?Fn.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(gd(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),gt(),lt()},setMobileOpen(q){he=q,!q&&d?(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):lt()}}}function on(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Pl(e,t){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(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.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 fd(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 Ls(e,t){var d,c,g,p,y,m,C,v,E,x;if(!on(t)){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"),fd(e),Pl(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(g=n==null?void 0:n.splitGap)!=null?g:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=n==null?void 0:n.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(y=n==null?void 0:n.paneMaxWidth)!=null?y:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=n==null?void 0:n.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=n==null?void 0:n.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=n==null?void 0:n.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=n==null?void 0:n.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=n==null?void 0:n.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"),Pl(e,t)}var Il=["panel","seamless"];function Ps(e,t){var i,d,c,g,p,y;for(let m of Il)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(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",o=Il.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(g=n==null?void 0:n.paneBorderRadius)==null?void 0:g.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(p=n==null?void 0:n.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((y=n.unifiedSplitOuterRadius)==null?void 0:y.trim())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Wl(e,t){var n,r,o;return!t||!on(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function hd(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function yd(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function bd(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function xd(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function Rl(e,t){var a;let r=(a=(t.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 Hl(e,t,n,r,o,s){let a=hd(o,200),i=xd(t,n,r,200);i=Math.max(a,i);let d=yd(s);return d!==null&&(i=Math.min(i,d)),bd(e,a,i)}var Bl={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"}},go=(e,t,n,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=Bl[a])!=null?v:Bl.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=`${t.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=`${t.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=n.formEndpoint)!=null?O:"/form",U=new FormData(g),M={};U.forEach((N,Z)=>{M[Z]=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 Z=await N.json();y.textContent=(S=Z.message)!=null?S:"Thanks! We'll be in touch soon.",Z.success&&Z.nextPrompt&&await r.sendMessage(String(Z.nextPrompt))}catch(N){y.textContent=N instanceof Error?N.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var mo=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Is=new mo;var $l={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"},Fl={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"},yt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:$l,darkTheme:Fl,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 fo(e){var t,n,r,o,s,a,i,d,c,g,p,y,m,C,v,E,x,k,U,M,O;return e?{...yt,...e,theme:{...yt.theme,...e.theme},darkTheme:{...yt.darkTheme,...e.darkTheme},launcher:{...yt.launcher,...e.launcher,dock:{...(t=yt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=yt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...yt.copy,...e.copy},sendButton:{...yt.sendButton,...e.sendButton},statusIndicator:{...yt.statusIndicator,...e.statusIndicator},voiceRecognition:{...yt.voiceRecognition,...e.voiceRecognition},features:(()=>{var K,re;let S=(K=yt.features)==null?void 0:K.artifacts,N=(re=e.features)==null?void 0:re.artifacts,Z=S===void 0&&N===void 0?void 0:{...S,...N,layout:{...S==null?void 0:S.layout,...N==null?void 0:N.layout}};return{...yt.features,...e.features,...Z!==void 0?{artifacts:Z}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:yt.suggestionChips,suggestionChipsConfig:{...yt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...yt.layout,...e.layout,header:{...(a=yt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=yt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(g=yt.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=yt.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=yt.layout)==null?void 0:k.slots,...(U=e.layout)==null?void 0:U.slots}},markdown:{...yt.markdown,...e.markdown,options:{...(M=yt.markdown)==null?void 0:M.options,...(O=e.markdown)==null?void 0:O.options}},messageActions:{...yt.messageActions,...e.messageActions}}:yt}var Nl=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,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 vd=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Cd=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},Ws=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=vd(e),n=Cd(t);if(!n)return null;let r=JSON.parse(n);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}},ho=e=>typeof e=="string"?e:e==null?"":String(e),yr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ho(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=ho(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:ho(n.text)}}},Ol=e=>Array.isArray(e)?e.map(t=>String(t)):[],Rs=e=>{let t=new Set(Ol(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Ol(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.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;t.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:n}};var wd=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Sd=e=>e.map(t=>({...t,streaming:!1})),yo=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?wd(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?Sd(n.messages):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as Ad,STR as Ed,OBJ as Td}from"partial-json";function Md(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function kd(e,t){if(!Md(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function bo(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let o=Ad(n,Ed|Td),s=kd(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Ld(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function xo(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=Fn.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:n,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 Pd(){let e=bo();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function vo(e){if(!e.rawContent)return!1;try{let t=JSON.parse(e.rawContent);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Co(e){if(!e.rawContent)return null;try{let t=JSON.parse(e.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:e.rawContent}}catch{}return null}var Id=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function wo(e){let{onSubmit:t,onDismiss:n,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=Id}=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 $r(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 Gn="persona-chat-history",Wl=30*1e3,Pl={"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 Rl(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=Pl[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 Hl(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 Bl(n){try{let t=n==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Nr=n=>!n||typeof n!="object"?{}:{...n},ha=n=>n.map(t=>({...t,streaming:!1})),ma=(n,t,r)=>{let e=n!=null&&n.markdown?js(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):ur(s)}},Or=(n,t,r)=>{var q,We,_e,dt,vt,Tt,it,f,Re,$,b,R,ae,Te,Ke,Wt,at,St,wt,De,qe,ht,Ve,At,jt,Zt,_r,Ur,qr,Vr,zr,Jr,Kr,Yr,Xr;n.id&&n.id!=="persona-root"&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.id="persona-root";let e=kr(t),o=Gs.getForInstance(e.plugins);e.components&&As.registerAll(e.components);let s=pa(),i=(q=e.storageAdapter)!=null?q:Lr(),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=Nr(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:{},ns()},m=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Zs],w=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Xn.message,Xn.messageAndClick],C=Qs({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=(it=(Tt=e.launcher)==null?void 0:Tt.autoExpand)!=null?it:!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=ma(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"?(at=e.persistState)==null?void 0:at.keyPrefix:void 0)!=null?St:"persona-"}event-stream`,G=_?new Ss(se):null,U=(qe=(De=(wt=e.features)==null?void 0:wt.eventStream)==null?void 0:De.maxEvents)!=null?qe:2e3,N=_?new xs(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}=ea(e),xe=ta(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=qn.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=Cn({config:e,showClose:y});return Vn(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=la({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:()=>bs({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"?(Jn.has(W)?Jn.delete(W):Jn.add(W),oa(W,S)):M==="tool"&&(Kn.has(W)?Kn.delete(W):Kn.add(W),ia(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,kn,Ns,lr,cr,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=(kn=(nn=e==null?void 0:e.launcher)==null?void 0:nn.width)!=null?kn: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=((Ns=e.launcher)==null?void 0:Ns.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&&((lr=sn[S])!=null?lr:sn["bottom-right"]).split(" ").forEach(Dn=>je.classList.add(Dn)),l){let On=(mt=(cr=e.launcher)==null?void 0:cr.sidebarWidth)!=null?mt:"420px";je.style.cssText=`
20
+ `,N.addEventListener("click",()=>{p=S,x.forEach((Z,K)=>{let re=K<S;Z.classList.toggle("selected",re),Z.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",()=>{n==null||n(),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 t(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 So(e){let{onSubmit:t,onDismiss:n,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 z=0;z<=10;z++){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 ${z} out of 10`),pe.textContent=String(z),pe.dataset.rating=String(z),z<=6?pe.classList.add("persona-feedback-detractor"):z<=8?pe.classList.add("persona-feedback-passive"):pe.classList.add("persona-feedback-promoter"),pe.addEventListener("click",()=>{y=z,S.forEach((Le,Ye)=>{Le.classList.toggle("selected",Ye===z),Le.setAttribute("aria-checked",Ye===z?"true":"false")})}),S.push(pe),O.appendChild(pe)}x.appendChild(k),x.appendChild(O),m.appendChild(x);let N=null;if(d){let z=document.createElement("div");z.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"),z.appendChild(N),m.appendChild(z)}let Z=document.createElement("div");Z.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",()=>{n==null||n(),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 z=(N==null?void 0:N.value.trim())||void 0;await t(y,z),p.remove()}catch(z){re.disabled=!1,re.textContent=a,console.error("[NPS Feedback] Failed to submit:",z)}}),Z.appendChild(K),Z.appendChild(re),m.appendChild(Z),p.appendChild(m),p}var br="persona-chat-history",Wd=30*1e3,Rd={"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 Hd(e){var r,o,s;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=Rd[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Bd(e){var t,n,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:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"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 $d(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ao=e=>!e||typeof e!="object"?{}:{...e},Dl=e=>e.map(t=>({...t,streaming:!1})),_l=(e,t,n)=>{let r=e!=null&&e.markdown?ir(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(t){let g=t.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&&n&&n())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...o,text:s,raw:(c=a!=null?a:o.text)!=null?c:""}):r?r(s):Dr(s)}},Eo=(e,t,n)=>{var ae,Se,nt,Mt,wt,Wt,kt,rt,at,Et,it,Rt,Jt,rn,Wo,Ro,Ho,Bo,$o,Fo,No,Oo,Do,_o,jo,Vo,qo,Uo,zo,Jo,Ko,Yo,Xo,Go,Zo,Qo,ea,ta;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let r=fo(t),o=Is.getForInstance(r.plugins);r.components&&Fn.registerAll(r.components);let s=Nl(),a=(ae=r.storageAdapter)!=null?ae:yo(),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=Ao(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:{},kr()},y=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ws],m=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[yr.message,yr.messageAndClick],C=Rs({parsers:y,handlers:m,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let v=(wt=(Mt=r.launcher)==null?void 0:Mt.enabled)!=null?wt:!0,E=(kt=(Wt=r.launcher)==null?void 0:Wt.autoExpand)!=null?kt:!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,Z=null,K=()=>{N=!0,Z&&clearTimeout(Z),Z=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},re=_l(r,C,K),z=(Rt=(it=r.features)==null?void 0:it.showReasoning)!=null?Rt:!0,pe=(rn=(Jt=r.features)==null?void 0:Jt.showToolCalls)!=null?rn:!0,Le=(Ro=(Wo=r.features)==null?void 0:Wo.showEventStreamToggle)!=null?Ro:!1,fe=`${(Bo=typeof r.persistState=="object"?(Ho=r.persistState)==null?void 0:Ho.keyPrefix:void 0)!=null?Bo:"persona-"}event-stream`,Q=Le?new Zr(fe):null,Y=(No=(Fo=($o=r.features)==null?void 0:$o.eventStream)==null?void 0:Fo.maxEvents)!=null?No:2e3,V=Le?new Gr(Y,Q):null,j=null,ce=!1,he=null,gt=0;Q==null||Q.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)}},mt=(Oo=r.statusIndicator)!=null?Oo:{},Pt=l=>{var u,h,A,L;return l==="idle"?(u=mt.idleText)!=null?u:_t.idle:l==="connecting"?(h=mt.connectingText)!=null?h:_t.connecting:l==="connected"?(A=mt.connectedText)!=null?A:_t.connected:l==="error"?(L=mt.errorText)!=null?L:_t.error:_t[l]},{wrapper:le,panel:se}=bl(r),q=xl(r,v),{container:ne,body:oe,messagesWrapper:Ee,suggestions:Ke,textarea:ee,sendButton:X,sendButtonWrapper:He,composerForm:Ve,statusText:et,introTitle:jt,introSubtitle:Dt,closeButton:ie,iconHolder:Ue,headerTitle:Te,headerSubtitle:tt,header:_e,footer:Xe,actionsRow:$t,leftActions:Ft,rightActions:It}=q,H=q.micButton,te=q.micButtonWrapper,J=q.attachmentButton,We=q.attachmentButtonWrapper,Ce=q.attachmentInput,Pe=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=$n({config:r,showClose:v});return ur(ne,u,r),u.header},onClose:()=>ft(!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=Tl({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();$-gt>=200&&(j==null||j.update(),gt=$),he=requestAnimationFrame(l)};gt=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=(_o=(Do=r.features)==null?void 0:Do.eventStream)==null?void 0:_o.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:Mn).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:()=>Yr({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:((jo=r.voiceRecognition)==null?void 0:jo.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&&(ee=h),A&&(X=A),L&&(H=L,te=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&&(J=D,We=D.parentElement),Ce=l.querySelector('input[type="file"]'),Pe=l.querySelector(".persona-attachment-previews");let B=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");B&&($t=B)};bt(Xe),pn(Xe);let un=(Vo=r.layout)==null?void 0:Vo.contentMaxWidth;un&&Ve&&(Ve.style.maxWidth=un,Ve.style.marginLeft="auto",Ve.style.marginRight="auto"),(qo=r.attachments)!=null&&qo.enabled&&Ce&&Pe&&(Be=pr.fromConfig(r.attachments),Be.setPreviewsContainer(Pe),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 Ln=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"?(mr.has(L)?mr.delete(L):mr.add(L),Sl(L,A)):$==="tool"&&(fr.has(L)?fr.delete(L):fr.add(L),Al(L,A,r))};Ee.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ln(l))}),Ee.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ln(l))});let Xn=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=Xn.get(L))!=null?R:null)===$)Xn.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"),Xn.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,Pn={artifacts:[],selectedId:null},an=!1,vr={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,Cr=()=>{};function Gn(){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`},Nn=()=>{},fn=()=>{var h,A,L,$,R;if(!Ge||!on(r))return;Ls(e,r),Ps(e,r),Nn();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(Pn),an?(Ge.setMobileOpen(!1),Ge.element.classList.add("persona-hidden"),(R=Ge.backdrop)==null||R.classList.add("persona-hidden")):Pn.artifacts.length>0&&(Ge.element.classList.remove("persona-hidden"),Ge.setMobileOpen(!0)),Cr()};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=Ll(r,{onSelect:h=>{var A;return(A=vr.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),Cr=()=>{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,Gn(),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,Ie;if(!Ge||Me.button!==0||e.classList.contains("persona-artifact-narrow-host")||me.innerWidth<=640)return;Me.preventDefault(),Gn();let je=Me.clientX,xe=Ge.element.getBoundingClientRect().width,P=(Ie=(F=r.features)==null?void 0:F.artifacts)==null?void 0:Ie.layout,ke=st=>{let Ze=mn.getBoundingClientRect().width,St=e.classList.contains("persona-artifact-appearance-seamless"),ct=St?0:Rl(mn,me),ot=St?0:D.getBoundingClientRect().width||6,Kt=xe-(st.clientX-je),ve=Hl(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=Pn.artifacts.length>0&&!an;dt.classList.toggle("persona-hidden",!D),wr()}},Nn=()=>{var me,ge,Me,je,xe,P,ke,Ae,F,Ie,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<=$||!Wl(r,v))return;let R=(Ie=(F=(Ae=r.launcher)==null?void 0:Ae.width)!=null?F:r.launcherWidth)!=null?Ie:"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))";Pn.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 On=()=>{var Ze,St,ct,ot,Kt,ve,pt,Ht,sn,ms,fs,hs,Vs,qs,Tt,ys,Hr,Br,ar,bs,Bn;let l=Ut(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=(Ht=r.launcher)==null?void 0:Ht.mobileFullscreen)!=null?sn:!0,D=(fs=(ms=r.launcher)==null?void 0:ms.mobileBreakpoint)!=null?fs:640,B=$.innerWidth<=D,me=R&&B&&v,ge=(Vs=(hs=r.launcher)==null?void 0:hs.position)!=null?Vs:"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=(qs=L.panelBorder)!=null?qs:je,Ae=(Tt=L.panelShadow)!=null?Tt:xe,F=(ys=L.panelBorderRadius)!=null?ys: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 Ie=(Br=(Hr=r==null?void 0:r.launcher)==null?void 0:Hr.width)!=null?Br:r==null?void 0:r.launcherWidth,st=Ie!=null?Ie:"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%"),Nn(),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&&((ar=dn[ge])!=null?ar:dn["bottom-right"]).split(" ").forEach(Yt=>le.classList.add(Yt)),u){let Tn=(Bn=(bs=r.launcher)==null?void 0:bs.sidebarWidth)!=null?Bn:"420px";le.style.cssText=`
21
56
  position: fixed !important;
22
57
  top: 0 !important;
23
58
  bottom: 0 !important;
24
- width: ${On} !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 @@ import{Marked as Ta}from"marked";var Ma=n=>{if(n)return n},Ds=n=>{var o,s;let t=
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 @@ import{Marked as Ta}from"marked";var Ma=n=>{if(n)return n},Ds=n=>{var o,s;let t=
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 On="max-height: -moz-available !important; max-height: stretch !important;",Dn=l?"":"padding-top: 1.25em !important;";je.style.cssText+=On+Dn}};Qt(),Xs(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,mn=()=>{en&&(en(),en=null),e.colorScheme==="auto"&&(en=Ki(()=>{Xs(n,e)}))};mn(),Ze.push(()=>{en&&(en(),en=null)});let fn=aa(Ot),rn=null,T,vn=!1,ln=!0,xn=0,Qn=0,cn=null,dn=!1,Wn=0,Pn=!1,Es=125,Ts=2e3,Ms=5,es=50,Rn=new Map,Ae={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ts=(_r=(Zt=e.voiceRecognition)==null?void 0:Zt.autoResume)!=null?_r:!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}}))},ks=()=>{var S,W;if(((S=e.voiceRecognition)==null?void 0:S.enabled)===!1)return;let l=Nr(a.voiceState),u=!!l.active,h=Number((W=l.timestamp)!=null?W:0);Ae.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<Wl&&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()&&wn()}):Tn("restore"))},1e3)},Is=()=>T?ha(T.getMessages()).filter(l=>!l.__skipPersist):[];function ns(l){if(!(i!=null&&i.save))return;let h={messages:l?ha(l):T?Is():[],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 Sn=(l=!1)=>{if(!ln)return;let u=Date.now();dn&&u<Wn&&!l||(dn&&u>=Wn&&(dn=!1),!(!l&&!vn)&&(u-Qn<Es||(Qn=u,cn&&cancelAnimationFrame(cn),cn=requestAnimationFrame(()=>{dn||!ln||(Pn=!0,$e.scrollTop=$e.scrollHeight,xn=$e.scrollTop,requestAnimationFrame(()=>{Pn=!1}),cn=null)}))))},un=null,Ls=()=>je.querySelector("#persona-scroll-container")||$e,Ws=(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)},Ps=l=>{let u=new Map;l.forEach(h=>{let S=Rn.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}))}),Rn.clear(),u.forEach((h,S)=>{Rn.set(S,h)})},An=(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:()=>xr(E),config:e})}else if(E.variant==="tool"&&E.toolCall&&ge.renderToolCall){if(!X)return;ce=ge.renderToolCall({message:E,defaultRenderer:()=>Sr(E,e),config:e})}else if(E.variant==="approval"&&E.approval&&ge.renderApproval){if(e.approval===!1)return;ce=ge.renderApproval({message:E,defaultRenderer:()=>Ar(E,e),config:e})}else ge.renderMessage&&(ce=ge.renderMessage({message:E,defaultRenderer:()=>{let K=Cs(E,h,Oe,e.messageActions,gt,{loadingIndicatorRenderer:M,widgetConfig:e});return E.role!=="user"&&Tr(K,E,e,T),K},config:e}));if(!ce&&E.role==="assistant"&&!E.variant&&e.enableComponentStreaming!==!1&&Hr(E)){let Ue=Br(E);if(Ue){let on=Rr(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=xr(E)}else if(E.variant==="tool"&&E.toolCall){if(!X)return;ce=Sr(E,e)}else if(E.variant==="approval"&&E.approval){if(e.approval===!1)return;ce=Ar(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=Cs(E,h,K,e.messageActions,gt,{loadingIndicatorRenderer:M,widgetConfig:e}),E.role!=="user"&&ce&&Tr(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(vn&&u.some(E=>E.role==="user")&&!j&&!de){let E={config:e,streaming:!0,location:"standalone",defaultRenderer:zn},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=zn()),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(!vn&&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)}}Yi(l,S),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let E=Ls();Ws(E)})})},En=()=>{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,En(),P&&(yn(),Sn(!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()})},Hn=l=>{Z.disabled=l,I&&(I.disabled=l),fn.buttons.forEach(u=>{u.disabled=l})},Bn=()=>{Ae.active||he&&he.focus()};s.on("widget:opened",()=>{e.autoFocusInput&&setTimeout(()=>Bn(),200)});let ss=()=>{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 vs(e,{onMessagesChanged(l){An(ze,l,z),T&&(l.some(W=>W.role==="user")?fn.render([],T,he,l):fn.render(e.suggestionChips,T,he,l,e.suggestionChipsConfig)),Sn(!vn),Ps(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),ns(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){vn=l,Hn(l),T&&An(ze,T.getMessages(),z),l||Sn(!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(),Hs();break;case"speaking":Gt(),Bs();break;default:l==="idle"&&T.isBargeInActive()?(Gt(),wn(),I==null||I.setAttribute("aria-label","End voice session")):(Ae.active=!1,Gt(),Xt("system"),Dt());break}}}),((qr=(Ur=e.voiceRecognition)==null?void 0:Ur.provider)==null?void 0:qr.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=Nr(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 rs=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(wr(u))),he.value="",he.style.height="auto",T.sendMessage(u,{contentParts:S}),h&&oe.clearAttachments()},os=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Z.click())},is=async l=>{var h;if(((h=e.attachments)==null?void 0:h.enabled)!==!0||!oe)return;let u=Rl(l.clipboardData);u.length!==0&&(l.preventDefault(),await oe.handleFiles(u))},Ft=null,Vt=!1,pn=null,ke=null,as=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Tn=(l="user")=>{var M,j,le,de,ye,we,Me,J;if(Vt||T.isStreaming())return;let u=as();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()}},Rs=(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 kn=g("div","tvw-send-button-tooltip");kn.textContent=ge,M.appendChild(kn)}return{micButton:j,micButtonWrapper:M}},Fn=()=>{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}},$n=(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)},Mn=()=>{I&&I.classList.remove("tvw-voice-recording","tvw-voice-processing","tvw-voice-speaking")},wn=()=>{var W,M;if(!I)return;Fn();let l=(W=e.voiceRecognition)!=null?W:{},u=(M=l.recordingBackgroundColor)!=null?M:"#ef4444",h=l.recordingIconColor,S=l.recordingBorderColor;if(Mn(),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")},Hs=()=>{var le,de,ye,we,Me,J,E,ce;if(!I)return;Fn();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:"";Mn(),I.classList.add("tvw-voice-processing"),I.style.backgroundColor=W,I.style.borderColor=M;let j=S||"currentColor";I.style.color=j,$n(h,j),I.setAttribute("aria-label","Processing voice input"),u==="none"&&(I.style.cursor="default")},Bs=()=>{var ye,we,Me,J,E,ce,ge,Oe,me,Ye,ut,K;if(!I)return;Fn();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:"";Mn(),I.classList.add("tvw-voice-speaking"),I.style.backgroundColor=M,I.style.borderColor=j;let le=W||"currentColor";I.style.color=le,$n(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&&(Mn(),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:"",$n(ke.iconName,ke.color||"currentColor"),ke=null),I.style.cursor="",I.setAttribute("aria-label","Start voice recognition"))},Nn=()=>{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()?wn():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(),Tn("user")};I&&(I.addEventListener("click",Nn),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",Nn)}));let Fs=s.on("assistant:complete",()=>{ts&&(Ae.active||Ae.manuallyDeactivated||ts==="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()&&wn()}):Tn("auto"))},600))});Ze.push(Fs);let $s=s.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});Ze.push($s);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:()=>ws(e,gn).element,onToggle:gn});u&&(et=u)}et||(Qe=ws(e,gn))}Qe?n.appendChild(Qe.element):et&&n.appendChild(et),En(),fn.render(e.suggestionChips,T,he,void 0,e.suggestionChipsConfig),ss(),Hn(T.isStreaming()),Sn(!0),ks(),x&&(y?P&&setTimeout(()=>Bn(),200):setTimeout(()=>Bn(),0));let yn=()=>{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`}};yn(),window.addEventListener("resize",yn),Ze.push(()=>window.removeEventListener("resize",yn)),xn=$e.scrollTop;let ls=()=>{let l=$e.scrollTop,u=$e.scrollHeight,h=$e.clientHeight,S=u-l-h,W=Math.abs(l-xn);if(xn=l,!Pn&&!(W<=Ms)){if(!ln&&S<es){dn=!1,ln=!0;return}ln&&S>es&&(dn=!0,Wn=Date.now()+Ts,ln=!1)}};$e.addEventListener("scroll",ls,{passive:!0}),Ze.push(()=>$e.removeEventListener("scroll",ls)),Ze.push(()=>{cn&&cancelAnimationFrame(cn)});let cs=()=>{te&&(rn&&(te.removeEventListener("click",rn),rn=null),y?(te.style.display="",rn=()=>{P=!1,En()},te.addEventListener("click",rn)):te.style.display="none")};cs(),(()=>{let{clearChatButton:l}=xe;l&&l.addEventListener("click",()=>{T.clearMessages();try{localStorage.removeItem(Gn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gn}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gn)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",rs),he.addEventListener("keydown",os),he.addEventListener("paste",is),Ze.push(()=>{bt.removeEventListener("submit",rs),he.removeEventListener("keydown",os),he.removeEventListener("paste",is)}),Ze.push(()=>{T.cancel()}),Qe?Ze.push(()=>{Qe==null||Qe.destroy()}):et&&Ze.push(()=>{et==null||et.remove()});let Lt={update(l){var Zr,Qr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,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;let u=e.toolCall,h=e.colorScheme;e={...e,...l},Qt(),Xs(n,e),e.colorScheme!==h&&mn();let S=Gs.getForInstance(e.plugins);o.length=0,o.push(...S),y=(Qr=(Zr=e.launcher)==null?void 0:Zr.enabled)!=null?Qr:!0,A=(to=(eo=e.launcher)==null?void 0:eo.autoExpand)!=null?to:!1,V=(so=(no=e.features)==null?void 0:no.showReasoning)!=null?so:!0,X=(oo=(ro=e.features)==null?void 0:ro.showToolCalls)!=null?oo:!0;let W=_;if(_=(ao=(io=e.features)==null?void 0:io.showEventStreamToggle)!=null?ao:!1,_&&!W){if(N||(G=new Ss(se),N=new xs(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=(co=(lo=e.features)==null?void 0:lo.eventStream)==null?void 0:co.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(((uo=e.launcher)==null?void 0:uo.enabled)===!1&&Qe&&(Qe.destroy(),Qe=null),((po=e.launcher)==null?void 0:po.enabled)===!1&&et&&(et.remove(),et=null),((go=e.launcher)==null?void 0:go.enabled)!==!1&&!Qe&&!et){let B=o.find(Ie=>Ie.renderLauncher);if(B!=null&&B.renderLauncher){let Ie=B.renderLauncher({config:e,defaultRenderer:()=>ws(e,gn).element,onToggle:gn});Ie&&(et=Ie,n.appendChild(et))}et||(Qe=ws(e,gn),n.appendChild(Qe.element))}Qe&&Qe.update(e),xt&&((ho=e.launcher)==null?void 0:ho.title)!==void 0&&(xt.textContent=e.launcher.title),ve&&((mo=e.launcher)==null?void 0:mo.subtitle)!==void 0&&(ve.textContent=e.launcher.subtitle);let M=(fo=e.layout)==null?void 0:fo.header;if((M==null?void 0:M.layout)!==k&&Se){let B=M?ys(e,M,{showClose:y,onClose:()=>ot(!1,"user")}):Cn({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=((vo=e.layout)==null?void 0:vo.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,En()):A!==H&&ot(A,"auto"),H=A,Y=y,yn(),cs(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&T&&An(ze,T.getMessages(),z);let J=(yo=e.launcher)!=null?yo:{},E=(bo=J.headerIconHidden)!=null?bo:!1,ce=(xo=(Co=e.layout)==null?void 0:Co.header)==null?void 0:xo.showIcon,ge=E||ce===!1,Oe=J.headerIconName,me=(So=J.headerIconSize)!=null?So:"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=(Ao=J.agentIconText)!=null?Ao:"\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=(Eo=J.agentIconText)!=null?Eo:"\u{1F4AC}"}let tt=Pe.querySelector("img");tt&&(tt.style.height=me,tt.style.width=me)}}let Ye=(Mo=(To=e.layout)==null?void 0:To.header)==null?void 0:Mo.showTitle,ut=(Io=(ko=e.layout)==null?void 0:ko.header)==null?void 0:Io.showSubtitle;if(xt&&(xt.style.display=Ye===!1?"none":""),ve&&(ve.style.display=ut===!1?"none":""),te){((Wo=(Lo=e.layout)==null?void 0:Lo.header)==null?void 0:Wo.showCloseButton)===!1?te.style.display="none":te.style.display="";let Ie=(Po=J.closeButtonSize)!=null?Po:"32px",tt=(Ro=J.closeButtonPlacement)!=null?Ro:"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=(Bo=(Ho=J.clearChat)==null?void 0:Ho.placement)!=null?Bo:"inline",Et=($o=(Fo=J.clearChat)==null?void 0:Fo.enabled)!=null?$o:!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=(No=J.closeButtonIconName)!=null?No:"x",zt=(Oo=J.closeButtonIconText)!=null?Oo:"\xD7";te.innerHTML="";let Nt=ie(Pt,"20px",J.closeButtonColor||"",2);Nt?te.appendChild(Nt):te.textContent=zt;let pt=(Do=J.closeButtonTooltipText)!=null?Do:"Close chat",Jt=(jo=J.closeButtonShowTooltip)!=null?jo:!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 gs=g("div");gs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(gs);let In=te.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${In.left+In.width/2}px`,Le.style.top=`${In.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=(_o=J.clearChat)!=null?_o:{},Ie=(Uo=B.enabled)!=null?Uo:!0,tt=(Vo=(qo=e.layout)==null?void 0:qo.header)==null?void 0:Vo.showClearChat,be=tt!==void 0?tt:Ie,Be=(zo=B.placement)!=null?zo:"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=(Jo=B.size)!=null?Jo:"32px";K.style.height=yt,K.style.width=yt;let Pt=(Ko=B.iconName)!=null?Ko:"refresh-cw",zt=(Yo=B.iconColor)!=null?Yo:"";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=(Xo=B.tooltipText)!=null?Xo:"Clear chat",Jt=(Go=B.showTooltip)!=null?Go:!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 gs=g("div");gs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(gs);let In=K.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${In.left+In.width/2}px`,Le.style.top=`${In.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:[Zs],_t=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Xn.message,Xn.messageAndClick];C=Qs({parsers:on,handlers:_t,getSessionMetadata:v,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),z=ma(e,C,ue),T.updateConfig(e),An(ze,T.getMessages(),z),fn.render(e.suggestionChips,T,he,void 0,e.suggestionChipsConfig),ss(),Hn(T.isStreaming());let nn=((Zo=e.voiceRecognition)==null?void 0:Zo.enabled)===!0,kn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ns=((ei=(Qo=e.voiceRecognition)==null?void 0:Qo.provider)==null?void 0:ei.type)==="runtype";if(nn&&(kn||Ns))if(!I||!nt){let B=Rs(e.voiceRecognition,e.sendButton);B&&(I=B.micButton,nt=B.micButtonWrapper,qt.insertBefore(nt,ct),I.addEventListener("click",Nn),I.disabled=T.isStreaming())}else{let B=(ti=e.voiceRecognition)!=null?ti:{},Ie=(ni=e.sendButton)!=null?ni:{},tt=(si=B.iconName)!=null?si:"mic",be=(ri=Ie.size)!=null?ri:"40px",Be=(oi=B.iconSize)!=null?oi:be,yt=parseFloat(Be)||24;I.style.width=Be,I.style.height=Be,I.style.minWidth=Be,I.style.minHeight=Be;let Pt=(ai=(ii=B.iconColor)!=null?ii:Ie.textColor)!=null?ai:"currentColor";I.innerHTML="";let zt=ie(tt,yt,Pt,2);zt?I.appendChild(zt):I.textContent="\u{1F3A4}";let Nt=(li=B.backgroundColor)!=null?li: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=(ci=B.tooltipText)!=null?ci:"Start voice recognition";if(((di=B.showTooltip)!=null?di:!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",((pi=(ui=e.voiceRecognition)==null?void 0:ui.provider)==null?void 0:pi.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Vt&&tn());if(((gi=e.attachments)==null?void 0:gi.enabled)===!0)if(!Q||!O){let B=(hi=e.attachments)!=null?hi:{},tt=(fi=((mi=e.sendButton)!=null?mi:{}).size)!=null?fi:"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=((vi=B.allowedTypes)!=null?vi:bn).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",(yi=B.buttonTooltipText)!=null?yi:"Attach file");let be=(bi=B.buttonIconName)!=null?bi:"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=(Ci=B.buttonTooltipText)!=null?Ci:"Attach file",pt=g("div","tvw-send-button-tooltip");pt.textContent=Nt,Q.appendChild(pt),It.append(Q),!oe&&re&&Ne&&(oe=qn.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=(xi=e.attachments)!=null?xi:{};re&&(re.accept=((Si=B.allowedTypes)!=null?Si:bn).join(","),re.multiple=((Ai=B.maxFiles)!=null?Ai: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=(Ei=e.sendButton)!=null?Ei:{},On=(Ti=mt.useIcon)!=null?Ti:!1,Dn=(Mi=mt.iconText)!=null?Mi:"\u2191",Gr=mt.iconName,dr=(ki=mt.tooltipText)!=null?ki:"Send message",Aa=(Ii=mt.showTooltip)!=null?Ii:!1,ds=(Li=mt.size)!=null?Li:"40px",Os=mt.backgroundColor,an=mt.textColor;if(On){if(Z.style.width=ds,Z.style.height=ds,Z.style.minWidth=ds,Z.style.minHeight=ds,Z.style.fontSize="18px",Z.style.lineHeight="1",Z.innerHTML="",Gr){let B=parseFloat(ds)||24,Ie=an&&typeof an=="string"&&an.trim()?an.trim():"currentColor",tt=ie(Gr,B,Ie,2);tt?(Z.appendChild(tt),Z.style.color=Ie):(Z.textContent=Dn,an?Z.style.color=an:Z.classList.add("tvw-text-white"))}else Z.textContent=Dn,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",Os?(Z.style.backgroundColor=Os,Z.classList.remove("tvw-bg-cw-primary")):Z.classList.add("tvw-bg-cw-primary")}else Z.textContent=(Pi=(Wi=e.copy)==null?void 0:Wi.sendButtonLabel)!=null?Pi:"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",Os?(Z.style.backgroundColor=Os,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 us=ct==null?void 0:ct.querySelector(".tvw-send-button-tooltip");if(Aa&&dr)if(us)us.textContent=dr,us.style.display="";else{let B=document.createElement("div");B.className="tvw-send-button-tooltip",B.textContent=dr,ct==null||ct.insertBefore(B,Z)}else us&&(us.style.display="none");let ps=(Ri=e.statusIndicator)!=null?Ri:{},Ea=(Hi=ps.visible)!=null?Hi:!0;if(kt.style.display=Ea?"":"none",T){let B=T.getStatus(),Ie=tt=>{var be,Be,yt,Pt;return tt==="idle"?(be=ps.idleText)!=null?be:Rt.idle:tt==="connecting"?(Be=ps.connectingText)!=null?Be:Rt.connecting:tt==="connected"?(yt=ps.connectedText)!=null?yt:Rt.connected:tt==="error"?(Pt=ps.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(Gn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Gn}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Gn)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()&&wn()})),!0):Vt?!0:as()?(!P&&y&&ot(!0,"system"),Ae.manuallyDeactivated=!1,Dt(),Tn("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=Fr({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=$r({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((((Vr=r==null?void 0:r.debugTools)!=null?Vr:!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=Hl(e.persistState);if($t&&y){let l=Bl($t.storage),u=`${$t.keyPrefix}widget-open`,h=`${$t.keyPrefix}widget-voice`,S=`${$t.keyPrefix}widget-voice-mode`;if(l){let W=((zr=$t.persist)==null?void 0:zr.openState)&&l.getItem(u)==="true",M=((Jr=$t.persist)==null?void 0:Jr.voiceState)&&l.getItem(h)==="true",j=((Kr=$t.persist)==null?void 0:Kr.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),(Yr=$t.persist)!=null&&Yr.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(Xr=$t.persist)!=null&&Xr.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 Dr={},Fl=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},$l=()=>{try{if(typeof Dr!="undefined"&&Dr.url)return new URL("../widget.css",Dr.url).href}catch{}return null},fa=n=>{let t=$l(),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)}},va=n=>{var c,v,p,m;let t=Fl(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),fa(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),fa(r);t.id&&s.setAttribute("data-persona-instance",t.id);let a=Or(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 wa={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 Zn=wa.version;function hn(n){if(n!==void 0)return typeof n=="string"?n:Array.isArray(n)?`[${n.map(t=>t.toString()).join(", ")}]`:n.toString()}function Ol(n){if(n)return{getHeaders:hn(n.getHeaders),onFeedback:hn(n.onFeedback),onCopy:hn(n.onCopy),requestMiddleware:hn(n.requestMiddleware),actionHandlers:hn(n.actionHandlers),actionParsers:hn(n.actionParsers),postprocessMessage:hn(n.postprocessMessage),contextProviders:hn(n.contextProviders),streamParser:hn(n.streamParser)}}var ya=`({ 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}};On(),Yn(e,r),Ls(e,r),Ps(e,r);let xt=[];gn&&xt.push(()=>{gn==null||gn.disconnect(),gn=null}),xt.push(()=>{tn==null||tn(),tn=null,Gn(),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,Q=null});let hn=null,Sr=()=>{hn&&(hn(),hn=null),r.colorScheme==="auto"&&(hn=oo(()=>{Yn(e,r)}))};Sr(),xt.push(()=>{hn&&(hn(),hn=null)});let In=El(Ke),yn=null,W,Wn=!1,Rn=pl(),Ar=0,Cn=!0,Dn=0,Er=0,wn=null,Sn=!1,Zn=0,Qn=!1,ns=125,rs=2e3,ss=5,Tr=50,er=new Map,qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Mr=(zo=(Uo=r.voiceRecognition)==null?void 0:Uo.autoResume)!=null?zo:!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}}))},os=()=>{var A,L;if(((A=r.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Ao(i.voiceState),u=!!l.active,h=Number((L=l.timestamp)!=null?L:0);qe.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<Wd&&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()&&Hn()}):Vn("restore"))},1e3)},as=()=>W?Dl(W.getMessages()).filter(l=>!l.__skipPersist):[];function kr(l){if(!(a!=null&&a.save))return;let h={messages:l?Dl(l):W?as():[],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 _n=(l=!1)=>{if(!Cn)return;let u=Date.now();Sn&&u<Zn&&!l||(Sn&&u>=Zn&&(Sn=!1),!(!l&&!Wn)&&(u-Er<ns||(Er=u,wn&&cancelAnimationFrame(wn),wn=requestAnimationFrame(()=>{Sn||!Cn||(Qn=!0,oe.scrollTop=oe.scrollHeight,Dn=oe.scrollTop,requestAnimationFrame(()=>{Qn=!1}),wn=null)}))))},An=null,is=()=>le.querySelector("#persona-scroll-container")||oe,ls=(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)},cs=l=>{let u=new Map;l.forEach(h=>{let A=er.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}))}),er.clear(),u.forEach((h,A)=>{er.set(A,h)})},jn=(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=dl(P,Ar),Ae=ul(Rn,P.id,ke);if(Ae){A.appendChild(Ae.cloneNode(!0));return}let F=null,Ie=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(Ie)if(P.variant==="reasoning"&&P.reasoning&&Ie.renderReasoning){if(!z)return;F=Ie.renderReasoning({message:P,defaultRenderer:()=>io(P),config:r})}else if(P.variant==="tool"&&P.toolCall&&Ie.renderToolCall){if(!pe)return;F=Ie.renderToolCall({message:P,defaultRenderer:()=>lo(P,r),config:r})}else if(P.variant==="approval"&&P.approval&&Ie.renderApproval){if(r.approval===!1)return;F=Ie.renderApproval({message:P,defaultRenderer:()=>co(P,r),config:r})}else Ie.renderMessage&&(F=Ie.renderMessage({message:P,defaultRenderer:()=>{let ot=Xr(P,h,st,r.messageActions,lt,{loadingIndicatorRenderer:$,widgetConfig:r});return P.role!=="user"&&go(ot,P,r,W),ot},config:r}));if(!F&&P.role==="assistant"&&!P.variant&&r.enableComponentStreaming!==!1&&vo(P)){let Kt=Co(P);if(Kt){let ve=xo(Kt,{config:r,message:P,transform:h});if(ve)if(r.wrapComponentDirectiveInBubble!==!1){let Ht=document.createElement("div");if(Ht.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(" "),Ht.id=`bubble-${P.id}`,Ht.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}),Ht.appendChild(sn)}Ht.appendChild(ve),F=Ht}else{let Ht=document.createElement("div");if(Ht.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ht.id=`bubble-${P.id}`,Ht.setAttribute("data-message-id",P.id),Ht.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}),Ht.appendChild(sn)}Ht.appendChild(ve),F=Ht}}}if(!F)if(P.variant==="reasoning"&&P.reasoning){if(!z)return;F=io(P)}else if(P.variant==="tool"&&P.toolCall){if(!pe)return;F=lo(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;F=co(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=Xr(P,h,ot,r.messageActions,lt,{loadingIndicatorRenderer:$,widgetConfig:r}),P.role!=="user"&&F&&go(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),gl(Rn,P.id,ke,Ze),A.appendChild(Ze)}),ml(Rn,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(Wn&&u.some(P=>P.role==="user")&&!D&&!me){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:gr},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=gr()),Ae){let F=document.createElement("div"),Ie=((Me=r.loadingIndicator)==null?void 0:Me.showBubble)!==!1;F.className=Ie?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),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(!Wn&&u.length>0){let P=u[u.length-1],ke={config:r,lastMessage:P,messageCount:u.length},Ae=o.find(Ie=>Ie.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 Ie=document.createElement("div"),st=((xe=r.loadingIndicator)==null?void 0:xe.showBubble)!==!1;Ie.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(" "),Ie.setAttribute("data-idle-indicator","true"),Ie.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(Ie),A.appendChild(Ze)}}cl(l,A),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let P=is();ls(P)})})},tr=()=>{if(!v)return;let l=Ut(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=""))},ft=(l,u="user")=>{if(!v||S===l)return;let h=S;S=l,tr(),S&&(vt(),_n(!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()})},nr=l=>{X.disabled=l,H&&(H.disabled=l),In.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)})},rr=()=>{qe.active||ee&&ee.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>rr(),200)});let Lr=()=>{var L,$,R,D,B,me,ge,Me,je,xe,P,ke,Ae,F;jt.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.",ee.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=Ie=>{switch(Ie){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};ee.style.fontFamily=A(u),ee.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 qr(r,{onMessagesChanged(l){jn(Ee,l,re),W&&(l.some(L=>L.role==="user")?In.render([],W,ee,l):In.render(r.suggestionChips,W,ee,l,r.suggestionChipsConfig)),_n(!Wn),cs(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),kr(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){Wn=l,nr(l),W&&jn(Ee,W.getMessages(),re),l||_n(!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(),ps();break;case"speaking":cn(),us();break;default:l==="idle"&&W.isBargeInActive()?(cn(),Hn(),H==null||H.setAttribute("aria-label","End voice session")):(qe.active=!1,cn(),nn("system"),zt());break}},onArtifactsState(l){Pn=l,fn()}}),vr.current=W,((Ko=(Jo=r.voiceRecognition)==null?void 0:Jo.provider)==null?void 0:Ko.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=Ao(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 Pr=l=>{var L;l.preventDefault();let u=ee.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(Gs(u))),ee.value="",ee.style.height="auto",W.sendMessage(u,{contentParts:A}),h&&Be.clearAttachments()},Ir=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),X.click())},Wr=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!Be)return;let u=Hd(l.clipboardData);u.length!==0&&(l.preventDefault(),await Be.handleFiles(u))},Vt=null,Zt=!1,En=null,Re=null,Rr=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Vn=(l="user")=>{var $,R,D,B,me,ge,Me,je;if(Zt||W.isStreaming())return;let u=Rr();if(!u)return;Vt=new u;let A=(R=(($=r.voiceRecognition)!=null?$:{}).pauseDuration)!=null?R:2e3;Vt.continuous=!0,Vt.interimResults=!0,Vt.lang="en-US";let L=ee.value;Vt.onresult=xe=>{let P="",ke="";for(let F=0;F<xe.results.length;F++){let Ie=xe.results[F],st=Ie[0].transcript;Ie.isFinal?P+=st+" ":ke=st}let Ae=L+P+ke;ee.value=Ae,En&&clearTimeout(En),(P||ke)&&(En=window.setTimeout(()=>{let F=ee.value.trim();F&&Vt&&Zt&&(ln(),ee.value="",ee.style.height="auto",W.sendMessage(F,{viaVoice:!0}))},A))},Vt.onerror=xe=>{xe.error!=="no-speech"&&ln()},Vt.onend=()=>{if(Zt){let xe=ee.value.trim();xe&&xe!==L.trim()&&(ee.value="",ee.style.height="auto",W.sendMessage(xe,{viaVoice:!0})),ln()}};try{if(Vt.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),Vt){try{Vt.stop()}catch{}Vt=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")}}},ds=(l,u)=>{var F,Ie,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=(Ie=l==null?void 0:l.iconName)!=null?Ie:"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:$}},sr=()=>{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}},or=(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)},qn=()=>{H&&H.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Hn=()=>{var L,$;if(!H)return;sr();let l=(L=r.voiceRecognition)!=null?L:{},u=($=l.recordingBackgroundColor)!=null?$:"#ef4444",h=l.recordingIconColor,A=l.recordingBorderColor;if(qn(),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")},ps=()=>{var D,B,me,ge,Me,je,xe,P;if(!H)return;sr();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:"";qn(),H.classList.add("persona-voice-processing"),H.style.backgroundColor=L,H.style.borderColor=$;let R=A||"currentColor";H.style.color=R,or(h,R),H.setAttribute("aria-label","Processing voice input"),u==="none"&&(H.style.cursor="default")},us=()=>{var me,ge,Me,je,xe,P,ke,Ae,F,Ie,st,Ze;if(!H)return;sr();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"?(Ie=l.recordingBorderColor)!=null?Ie:"":(st=Re==null?void 0:Re.borderColor)!=null?st:"";qn(),H.classList.add("persona-voice-speaking"),H.style.backgroundColor=$,H.style.borderColor=R;let D=L||"currentColor";H.style.color=D,or(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&&(qn(),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:"",or(Re.iconName,Re.color||"currentColor"),Re=null),H.style.cursor="",H.setAttribute("aria-label","Start voice recognition"))},Un=()=>{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()?Hn():cn()});return}if(Zt){let h=ee.value.trim();qe.manuallyDeactivated=!0,zt(),ln("user"),h&&(ee.value="",ee.style.height="auto",W.sendMessage(h))}else qe.manuallyDeactivated=!1,zt(),Vn("user")};ut=Un,H&&(H.addEventListener("click",Un),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",Un)}));let gs=s.on("assistant:complete",()=>{Mr&&(qe.active||qe.manuallyDeactivated||Mr==="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()&&Hn()}):Vn("auto"))},600))});xt.push(gs);let G=s.on("action:resubmit",()=>{setTimeout(()=>{W&&!W.isStreaming()&&W.continueConversation()},100)});xt.push(G);let Fe=()=>{ft(!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:()=>Jr(r,Fe).element,onToggle:Fe});u&&(Ne=u)}Ne||(we=Jr(r,Fe))}we?e.appendChild(we.element):Ne&&e.appendChild(Ne),tr(),In.render(r.suggestionChips,W,ee,void 0,r.suggestionChipsConfig),Lr(),nr(W.isStreaming()),_n(!0),os(),x&&(v?S&&setTimeout(()=>rr(),200):setTimeout(()=>rr(),0));let vt=()=>{var B,me,ge,Me,je,xe,P,ke,Ae,F,Ie,st,Ze;let l=Ut(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){On(),Yn(e,r);return}if(O&&(O=!1,On(),Yn(e,r)),!v&&!l){se.style.height="",se.style.width="";return}if(!u&&!l){let St=(Ie=(F=r==null?void 0:r.launcher)==null?void 0:F.width)!=null?Ie:r==null?void 0:r.launcherWidth,ct=St!=null?St:"min(400px, calc(100vw - 24px))";se.style.width=ct,se.style.maxWidth=ct}if(Nn(),!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=(Yo=e.ownerDocument.defaultView)!=null?Yo:window;Nt.addEventListener("resize",vt),xt.push(()=>Nt.removeEventListener("resize",vt)),Dn=oe.scrollTop;let Ct=()=>{let l=oe.scrollTop,u=oe.scrollHeight,h=oe.clientHeight,A=u-l-h,L=Math.abs(l-Dn);if(Dn=l,!Qn&&!(L<=ss)){if(!Cn&&A<Tr){Sn=!1,Cn=!0;return}Cn&&A>Tr&&(Sn=!0,Zn=Date.now()+rs,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=()=>{ft(!1,"user")},ie.addEventListener("click",yn)):ie.style.display="none")};b(),(()=>{let{clearChatButton:l}=q;l&&l.addEventListener("click",()=>{W.clearMessages(),Rn.clear();try{localStorage.removeItem(br),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${br}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==br)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",Pr),ee==null||ee.addEventListener("keydown",Ir),ee==null||ee.addEventListener("paste",Wr),xt.push(()=>{Ve&&Ve.removeEventListener("submit",Pr),ee==null||ee.removeEventListener("keydown",Ir),ee==null||ee.removeEventListener("paste",Wr)}),xt.push(()=>{W.cancel()}),we?xt.push(()=>{we==null||we.destroy()}):Ne&&xt.push(()=>{Ne==null||Ne.remove()});let T={update(l){var na,ra,sa,oa,aa,ia,la,ca,da,pa,ua,ga,ma,fa,ha,ya,ba,xa,va,Ca,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;let u=r.toolCall,h=r.messageActions,A=(na=r.layout)==null?void 0:na.messages,L=r.colorScheme;r={...r,...l},On(),Yn(e,r),Ls(e,r),Ps(e,r),fn(),r.colorScheme!==L&&Sr();let $=Is.getForInstance(r.plugins);o.length=0,o.push(...$),v=(sa=(ra=r.launcher)==null?void 0:ra.enabled)!=null?sa:!0,E=(aa=(oa=r.launcher)==null?void 0:oa.autoExpand)!=null?aa:!1,z=(la=(ia=r.features)==null?void 0:ia.showReasoning)!=null?la:!0,pe=(da=(ca=r.features)==null?void 0:ca.showToolCalls)!=null?da:!0;let R=Le;if(Le=(ua=(pa=r.features)==null?void 0:pa.showEventStreamToggle)!=null?ua:!1,Le&&!R){if(V||(Q=new Zr(fe),V=new Gr(Y,Q),Q.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 _=(ma=(ga=r.features)==null?void 0:ga.eventStream)==null?void 0:ma.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 ht=ue("activity","18px","currentColor",1.5);ht&&de.appendChild(ht);let Oe=q.clearChatButtonWrapper,Qe=q.closeButtonWrapper,Lt=Oe||Qe;Lt&&Lt.parentNode===_e?_e.insertBefore(de,Lt):_e.appendChild(de),de.addEventListener("click",()=>{ce?$e():be()})}}else!Le&&R&&($e(),de&&(de.remove(),de=null),V==null||V.clear(),Q==null||Q.destroy(),V=null,Q=null);if(((fa=r.launcher)==null?void 0:fa.enabled)===!1&&we&&(we.destroy(),we=null),((ha=r.launcher)==null?void 0:ha.enabled)===!1&&Ne&&(Ne.remove(),Ne=null),((ya=r.launcher)==null?void 0:ya.enabled)!==!1&&!we&&!Ne){let _=o.find(ze=>ze.renderLauncher);if(_!=null&&_.renderLauncher){let ze=_.renderLauncher({config:r,defaultRenderer:()=>Jr(r,Fe).element,onToggle:Fe});ze&&(Ne=ze,e.appendChild(Ne))}Ne||(we=Jr(r,Fe),e.appendChild(we.element))}we&&we.update(r),Te&&((ba=r.launcher)==null?void 0:ba.title)!==void 0&&(Te.textContent=r.launcher.title),tt&&((xa=r.launcher)==null?void 0:xa.subtitle)!==void 0&&(tt.textContent=r.launcher.subtitle);let D=(va=r.layout)==null?void 0:va.header;if((D==null?void 0:D.layout)!==M&&_e){let _=D?Kr(r,D,{showClose:v,onClose:()=>ft(!1,"user")}):$n({config:r,showClose:v,onClose:()=>ft(!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=((Ca=r.layout)==null?void 0:Ca.showHeader)!==!1;_e&&(_e.style.display=me?"":"none");let ge=((wa=r.layout)==null?void 0:wa.showFooter)!==!1;Xe&&(Xe.style.display=ge?"":"none"),v!==U?v?ft(E,"auto"):(S=!0,tr()):E!==k&&ft(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((Sa=r.layout)==null?void 0:Sa.messages)!==JSON.stringify(A);(xe||P||ke)&&W&&(Ar++,jn(Ee,W.getMessages(),re));let F=(Aa=r.launcher)!=null?Aa:{},Ie=(Ea=F.headerIconHidden)!=null?Ea:!1,st=(Ma=(Ta=r.layout)==null?void 0:Ta.header)==null?void 0:Ma.showIcon,Ze=Ie||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=(La=F.agentIconText)!=null?La:"\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=(Pa=F.agentIconText)!=null?Pa:"\u{1F4AC}"}let ht=Ue.querySelector("img");ht&&(ht.style.height=ct,ht.style.width=ct)}}let ot=(Wa=(Ia=r.layout)==null?void 0:Ia.header)==null?void 0:Wa.showTitle,Kt=(Ha=(Ra=r.layout)==null?void 0:Ra.header)==null?void 0:Ha.showSubtitle;if(Te&&(Te.style.display=ot===!1?"none":""),tt&&(tt.style.display=Kt===!1?"none":""),ie){(($a=(Ba=r.layout)==null?void 0:Ba.header)==null?void 0:$a.showCloseButton)===!1?ie.style.display="none":ie.style.display="";let ze=(Fa=F.closeButtonSize)!=null?Fa:"32px",ht=(Na=F.closeButtonPlacement)!=null?Na:"inline";ie.style.height=ze,ie.style.width=ze;let{closeButtonWrapper:Oe}=q,Qe=ht==="top-right",Lt=Oe==null?void 0:Oe.classList.contains("persona-absolute");if(Oe&&Qe!==Lt)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=(Da=(Oa=F.clearChat)==null?void 0:Oa.placement)!=null?Da:"inline",Bt=(ja=(_a=F.clearChat)==null?void 0:_a.enabled)!=null?ja:!0;Oe.className=Bt&&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",Bt=F.closeButtonBorderColor||"transparent";ie.style.border=`${Je} solid ${Bt}`,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=(Va=F.closeButtonIconName)!=null?Va:"x",Qt=(qa=F.closeButtonIconText)!=null?qa:"\xD7";ie.innerHTML="";let qt=ue(Ot,"20px",F.closeButtonColor||"",2);qt?ie.appendChild(qt):ie.textContent=Qt;let At=(Ua=F.closeButtonTooltipText)!=null?Ua:"Close chat",en=(za=F.closeButtonShowTooltip)!=null?za:!0;if(ie.setAttribute("aria-label",At),Oe&&(Oe._cleanupTooltip&&(Oe._cleanupTooltip(),delete Oe._cleanupTooltip),en&&At)){let Je=null,Bt=()=>{if(Je||!ie)return;let zn=ie.ownerDocument,Nr=zn.body;if(!Nr)return;Je=bn(zn,"div","persona-clear-chat-tooltip"),Je.textContent=At;let Or=bn(zn,"div");Or.className="persona-clear-chat-tooltip-arrow",Je.appendChild(Or);let Jn=ie.getBoundingClientRect();Je.style.position="fixed",Je.style.left=`${Jn.left+Jn.width/2}px`,Je.style.top=`${Jn.top-8}px`,Je.style.transform="translate(-50%, -100%)",Nr.appendChild(Je)},Xt=()=>{Je&&Je.parentNode&&(Je.parentNode.removeChild(Je),Je=null)};Oe.addEventListener("mouseenter",Bt),Oe.addEventListener("mouseleave",Xt),ie.addEventListener("focus",Bt),ie.addEventListener("blur",Xt),Oe._cleanupTooltip=()=>{Xt(),Oe&&(Oe.removeEventListener("mouseenter",Bt),Oe.removeEventListener("mouseleave",Xt)),ie&&(ie.removeEventListener("focus",Bt),ie.removeEventListener("blur",Xt))}}}let{clearChatButton:ve,clearChatButtonWrapper:pt}=q;if(ve){let _=(Ja=F.clearChat)!=null?Ja:{},ze=(Ka=_.enabled)!=null?Ka:!0,ht=(Xa=(Ya=r.layout)==null?void 0:Ya.header)==null?void 0:Xa.showClearChat,Oe=ht!==void 0?ht:ze,Qe=(Ga=_.placement)!=null?Ga:"inline";if(pt){pt.style.display=Oe?"":"none";let{closeButtonWrapper:Lt}=q;Lt&&!Lt.classList.contains("persona-absolute")&&(Oe?Lt.classList.remove("persona-ml-auto"):Lt.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 qt=q.closeButtonWrapper;qt&&!qt.classList.contains("persona-absolute")&&(Ot?qt.classList.add("persona-ml-auto"):qt.classList.remove("persona-ml-auto"))}}if(Oe){let Lt=(Za=_.size)!=null?Za:"32px";ve.style.height=Lt,ve.style.width=Lt;let Ot=(Qa=_.iconName)!=null?Qa:"refresh-cw",Qt=(ei=_.iconColor)!=null?ei:"";ve.innerHTML="";let qt=ue(Ot,"20px",Qt||"",2);if(qt&&ve.appendChild(qt),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",Bt=_.borderColor||"transparent";ve.style.border=`${Je} solid ${Bt}`,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=(ti=_.tooltipText)!=null?ti:"Clear chat",en=(ni=_.showTooltip)!=null?ni:!0;if(ve.setAttribute("aria-label",At),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),en&&At)){let Je=null,Bt=()=>{if(Je||!ve)return;let zn=ve.ownerDocument,Nr=zn.body;if(!Nr)return;Je=bn(zn,"div","persona-clear-chat-tooltip"),Je.textContent=At;let Or=bn(zn,"div");Or.className="persona-clear-chat-tooltip-arrow",Je.appendChild(Or);let Jn=ve.getBoundingClientRect();Je.style.position="fixed",Je.style.left=`${Jn.left+Jn.width/2}px`,Je.style.top=`${Jn.top-8}px`,Je.style.transform="translate(-50%, -100%)",Nr.appendChild(Je)},Xt=()=>{Je&&Je.parentNode&&(Je.parentNode.removeChild(Je),Je=null)};pt.addEventListener("mouseenter",Bt),pt.addEventListener("mouseleave",Xt),ve.addEventListener("focus",Bt),ve.addEventListener("blur",Xt),pt._cleanupTooltip=()=>{Xt(),pt&&(pt.removeEventListener("mouseenter",Bt),pt.removeEventListener("mouseleave",Xt)),ve&&(ve.removeEventListener("focus",Bt),ve.removeEventListener("blur",Xt))}}}}let Ht=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ws],sn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[yr.message,yr.messageAndClick];C=Rs({parsers:Ht,handlers:sn,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),re=_l(r,C,K),W.updateConfig(r),jn(Ee,W.getMessages(),re),In.render(r.suggestionChips,W,ee,void 0,r.suggestionChipsConfig),Lr(),nr(W.isStreaming());let ms=((ri=r.voiceRecognition)==null?void 0:ri.enabled)===!0,fs=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),hs=((oi=(si=r.voiceRecognition)==null?void 0:si.provider)==null?void 0:oi.type)==="runtype";if(ms&&(fs||hs))if(!H||!te){let _=ds(r.voiceRecognition,r.sendButton);_&&(H=_.micButton,te=_.micButtonWrapper,It.insertBefore(te,He),H.addEventListener("click",Un),H.disabled=W.isStreaming())}else{let _=(ai=r.voiceRecognition)!=null?ai:{},ze=(ii=r.sendButton)!=null?ii:{},ht=(li=_.iconName)!=null?li:"mic",Oe=(ci=ze.size)!=null?ci:"40px",Qe=(di=_.iconSize)!=null?di:Oe,Lt=parseFloat(Qe)||24;H.style.width=Qe,H.style.height=Qe,H.style.minWidth=Qe,H.style.minHeight=Qe;let Ot=(ui=(pi=_.iconColor)!=null?pi:ze.textColor)!=null?ui:"currentColor";H.innerHTML="";let Qt=ue(ht,Lt,Ot,2);Qt?H.appendChild(Qt):H.textContent="\u{1F3A4}";let qt=(gi=_.backgroundColor)!=null?gi:ze.backgroundColor;qt?(H.style.backgroundColor=qt,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=te==null?void 0:te.querySelector(".persona-send-button-tooltip"),en=(mi=_.tooltipText)!=null?mi:"Start voice recognition";if(((fi=_.showTooltip)!=null?fi:!1)&&en)if(At)At.textContent=en,At.style.display="";else{let Bt=document.createElement("div");Bt.className="persona-send-button-tooltip",Bt.textContent=en,te==null||te.insertBefore(Bt,H)}else At&&(At.style.display="none");te.style.display="",H.disabled=W.isStreaming()}else H&&te&&(te.style.display="none",((yi=(hi=r.voiceRecognition)==null?void 0:hi.provider)==null?void 0:yi.type)==="runtype"?W.isVoiceActive()&&W.toggleVoice():Zt&&ln());if(((bi=r.attachments)==null?void 0:bi.enabled)===!0)if(!We||!J){let _=(xi=r.attachments)!=null?xi:{},ht=(Ci=((vi=r.sendButton)!=null?vi:{}).size)!=null?Ci:"40px";Pe||(Pe=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Pe.style.display="none",Ve.insertBefore(Pe,ee)),Ce||(Ce=document.createElement("input"),Ce.type="file",Ce.accept=((wi=_.allowedTypes)!=null?wi:Mn).join(","),Ce.multiple=((Si=_.maxFiles)!=null?Si:4)>1,Ce.style.display="none",Ce.setAttribute("aria-label","Attach files"),Ve.insertBefore(Ce,ee)),We=f("div","persona-send-button-wrapper"),J=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),J.type="button",J.setAttribute("aria-label",(Ai=_.buttonTooltipText)!=null?Ai:"Attach file");let Oe=(Ei=_.buttonIconName)!=null?Ei:"paperclip",Qe=ht,Lt=parseFloat(Qe)||40,Ot=Math.round(Lt*.6);J.style.width=Qe,J.style.height=Qe,J.style.minWidth=Qe,J.style.minHeight=Qe,J.style.fontSize="18px",J.style.lineHeight="1",J.style.backgroundColor="transparent",J.style.color="var(--persona-primary, #111827)",J.style.border="none",J.style.borderRadius="6px",J.style.transition="background-color 0.15s ease",J.addEventListener("mouseenter",()=>{J.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),J.addEventListener("mouseleave",()=>{J.style.backgroundColor="transparent"});let Qt=ue(Oe,Ot,"currentColor",1.5);Qt?J.appendChild(Qt):J.textContent="\u{1F4CE}",J.addEventListener("click",en=>{en.preventDefault(),Ce==null||Ce.click()}),We.appendChild(J);let qt=(Ti=_.buttonTooltipText)!=null?Ti:"Attach file",At=f("div","persona-send-button-tooltip");At.textContent=qt,We.appendChild(At),Ft.append(We),!Be&&Ce&&Pe&&(Be=pr.fromConfig(_),Be.setPreviewsContainer(Pe),Ce.addEventListener("change",async()=>{Be&&(Ce!=null&&Ce.files)&&(await Be.handleFileSelect(Ce.files),Ce.value="")}))}else{We.style.display="";let _=(Mi=r.attachments)!=null?Mi:{};Ce&&(Ce.accept=((ki=_.allowedTypes)!=null?ki:Mn).join(","),Ce.multiple=((Li=_.maxFiles)!=null?Li:4)>1),Be&&Be.updateConfig({allowedTypes:_.allowedTypes,maxFileSize:_.maxFileSize,maxFiles:_.maxFiles})}else We&&(We.style.display="none"),Be&&Be.clearAttachments();let Tt=(Pi=r.sendButton)!=null?Pi:{},ys=(Ii=Tt.useIcon)!=null?Ii:!1,Hr=(Wi=Tt.iconText)!=null?Wi:"\u2191",Br=Tt.iconName,ar=(Ri=Tt.tooltipText)!=null?Ri:"Send message",bs=(Hi=Tt.showTooltip)!=null?Hi:!1,Bn=(Bi=Tt.size)!=null?Bi:"40px",Tn=Tt.backgroundColor,Yt=Tt.textColor;if(ys){if(X.style.width=Bn,X.style.height=Bn,X.style.minWidth=Bn,X.style.minHeight=Bn,X.style.fontSize="18px",X.style.lineHeight="1",X.innerHTML="",Br){let _=parseFloat(Bn)||24,ze=Yt&&typeof Yt=="string"&&Yt.trim()?Yt.trim():"currentColor",ht=ue(Br,_,ze,2);ht?(X.appendChild(ht),X.style.color=ze):(X.textContent=Hr,Yt?X.style.color=Yt:X.classList.add("persona-text-white"))}else X.textContent=Hr,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=(Fi=($i=r.copy)==null?void 0:$i.sendButtonLabel)!=null?Fi:"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 $r=He==null?void 0:He.querySelector(".persona-send-button-tooltip");if(bs&&ar)if($r)$r.textContent=ar,$r.style.display="";else{let _=document.createElement("div");_.className="persona-send-button-tooltip",_.textContent=ar,He==null||He.insertBefore(_,X)}else $r&&($r.style.display="none");let Fr=(Ni=r.statusIndicator)!=null?Ni:{},dc=(Oi=Fr.visible)!=null?Oi:!0;if(et.style.display=dc?"":"none",W){let _=W.getStatus(),ze=ht=>{var Oe,Qe,Lt,Ot;return ht==="idle"?(Oe=Fr.idleText)!=null?Oe:_t.idle:ht==="connecting"?(Qe=Fr.connectingText)!=null?Qe:_t.connecting:ht==="connected"?(Lt=Fr.connectedText)!=null?Lt:_t.connected:ht==="error"?(Ot=Fr.errorText)!=null?Ot:_t.error:_t[ht]};et.textContent=ze(_)}},open(){v&&ft(!0,"api")},close(){v&&ft(!1,"api")},toggle(){v&&ft(!S,"api")},clearChat(){an=!1,W.clearMessages(),Rn.clear();try{localStorage.removeItem(br),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${br}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==br)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!ee||W.isStreaming()?!1:(!S&&v&&ft(!0,"system"),ee.value=l,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(W.isStreaming())return!1;let u=(l==null?void 0:l.trim())||ee.value.trim();return u?(!S&&v&&ft(!0,"system"),ee.value="",ee.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&&ft(!0,"system"),qe.manuallyDeactivated=!1,zt(),W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),nn("user"),W.isVoiceActive()&&Hn()})),!0):Zt?!0:Rr()?(!S&&v&&ft(!0,"system"),qe.manuallyDeactivated=!1,zt(),Vn("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&&ft(!0,"system"),W.injectMessage(l)},injectAssistantMessage(l){!S&&v&&ft(!0,"system");let u=W.injectAssistantMessage(l);return N&&(N=!1,Z&&(clearTimeout(Z),Z=null),setTimeout(()=>{W&&!W.isStreaming()&&W.continueConversation()},100)),u},injectUserMessage(l){return!S&&v&&ft(!0,"system"),W.injectUserMessage(l)},injectSystemMessage(l){return!S&&v&&ft(!0,"system"),W.injectSystemMessage(l)},injectMessageBatch(l){return!S&&v&&ft(!0,"system"),W.injectMessageBatch(l)},injectTestMessage(l){!S&&v&&ft(!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||!ee?!1:(ee.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&&ft(!0,"system");let u=Ee.querySelector(".persona-feedback-container");u&&u.remove();let h=wo({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&&ft(!0,"system");let u=Ee.querySelector(".persona-feedback-container");u&&u.remove();let h=So({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((((Xo=n==null?void 0:n.debugTools)!=null?Xo:!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=Bd(r.persistState);if(I&&v){let l=$d(I.storage),u=`${I.keyPrefix}widget-open`,h=`${I.keyPrefix}widget-voice`,A=`${I.keyPrefix}widget-voice-mode`;if(l){let L=((Go=I.persist)==null?void 0:Go.openState)&&l.getItem(u)==="true",$=((Zo=I.persist)==null?void 0:Zo.voiceState)&&l.getItem(h)==="true",R=((Qo=I.persist)==null?void 0:Qo.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),(ea=I.persist)!=null&&ea.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(ta=I.persist)!=null&&ta.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 jl=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},To=(e,t,n,r,o,s)=>{let a=zr(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",t.style.display="flex",t.style.flexDirection="column",t.style.flex="1 1 auto",t.style.minWidth="0",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${i}`,n.style.width=i,n.style.maxWidth=i,n.style.minWidth=i,n.style.minHeight="0",n.style.position="relative",n.style.overflow="visible",n.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!==n&&e.replaceChildren(n,t):e.lastElementChild!==n&&e.replaceChildren(t,n)},Fd=(e,t)=>{let n=e.ownerDocument.createElement("div");return jl(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){jl(n,r)},destroy(){n.remove()}}},Nd=(e,t)=>{var p,y,m,C;let{ownerDocument:n}=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=n.createElement("div"),i=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),g=(y=(p=t==null?void 0:t.launcher)==null?void 0:p.enabled)==null||y?(C=(m=t==null?void 0:t.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),To(a,i,d,c,t,g),{mode:"docked",host:c,shell:a,syncWidgetState(v){let E=v.launcherEnabled?v.open:!0;g!==E&&(g=E,To(a,i,d,c,t,g))},updateConfig(v){var E,x;t=v,((x=(E=t==null?void 0:t.launcher)==null?void 0:E.enabled)!=null?x:!0)===!1&&(g=!0),To(a,i,d,c,t,g)},destroy(){r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Hs=(e,t)=>Ut(t)?Nd(e,t):Fd(e,t);var Mo={},Od=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 t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Dd=()=>{try{if(typeof Mo!="undefined"&&Mo.url)return new URL("../widget.css",Mo.url).href}catch{}return null},Vl=(e,t)=>{let n=Dd(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},ql=e=>{var E;let t=Od(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Hs(t,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)||Ut(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"),n){let Z=x.attachShadow({mode:"open"});Z.appendChild(O),Vl(Z,r)}else x.appendChild(O),Vl(x,r);return t.id&&O.setAttribute("data-persona-instance",t.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=Eo(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=Hs(t,x),o=x,p()},C={update(x){var O,S,N,Z,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:{...(Z=(N=o==null?void 0:o.launcher)==null?void 0:N.dock)!=null?Z:{},...(re=(K=x==null?void 0:x.launcher)==null?void 0:K.dock)!=null?re:{}}}},U=Ut(o),M=Ut(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 Yl=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),_d=new Set(["button","a","input","select","textarea","details","summary"]),jd=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ko=/\b(product|card|item|listing|result)\b/i,Po=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Vd=3e3,qd=100;function Xl(e){let t=typeof e.className=="string"?e.className:"";if(ko.test(t)||e.id&&ko.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&ko.test(r.value))return!0}return!1}function Gl(e){var t;return Po.test(((t=e.textContent)!=null?t:"").trim())}function Zl(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Ud(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Ul(e){let t=e.match(Po);return t?t[0]:null}function zl(e){var r,o,s;let t=(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(t&&((o=t.textContent)!=null&&o.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function zd(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var Jd="commerce-card",Kd="result-card";function Jl(e){return!Xl(e)||!Gl(e)||!Zl(e)&&!Ud(e)?0:5200}function Kl(e){var r;return!Xl(e)||Gl(e)||!Zl(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 Ql=[{id:Jd,scoreElement(e){return Jl(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||Po.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,g;if(Jl(e)===0)return null;let{title:n,href:r}=zl(e),o=(g=(c=Ul(((d=e.textContent)!=null?d:"").trim()))!=null?c:Ul(t.text))!=null?g:"",s=zd(e);return[r&&n?`[${n}](${r})${o?` \u2014 ${o}`:""}`:n?`${n}${o?` \u2014 ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
96
+ `)}},{id:Kd,scoreElement(e){return Kl(e)},formatSummary(e,t){if(Kl(e)===0)return null;let{title:n,href:r}=zl(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
97
+ `)}}];function Yd(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Xd(e){var g,p,y,m,C,v,E,x,k,U,M,O,S;let t=(g=e.options)!=null?g:{},n=(y=(p=t.maxElements)!=null?p:e.maxElements)!=null?y:80,r=(C=(m=t.excludeSelector)!=null?m:e.excludeSelector)!=null?C:".persona-host",o=(E=(v=t.maxTextLength)!=null?v:e.maxTextLength)!=null?E:200,s=(k=(x=t.visibleOnly)!=null?x:e.visibleOnly)!=null?k:!0,a=(U=t.root)!=null?U:e.root,i=(M=t.mode)!=null?M:"structured",d=(O=t.maxCandidates)!=null?O:Math.max(500,n*10),c=(S=e.rules)!=null?S:Ql;return i==="simple"&&e.rules&&e.rules.length>0?(Yd(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:c}}function Lo(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Gd=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Zd(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||_d.has(t)||n&&jd.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function ec(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Qd(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let c=0;c<e.attributes.length;c++){let g=e.attributes[c];g.name.startsWith("data-")&&(t[g.name]=g.value)}return t}function tc(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${Lo(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of Gd){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${Lo(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>Lo(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 > ${t}`)).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 > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function ep(e){return e==="static"?qd:Vd}function nc(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:tc(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Zd(e),attributes:Qd(e)}}function tp(e,t,n,r){let o=ep(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function np(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function rp(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,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(Yl.has(g)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!ec(c)){i=a.nextNode();continue}let p=nc(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}=tp(c,p,e.rules,n);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;np(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,n);m&&(g=m)}let p={...c.enriched};return g&&(p.formattedSummary=g),p})}function sp(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,c=d.tagName.toLowerCase();if(Yl.has(c)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!ec(d)){s=o.nextNode();continue}let g=nc(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),n.push(g))}s=o.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function op(e={}){var r;let t=Xd(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?sp(t,n):rp(t,n):[]}var Bs=100;function ap(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"structured",r=[];if(n==="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)n==="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,Bs)}" (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,Bs)}" (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,Bs)}" (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,Bs)}"`);r.push(`Content:
108
+ ${a.join(`
109
+ `)}`)}return r.join(`
110
+
111
+ `)}var rc={name:"@runtypelabs/persona",version:"2.0.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 xr=rc.version;function kn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function lp(e){if(e)return{getHeaders:kn(e.getHeaders),onFeedback:kn(e.onFeedback),onCopy:kn(e.onCopy),requestMiddleware:kn(e.requestMiddleware),actionHandlers:kn(e.actionHandlers),actionParsers:kn(e.actionParsers),postprocessMessage:kn(e.postprocessMessage),contextProviders:kn(e.contextProviders),streamParser:kn(e.streamParser)}}var sc=`({ 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 @@ import{Marked as Ta}from"marked";var Ma=n=>{if(n)return n},Ds=n=>{var o,s;let t=
70
121
  if (parsed.action) return { type: parsed.action, payload: parsed };
71
122
  } catch (e) { return null; }
72
123
  return null;
73
- }`,ba=`function(ctx) {
124
+ }`,oc=`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 @@ import{Marked as Ta}from"marked";var Ma=n=>{if(n)return n},Ds=n=>{var o,s;let t=
83
134
  if (parsed.action) return { type: parsed.action, payload: parsed };
84
135
  } catch (e) { return null; }
85
136
  return null;
86
- }`,Ca=`(action: any, context: any) => {
137
+ }`,ac=`(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 @@ import{Marked as Ta}from"marked";var Ma=n=>{if(n)return n},Ds=n=>{var o,s;let t=
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
- }`,xa=`function(action, context) {
154
+ }`,ic=`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 @@ import{Marked as Ta}from"marked";var Ma=n=>{if(n)return n},Ds=n=>{var o,s;let t=
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
- }`,Dl=`(parsed: any) => {
171
+ }`,cp=`(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
- }`,jl=`function(parsed) {
177
+ }`,dp=`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 _l(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 er(n){var t,r;return(r=(t=n.parserType)!=null?t:_l(n.streamParser))!=null?r:"plain"}function tr(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 nr(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 rr(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 jr(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 Ul(n,t="esm",r){let e={...n};delete e.postprocessMessage,delete e.initialMessages;let o=r?{...r,hooks:Ol(r.hooks)}:void 0;return t==="esm"?ql(e,o):t==="script-installer"?Jl(e):t==="script-advanced"?Yl(e,o):t==="react-component"?Vl(e,o):t==="react-advanced"?zl(e,o):Kl(e,o)}function ql(n,t){let r=t==null?void 0:t.hooks,e=er(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(...tr(n," ")),s.push(...nr(n," ",r)),s.push(...sr(n," ")),s.push(...rr(n," ")),s.push(...jr(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 Vl(n,t){let r=t==null?void 0:t.hooks,e=er(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(...tr(n," ")),s.push(...nr(n," ",r)),s.push(...sr(n," ")),s.push(...rr(n," ")),s.push(...jr(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(...tr(n," ")),e.push(...nr(n," ",r)),e.push(...sr(n," ")),e.push(...rr(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(${Dl}),`)),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(` ${ya}`),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(` ${ya}`),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(` ${Ca}`),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(` ${Ca}`),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 Sa(n){var o;let t=er(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 Jl(n){let t=Sa(n),r=JSON.stringify(t,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Zn}/dist/install.global.js" data-config='${r}'></script>`}function Kl(n,t){let r=t==null?void 0:t.hooks,e=er(n),o=e!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Zn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Zn}/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(...tr(n," ")),s.push(...nr(n," ",r)),s.push(...sr(n," ")),s.push(...rr(n," ")),s.push(...jr(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 Yl(n,t){let r=t==null?void 0:t.hooks,e=Sa(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@${Zn}/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(${jl});`),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(` ${ba}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${ba}`),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(` ${xa}`),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(` ${xa}`),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 Lu=va;export{jn as AgentWidgetClient,vs as AgentWidgetSession,qn as AttachmentManager,ua as DEFAULT_DARK_THEME,da as DEFAULT_LIGHT_THEME,lt as DEFAULT_WIDGET_CONFIG,Zn as VERSION,Vn as attachHeaderToContainer,bs as buildComposer,Xi as buildDefaultHeader,Zi as buildExpandedHeader,Cn as buildHeader,ys as buildHeaderWithLayout,Gi as buildMinimalHeader,As as componentRegistry,Qs as createActionManager,Or as createAgentExperience,yr as createBestAvailableVoiceProvider,al as createBubbleWithLayout,Fr as createCSATFeedback,Il as createComponentMiddleware,Pr as createComponentStreamParser,Ia as createDirectivePostprocessor,Ha as createFlexibleJsonStreamParser,_a as createImagePart,hr as createJsonStreamParser,Lr as createLocalStorageAdapter,Ds as createMarkdownProcessor,js as createMarkdownProcessorFromConfig,ra as createMessageActions,$r as createNPSFeedback,pr as createPlainTextParser,gr as createRegexJsonParser,Cs as createStandardBubble,wr as createTextPart,zn as createTypingIndicator,Un as createVoiceProvider,mr as createXmlParser,Lu as default,Xn as defaultActionHandlers,Zs as defaultJsonActionParser,La as directivePostprocessor,ur as escapeHtml,Br as extractComponentDirectiveFromMessage,Ua as fileToImagePart,_n as generateAssistantMessageId,Ul as generateCodeSnippet,$a as generateMessageId,ms as generateUserMessageId,Oa as getDisplayText,Qi as getHeaderLayout,ja as getImageParts,Hr as hasComponentDirective,Da as hasImages,Cr as headerLayouts,va as initAgentWidget,kl as isComponentDirectiveType,Ks as isVoiceSupported,Fi as markdownPostprocessor,kr as mergeWithDefaults,Na as normalizeContent,Gs as pluginRegistry,Rr as renderComponentDirective,sa as renderLoadingIndicatorWithFallback,qa as validateImageFile};
183
+ }`;function pp(e){if(!e)return null;let t=e.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 $s(e){var t,n;return(n=(t=e.parserType)!=null?t:pp(e.streamParser))!=null?n:"plain"}function Fs(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&n.push(`${t} ${r}: "${o}",`)}),n.push(`${t}},`)),n}function Ns(e,t,n){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||s)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function Os(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),o&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Ds(e,t){let n=[];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)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),o&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?n.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${d}: ${c},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Io(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function lc(e,t,n){Object.entries(t).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${r}: {`),lc(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function _s(e,t,n,r){n&&(e.push(`${r}${t}: {`),lc(e,n,`${r} `),e.push(`${r}},`))}function up(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:lp(n.hooks)}:void 0;return t==="esm"?gp(r,o):t==="script-installer"?hp(r):t==="script-advanced"?bp(r,o):t==="react-component"?mp(r,o):t==="react-advanced"?fp(r,o):yp(r,o)}function gp(e,t){let n=t==null?void 0:t.hooks,r=$s(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&&_s(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(...Fs(e," ")),s.push(...Ns(e," ",n)),s.push(...Os(e," ")),s.push(...Ds(e," ")),s.push(...Io(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
184
+ `)}function mp(e,t){let n=t==null?void 0:t.hooks,r=$s(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&&_s(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(...Fs(e," ")),s.push(...Ns(e," ",n)),s.push(...Os(e," ")),s.push(...Ds(e," ")),s.push(...Io(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.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 fp(e,t){let n=t==null?void 0:t.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&&_s(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(...Fs(e," ")),r.push(...Ns(e," ",n)),r.push(...Os(e," ")),r.push(...Ds(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${cp}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${sc}`),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(` ${sc}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${ac}`),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(` ${ac}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.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 cc(e){var o;let t=$s(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),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 hp(e){let t=cc(e),n=JSON.stringify(t,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xr}/dist/install.global.js" data-config='${n}'></script>`}function yp(e,t){let n=t==null?void 0:t.hooks,r=$s(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xr}/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&&_s(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(...Fs(e," ")),s.push(...Ns(e," ",n)),s.push(...Os(e," ")),s.push(...Ds(e," ")),s.push(...Io(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
187
+ `)}function bp(e,t){let n=t==null?void 0:t.hooks,r=cc(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@${xr}/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 n!=null&&n.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n!=null&&n.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n!=null&&n.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${dp});`),s.push(" };")),s.push(""),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${oc}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${oc}`),s.push(" ];")),s.push(""),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${ic}`),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(` ${ic}`),s.push(" ];")),s.push(""),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.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(""),n!=null&&n.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.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 xp(){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 vp(){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 Cp(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.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)}}),{...t,palette:n}}}}function wp(){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 Sp(){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,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Ap(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Rm=ql;export{lr as AgentWidgetClient,qr as AgentWidgetSession,pr as AttachmentManager,tl as DEFAULT_COMPONENTS,Fl as DEFAULT_DARK_THEME,$l as DEFAULT_LIGHT_THEME,Qi as DEFAULT_PALETTE,el as DEFAULT_SEMANTIC,yt as DEFAULT_WIDGET_CONFIG,xr as VERSION,xp as accessibilityPlugin,vp as animationsPlugin,Yn as applyThemeVariables,ur as attachHeaderToContainer,Cp as brandPlugin,Yr as buildComposer,fl as buildDefaultHeader,$n as buildHeader,Kr as buildHeaderWithLayout,hl as buildMinimalHeader,op as collectEnrichedPageContext,Fn as componentRegistry,Rs as createActionManager,Eo as createAgentExperience,Zs as createBestAvailableVoiceProvider,td as createBubbleWithLayout,wo as createCSATFeedback,Pd as createComponentMiddleware,bo as createComponentStreamParser,mc as createDirectivePostprocessor,xc as createFlexibleJsonStreamParser,Mc as createImagePart,Js as createJsonStreamParser,yo as createLocalStorageAdapter,xs as createMarkdownProcessor,ir as createMarkdownProcessorFromConfig,wl as createMessageActions,So as createNPSFeedback,Us as createPlainTextParser,Ap as createPlugin,zs as createRegexJsonParser,Xr as createStandardBubble,Gs as createTextPart,Ur as createTheme,oo as createThemeObserver,gr as createTypingIndicator,dr as createVoiceProvider,Hs as createWidgetHostLayout,Ks as createXmlParser,Rm as default,yr as defaultActionHandlers,Ws as defaultJsonActionParser,Ql as defaultParseRules,ks as detectColorScheme,fc as directivePostprocessor,Dr as escapeHtml,Co as extractComponentDirectiveFromMessage,kc as fileToImagePart,ap as formatEnrichedContext,cr as generateAssistantMessageId,up as generateCodeSnippet,wc as generateMessageId,tc as generateStableSelector,jr as generateUserMessageId,ll as getActiveTheme,il as getColorScheme,Ac as getDisplayText,yl as getHeaderLayout,Tc as getImageParts,vo as hasComponentDirective,Ec as hasImages,ao as headerLayouts,Sp as highContrastPlugin,ql as initAgentWidget,Ld as isComponentDirectiveType,Ut as isDockedMountMode,Ts as isVoiceSupported,_i as markdownPostprocessor,fo as mergeWithDefaults,no as migrateV1Theme,Sc as normalizeContent,Is as pluginRegistry,wp as reducedMotionPlugin,xo as renderComponentDirective,Cl as renderLoadingIndicatorWithFallback,zr as resolveDockConfig,Qs as resolveTokens,eo as themeToCssVariables,Lc as validateImageFile,rl as validateTheme,Nc as validateV1Theme};
140
191
  //# sourceMappingURL=index.js.map