@runtypelabs/persona 1.47.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 (73) 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 +1093 -25
  5. package/dist/index.d.ts +1093 -25
  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 +852 -505
  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 +173 -7
  44. package/src/styles/tailwind.css +1 -1
  45. package/src/styles/widget.css +852 -505
  46. package/src/types/theme.ts +354 -0
  47. package/src/types.ts +348 -16
  48. package/src/ui.docked.test.ts +104 -0
  49. package/src/ui.ts +1093 -244
  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
  70. package/src/voice/audio-playback-manager.ts +187 -0
  71. package/src/voice/runtype-voice-provider.ts +305 -69
  72. package/src/voice/voice-activity-detector.ts +90 -0
  73. package/src/voice/voice.test.ts +6 -5
package/dist/index.js CHANGED
@@ -1,35 +1,70 @@
1
- import{Marked as ya}from"marked";var ba=n=>{if(n)return n},Ds=n=>{var o,s;let t=n==null?void 0:n.markedOptions,r=new ya({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=ba(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(),Ca=Ds(),Ii=n=>Ca(n),cr=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Li=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),ki=n=>`%%FORM_PLACEHOLDER_${n}%%`,Wi=(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=ki(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=ki(t.length);return t.push({token:s,type:o}),s}),r},xa=n=>{let t=js(n);return r=>{let e=[],o=Wi(r,e),s=t(o);return e.forEach(({token:i,type:a})=>{let u=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),v=`<div class="tvw-form-directive" data-tv-form="${Li(a)}"></div>`;s=s.replace(u,v)}),s}},Sa=n=>{let t=[],r=Wi(n,t),e=Ii(r);return t.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="tvw-form-directive" data-tv-form="${Li(s)}"></div>`;e=e.replace(i,u)}),e};import{parse as Pi,STR as Ri,OBJ as Hi}from"partial-json";var _s=n=>n.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),fs=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)}},Aa=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`},Bi=n=>n.status==="complete"?Aa(n):n.status==="pending"?"Waiting":"",Ea=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 Fi=n=>n.status==="complete"?Ea(n):"Using tool...",Ta=()=>{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()=>{}}},Vs=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},dr=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},ur=()=>{var t;let n=Ta();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)}},pr=()=>{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=Pi(r,Ri|Hi);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:()=>{}}},Ma=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=Pi(s,Ri|Hi),u=o(a);u!==null&&(t=u)}catch{}return r=s.length,{text:t||"",raw:s}},close:()=>{}}},gr=()=>{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 ka="https://api.runtype.com/v1/dispatch",mr="https://api.runtype.com",hr=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 Ia(n){switch(n){case"json":return pr;case"regex-json":return ur;case"xml":return gr;default:return dr}}var On=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var r,e,o;this.apiUrl=(r=t.apiUrl)!=null?r:ka,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(e=t.streamParser)!=null?e:Ia(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$/,""))||mr;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$/,""))||mr}/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 u=await this.initSession();if(new Date>=new Date(u.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,d={sessionId:u.sessionId,messages:t.messages.filter(hr).map(w=>{var b,y,S;return{id:w.id,role:w.role,content:(S=(y=(b=w.contentParts)!=null?b:w.llmContent)!=null?y:w.rawContent)!=null?S: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",d);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),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 b=new Error(w.error||"Failed to send message");throw r({type:"error",error:b}),b}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(u){let c=u instanceof Error?u:new Error(String(u));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 u=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:u}),u}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 u=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:u}),u}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$/,""))||mr}/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(hr).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(hr).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 u={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=u,o(u),u};if(i.text!==void 0){let u=a();u.content+=i.text,o(u)}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 ue,Be,Et,dt,gt,Ht,Ne,ne,be,Re,Fe,Ue,Nt,de,X,at,vt,Tt,yt,Kt,ee,Le,bt,pe,Ce,qe,Bt,Mt,Vt,F,Qe,N,G,re,$e,oe,Je,Ke,ce,D,Se,et,tt,Yt,Gt,Ye,Zt,mn,hn,sn,M,fn,an,bn,Xn,ln,cn,Ln,Wn,Ms,ks,Is,Gn,Pn,Ee,Zn,Qt,Ut,Ls,Ws,Qn,Cn,dn,Ps,Rs,Hs,sr,xn,Sn,nt,Rn,Hn,es,ts,ns,ss,Ft,qt,un,kt,rs,An,en,Bs,En,Tn,Bn,Fs,$s,pn,Xe,Ge,wn,os,is,rr,It,or,$t,as,ls,cs,ds,us;let o=t.getReader(),s=new TextDecoder,i="",a=Date.now(),u=0,c=()=>a+u++,v=V=>{let Ie=V.reasoning?{...V.reasoning,chunks:[...V.reasoning.chunks]}:void 0,De=V.toolCall?{...V.toolCall,chunks:V.toolCall.chunks?[...V.toolCall.chunks]:void 0}:void 0,lt=V.tools?V.tools.map(mt=>({...mt,chunks:mt.chunks?[...mt.chunks]:void 0})):void 0;return{...V,reasoning:Ie,toolCall:De,tools:lt}},d=V=>{r({type:"message",message:v(V)})},m=null,w={current:null},b=new Map,y=new Map,S={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=V=>{if(V==null)return null;try{return String(V)}catch{return null}},J=V=>{var Ie,De,lt,mt,At;return k((At=(mt=(lt=(De=(Ie=V.stepId)!=null?Ie:V.step_id)!=null?De:V.step)!=null?lt:V.parentId)!=null?mt:V.flowStepId)!=null?At:V.flow_step_id)},E=V=>{var Ie,De,lt,mt,At,rt,h;return k((h=(rt=(At=(mt=(lt=(De=(Ie=V.callId)!=null?Ie:V.call_id)!=null?De:V.requestId)!=null?lt:V.request_id)!=null?mt:V.toolCallId)!=null?At:V.tool_call_id)!=null?rt:V.stepId)!=null?h:V.step_id)},I=()=>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()},d(m),m),T=(V,Ie)=>{S.lastId=Ie,V&&S.byStep.set(V,Ie)},B=(V,Ie)=>{var At;let De=(At=V.reasoningId)!=null?At:V.id,lt=J(V);if(De){let rt=String(De);return T(lt,rt),rt}if(lt){let rt=S.byStep.get(lt);if(rt)return S.lastId=rt,rt}if(S.lastId&&!Ie)return S.lastId;if(!Ie)return null;let mt=`reason-${c()}`;return T(lt,mt),mt},le=V=>{let Ie=b.get(V);if(Ie)return Ie;let De={id:`reason-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:V,status:"streaming",chunks:[]}};return b.set(V,De),d(De),De},z=(V,Ie)=>{x.lastId=Ie,V&&x.byCall.set(V,Ie)},U=(V,Ie)=>{var At;let De=(At=V.toolId)!=null?At:V.id,lt=E(V);if(De){let rt=String(De);return z(lt,rt),rt}if(lt){let rt=x.byCall.get(lt);if(rt)return x.lastId=rt,rt}if(x.lastId&&!Ie)return x.lastId;if(!Ie)return null;let mt=`tool-${c()}`;return z(lt,mt),mt},K=V=>{let Ie=y.get(V);if(Ie)return Ie;let De={id:`tool-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:V,status:"pending"}};return y.set(V,De),d(De),De},j=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){let Ie=Number(V);if(!Number.isNaN(Ie)&&Number.isFinite(Ie))return Ie;let De=Date.parse(V);if(!Number.isNaN(De))return De}return Date.now()},ye=V=>{if(typeof V=="string")return V;if(V==null)return"";try{return JSON.stringify(V)}catch{return String(V)}},se=new Map,Y=new Map,_=null,O=new Map,Q=(ue=this.config.iterationDisplay)!=null?ue:"separate";for(;;){let{done:V,value:Ie}=await o.read();if(V)break;i+=s.decode(Ie,{stream:!0});let De=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=(Be=De.pop())!=null?Be:"";for(let lt of De){let mt=lt.split(`
7
- `),At="message",rt="";for(let $ of mt)$.startsWith("event:")?At=$.replace("event:","").trim():$.startsWith("data:")&&(rt+=$.replace("data:","").trim());if(!rt)continue;let h;try{h=JSON.parse(rt)}catch($){r({type:"error",error:$ instanceof Error?$:new Error("Failed to parse chat stream payload")});continue}let We=At!=="message"?At:(Et=h.type)!=null?Et:"message";if((dt=this.onSSEEvent)==null||dt.call(this,We,h),this.parseSSEEvent){w.current=m;let $=await this.handleCustomSSEEvent(h,r,w,d,c);if(w.current&&!m&&(m=w.current),$)continue}if(We==="reason_start"){let $=(gt=B(h,!0))!=null?gt:`reason-${c()}`,C=le($);C.reasoning=(Ht=C.reasoning)!=null?Ht:{id:$,status:"streaming",chunks:[]},C.reasoning.startedAt=(ne=C.reasoning.startedAt)!=null?ne:j((Ne=h.startedAt)!=null?Ne:h.timestamp),C.reasoning.completedAt=void 0,C.reasoning.durationMs=void 0,C.streaming=!0,C.reasoning.status="streaming",d(C)}else if(We==="reason_delta"||We==="reason_chunk"){let $=(Re=(be=B(h,!1))!=null?be:B(h,!0))!=null?Re:`reason-${c()}`,C=le($);C.reasoning=(Fe=C.reasoning)!=null?Fe:{id:$,status:"streaming",chunks:[]},C.reasoning.startedAt=(Nt=C.reasoning.startedAt)!=null?Nt:j((Ue=h.startedAt)!=null?Ue:h.timestamp);let L=(at=(X=(de=h.reasoningText)!=null?de:h.text)!=null?X:h.delta)!=null?at:"";if(L&&h.hidden!==!0&&C.reasoning.chunks.push(String(L)),C.reasoning.status=h.done?"complete":"streaming",h.done){C.reasoning.completedAt=j((vt=h.completedAt)!=null?vt:h.timestamp);let ae=(Tt=C.reasoning.startedAt)!=null?Tt:Date.now();C.reasoning.durationMs=Math.max(0,((yt=C.reasoning.completedAt)!=null?yt:Date.now())-ae)}C.streaming=C.reasoning.status!=="complete",d(C)}else if(We==="reason_complete"){let $=(ee=(Kt=B(h,!1))!=null?Kt:B(h,!0))!=null?ee:`reason-${c()}`,C=b.get($);if(C!=null&&C.reasoning){C.reasoning.status="complete",C.reasoning.completedAt=j((Le=h.completedAt)!=null?Le:h.timestamp);let ae=(bt=C.reasoning.startedAt)!=null?bt:Date.now();C.reasoning.durationMs=Math.max(0,((pe=C.reasoning.completedAt)!=null?pe:Date.now())-ae),C.streaming=!1,d(C)}let L=J(h);L&&S.byStep.delete(L)}else if(We==="tool_start"){let $=(Ce=U(h,!0))!=null?Ce:`tool-${c()}`,C=K($),L=(qe=C.toolCall)!=null?qe:{id:$,status:"pending"};L.name=(Bt=h.toolName)!=null?Bt:L.name,L.status="running",h.args!==void 0?L.args=h.args:h.parameters!==void 0&&(L.args=h.parameters),L.startedAt=(Vt=L.startedAt)!=null?Vt:j((Mt=h.startedAt)!=null?Mt:h.timestamp),L.completedAt=void 0,L.durationMs=void 0,C.toolCall=L,C.streaming=!0;let ae=h.agentContext;(ae||h.executionId)&&(C.agentMetadata={executionId:(F=ae==null?void 0:ae.executionId)!=null?F:h.executionId,iteration:(Qe=ae==null?void 0:ae.iteration)!=null?Qe:h.iteration}),d(C)}else if(We==="tool_chunk"||We==="tool_delta"){let $=(G=(N=U(h,!1))!=null?N:U(h,!0))!=null?G:`tool-${c()}`,C=K($),L=(re=C.toolCall)!=null?re:{id:$,status:"running"};L.startedAt=(oe=L.startedAt)!=null?oe:j(($e=h.startedAt)!=null?$e:h.timestamp);let ae=(ce=(Ke=(Je=h.text)!=null?Je:h.delta)!=null?Ke:h.message)!=null?ce:"";ae&&(L.chunks=(D=L.chunks)!=null?D:[],L.chunks.push(String(ae))),L.status="running",C.toolCall=L,C.streaming=!0;let Ae=h.agentContext;(Ae||h.executionId)&&(C.agentMetadata=(tt=C.agentMetadata)!=null?tt:{executionId:(Se=Ae==null?void 0:Ae.executionId)!=null?Se:h.executionId,iteration:(et=Ae==null?void 0:Ae.iteration)!=null?et:h.iteration}),d(C)}else if(We==="tool_complete"){let $=(Gt=(Yt=U(h,!1))!=null?Yt:U(h,!0))!=null?Gt:`tool-${c()}`,C=K($),L=(Ye=C.toolCall)!=null?Ye:{id:$,status:"running"};L.status="complete",h.result!==void 0&&(L.result=h.result),typeof h.duration=="number"&&(L.duration=h.duration),L.completedAt=j((Zt=h.completedAt)!=null?Zt:h.timestamp);let ae=(mn=h.duration)!=null?mn:h.executionTime;if(typeof ae=="number")L.durationMs=ae;else{let Lt=(hn=L.startedAt)!=null?hn:Date.now();L.durationMs=Math.max(0,((sn=L.completedAt)!=null?sn:Date.now())-Lt)}C.toolCall=L,C.streaming=!1;let Ae=h.agentContext;(Ae||h.executionId)&&(C.agentMetadata=(an=C.agentMetadata)!=null?an:{executionId:(M=Ae==null?void 0:Ae.executionId)!=null?M:h.executionId,iteration:(fn=Ae==null?void 0:Ae.iteration)!=null?fn:h.iteration}),d(C);let ze=E(h);ze&&x.byCall.delete(ze)}else if(We==="step_chunk"||We==="step_delta"){let $=h.stepType,C=h.executionType;if($==="tool"||C==="context")continue;let L=I(),ae=(cn=(ln=(Xn=(bn=h.text)!=null?bn:h.delta)!=null?Xn:h.content)!=null?ln:h.chunk)!=null?cn:"";if(ae){let ze=((Ln=Y.get(L.id))!=null?Ln:"")+ae;L.rawContent=ze,se.has(L.id)||se.set(L.id,this.createStreamParser());let Lt=se.get(L.id),ot=ze.trim().startsWith("{")||ze.trim().startsWith("[");if(ot&&Y.set(L.id,ze),Lt.__isPlainTextParser===!0){L.content+=ae,Y.delete(L.id),se.delete(L.id),L.rawContent=void 0,d(L);continue}let ht=Lt.processChunk(ze);if(ht instanceof Promise)ht.then(Oe=>{var ut;let _e=typeof Oe=="string"?Oe:(ut=Oe==null?void 0:Oe.text)!=null?ut:null;if(_e!==null&&_e.trim()!==""){let Ve=m;Ve&&Ve.id===L.id&&(Ve.content=_e,d(Ve))}else if(!ot&&!ze.trim().startsWith("<")){let Ve=m;Ve&&Ve.id===L.id&&(Ve.content+=ae,Y.delete(Ve.id),se.delete(Ve.id),Ve.rawContent=void 0,d(Ve))}}).catch(()=>{L.content+=ae,Y.delete(L.id),se.delete(L.id),L.rawContent=void 0,d(L)});else{let Oe=typeof ht=="string"?ht:(Wn=ht==null?void 0:ht.text)!=null?Wn:null;Oe!==null&&Oe.trim()!==""?(L.content=Oe,d(L)):!ot&&!ze.trim().startsWith("<")&&(L.content+=ae,Y.delete(L.id),se.delete(L.id),L.rawContent=void 0,d(L))}}if(h.isComplete){let Ae=(ks=(Ms=h.result)==null?void 0:Ms.response)!=null?ks:L.content;if(Ae){let ze=Y.get(L.id),Lt=ze!=null?ze:ye(Ae);L.rawContent=Lt;let ot=se.get(L.id),Ct=null,ht=!1;if(ot&&(Ct=ot.getExtractedText(),Ct===null&&(Ct=Vs(Lt)),Ct===null)){let Oe=ot.processChunk(Lt);Oe instanceof Promise?(ht=!0,Oe.then(_e=>{var Ve;let ut=typeof _e=="string"?_e:(Ve=_e==null?void 0:_e.text)!=null?Ve:null;if(ut!==null){let xt=m;xt&&xt.id===L.id&&(xt.content=ut,xt.streaming=!1,se.delete(xt.id),Y.delete(xt.id),d(xt))}})):Ct=typeof Oe=="string"?Oe:(Is=Oe==null?void 0:Oe.text)!=null?Is:null}if(!ht){Ct!==null&&Ct.trim()!==""?L.content=Ct:Y.has(L.id)||(L.content=ye(Ae));let Oe=se.get(L.id);if(Oe){let _e=(Gn=Oe.close)==null?void 0:Gn.call(Oe);_e instanceof Promise&&_e.catch(()=>{}),se.delete(L.id)}Y.delete(L.id),L.streaming=!1,d(L)}}}}else if(We==="step_complete"){let $=h.stepType,C=h.executionType;if($==="tool"||C==="context")continue;let L=(Pn=h.result)==null?void 0:Pn.response,ae=I();if(L!=null){let Ae=se.get(ae.id),ze=!1,Lt=!1;if(Ae){let ot=Ae.getExtractedText(),Ct=Y.get(ae.id),ht=Ct!=null?Ct:ye(L);if(ae.rawContent=ht,ot!==null&&ot.trim()!=="")ae.content=ot,ze=!0;else{let Oe=Vs(ht);if(Oe!==null)ae.content=Oe,ze=!0;else{let _e=Ae.processChunk(ht);if(_e instanceof Promise)Lt=!0,_e.then(ut=>{var xt;let Ve=typeof ut=="string"?ut:(xt=ut==null?void 0:ut.text)!=null?xt:null;if(Ve!==null&&Ve.trim()!==""){let Dt=m;Dt&&Dt.id===ae.id&&(Dt.content=Ve,Dt.streaming=!1,se.delete(Dt.id),Y.delete(Dt.id),d(Dt))}else{let Dt=Ae.getExtractedText(),Xt=m;Xt&&Xt.id===ae.id&&(Dt!==null&&Dt.trim()!==""?Xt.content=Dt:Y.has(Xt.id)||(Xt.content=ye(L)),Xt.streaming=!1,se.delete(Xt.id),Y.delete(Xt.id),d(Xt))}});else{let ut=typeof _e=="string"?_e:(Ee=_e==null?void 0:_e.text)!=null?Ee:null;if(ut!==null&&ut.trim()!=="")ae.content=ut,ze=!0;else{let Ve=Ae.getExtractedText();Ve!==null&&Ve.trim()!==""&&(ae.content=Ve,ze=!0)}}}}}if(!Lt){if(!ae.rawContent){let ot=Y.get(ae.id);ae.rawContent=ot!=null?ot:ye(L)}if(!ze&&!Y.has(ae.id)&&(ae.content=ye(L)),Ae){let ot=(Zn=Ae.close)==null?void 0:Zn.call(Ae);ot instanceof Promise&&ot.catch(()=>{})}se.delete(ae.id),Y.delete(ae.id),ae.streaming=!1,d(ae)}}else se.delete(ae.id),Y.delete(ae.id),ae.streaming=!1,d(ae)}else if(We==="flow_complete"){let $=(Qt=h.result)==null?void 0:Qt.response;if($!=null){let C=I(),L=Y.get(C.id),ae=L!=null?L:ye($);C.rawContent=ae;let Ae=ye($),ze=se.get(C.id);if(ze){let Ct=Vs(ae);if(Ct!==null)Ae=Ct;else{let ht=ze.processChunk(ae);ht instanceof Promise&&ht.then(_e=>{var Ve;let ut=typeof _e=="string"?_e:(Ve=_e==null?void 0:_e.text)!=null?Ve:null;if(ut!==null){let xt=m;xt&&xt.id===C.id&&(xt.content=ut,xt.streaming=!1,d(xt))}});let Oe=ze.getExtractedText();Oe!==null&&(Ae=Oe)}}se.delete(C.id),Y.delete(C.id);let Lt=Ae!==C.content,ot=C.streaming!==!1;Lt&&(C.content=Ae),C.streaming=!1,(Lt||ot)&&d(C)}else if(m!==null){let C=m;se.delete(C.id),Y.delete(C.id),C.streaming!==!1&&(C.streaming=!1,d(C))}r({type:"status",status:"idle"})}else if(We==="agent_start")_={executionId:h.executionId,agentId:(Ut=h.agentId)!=null?Ut:"virtual",agentName:(Ls=h.agentName)!=null?Ls:"",status:"running",currentIteration:0,maxIterations:(Ws=h.maxIterations)!=null?Ws:1,startedAt:j(h.startedAt)};else if(We==="agent_iteration_start"){if(_&&(_.currentIteration=h.iteration),Q==="separate"&&h.iteration>1){let $=m;$&&($.streaming=!1,d($),O.set(h.iteration-1,$),m=null)}}else if(We!=="agent_turn_start"){if(We==="agent_turn_delta"){if(h.contentType==="text"){let $=I();$.content+=(Qn=h.delta)!=null?Qn:"",$.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:h.turnId,agentName:_==null?void 0:_.agentName},d($)}else if(h.contentType==="thinking"){let $=(Cn=h.turnId)!=null?Cn:`agent-think-${h.iteration}`,C=le($);C.reasoning=(dn=C.reasoning)!=null?dn:{id:$,status:"streaming",chunks:[]},C.reasoning.chunks.push((Ps=h.delta)!=null?Ps:""),C.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:h.turnId},d(C)}else if(h.contentType==="tool_input"){let $=(Rs=h.toolCallId)!=null?Rs:x.lastId;if($){let C=y.get($);C!=null&&C.toolCall&&(C.toolCall.chunks=(Hs=C.toolCall.chunks)!=null?Hs:[],C.toolCall.chunks.push((sr=h.delta)!=null?sr:""),d(C))}}}else if(We==="agent_turn_complete"){let $=h.turnId;if($){let C=b.get($);if(C!=null&&C.reasoning){C.reasoning.status="complete",C.reasoning.completedAt=j(h.completedAt);let L=(xn=C.reasoning.startedAt)!=null?xn:Date.now();C.reasoning.durationMs=Math.max(0,((Sn=C.reasoning.completedAt)!=null?Sn:Date.now())-L),C.streaming=!1,d(C)}}}else if(We==="agent_tool_start"){let $=(nt=h.toolCallId)!=null?nt:`agent-tool-${c()}`;z(E(h),$);let C=K($),L=(Rn=C.toolCall)!=null?Rn:{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};L.name=(Hn=h.toolName)!=null?Hn:L.name,L.status="running",h.parameters!==void 0&&(L.args=h.parameters),L.startedAt=j((es=h.startedAt)!=null?es:h.timestamp),C.toolCall=L,C.streaming=!0,C.agentMetadata={executionId:h.executionId,iteration:h.iteration},d(C)}else if(We==="agent_tool_delta"){let $=(ts=h.toolCallId)!=null?ts:x.lastId;if($){let C=(ns=y.get($))!=null?ns:K($);C.toolCall&&(C.toolCall.chunks=(ss=C.toolCall.chunks)!=null?ss:[],C.toolCall.chunks.push((Ft=h.delta)!=null?Ft:""),C.toolCall.status="running",C.streaming=!0,d(C))}}else if(We==="agent_tool_complete"){let $=(qt=h.toolCallId)!=null?qt:x.lastId;if($){let C=(un=y.get($))!=null?un:K($);if(C.toolCall){C.toolCall.status="complete",h.result!==void 0&&(C.toolCall.result=h.result),typeof h.executionTime=="number"&&(C.toolCall.durationMs=h.executionTime),C.toolCall.completedAt=j((kt=h.completedAt)!=null?kt:h.timestamp),C.streaming=!1,d(C);let L=E(h);L&&x.byCall.delete(L)}}}else if(We!=="agent_iteration_complete"){if(We==="agent_reflection"||We==="agent_reflect"){let $=`agent-reflection-${h.executionId}-${h.iteration}`,C={id:$,role:"assistant",content:(rs=h.reflection)!=null?rs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(An=h.reflection)!=null?An:""]},agentMetadata:{executionId:h.executionId,iteration:h.iteration}};d(C)}else if(We==="agent_complete"){_&&(_.status=h.success?"complete":"error",_.completedAt=j(h.completedAt),_.stopReason=h.stopReason);let $=m;$&&($.streaming=!1,d($)),r({type:"status",status:"idle"})}else if(We==="agent_error"){let $=typeof h.error=="string"?h.error:(Bs=(en=h.error)==null?void 0:en.message)!=null?Bs:"Agent execution error";h.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):r({type:"error",error:new Error($)})}else if(We!=="agent_ping")if(We==="agent_approval_start"){let $=(En=h.approvalId)!=null?En:`approval-${c()}`,C={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Tn=_==null?void 0:_.agentId)!=null?Tn:"virtual",executionId:(Fs=(Bn=h.executionId)!=null?Bn:_==null?void 0:_.executionId)!=null?Fs:"",toolName:($s=h.toolName)!=null?$s:"",toolType:h.toolType,description:(Xe=h.description)!=null?Xe:`Execute ${(pn=h.toolName)!=null?pn:"tool"}`,parameters:h.parameters}};d(C)}else if(We==="step_await"&&h.awaitReason==="approval_required"){let $=(Ge=h.approvalId)!=null?Ge:`approval-${c()}`,C={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(wn=_==null?void 0:_.agentId)!=null?wn:"virtual",executionId:(is=(os=h.executionId)!=null?os:_==null?void 0:_.executionId)!=null?is:"",toolName:(rr=h.toolName)!=null?rr:"",toolType:h.toolType,description:(or=h.description)!=null?or:`Execute ${(It=h.toolName)!=null?It:"tool"}`,parameters:h.parameters}};d(C)}else if(We==="agent_approval_complete"){let $=h.approvalId;if($){let L={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:($t=h.decision)!=null?$t:"approved",agentId:(as=_==null?void 0:_.agentId)!=null?as:"virtual",executionId:(cs=(ls=h.executionId)!=null?ls:_==null?void 0:_.executionId)!=null?cs:"",toolName:(ds=h.toolName)!=null?ds:"",description:(us=h.description)!=null?us:"",resolvedAt:Date.now()}};d(L)}}else We==="error"&&h.error&&r({type:"error",error:h.error instanceof Error?h.error:new Error(String(h.error))})}}}}}};function La(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${n}_${t}`}function ws(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function Nn(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var Us="[Image]";function Wa(n){return typeof n=="string"?[{type:"text",text:n}]:n}function Pa(n){return typeof n=="string"?n:n.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ra(n){return typeof n=="string"?!1:n.some(t=>t.type==="image")}function Ha(n){return typeof n=="string"?[]:n.filter(t=>t.type==="image")}function fr(n){return{type:"text",text:n}}function Ba(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 Fa(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 $a(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 $i=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Oa=["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"],vn=[...$i,...Oa];function Na(n){return $i.includes(n)||n.startsWith("image/")}function qs(n){return Na(n.type)}async function Oi(n){return new Promise((t,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;qs(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 Ni(n,t=vn,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 Da(n){let t=n.split(".");return t.length>1?t.pop().toLowerCase():""}function Di(n,t){let r=Da(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 vs=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.analyserNode=null;this.mediaStream=null;this.silenceCheckInterval=null;this.silenceStart=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,u=(e=this.config)==null?void 0:e.clientToken;if(!a||!u)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=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let v=`${s}//${i}/ws/agents/${a}/voice?token=...`,d=" 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 b=!1,y=x=>{b||(b=!0,clearTimeout(S),w(new Error(x)))},S=setTimeout(()=>y("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{b||(b=!0,clearTimeout(S),m())},{once:!0}),this.ws.addEventListener("error",()=>{y("WebSocket connection failed to "+v+"."+d)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!b){let k=x.code!==1006?` (code ${x.code})`:"";y("WebSocket connection failed"+k+"."+d)}},{once:!0})})}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.onmessage=t=>{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;switch(t.type){case"voice_response":(r=t.response.audio)!=null&&r.base64&&this.playAudio(t.response.audio).catch(e=>this.errorCallbacks.forEach(o=>o(e instanceof Error?e:new Error(String(e))))),this.resultCallbacks.forEach(e=>e({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),this.isProcessing=!1,this.statusCallbacks.forEach(e=>e("idle"));break;case"error":this.errorCallbacks.forEach(e=>e(new Error(t.error))),this.statusCallbacks.forEach(e=>e("error")),this.isProcessing=!1;break;case"pong":break}}async startListening(){var t,r,e,o;try{if(this.isProcessing)throw new Error("Already processing audio");let s=await navigator.mediaDevices.getUserMedia({audio:!0});this.mediaStream=s;let i=this.w;this.audioContext=new(i.AudioContext||i.webkitAudioContext);let a=this.audioContext,u=a.createMediaStreamSource(s);this.analyserNode=a.createAnalyser(),this.analyserNode.fftSize=2048,u.connect(this.analyserNode);let c=(r=(t=this.config)==null?void 0:t.pauseDuration)!=null?r:2e3,v=(o=(e=this.config)==null?void 0:e.silenceThreshold)!=null?o:.01;this.silenceStart=null;let d=new Float32Array(this.analyserNode.fftSize);this.silenceCheckInterval=setInterval(()=>{if(!this.analyserNode)return;this.analyserNode.getFloatTimeDomainData(d);let m=0;for(let b=0;b<d.length;b++)m+=d[b]*d[b];Math.sqrt(m/d.length)<v?this.silenceStart===null?this.silenceStart=Date.now():Date.now()-this.silenceStart>=c&&this.stopListening():this.silenceStart=null},100),this.mediaRecorder=new MediaRecorder(s),this.audioChunks=[],this.mediaRecorder.ondataavailable=m=>{m.data.size>0&&this.audioChunks.push(m.data)},this.mediaRecorder.onstop=async()=>{var m;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(y=>y("processing")),this.processingStartCallbacks.forEach(y=>y());let w=((m=this.mediaRecorder)==null?void 0:m.mimeType)||"audio/webm",b=new Blob(this.audioChunks,{type:w});await this.sendAudio(b),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(m=>m("listening"))}catch(s){throw this.errorCallbacks.forEach(i=>i(s)),this.statusCallbacks.forEach(i=>i("error")),s}}async stopListening(){this.silenceCheckInterval&&(clearInterval(this.silenceCheckInterval),this.silenceCheckInterval=null),this.analyserNode=null,this.silenceStart=null,this.mediaRecorder&&(this.mediaRecorder.stop(),this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder=null),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 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);this.ws.send(JSON.stringify({type:"audio_input",audio:e,format:o,sampleRate:16e3,voiceId:(r=this.config)==null?void 0:r.voiceId}))}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),u=new Audio(a);u.onended=()=>URL.revokeObjectURL(a),await u.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(await this.stopListening(),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 In=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(u=>u[0]).map(u=>u.transcript).join(""),i=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({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 Dn(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new vs(n.runtype);case"browser":if(!In.isSupported())throw new Error("Browser speech recognition not supported");return new In(n.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function wr(n){if((n==null?void 0:n.type)==="runtype"&&n.runtype)return Dn({type:"runtype",runtype:n.runtype});if(In.isSupported())return Dn({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function zs(n){try{return wr(n),!0}catch{return!1}}var ys=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,u;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"),(u=(a=this.callbacks).onError)==null||u.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 On(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 zs((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}setupVoice(t){var r,e,o;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Dn(s);let i=(r=this.config.voiceRecognition)!=null?r:{},a=(e=i.processingText)!=null?e:"\u{1F3A4} Processing voice...",u=(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,d,m,w,b,y,S;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){if(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}):(d=c.transcript)!=null&&d.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()}),(b=c.audio)!=null&&b.base64){let x=(S=this.pendingVoiceAssistantMessageId)!=null?S:(y=[...this.messages].reverse().find(k=>k.role==="assistant"))==null?void 0:y.id;x&&this.ttsSpokenMessageIds.add(x)}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:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var v,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(v=this.callbacks).onVoiceStatusChanged)==null||d.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,u,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:(u=t.runtype)==null?void 0:u.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 On(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:u,streaming:c=!1,voiceProcessing:v}=t,m={id:i!=null?i:r==="user"?ws():r==="assistant"?Nn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:e,createdAt:a!=null?a:new Date().toISOString(),sequence:u!=null?u: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:u,createdAt:c,sequence:v,streaming:d=!1}=e,w={id:u!=null?u:o==="user"?ws():o==="assistant"?Nn():`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:d,...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,d,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=ws(),s=Nn(),i={id:o,role:"user",content:e||Us,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 u=[...this.messages];try{await this.client.dispatch({messages:u,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(b){let y=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!y){let S={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(S)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,y||(b instanceof Error?(d=(v=this.callbacks).onError)==null||d.call(v,b):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(b))))}}async continueConversation(){var o,s,i,a,u;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Nn();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):(u=(a=this.callbacks).onError)==null||u.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 u,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 d;if(a?d=await a({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r):d=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),d){let m=null;if(d instanceof Response){if(!d.ok){let w=await d.json().catch(()=>null);throw new Error((u=w==null?void 0:w.error)!=null?u:`Approval request failed: ${d.status}`)}m=d.body}else d instanceof ReadableStream&&(m=d);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(d){(v=(c=this.callbacks).onError)==null||v.call(c,d instanceof Error?d:new Error(String(d)))}}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 u,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=(u=r.sequence)!=null?u: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 ja 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=ja[o];return s?_a(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 _a(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 u=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([c,v])=>{c!=="stroke"&&u.setAttribute(c,String(v))}),o.appendChild(u)}}}),o}var Js={allowedTypes:vn,maxFileSize:10*1024*1024,maxFiles:4};function Va(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ua(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 jn=class n{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,e,o;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Js.allowedTypes,maxFileSize:(e=t.maxFileSize)!=null?e:Js.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Js.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:Js.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,u;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=Ni(c,this.config.allowedTypes,this.config.maxFileSize);if(!v.valid){let d=(o=v.error)!=null&&o.includes("type")?"type":"size";(i=(s=this.config).onFileRejected)==null||i.call(s,c,d);continue}try{let d=await Oi(c),m=qs(c)?URL.createObjectURL(c):null,w={id:Va(),file:c,previewUrl:m,contentPart:d};this.attachments.push(w),this.renderPreview(w)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(a=this.config).onAttachmentsChange)==null||u.call(a,this.getAttachments())}}removeAttachment(t){var s,i,a;let r=this.attachments.findIndex(u=>u.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=qs(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=Ua(t.file.type),u=ie(a,20,"var(--cw-muted, #6b7280)",1.5);u&&i.appendChild(u);let c=g("span");c.textContent=Di(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 vr=()=>{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"},qa=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"||vr()==="dark"?e:r},ji=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{n(vr())});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(vr());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())}},Ks=(n,t)=>{let r=qa(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 za}from"idiomorph";var _i=(n,t,r={})=>{let{preserveTypingAnimation:e=!0}=r;za.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 nn={"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 bs=(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,k,J,E,I,T,B,le,z,U,K,j;let i=(x=s.launcher)!=null?x:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(k=i.title)!=null?k:"Chat Assistant");let u=r.querySelector("[data-role='launcher-subtitle']");u&&(u.textContent=(J=i.subtitle)!=null?J:"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 ye=(E=i.agentIconSize)!=null?E:"40px";if(v.style.height=ye,v.style.width=ye,v.innerHTML="",i.agentIconName){let se=parseFloat(ye)||24,Y=ie(i.agentIconName,se*.6,"#ffffff",2);Y?(v.appendChild(Y),v.style.display=""):(v.textContent=(I=i.agentIconText)!=null?I:"\u{1F4AC}",v.style.display="")}else i.iconUrl?v.style.display="none":(v.textContent=(T=i.agentIconText)!=null?T:"\u{1F4AC}",v.style.display="")}let d=r.querySelector("[data-role='launcher-image']");if(d){let ye=(B=i.agentIconSize)!=null?B:"40px";d.style.height=ye,d.style.width=ye,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(d.src=i.iconUrl,d.style.display="block"):d.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ye=(le=i.callToActionIconSize)!=null?le:"32px";m.style.height=ye,m.style.width=ye,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 Y=parseFloat(ye)||24,_=Math.max(Y-se,8),O=ie(i.callToActionIconName,_,"currentColor",2);O?m.appendChild(O):m.textContent=(z=i.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(U=i.callToActionIconText)!=null?U:"\u2197"}let w=i.position&&nn[i.position]?nn[i.position]:nn["bottom-right"],b="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=`${b} ${w}`;let y="1px solid #e5e7eb",S="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(K=i.border)!=null?K:y,r.style.boxShadow=(j=i.shadow)!=null?j:S},o=()=>{r.removeEventListener("click",t),r.remove()};return n&&e(n),{element:r,update:e,destroy:o}};var yn=n=>{var U,K,j,ye,se,Y,_,O,Q,ue,Be,Et,dt,gt,Ht,Ne,ne,be,Re,Fe,Ue,Nt,de,X,at,vt,Tt,yt,Kt,ee,Le,bt;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=(U=t==null?void 0:t.launcher)!=null?U:{},s=(K=o.headerIconSize)!=null?K:"48px",i=(j=o.closeButtonSize)!=null?j:"32px",a=(ye=o.closeButtonPlacement)!=null?ye:"inline",u=(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,!u)if(c){let pe=parseFloat(s)||24,Ce=ie(c,pe*.6,"#ffffff",1);Ce?v.replaceChildren(Ce):v.textContent=(_=(Y=t==null?void 0:t.launcher)==null?void 0:Y.agentIconText)!=null?_:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let pe=g("img");pe.src=t.launcher.iconUrl,pe.alt="",pe.className="tvw-rounded-xl tvw-object-cover",pe.style.height=s,pe.style.width=s,v.replaceChildren(pe)}else v.textContent=(ue=(Q=t==null?void 0:t.launcher)==null?void 0:Q.agentIconText)!=null?ue:"\u{1F4AC}";let d=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(Et=(Be=t==null?void 0:t.launcher)==null?void 0:Be.title)!=null?Et:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(gt=(dt=t==null?void 0:t.launcher)==null?void 0:dt.subtitle)!=null?gt:"Here to help you get answers fast",d.append(m,w),u?e.append(d):e.append(v,d);let b=(Ht=o.clearChat)!=null?Ht:{},y=(Ne=b.enabled)!=null?Ne:!0,S=(ne=b.placement)!=null?ne:"inline",x=null,k=null;if(y){let pe=(be=b.size)!=null?be:"32px",Ce=(Re=b.iconName)!=null?Re:"refresh-cw",qe=(Fe=b.iconColor)!=null?Fe:"",Bt=(Ue=b.backgroundColor)!=null?Ue:"",Mt=(Nt=b.borderWidth)!=null?Nt:"",Vt=(de=b.borderColor)!=null?de:"",F=(X=b.borderRadius)!=null?X:"",Qe=(at=b.paddingX)!=null?at:"",N=(vt=b.paddingY)!=null?vt:"",G=(Tt=b.tooltipText)!=null?Tt:"Clear chat",re=(yt=b.showTooltip)!=null?yt:!0;k=g("div",S==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),S==="top-right"&&(k.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=pe,x.style.width=pe,x.type="button",x.setAttribute("aria-label",G);let $e=ie(Ce,"20px",qe||"",1);if($e&&x.appendChild($e),qe&&(x.style.color=qe,x.classList.remove("tvw-text-cw-muted")),Bt&&(x.style.backgroundColor=Bt,x.classList.remove("hover:tvw-bg-gray-100")),Mt||Vt){let oe=Mt||"0px",Je=Vt||"transparent";x.style.border=`${oe} solid ${Je}`,x.classList.remove("tvw-border-none")}if(F&&(x.style.borderRadius=F,x.classList.remove("tvw-rounded-full")),Qe?(x.style.paddingLeft=Qe,x.style.paddingRight=Qe):(x.style.paddingLeft="",x.style.paddingRight=""),N?(x.style.paddingTop=N,x.style.paddingBottom=N):(x.style.paddingTop="",x.style.paddingBottom=""),k.appendChild(x),re&&G&&x&&k){let oe=null,Je=()=>{if(oe||!x)return;oe=g("div","tvw-clear-chat-tooltip"),oe.textContent=G;let ce=g("div");ce.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(ce);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)},Ke=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};k.addEventListener("mouseenter",Je),k.addEventListener("mouseleave",Ke),x.addEventListener("focus",Je),x.addEventListener("blur",Ke),k._cleanupTooltip=()=>{Ke(),k&&(k.removeEventListener("mouseenter",Je),k.removeEventListener("mouseleave",Ke)),x&&(x.removeEventListener("focus",Je),x.removeEventListener("blur",Ke))}}S==="inline"&&e.appendChild(k)}let J=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":y&&S==="inline"?"":"tvw-ml-auto"),E=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");E.style.height=i,E.style.width=i,E.type="button";let I=(Kt=o.closeButtonTooltipText)!=null?Kt:"Close chat",T=(ee=o.closeButtonShowTooltip)!=null?ee:!0;E.setAttribute("aria-label",I),E.style.display=r?"":"none";let B=(Le=o.closeButtonIconName)!=null?Le:"x",le=(bt=o.closeButtonIconText)!=null?bt:"\xD7",z=ie(B,"20px",o.closeButtonColor||"",1);if(z?E.appendChild(z):E.textContent=le,o.closeButtonColor?(E.style.color=o.closeButtonColor,E.classList.remove("tvw-text-cw-muted")):(E.style.color="",E.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(E.style.backgroundColor=o.closeButtonBackgroundColor,E.classList.remove("hover:tvw-bg-gray-100")):(E.style.backgroundColor="",E.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let pe=o.closeButtonBorderWidth||"0px",Ce=o.closeButtonBorderColor||"transparent";E.style.border=`${pe} solid ${Ce}`,E.classList.remove("tvw-border-none")}else E.style.border="",E.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(E.style.borderRadius=o.closeButtonBorderRadius,E.classList.remove("tvw-rounded-full")):(E.style.borderRadius="",E.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(E.style.paddingLeft=o.closeButtonPaddingX,E.style.paddingRight=o.closeButtonPaddingX):(E.style.paddingLeft="",E.style.paddingRight=""),o.closeButtonPaddingY?(E.style.paddingTop=o.closeButtonPaddingY,E.style.paddingBottom=o.closeButtonPaddingY):(E.style.paddingTop="",E.style.paddingBottom=""),J.appendChild(E),T&&I){let pe=null,Ce=()=>{if(pe)return;pe=g("div","tvw-clear-chat-tooltip"),pe.textContent=I;let Bt=g("div");Bt.className="tvw-clear-chat-tooltip-arrow",pe.appendChild(Bt);let Mt=E.getBoundingClientRect();pe.style.position="fixed",pe.style.left=`${Mt.left+Mt.width/2}px`,pe.style.top=`${Mt.top-8}px`,pe.style.transform="translate(-50%, -100%)",document.body.appendChild(pe)},qe=()=>{pe&&pe.parentNode&&(pe.parentNode.removeChild(pe),pe=null)};J.addEventListener("mouseenter",Ce),J.addEventListener("mouseleave",qe),E.addEventListener("focus",Ce),E.addEventListener("blur",qe),J._cleanupTooltip=()=>{qe(),J.removeEventListener("mouseenter",Ce),J.removeEventListener("mouseleave",qe),E.removeEventListener("focus",Ce),E.removeEventListener("blur",qe)}}return a!=="top-right"&&e.appendChild(J),{header:e,iconHolder:v,headerTitle:m,headerSubtitle:w,closeButton:E,closeButtonWrapper:J,clearChatButton:x,clearChatButtonWrapper:k}},_n=(n,t,r)=>{var i,a,u,c;let e=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=e.closeButtonPlacement)!=null?a:"inline",s=(c=(u=e.clearChat)==null?void 0:u.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 Vi=n=>yn({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Ui=n=>{var b,y,S,x;let{config:t,showClose:r=!0,onClose:e}=n,o=(b=t==null?void 0:t.launcher)!=null?b:{},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=(S=o.closeButtonSize)!=null?S:"32px",u=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",d=ie(v,"20px",o.closeButtonColor||"",2);d?c.appendChild(d):c.textContent="\xD7",e&&c.addEventListener("click",e),u.appendChild(c),s.appendChild(u);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:u,clearChatButton:null,clearChatButtonWrapper:null}},qi=n=>{var E,I,T,B,le,z,U,K;let{config:t,showClose:r=!0,onClose:e,onClearChat:o}=n,s=(E=t==null?void 0:t.launcher)!=null?E:{},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"),u=(I=s.headerIconSize)!=null?I:"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=u,c.style.width=u;let v=s.headerIconName;if(v){let j=parseFloat(u)||24,ye=ie(v,j*.5,"#ffffff",2);ye?c.replaceChildren(ye):c.textContent=(T=s.agentIconText)!=null?T:"\u{1F4AC}"}else if(s.iconUrl){let j=g("img");j.src=s.iconUrl,j.alt="",j.className="tvw-rounded-xl tvw-object-cover",j.style.height=u,j.style.width=u,c.replaceChildren(j)}else c.textContent=(B=s.agentIconText)!=null?B:"\u{1F4AC}";let d=g("div","tvw-flex tvw-flex-col tvw-flex-1"),m=g("span","tvw-text-lg tvw-font-semibold");m.textContent=(le=s.title)!=null?le:"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",d.append(m,w),a.append(c,d);let b=(U=s.closeButtonSize)!=null?U:"32px",y=g("div",""),S=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");S.style.height=b,S.style.width=b,S.type="button",S.setAttribute("aria-label","Close chat"),S.style.display=r?"":"none";let x=(K=s.closeButtonIconName)!=null?K:"x",k=ie(x,"20px",s.closeButtonColor||"",2);k?S.appendChild(k):S.textContent="\xD7",e&&S.addEventListener("click",e),y.appendChild(S),a.appendChild(y),i.appendChild(a);let J=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return J.textContent="Online and ready to help",i.appendChild(J),{header:i,iconHolder:c,headerTitle:m,headerSubtitle:w,closeButton:S,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}},yr={default:Vi,minimal:Ui,expanded:qi},zi=n=>{var t;return(t=yr[n])!=null?t:yr.default},Cs=(n,t,r)=>{var i,a,u;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 d=g("span"),m=g("span"),w=g("button");w.style.display="none";let b=g("div");return b.style.display="none",{header:c,iconHolder:v,headerTitle:d,headerSubtitle:m,closeButton:w,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=t==null?void 0:t.layout)!=null?i:"default",s=zi(e)({config:n,showClose:(u=(a=t==null?void 0:t.showCloseButton)!=null?a:r==null?void 0:r.showClose)!=null?u:!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 Ja=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'}},xs=n=>{var ne,be,Re,Fe,Ue,Nt,de,X,at,vt,Tt,yt,Kt,ee,Le,bt,pe,Ce,qe,Bt,Mt,Vt,F,Qe,N,G,re,$e,oe,Je,Ke;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=(be=(ne=t==null?void 0:t.copy)==null?void 0:ne.inputPlaceholder)!=null?be:"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=(Fe=(Re=t==null?void 0:t.theme)==null?void 0:Re.inputFontFamily)!=null?Fe:"sans-serif",a=(Nt=(Ue=t==null?void 0:t.theme)==null?void 0:Ue.inputFontWeight)!=null?Nt:"400";s.style.fontFamily=Ja(i),s.style.fontWeight=a;let v=3*20;s.style.maxHeight=`${v}px`,s.style.overflowY="auto";let d=()=>{s.style.height="auto";let ce=Math.min(s.scrollHeight,v);s.style.height=`${ce}px`};s.addEventListener("input",d),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=(de=t==null?void 0:t.sendButton)!=null?de:{},w=(X=m.useIcon)!=null?X:!1,b=(at=m.iconText)!=null?at:"\u2191",y=m.iconName,S=(vt=m.tooltipText)!=null?vt:"Send message",x=(Tt=m.showTooltip)!=null?Tt:!1,k=(yt=m.size)!=null?yt:"40px",J=m.backgroundColor,E=m.textColor,I=g("div","tvw-send-button-wrapper"),T=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(T.type="submit",w){if(T.style.width=k,T.style.height=k,T.style.minWidth=k,T.style.minHeight=k,T.style.fontSize="18px",T.style.lineHeight="1",T.innerHTML="",y){let ce=parseFloat(k)||24,D=E&&typeof E=="string"&&E.trim()?E.trim():"currentColor",Se=ie(y,ce,D,2);Se?(T.appendChild(Se),T.style.color=D):(T.textContent=b,E?T.style.color=E:T.classList.add("tvw-text-white"))}else T.textContent=b,E?T.style.color=E:T.classList.add("tvw-text-white");J?T.style.backgroundColor=J:T.classList.add("tvw-bg-cw-primary")}else T.textContent=(ee=(Kt=t==null?void 0:t.copy)==null?void 0:Kt.sendButtonLabel)!=null?ee:"Send",E?T.style.color=E:T.classList.add("tvw-text-white");if(m.borderWidth&&(T.style.borderWidth=m.borderWidth,T.style.borderStyle="solid"),m.borderColor&&(T.style.borderColor=m.borderColor),m.paddingX?(T.style.paddingLeft=m.paddingX,T.style.paddingRight=m.paddingX):(T.style.paddingLeft="",T.style.paddingRight=""),m.paddingY?(T.style.paddingTop=m.paddingY,T.style.paddingBottom=m.paddingY):(T.style.paddingTop="",T.style.paddingBottom=""),x&&S){let ce=g("div","tvw-send-button-tooltip");ce.textContent=S,I.appendChild(ce)}I.appendChild(T);let B=(Le=t==null?void 0:t.voiceRecognition)!=null?Le:{},le=B.enabled===!0,z=null,U=null,K=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),j=((bt=B.provider)==null?void 0:bt.type)==="runtype";if(le&&(K||j)){U=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 ce=(pe=B.iconName)!=null?pe:"mic",D=(Ce=B.iconSize)!=null?Ce:k,Se=parseFloat(D)||24,et=(qe=B.backgroundColor)!=null?qe:J,tt=(Bt=B.iconColor)!=null?Bt:E;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=tt||"currentColor",Gt=ie(ce,Se,Yt,1.5);Gt?(z.appendChild(Gt),z.style.color=Yt):(z.textContent="\u{1F3A4}",z.style.color=Yt),et?z.style.backgroundColor=et:z.classList.add("tvw-bg-cw-primary"),tt?z.style.color=tt:!tt&&!E&&z.classList.add("tvw-text-white"),B.borderWidth&&(z.style.borderWidth=B.borderWidth,z.style.borderStyle="solid"),B.borderColor&&(z.style.borderColor=B.borderColor),B.paddingX&&(z.style.paddingLeft=B.paddingX,z.style.paddingRight=B.paddingX),B.paddingY&&(z.style.paddingTop=B.paddingY,z.style.paddingBottom=B.paddingY),U.appendChild(z);let Ye=(Mt=B.tooltipText)!=null?Mt:"Start voice recognition";if(((Vt=B.showTooltip)!=null?Vt:!1)&&Ye){let mn=g("div","tvw-send-button-tooltip");mn.textContent=Ye,U.appendChild(mn)}}let se=(F=t==null?void 0:t.attachments)!=null?F:{},Y=se.enabled===!0,_=null,O=null,Q=null,ue=null;if(Y){ue=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),ue.style.display="none",Q=g("input"),Q.type="file",Q.accept=((Qe=se.allowedTypes)!=null?Qe:vn).join(","),Q.multiple=((N=se.maxFiles)!=null?N:4)>1,Q.style.display="none",Q.setAttribute("aria-label","Attach files"),O=g("div","tvw-send-button-wrapper"),_=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),_.type="button",_.setAttribute("aria-label",(G=se.buttonTooltipText)!=null?G:"Attach file");let ce=(re=se.buttonIconName)!=null?re:"paperclip",D=k,Se=parseFloat(D)||40,et=Math.round(Se*.6);_.style.width=D,_.style.height=D,_.style.minWidth=D,_.style.minHeight=D,_.style.fontSize="18px",_.style.lineHeight="1",_.style.backgroundColor="transparent",_.style.color="var(--cw-primary, #111827)",_.style.border="none",_.style.borderRadius="6px",_.style.transition="background-color 0.15s ease",_.addEventListener("mouseenter",()=>{_.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),_.addEventListener("mouseleave",()=>{_.style.backgroundColor="transparent"});let tt=ie(ce,et,"currentColor",1.5);tt?_.appendChild(tt):_.textContent="\u{1F4CE}",_.addEventListener("click",Ye=>{Ye.preventDefault(),Q==null||Q.click()}),O.appendChild(_);let Yt=($e=se.buttonTooltipText)!=null?$e:"Attach file",Gt=g("div","tvw-send-button-tooltip");Gt.textContent=Yt,O.appendChild(Gt)}o.addEventListener("click",ce=>{ce.target!==T&&ce.target!==I&&ce.target!==z&&ce.target!==U&&ce.target!==_&&ce.target!==O&&s.focus()}),ue&&(ue.style.gap="8px",o.append(ue)),Q&&o.append(Q),o.append(s);let Be=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),Et=g("div","tvw-flex tvw-items-center tvw-gap-2");O&&Et.append(O);let dt=g("div","tvw-flex tvw-items-center tvw-gap-1");U&&dt.append(U),dt.append(I),Be.append(Et,dt),o.append(Be);let gt=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:{},Ne=(Je=Ht.visible)!=null?Je:!0;return gt.style.display=Ne?"":"none",gt.textContent=(Ke=Ht.idleText)!=null?Ke:"Online",r.append(e,o,gt),{footer:r,suggestions:e,composerForm:o,textarea:s,sendButton:T,sendButtonWrapper:I,micButton:z,micButtonWrapper:U,statusText:gt,attachmentButton:_,attachmentButtonWrapper:O,attachmentInput:Q,attachmentPreviewsContainer:ue,actionsRow:Be,leftActions:Et,rightActions:dt}};var Ji=n=>{var u,c,v,d,m,w,b;if(!((c=(u=n==null?void 0:n.launcher)==null?void 0:u.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"),S=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),x=(d=(v=n==null?void 0:n.launcher)==null?void 0:v.width)!=null?d:"100%";return y.style.width=x,S.style.width="100%",y.appendChild(S),{wrapper:y,panel:S}}let r=(m=n==null?void 0:n.launcher)!=null?m:{},e=r.position&&nn[r.position]?nn[r.position]:nn["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=(b=(w=n==null?void 0:n.launcher)==null?void 0:w.width)!=null?b: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}},Ki=(n,t=!0)=>{var w,b,y,S,x,k,J;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=((b=n==null?void 0:n.layout)==null?void 0:b.showHeader)!==!1,s=e?Cs(n,e,{showClose:t}):yn({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"),u=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");u.textContent=(S=(y=n==null?void 0:n.copy)==null?void 0:y.welcomeTitle)!=null?S:"Hello \u{1F44B}";let c=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(k=(x=n==null?void 0:n.copy)==null?void 0:x.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",a.append(u,c);let v=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,v);let d=xs({config:n}),m=((J=n==null?void 0:n.layout)==null?void 0:J.showFooter)!==!1;return o?_n(r,s,n):(s.header.style.display="none",_n(r,s,n)),r.append(i),m||(d.footer.style.display="none"),r.append(d.footer),{container:r,body:i,messagesWrapper:v,suggestions:d.suggestions,textarea:d.textarea,sendButton:d.sendButton,sendButtonWrapper:d.sendButtonWrapper,micButton:d.micButton,micButtonWrapper:d.micButtonWrapper,composerForm:d.composerForm,statusText:d.statusText,introTitle:u,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:d.footer,attachmentButton:d.attachmentButton,attachmentButtonWrapper:d.attachmentButtonWrapper,attachmentInput:d.attachmentInput,attachmentPreviewsContainer:d.attachmentPreviewsContainer,actionsRow:d.actionsRow,leftActions:d.leftActions,rightActions:d.rightActions}};var Ka=320,Ya=320,Xa=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Ga=(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,u)=>{var d;let c=g("img");c.alt=((d=a.alt)==null?void 0:d.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Ka}px`,c.style.maxHeight=`${Ya}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}},Vn=()=>{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},Xi=(n,t,r)=>{let e={config:r!=null?r:{},streaming:!0,location:n,defaultRenderer:Vn};if(t){let o=t(e);if(o!==null)return o}return Vn()},Za=(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},Yi=(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},Qa=(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},Gi=(n,t,r)=>{var w,b,y,S,x,k;let e=(w=t.showCopy)!=null?w:!0,o=(b=t.showUpvote)!=null?b:!0,s=(y=t.showDownvote)!=null?y:!0,i=(S=t.visibility)!=null?S:"hover",a=(x=t.align)!=null?x:"right",u=(k=t.layout)!=null?k:"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"}[u],d=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${v} ${i==="hover"?"tvw-message-actions-hover":""}`);d.id=`actions-${n.id}`,d.setAttribute("data-actions-for",n.id);let m=(J,E,I)=>{let T=document.createElement("button");T.className="tvw-message-action-btn",T.setAttribute("aria-label",E),T.setAttribute("title",E),T.setAttribute("data-action",I);let B=ie(J,14,"currentColor",2);return B&&T.appendChild(B),T};return e&&d.appendChild(m("copy","Copy message","copy")),o&&d.appendChild(m("thumbs-up","Upvote","upvote")),s&&d.appendChild(m("thumbs-down","Downvote","downvote")),d},Ss=(n,t,r,e,o,s)=>{var U,K,j,ye,se,Y,_;let i=r!=null?r:{},a=(U=i.layout)!=null?U:"bubble",u=i.avatar,c=i.timestamp,v=(K=u==null?void 0:u.show)!=null?K:!1,d=(j=c==null?void 0:c.show)!=null?j:!1,m=(ye=u==null?void 0:u.position)!=null?ye:"left",w=(se=c==null?void 0:c.position)!=null?se:"below",b=Qa(n.role,a),y=g("div",b.join(" "));y.id=`bubble-${n.id}`,y.setAttribute("data-message-id",n.id);let S=Xa(n),x=(_=(Y=n.content)==null?void 0:Y.trim())!=null?_:"",J=S.length>0&&x===Us,E=document.createElement("div"),I=t({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),T=null;if(J?(T=document.createElement("div"),T.innerHTML=I,T.style.display="none",E.appendChild(T)):E.innerHTML=I,d&&w==="inline"&&n.createdAt){let O=Yi(n,c);O.classList.add("tvw-ml-2","tvw-inline"),E.appendChild(O)}if(S.length>0){let O=Ga(S,!J&&!!x,()=>{J&&T&&(T.style.display="")});O?y.appendChild(O):J&&T&&(T.style.display="")}if(y.appendChild(E),d&&w==="below"&&n.createdAt){let O=Yi(n,c);O.classList.add("tvw-mt-1"),y.appendChild(O)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let O=Xi("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);O&&y.appendChild(O)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let O=Gi(n,e,o);y.appendChild(O)}if(!v||n.role==="system")return y;let le=g("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),z=Za(u,n.role);return m==="right"||m==="left"&&n.role==="user"?le.append(y,z):le.append(z,y),y.classList.remove("tvw-max-w-[85%]"),y.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),le},el=(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}):Ss(n,t,r,e,o,s)};var Un=new Set,Zi=(n,t)=>{let r=Un.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 u=ie(r?"chevron-up":"chevron-down",16,"currentColor",2);u?i.appendChild(u):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},br=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=Un.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=Bi(t),s.appendChild(a),t.status==="complete"?i.style.display="none":i.style.display="";let u=g("div","tvw-flex tvw-items-center"),v=ie(e?"chevron-up":"chevron-down",16,"currentColor",2);v?u.appendChild(v):u.textContent=e?"Hide":"Show";let d=g("div","tvw-flex tvw-items-center tvw-ml-auto");d.append(u),o.append(s,d);let m=g("div","tvw-border-t tvw-px-4 tvw-py-3");m.style.display=e?"":"none";let w=t.chunks.join(""),b=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return b.textContent=w||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(b),(()=>{o.setAttribute("aria-expanded",e?"true":"false"),u.innerHTML="";let x=ie(e?"chevron-up":"chevron-down",16,"currentColor",2);x?u.appendChild(x):u.textContent=e?"Hide":"Show",m.style.display=e?"":"none"})(),r.append(o,m),r};var qn=new Set,Qi=(n,t,r)=>{var c;let e=qn.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"),u=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(u){u.innerHTML="";let v=o.toggleTextColor||o.headerTextColor||"currentColor",d=ie(e?"chevron-up":"chevron-down",16,v,2);d?u.appendChild(d):u.textContent=e?"Hide":"Show"}i.style.display=e?"":"none"},Cr=(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=qn.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"),u=g("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(u.style.color=e.headerTextColor),u.textContent=Fi(r),a.appendChild(u);let c=g("div","tvw-flex tvw-items-center"),v=e.toggleTextColor||e.headerTextColor||"currentColor",d=ie(s?"chevron-up":"chevron-down",16,v,2);d?c.appendChild(d):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 S=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?S.style.color=e.contentTextColor:e.headerTextColor&&(S.style.color=e.headerTextColor),S.textContent=r.name,w.appendChild(S)}if(r.args!==void 0){let S=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 k=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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(k.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(k.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(k.style.color=e.codeBlockTextColor),k.textContent=fs(r.args),S.append(x,k),w.appendChild(S)}if(r.chunks&&r.chunks.length){let S=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 k=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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(k.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(k.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(k.style.color=e.codeBlockTextColor),k.textContent=r.chunks.join(`
16
- `),S.append(x,k),w.appendChild(S)}if(r.status==="complete"&&r.result!==void 0){let S=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 k=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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(k.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(k.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(k.style.color=e.codeBlockTextColor),k.textContent=fs(r.result),S.append(x,k),w.appendChild(S)}if(r.status==="complete"&&typeof r.duration=="number"){let S=g("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(S.style.color=e.contentTextColor),S.textContent=`Duration: ${r.duration}ms`,w.appendChild(S)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let S=e.toggleTextColor||e.headerTextColor||"currentColor",x=ie(s?"chevron-up":"chevron-down",16,S,2);x?c.appendChild(x):c.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),o.append(i,w),o};var xr=(n,t)=>{var y,S,x,k,J,E,I,T,B,le,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 u=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(u,20,c,2);v&&a.appendChild(v);let d=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=(S=e==null?void 0:e.title)!=null?S:"Approval Required",m.appendChild(w),!o){let U=g("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded-full tvw-text-xs tvw-font-medium");U.setAttribute("data-approval-status",r.status),r.status==="approved"?(U.className+=" tvw-approval-badge-approved",U.textContent="Approved"):r.status==="denied"?(U.className+=" tvw-approval-badge-denied",U.textContent="Denied"):r.status==="timeout"&&(U.className+=" tvw-approval-badge-timeout",U.textContent="Timeout"),m.appendChild(U)}d.appendChild(m);let b=g("p","tvw-text-sm tvw-mt-0.5 tvw-text-cw-muted");if(e!=null&&e.descriptionColor&&(b.style.color=e.descriptionColor),b.textContent=r.description,d.appendChild(b),r.parameters){let U=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&&(U.style.backgroundColor=e.parameterBackgroundColor),e!=null&&e.parameterTextColor&&(U.style.color=e.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=fs(r.parameters),d.appendChild(U)}if(o){let U=g("div","tvw-flex tvw-gap-2 tvw-mt-2");U.setAttribute("data-approval-buttons","true");let K=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");K.type="button",K.style.backgroundColor=(x=e==null?void 0:e.approveButtonColor)!=null?x:"#16a34a",K.style.color=(k=e==null?void 0:e.approveButtonTextColor)!=null?k:"#ffffff",K.setAttribute("data-approval-action","approve");let j=ie("shield-check",14,(J=e==null?void 0:e.approveButtonTextColor)!=null?J:"#ffffff",2);j&&(j.style.marginRight="4px",K.appendChild(j));let ye=document.createTextNode((E=e==null?void 0:e.approveLabel)!=null?E:"Approve");K.appendChild(ye);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=(I=e==null?void 0:e.denyButtonColor)!=null?I:"transparent",se.style.color=(T=e==null?void 0:e.denyButtonTextColor)!=null?T:"#dc2626",se.style.border=`1px solid ${(B=e==null?void 0:e.denyButtonTextColor)!=null?B:"#fca5a5"}`,se.setAttribute("data-approval-action","deny");let Y=ie("shield-x",14,(le=e==null?void 0:e.denyButtonTextColor)!=null?le:"#dc2626",2);Y&&(Y.style.marginRight="4px",se.appendChild(Y));let _=document.createTextNode((z=e==null?void 0:e.denyLabel)!=null?z:"Deny");se.appendChild(_),U.append(K,se),d.appendChild(U)}return i.append(a,d),s.appendChild(i),s};var ea=n=>{let t=[];return{buttons:t,render:(e,o,s,i,a)=>{if(n.innerHTML="",t.length=0,!e||!e.length||(i!=null?i:o?o.getMessages():[]).some(w=>w.role==="user"))return;let v=document.createDocumentFragment(),d=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 b=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");b.type="button",b.textContent=w,b.disabled=d,a!=null&&a.fontFamily&&(b.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(b.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(b.style.paddingLeft=a.paddingX,b.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(b.style.paddingTop=a.paddingY,b.style.paddingBottom=a.paddingY),b.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(w))}),v.appendChild(b),t.push(b)}),n.appendChild(v)}}};var As=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 Es=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 zn(n,t){t&&t.split(/\s+/).forEach(r=>r&&n.classList.add(r))}var tl={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"}},nl={bg:"#f3f4f6",text:"#4b5563"},sl=["flowName","stepName","reasoningText","text","name","tool","toolName"],rl=100;function ol(n,t){let r={...tl,...t};if(r[n])return r[n];for(let e of Object.keys(r))if(e.endsWith("_")&&n.startsWith(e))return r[e];return nl}function il(n,t){return`+${((n-t)/1e3).toFixed(3)}s`}function al(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 ll(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 cl(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 dl(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 ul(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]"),u=g("pre","tvw-m-0 tvw-whitespace-pre-wrap tvw-break-all tvw-text-[11px] tvw-text-cw-secondary tvw-font-mono");return u.textContent=e,a.appendChild(u),a}}function Sr(n,t,r,e,o,s,i,a){var m;let u=o.has(n.id),c=g("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");zn(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:()=>d(),isExpanded:u,onToggleExpand:()=>s(n.id)});if(w)return c.appendChild(w),c}return c.appendChild(d()),c;function d(){var j,ye;let w=g("div",""),b=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");b.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"),S=ie(u?"chevron-down":"chevron-right","14px","currentColor",2);S&&y.appendChild(S);let x=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),k=(j=e.timestampFormat)!=null?j:"relative";x.textContent=k==="relative"?il(n.timestamp,r):al(n.timestamp);let J=null;e.showSequenceNumbers!==!1&&(J=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),J.textContent=String(t+1));let E=ol(n.type,e.badgeColors),I=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");I.style.backgroundColor=E.bg,I.style.color=E.text,I.style.borderColor=E.text+"50",I.textContent=n.type;let T=(ye=e.descriptionFields)!=null?ye:sl,B=ll(n.payload,T),le=null;B&&(le=g("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),le.textContent=B);let z=g("div","tvw-flex-1 tvw-min-w-0"),U=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"),K=ie("clipboard","12px","currentColor",1.5);return K&&U.appendChild(K),U.addEventListener("click",async se=>{se.stopPropagation(),await cl(dl(n)),U.innerHTML="";let Y=ie("check","12px","currentColor",1.5);Y&&U.appendChild(Y),setTimeout(()=>{U.innerHTML="";let _=ie("clipboard","12px","currentColor",1.5);_&&U.appendChild(_)},1500)}),b.appendChild(y),b.appendChild(x),J&&b.appendChild(J),b.appendChild(I),le&&b.appendChild(le),b.appendChild(z),b.appendChild(U),w.appendChild(b),u&&w.appendChild(ul(n,i,a)),w}}function ta(n){var c,v;let{buffer:t,getFullHistory:r,onClose:e,config:o,plugins:s=[]}=n,i=(v=(c=o==null?void 0:o.features)==null?void 0:c.eventStream)!=null?v:{},a=s.find(d=>d.renderEventStreamView);if(a!=null&&a.renderEventStreamView&&o){let d=a.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>u().element,onClose:e});if(d)return{element:d,update:()=>{},destroy:()=>{}}}return u();function u(){let d=i.classNames,m=g("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");zn(m,d==null?void 0:d.panel);let w=[],b="",y="",S=null,x=[],k={},J=0,E=!1,I=0,T=0,B=!1,le=null,z=!1,U=0,K=new Set,j=new Map,ye="",se="",Y=null,_,O,Q,ue,Be;function Et(){let N=g("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),G=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");zn(G,d==null?void 0:d.headerBar);let re=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");re.textContent="Events",_=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"),_.textContent="0";let $e=g("div","tvw-flex-1");O=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",O.appendChild(oe),Q=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"),Q.type="button",Q.title="Copy All";let Ke=ie("clipboard-copy","12px","currentColor",1.5);Ke&&Q.appendChild(Ke);let ce=g("span","tvw-text-xs");ce.textContent="Copy All",Q.appendChild(ce),G.appendChild(re),G.appendChild(_),G.appendChild($e),G.appendChild(O),G.appendChild(Q);let D=g("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");zn(D,d==null?void 0:d.searchBar);let Se=ie("search","14px","var(--cw-muted, #9ca3af)",1.5),et=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");Se&&et.appendChild(Se),ue=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"),zn(ue,d==null?void 0:d.searchInput),ue.type="text",ue.placeholder="Search event payloads...",Be=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"),Be.type="button",Be.style.display="none";let tt=ie("x","12px","currentColor",2);return tt&&Be.appendChild(tt),D.appendChild(et),D.appendChild(ue),D.appendChild(Be),N.appendChild(G),N.appendChild(D),N}let dt,gt=s.find(N=>N.renderEventStreamToolbar);if(gt!=null&&gt.renderEventStreamToolbar&&o){let N=gt.renderEventStreamToolbar({config:o,defaultRenderer:()=>Et(),eventCount:t.getSize(),filteredCount:0,onFilterChange:G=>{b=G,at(),yt()},onSearchChange:G=>{y=G,at(),yt()}});dt=N!=null?N:Et()}else dt=Et();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 Ne=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 be=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");zn(be,d==null?void 0:d.scrollIndicator),be.style.display="none";let Re=ie("arrow-down","12px","currentColor",2);Re&&be.appendChild(Re);let Fe=g("span","");be.appendChild(Fe);let Ue=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");Ue.style.display="none",Ne.appendChild(ne),Ne.appendChild(Ue),Ne.appendChild(be),m.setAttribute("tabindex","0"),m.appendChild(dt),m.appendChild(Ht),m.appendChild(Ne);function Nt(){let N=t.getAll(),G={};for(let ce of N)G[ce.type]=(G[ce.type]||0)+1;let re=Object.keys(G).sort(),$e=re.length!==x.length||!re.every((ce,D)=>ce===x[D]),oe=!$e&&re.some(ce=>G[ce]!==k[ce]),Je=N.length!==Object.values(k).reduce((ce,D)=>ce+D,0);if(!$e&&!oe&&!Je||(x=re,k=G,!O))return;let Ke=O.value;if(O.options[0].textContent="All events",$e){for(;O.options.length>1;)O.remove(1);for(let ce of re){let D=g("option","");D.value=ce,D.textContent=`${ce} (${G[ce]||0})`,O.appendChild(D)}Ke&&re.includes(Ke)?O.value=Ke:Ke&&(O.value="",b="")}else for(let ce=1;ce<O.options.length;ce++){let D=O.options[ce];D.textContent=`${D.value} (${G[D.value]||0})`}}function de(){let N=t.getAll();if(b&&(N=N.filter(G=>G.type===b)),y){let G=y.toLowerCase();N=N.filter(re=>re.type.toLowerCase().includes(G)||re.payload.toLowerCase().includes(G))}return N}function X(){return b!==""||y!==""}function at(){J=0,I=0,E=!1,be.style.display="none"}function vt(N){K.has(N)?K.delete(N):K.add(N),Y=N;let G=ne.scrollTop,re=E;z=!0,E=!0,yt(),ne.scrollTop=G,E=re,z=!1}function Tt(){return ne.scrollHeight-ne.scrollTop-ne.clientHeight<=50}function yt(){T=Date.now(),B=!1,Nt();let N=t.getEvictedCount();N>0?(Ht.textContent=`${N.toLocaleString()} older events truncated`,Ht.style.display=""):Ht.style.display="none",w=de();let G=w.length,re=t.getSize()>0;_&&(_.textContent=String(t.getSize())),G===0&&re&&X()?(Ue.textContent=y?`No events matching '${y}'`:"No events matching filter",Ue.style.display="",ne.style.display="none"):(Ue.style.display="none",ne.style.display=""),Q&&(Q.title=X()?`Copy Filtered (${G})`:"Copy All"),E&&G>J&&(I+=G-J,Fe.textContent=`${I} new event${I===1?"":"s"}`,be.style.display=""),J=G;let $e=t.getAll(),oe=$e.length>0?$e[0].timestamp:0,Je=new Set(w.map(D=>D.id));for(let D of K)Je.has(D)||K.delete(D);let Ke=b!==ye||y!==se,ce=j.size===0&&w.length>0;if(Ke||ce||w.length===0){ne.innerHTML="",j.clear();let D=document.createDocumentFragment();for(let Se=0;Se<w.length;Se++){let et=Sr(w[Se],Se,oe,i,K,vt,s,o);j.set(w[Se].id,et),D.appendChild(et)}ne.appendChild(D),ye=b,se=y,Y=null}else{if(Y!==null){let Se=j.get(Y);if(Se&&Se.parentNode===ne){let et=w.findIndex(tt=>tt.id===Y);if(et>=0){let tt=Sr(w[et],et,oe,i,K,vt,s,o);ne.insertBefore(tt,Se),Se.remove(),j.set(Y,tt)}}Y=null}let D=new Set(w.map(Se=>Se.id));for(let[Se,et]of j)D.has(Se)||(et.remove(),j.delete(Se));for(let Se=0;Se<w.length;Se++){let et=w[Se];if(!j.has(et.id)){let tt=Sr(et,Se,oe,i,K,vt,s,o);j.set(et.id,tt),ne.appendChild(tt)}}}E||(ne.scrollTop=ne.scrollHeight)}function Kt(){if(Date.now()-T>=rl){le!==null&&(cancelAnimationFrame(le),le=null),yt();return}B||(B=!0,le=requestAnimationFrame(()=>{le=null,yt()}))}let ee=(N,G)=>{if(!Q)return;Q.innerHTML="";let re=ie(N,"12px","currentColor",1.5);re&&Q.appendChild(re);let $e=g("span","tvw-text-xs");$e.textContent="Copy All",Q.appendChild($e),setTimeout(()=>{Q.innerHTML="";let oe=ie("clipboard-copy","12px","currentColor",1.5);oe&&Q.appendChild(oe);let Je=g("span","tvw-text-xs");Je.textContent="Copy All",Q.appendChild(Je),Q.disabled=!1},G)},Le=async()=>{if(Q){Q.disabled=!0;try{let N;X()?N=w:r?(N=await r(),N.length===0&&(N=t.getAll())):N=t.getAll();let G=N.map(re=>{try{return JSON.parse(re.payload)}catch{return re.payload}});await navigator.clipboard.writeText(JSON.stringify(G,null,2)),ee("check",1500)}catch{ee("x",1500)}}},bt=()=>{O&&(b=O.value,at(),yt())},pe=()=>{!ue||!Be||(Be.style.display=ue.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{y=ue.value,at(),yt()},150))},Ce=()=>{!ue||!Be||(ue.value="",y="",Be.style.display="none",S&&clearTimeout(S),at(),yt())},qe=()=>{if(z)return;let N=ne.scrollTop,G=N>U;U=N,Tt()&&G?(E=!1,I=0,be.style.display="none"):Tt()||(E=!0)},Bt=N=>{N.deltaY<0&&(E=!0)},Mt=()=>{ne.scrollTop=ne.scrollHeight,E=!1,I=0,be.style.display="none"},Vt=N=>{let G=N.target;if(!G||G.closest("button"))return;let re=G.closest("[data-event-id]");if(!re)return;let $e=re.getAttribute("data-event-id");$e&&vt($e)},F=N=>{if((N.metaKey||N.ctrlKey)&&N.key==="f"){N.preventDefault(),ue==null||ue.focus(),ue==null||ue.select();return}N.key==="Escape"&&(ue&&document.activeElement===ue?(Ce(),ue.blur(),m.focus()):e&&e())};Q&&Q.addEventListener("click",Le),O&&O.addEventListener("change",bt),ue&&ue.addEventListener("input",pe),Be&&Be.addEventListener("click",Ce),ne.addEventListener("scroll",qe),ne.addEventListener("wheel",Bt,{passive:!0}),ne.addEventListener("click",Vt),be.addEventListener("click",Mt),m.addEventListener("keydown",F);function Qe(){S&&clearTimeout(S),le!==null&&(cancelAnimationFrame(le),le=null),B=!1,j.clear(),Q&&Q.removeEventListener("click",Le),O&&O.removeEventListener("change",bt),ue&&ue.removeEventListener("input",pe),Be&&Be.removeEventListener("click",Ce),ne.removeEventListener("scroll",qe),ne.removeEventListener("wheel",Bt),ne.removeEventListener("click",Vt),be.removeEventListener("click",Mt),m.removeEventListener("keydown",F)}return{element:m,update:Kt,destroy:Qe}}}var na={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"}},Ar=(n,t,r,e)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var b,y,S;if(s.dataset.enhanced==="true")return;let i=(b=s.dataset.tvForm)!=null?b:"init";s.dataset.enhanced="true";let a=(y=na[i])!=null?y:na.init;s.classList.add("tvw-form-card","tvw-space-y-4");let u=g("div","tvw-space-y-1"),c=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=a.title,u.appendChild(c),a.description){let x=g("p","tvw-text-sm tvw-text-cw-muted");x.textContent=a.description,u.appendChild(x)}let v=document.createElement("form");v.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(x=>{var T,B;let k=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");k.htmlFor=`${t.id}-${i}-${x.name}`;let J=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");J.textContent=x.label,k.appendChild(J);let E=(T=x.type)!=null?T:"text",I;E==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=E),I.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",I.id=`${t.id}-${i}-${x.name}`,I.name=x.name,I.placeholder=(B=x.placeholder)!=null?B:"",x.required&&(I.required=!0),k.appendChild(I),v.appendChild(k)});let d=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=(S=a.submitLabel)!=null?S:"Submit",d.appendChild(m),d.appendChild(w),v.appendChild(d),s.replaceChildren(u,v),v.addEventListener("submit",async x=>{var I,T;x.preventDefault();let k=(I=r.formEndpoint)!=null?I:"/form",J=new FormData(v),E={};J.forEach((B,le)=>{E[le]=B}),E.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let B=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!B.ok)throw new Error(`Form submission failed (${B.status})`);let le=await B.json();m.textContent=(T=le.message)!=null?T:"Thanks! We'll be in touch soon.",le.success&&le.nextPrompt&&await e.sendMessage(String(le.nextPrompt))}catch(B){m.textContent=B instanceof Error?B.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var Er=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,u;return((a=i.priority)!=null?a:0)-((u=s.priority)!=null?u:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},Ys=new Er;var sa={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"},ra={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},it={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:sa,darkTheme:ra,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 Tr(n){var t,r,e,o,s,i,a,u,c,v,d,m,w,b,y,S,x,k,J;return n?{...it,...n,theme:{...it.theme,...n.theme},darkTheme:{...it.darkTheme,...n.darkTheme},launcher:{...it.launcher,...n.launcher,clearChat:{...(t=it.launcher)==null?void 0:t.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...it.copy,...n.copy},sendButton:{...it.sendButton,...n.sendButton},statusIndicator:{...it.statusIndicator,...n.statusIndicator},voiceRecognition:{...it.voiceRecognition,...n.voiceRecognition},features:{...it.features,...n.features},suggestionChips:(e=n.suggestionChips)!=null?e:it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...it.layout,...n.layout,header:{...(o=it.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=it.layout)==null?void 0:i.messages,...(a=n.layout)==null?void 0:a.messages,avatar:{...(c=(u=it.layout)==null?void 0:u.messages)==null?void 0:c.avatar,...(d=(v=n.layout)==null?void 0:v.messages)==null?void 0:d.avatar},timestamp:{...(w=(m=it.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(y=(b=n.layout)==null?void 0:b.messages)==null?void 0:y.timestamp}},slots:{...(S=it.layout)==null?void 0:S.slots,...(x=n.layout)==null?void 0:x.slots}},markdown:{...it.markdown,...n.markdown,options:{...(k=it.markdown)==null?void 0:k.options,...(J=n.markdown)==null?void 0:J.options}},messageActions:{...it.messageActions,...n.messageActions}}:it}var oa=()=>{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(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var pl=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},gl=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},Xs=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=pl(n),r=gl(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}},Mr=n=>typeof n=="string"?n:n==null?"":String(n),Jn={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Mr(n.payload.text)},messageAndClick:(n,t)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,e=Mr(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:Mr(r.text)}}},ia=n=>Array.isArray(n)?n.map(t=>String(t)):[],Gs=n=>{let t=new Set(ia(n.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(ia(n.getSessionMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(t);n.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let a=i?n.parsers.reduce((c,v)=>c||(v==null?void 0:v({text:i,message:s.message}))||null,null):null;if(!a)return null;t.add(s.message.id),e();let u={action:a,message:s.message};n.emit("action:detected",u);for(let c of n.handlers)if(c)try{let v=()=>{n.emit("action:resubmit",u)},d=c(a,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:v});if(!d)continue;if(d.handled){let m=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:m,resubmit:d.resubmit}}}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",v)}return{text:"",persist:!0}},syncFromMetadata:r}};var ml=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},hl=n=>n.map(t=>({...t,streaming:!1})),kr=(n="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?ml(r.getItem(n)):null},save:r=>{let e=t();if(e)try{let o={...r,messages:r.messages?hl(r.messages):void 0};e.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=t();if(r)try{r.removeItem(n)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var Ir=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)})}},Ts=new Ir;import{parse as fl,STR as wl,OBJ as vl}from"partial-json";function yl(n){if(!n||typeof n!="object"||!("component"in n))return!1;let t=n.component;return typeof t=="string"&&t.length>0}function bl(n,t){if(!yl(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 Lr(){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=fl(r,wl|vl),s=bl(o,r);s&&(n=s)}catch{}return t=r.length,n},reset:()=>{n=null,t=0}}}function Cl(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function Wr(n,t){let{config:r,message:e,onPropsUpdate:o}=t,s=Ts.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 xl(){let n=Lr();return{processChunk:t=>n.processChunk(t),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Pr(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 Rr(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 Sl=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Hr(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:u=!0,ratingLabels:c=Sl}=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 d=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let b=document.createElement("h3");b.className="tvw-feedback-title",b.textContent=e,w.appendChild(b);let y=document.createElement("p");y.className="tvw-feedback-subtitle",y.textContent=o,w.appendChild(y),m.appendChild(w);let S=document.createElement("div");S.className="tvw-feedback-rating tvw-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let T=1;T<=5;T++){let B=document.createElement("button");B.type="button",B.className="tvw-feedback-rating-btn tvw-feedback-star-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`${T} star${T>1?"s":""}: ${c[T-1]}`),B.title=c[T-1],B.dataset.rating=String(T),B.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
- `,B.addEventListener("click",()=>{d=T,x.forEach((le,z)=>{let U=z<T;le.classList.toggle("selected",U),le.setAttribute("aria-checked",z===T-1?"true":"false")})}),x.push(B),S.appendChild(B)}m.appendChild(S);let k=null;if(u){let T=document.createElement("div");T.className="tvw-feedback-comment-container",k=document.createElement("textarea"),k.className="tvw-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),T.appendChild(k),m.appendChild(T)}let J=document.createElement("div");J.className="tvw-feedback-actions";let E=document.createElement("button");E.type="button",E.className="tvw-feedback-btn tvw-feedback-btn-skip",E.textContent=a,E.addEventListener("click",()=>{r==null||r(),v.remove()});let I=document.createElement("button");return I.type="button",I.className="tvw-feedback-btn tvw-feedback-btn-submit",I.textContent=i,I.addEventListener("click",async()=>{if(d===null){S.classList.add("tvw-feedback-shake"),setTimeout(()=>S.classList.remove("tvw-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let T=(k==null?void 0:k.value.trim())||void 0;await t(d,T),v.remove()}catch(T){I.disabled=!1,I.textContent=i,console.error("[CSAT Feedback] Failed to submit:",T)}}),J.appendChild(E),J.appendChild(I),m.appendChild(J),v.appendChild(m),v}function Br(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:u=!0,lowLabel:c="Not likely",highLabel:v="Very likely"}=n,d=document.createElement("div");d.className="tvw-feedback-container tvw-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let m=null,w=document.createElement("div");w.className="tvw-feedback-content";let b=document.createElement("div");b.className="tvw-feedback-header";let y=document.createElement("h3");y.className="tvw-feedback-title",y.textContent=e,b.appendChild(y);let S=document.createElement("p");S.className="tvw-feedback-subtitle",S.textContent=o,b.appendChild(S),w.appendChild(b);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 k=document.createElement("div");k.className="tvw-feedback-labels";let J=document.createElement("span");J.className="tvw-feedback-label-low",J.textContent=c;let E=document.createElement("span");E.className="tvw-feedback-label-high",E.textContent=v,k.appendChild(J),k.appendChild(E);let I=document.createElement("div");I.className="tvw-feedback-numbers";let T=[];for(let K=0;K<=10;K++){let j=document.createElement("button");j.type="button",j.className="tvw-feedback-rating-btn tvw-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${K} out of 10`),j.textContent=String(K),j.dataset.rating=String(K),K<=6?j.classList.add("tvw-feedback-detractor"):K<=8?j.classList.add("tvw-feedback-passive"):j.classList.add("tvw-feedback-promoter"),j.addEventListener("click",()=>{m=K,T.forEach((ye,se)=>{ye.classList.toggle("selected",se===K),ye.setAttribute("aria-checked",se===K?"true":"false")})}),T.push(j),I.appendChild(j)}x.appendChild(k),x.appendChild(I),w.appendChild(x);let B=null;if(u){let K=document.createElement("div");K.className="tvw-feedback-comment-container",B=document.createElement("textarea"),B.className="tvw-feedback-comment",B.placeholder=s,B.rows=3,B.setAttribute("aria-label","Additional comments"),K.appendChild(B),w.appendChild(K)}let le=document.createElement("div");le.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(),d.remove()});let U=document.createElement("button");return U.type="button",U.className="tvw-feedback-btn tvw-feedback-btn-submit",U.textContent=i,U.addEventListener("click",async()=>{if(m===null){I.classList.add("tvw-feedback-shake"),setTimeout(()=>I.classList.remove("tvw-feedback-shake"),500);return}U.disabled=!0,U.textContent="Submitting...";try{let K=(B==null?void 0:B.value.trim())||void 0;await t(m,K),d.remove()}catch(K){U.disabled=!1,U.textContent=i,console.error("[NPS Feedback] Failed to submit:",K)}}),le.appendChild(z),le.appendChild(U),w.appendChild(le),d.appendChild(w),d}var Kn="persona-chat-history",Al=30*1e3,El={"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 Tl(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 u=(o=El[a.type])!=null?o:"png";t.push(new File([a],`clipboard-image-${Date.now()}.${u}`,{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 Ml(n){var t,r,e,o,s,i,a,u,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:(u=(a=n.persist)==null?void 0:a.focusInput)!=null?u:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function kl(n){try{let t=n==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Fr=n=>!n||typeof n!="object"?{}:{...n},aa=n=>n.map(t=>({...t,streaming:!1})),la=(n,t,r)=>{let e=n!=null&&n.markdown?js(n.markdown):null;return o=>{var a,u,c;let s=(a=o.text)!=null?a:"",i=(u=o.message.rawContent)!=null?u: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):cr(s)}},$r=(n,t,r)=>{var as,ls,cs,ds,us,V,Ie,De,lt,mt,At,rt,h,We,$,C,L,ae,Ae,ze,Lt,ot,Ct,ht,Oe,_e,ut,Ve,xt,Dt,Xt,Dr,jr,_r,Vr;n.id&&n.id!=="persona-root"&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.id="persona-root";let e=Tr(t),o=Ys.getForInstance(e.plugins);e.components&&Ts.registerAll(e.components);let s=oa(),i=(as=e.storageAdapter)!=null?as:kr(),a={},u=null,c=l=>{if(e.onStateLoaded)try{return e.onStateLoaded(l)}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")u=l.then(p=>{let f=p!=null?p:{messages:[],metadata:{}};return c(f)});else{let p=l!=null?l:{messages:[],metadata:{}},f=c(p);f.metadata&&(a=Fr(f.metadata)),(ls=f.messages)!=null&&ls.length&&(e={...e,initialMessages:f.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:{}});(cs=l.messages)!=null&&cs.length&&(e={...e,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let v=()=>a,d=l=>{var f;a=(f=l({...a}))!=null?f:{},Qn()},m=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Xs],w=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Jn.message,Jn.messageAndClick],b=Gs({parsers:m,handlers:w,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});b.syncFromMetadata();let y=(us=(ds=e.launcher)==null?void 0:ds.enabled)!=null?us:!0,S=(Ie=(V=e.launcher)==null?void 0:V.autoExpand)!=null?Ie:!1,x=(De=e.autoFocusInput)!=null?De:!1,k=S,J=y,E=(mt=(lt=e.layout)==null?void 0:lt.header)==null?void 0:mt.layout,I=y?S:!0,T=!1,B=null,le=()=>{T=!0,B&&clearTimeout(B),B=setTimeout(()=>{T&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),T=!1)},1e4)},z=la(e,b,le),U=(rt=(At=e.features)==null?void 0:At.showReasoning)!=null?rt:!0,K=(We=(h=e.features)==null?void 0:h.showToolCalls)!=null?We:!0,j=(C=($=e.features)==null?void 0:$.showEventStreamToggle)!=null?C:!1,se=`${(ae=typeof e.persistState=="object"?(L=e.persistState)==null?void 0:L.keyPrefix:void 0)!=null?ae:"persona-"}event-stream`,Y=j?new Es(se):null,_=(Lt=(ze=(Ae=e.features)==null?void 0:Ae.eventStream)==null?void 0:ze.maxEvents)!=null?Lt:2e3,O=j?new As(_,Y):null,Q=null,ue=!1,Be=null,Et=0;Y==null||Y.open().then(()=>O==null?void 0:O.restore()).catch(l=>{e.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let dt={onCopy:l=>{var p,f;s.emit("message:copy",l),M!=null&&M.isClientTokenMode()&&M.submitMessageFeedback(l.id,"copy").catch(A=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(f=(p=e.messageActions)==null?void 0:p.onCopy)==null||f.call(p,l)},onFeedback:l=>{var p,f;s.emit("message:feedback",l),M!=null&&M.isClientTokenMode()&&M.submitMessageFeedback(l.messageId,l.type).catch(A=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(f=(p=e.messageActions)==null?void 0:p.onFeedback)==null||f.call(p,l)}},gt=(ot=e.statusIndicator)!=null?ot:{},Ht=l=>{var p,f,A,H;return l==="idle"?(p=gt.idleText)!=null?p:Rt.idle:l==="connecting"?(f=gt.connectingText)!=null?f:Rt.connecting:l==="connected"?(A=gt.connectedText)!=null?A:Rt.connected:l==="error"?(H=gt.errorText)!=null?H:Rt.error:Rt[l]},{wrapper:Ne,panel:ne}=Ji(e),be=Ki(e,y),{container:Re,body:Fe,messagesWrapper:Ue,suggestions:Nt,textarea:de,sendButton:X,sendButtonWrapper:at,composerForm:vt,statusText:Tt,introTitle:yt,introSubtitle:Kt,closeButton:ee,iconHolder:Le,headerTitle:bt,headerSubtitle:pe,header:Ce,footer:qe,actionsRow:Bt,leftActions:Mt,rightActions:Vt}=be,F=be.micButton,Qe=be.micButtonWrapper,N=be.attachmentButton,G=be.attachmentButtonWrapper,re=be.attachmentInput,$e=be.attachmentPreviewsContainer,oe=null;(Ct=e.attachments)!=null&&Ct.enabled&&re&&$e&&(oe=jn.fromConfig(e.attachments),oe.setPreviewsContainer($e),re.addEventListener("change",l=>{let p=l.target;oe==null||oe.handleFileSelect(p.files),p.value=""}));let Je=o.find(l=>l.renderHeader);if(Je!=null&&Je.renderHeader){let l=Je.renderHeader({config:e,defaultRenderer:()=>{let p=yn({config:e,showClose:y});return _n(Re,p,e),p.header},onClose:()=>nt(!1,"user")});if(l){let p=Re.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(l),Ce=l)}}let Ke=()=>{var p,f,A,H;if(!O)return;if(ue=!0,!Q&&O&&(Q=ta({buffer:O,getFullHistory:()=>O.getAllFromStore(),onClose:()=>ce(),config:e,plugins:o})),Q&&(Fe.style.display="none",(p=qe.parentNode)==null||p.insertBefore(Q.element,qe),Q.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 P=(H=(A=(f=e.features)==null?void 0:f.eventStream)==null?void 0:A.classNames)==null?void 0:H.toggleButtonActive;P&&P.split(/\s+/).forEach(q=>q&&D.classList.add(q))}let l=()=>{if(!ue)return;let P=Date.now();P-Et>=200&&(Q==null||Q.update(),Et=P),Be=requestAnimationFrame(l)};Et=0,Be=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},ce=()=>{var l,p,f;if(ue){if(ue=!1,Q&&Q.element.remove(),Fe.style.display="",D){D.classList.remove("tvw-text-cw-accent"),D.classList.add("tvw-text-cw-muted"),D.style.boxShadow="";let A=(f=(p=(l=e.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:f.toggleButtonActive;A&&A.split(/\s+/).forEach(H=>H&&D.classList.remove(H))}Be!==null&&(cancelAnimationFrame(Be),Be=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},D=null;if(j){let l=(Oe=(ht=e.features)==null?void 0:ht.eventStream)==null?void 0:Oe.classNames,p="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",p),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let f=ie("activity","18px","currentColor",1.5);f&&D.appendChild(f);let A=be.clearChatButtonWrapper,H=be.closeButtonWrapper,P=A||H;P&&P.parentNode===Ce?Ce.insertBefore(D,P):Ce.appendChild(D),D.addEventListener("click",()=>{ue?ce():Ke()})}let Se=o.find(l=>l.renderComposer);if(Se!=null&&Se.renderComposer){let l=Se.renderComposer({config:e,defaultRenderer:()=>xs({config:e}).footer,onSubmit:p=>{M&&!M.isStreaming()&&M.sendMessage(p)},disabled:!1});l&&(qe.replaceWith(l),qe=l)}(()=>{var A,H;let l=(H=(A=e.layout)==null?void 0:A.slots)!=null?H:{},p=P=>{switch(P){case"body-top":return Re.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Ue;case"footer-top":return Nt;case"composer":return vt;case"footer-bottom":return Tt;default:return null}},f=(P,q)=>{var ge;switch(P){case"header-left":case"header-center":case"header-right":if(P==="header-left")Ce.insertBefore(q,Ce.firstChild);else if(P==="header-right")Ce.appendChild(q);else{let me=Ce.querySelector(".tvw-flex-col");me?(ge=me.parentNode)==null||ge.insertBefore(q,me.nextSibling):Ce.appendChild(q)}break;case"body-top":{let me=Fe.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");me?me.replaceWith(q):Fe.insertBefore(q,Fe.firstChild);break}case"body-bottom":Fe.appendChild(q);break;case"footer-top":Nt.replaceWith(q);break;case"footer-bottom":Tt.replaceWith(q);break;default:break}};for(let[P,q]of Object.entries(l))if(q)try{let ge=q({config:e,defaultContent:()=>p(P)});ge&&f(P,ge)}catch(ge){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${P}":`,ge)}})();let tt=l=>{let f=l.target.closest('button[data-expand-header="true"]');if(!f)return;let A=f.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!A)return;let H=A.getAttribute("data-message-id");if(!H)return;let P=f.getAttribute("data-bubble-type");P==="reasoning"?(Un.has(H)?Un.delete(H):Un.add(H),Zi(H,A)):P==="tool"&&(qn.has(H)?qn.delete(H):qn.add(H),Qi(H,A,e))};Ue.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),tt(l))}),Ue.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),tt(l))});let Yt=new Map;Ue.addEventListener("click",l=>{var q;let f=l.target.closest(".tvw-message-action-btn[data-action]");if(!f)return;l.preventDefault(),l.stopPropagation();let A=f.closest("[data-actions-for]");if(!A)return;let H=A.getAttribute("data-actions-for");if(!H)return;let P=f.getAttribute("data-action");if(P==="copy"){let me=M.getMessages().find(fe=>fe.id===H);if(me&&dt.onCopy){let fe=me.content||"";navigator.clipboard.writeText(fe).then(()=>{f.classList.add("tvw-message-action-success");let xe=ie("check",14,"currentColor",2);xe&&(f.innerHTML="",f.appendChild(xe)),setTimeout(()=>{f.classList.remove("tvw-message-action-success");let Te=ie("copy",14,"currentColor",2);Te&&(f.innerHTML="",f.appendChild(Te))},2e3)}).catch(xe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",xe)}),dt.onCopy(me)}}else if(P==="upvote"||P==="downvote")if(((q=Yt.get(H))!=null?q:null)===P)Yt.delete(H),f.classList.remove("tvw-message-action-active");else{let fe=P==="upvote"?"downvote":"upvote",xe=A.querySelector(`[data-action="${fe}"]`);xe&&xe.classList.remove("tvw-message-action-active"),Yt.set(H,P),f.classList.add("tvw-message-action-active");let te=M.getMessages().find(W=>W.id===H);te&&dt.onFeedback&&dt.onFeedback({type:P,messageId:te.id,message:te})}}),Ue.addEventListener("click",l=>{let f=l.target.closest("button[data-approval-action]");if(!f)return;l.preventDefault(),l.stopPropagation();let A=f.closest(".vanilla-approval-bubble");if(!A)return;let H=A.getAttribute("data-message-id");if(!H)return;let P=f.getAttribute("data-approval-action");if(!P)return;let q=P==="approve"?"approved":"denied",me=M.getMessages().find(xe=>xe.id===H);if(!(me!=null&&me.approval))return;let fe=A.querySelector("[data-approval-buttons]");fe&&fe.querySelectorAll("button").forEach(Te=>{Te.disabled=!0,Te.style.opacity="0.5",Te.style.cursor="not-allowed"}),M.resolveApproval(me.approval,q)}),ne.appendChild(Re),n.appendChild(Ne);let Gt=()=>{var he,we,st,Pe,ft,Pt,Z,je,rn,jt,tn,Mn,Os,ir,ar,pt;let l=(we=(he=e.launcher)==null?void 0:he.sidebarMode)!=null?we:!1,p=l||((Pe=(st=e.launcher)==null?void 0:st.fullHeight)!=null?Pe:!1),f=(ft=e.theme)!=null?ft:{},A=(Z=(Pt=e.launcher)==null?void 0:Pt.position)!=null?Z:"bottom-left",H=A==="bottom-left"||A==="top-left",P=l?"none":"1px solid var(--tvw-cw-border)",q=l?H?"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)",ge=l?"0":"16px",me=(je=f.panelBorder)!=null?je:P,fe=(rn=f.panelShadow)!=null?rn:q,xe=(jt=f.panelBorderRadius)!=null?jt:ge;n.style.cssText="",Ne.style.cssText="",ne.style.cssText="",Re.style.cssText="",Fe.style.cssText="",qe.style.cssText="";let Te=(Mn=(tn=e==null?void 0:e.launcher)==null?void 0:tn.width)!=null?Mn:e==null?void 0:e.launcherWidth,te=Te!=null?Te:"min(400px, calc(100vw - 24px))";l||(ne.style.width=te,ne.style.maxWidth=te),ne.style.boxShadow=fe,ne.style.borderRadius=xe,Re.style.border=me,Re.style.borderRadius=xe;let W=((Os=e.launcher)==null?void 0:Os.enabled)===!1;if(p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",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%",W&&(Ne.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",Re.style.display="flex",Re.style.flexDirection="column",Re.style.flex="1 1 0%",Re.style.minHeight="0",Re.style.maxHeight="100%",Re.style.overflow="hidden",Fe.style.flex="1 1 0%",Fe.style.minHeight="0",Fe.style.overflowY="auto",qe.style.flexShrink="0"),Ne.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&&!W&&((ir=nn[A])!=null?ir:nn["bottom-right"]).split(" ").forEach($n=>Ne.classList.add($n)),l){let Fn=(pt=(ar=e.launcher)==null?void 0:ar.sidebarWidth)!=null?pt:"420px";Ne.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: ${Fn} !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
- ${H?"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 ya}from"marked";var ba=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: ${fe} !important;
44
- border-radius: ${xe} !important;
45
- `,ne.style.setProperty("width","100%","important"),ne.style.setProperty("max-width","100%","important"),Re.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 ya}from"marked";var ba=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: ${xe} !important;
55
- border: ${me} !important;
56
- `,qe.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(!W){let Fn="max-height: -moz-available !important; max-height: stretch !important;",$n=l?"":"padding-top: 1.25em !important;";Ne.style.cssText+=Fn+$n}};Gt(),Ks(n,e);let Ye=[];j&&Ye.push(()=>{Be!==null&&(cancelAnimationFrame(Be),Be=null),Q==null||Q.destroy(),Q=null,O==null||O.destroy(),O=null,Y=null});let Zt=null,mn=()=>{Zt&&(Zt(),Zt=null),e.colorScheme==="auto"&&(Zt=ji(()=>{Ks(n,e)}))};mn(),Ye.push(()=>{Zt&&(Zt(),Zt=null)});let hn=ea(Nt),sn=null,M,fn=!1,an=!0,bn=0,Xn=0,ln=null,cn=!1,Ln=0,Wn=!1,Ms=125,ks=2e3,Is=5,Gn=50,Pn=new Map,Ee={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Zn=(ut=(_e=e.voiceRecognition)==null?void 0:_e.autoResume)!=null?ut:!1,Qt=l=>{s.emit("voice:state",{active:Ee.active,source:l,timestamp:Date.now()})},Ut=()=>{d(l=>({...l,voiceState:{active:Ee.active,timestamp:Date.now(),manuallyDeactivated:Ee.manuallyDeactivated}}))},Ls=()=>{var A,H;if(((A=e.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Fr(a.voiceState),p=!!l.active,f=Number((H=l.timestamp)!=null?H:0);Ee.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-f<Al&&setTimeout(()=>{var P,q;Ee.active||(Ee.manuallyDeactivated=!1,((q=(P=e.voiceRecognition)==null?void 0:P.provider)==null?void 0:q.type)==="runtype"?M.toggleVoice().then(()=>{Ee.active=M.isVoiceActive(),Qt("restore"),M.isVoiceActive()&&En()}):An("restore"))},1e3)},Ws=()=>M?aa(M.getMessages()).filter(l=>!l.__skipPersist):[];function Qn(l){if(!(i!=null&&i.save))return;let f={messages:l?aa(l):M?Ws():[],metadata:a};try{let A=i.save(f);A instanceof Promise&&A.catch(H=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",H)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let Cn=(l=!1)=>{if(!an)return;let p=Date.now();cn&&p<Ln&&!l||(cn&&p>=Ln&&(cn=!1),!(!l&&!fn)&&(p-Xn<Ms||(Xn=p,ln&&cancelAnimationFrame(ln),ln=requestAnimationFrame(()=>{cn||!an||(Wn=!0,Fe.scrollTop=Fe.scrollHeight,bn=Fe.scrollTop,requestAnimationFrame(()=>{Wn=!1}),ln=null)}))))},dn=null,Ps=()=>Ne.querySelector("#persona-scroll-container")||Fe,Rs=(l,p=500)=>{let f=l.scrollTop,A=l.clientHeight,H=l.scrollHeight,P=H-f;if(f+A>=H-2||Math.abs(P)<5)return;dn!==null&&(cancelAnimationFrame(dn),dn=null);let ge=performance.now(),me=xe=>1-Math.pow(1-xe,3),fe=xe=>{let Te=l.scrollHeight;Te!==H&&(H=Te,P=H-f);let te=xe-ge,W=Math.min(te/p,1),he=me(W),we=f+P*he;l.scrollTop=we,W<1?dn=requestAnimationFrame(fe):(l.scrollTop=l.scrollHeight,dn=null)};dn=requestAnimationFrame(fe)},Hs=l=>{let p=new Map;l.forEach(f=>{let A=Pn.get(f.id);p.set(f.id,{streaming:f.streaming,role:f.role}),!A&&f.role==="assistant"&&s.emit("assistant:message",f),f.role==="assistant"&&(A!=null&&A.streaming)&&f.streaming===!1&&s.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(A?f.approval.status!=="pending"&&s.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):s.emit("approval:requested",{approval:f.approval,message:f}))}),Pn.clear(),p.forEach((f,A)=>{Pn.set(A,f)})},xn=(l,p,f)=>{var fe,xe,Te,te;let A=document.createElement("div"),P=(()=>{var he;let W=o.find(we=>we.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((he=e.loadingIndicator)!=null&&he.render)return e.loadingIndicator.render})();p.forEach(W=>{var ft,Pt;let he=null,we=o.find(Z=>!!(W.variant==="reasoning"&&Z.renderReasoning||W.variant==="tool"&&Z.renderToolCall||W.variant==="approval"&&Z.renderApproval||!W.variant&&Z.renderMessage)),st=(ft=e.layout)==null?void 0:ft.messages;if(we)if(W.variant==="reasoning"&&W.reasoning&&we.renderReasoning){if(!U)return;he=we.renderReasoning({message:W,defaultRenderer:()=>br(W),config:e})}else if(W.variant==="tool"&&W.toolCall&&we.renderToolCall){if(!K)return;he=we.renderToolCall({message:W,defaultRenderer:()=>Cr(W,e),config:e})}else if(W.variant==="approval"&&W.approval&&we.renderApproval){if(e.approval===!1)return;he=we.renderApproval({message:W,defaultRenderer:()=>xr(W,e),config:e})}else we.renderMessage&&(he=we.renderMessage({message:W,defaultRenderer:()=>{let Z=Ss(W,f,st,e.messageActions,dt,{loadingIndicatorRenderer:P,widgetConfig:e});return W.role!=="user"&&Ar(Z,W,e,M),Z},config:e}));if(!he&&W.role==="assistant"&&!W.variant&&e.enableComponentStreaming!==!1&&Pr(W)){let je=Rr(W);if(je){let rn=Wr(je,{config:e,message:W,transform:f});if(rn){let jt=document.createElement("div");if(jt.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(" "),jt.id=`bubble-${W.id}`,jt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let tn=document.createElement("div");tn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",tn.innerHTML=f({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),jt.appendChild(tn)}jt.appendChild(rn),he=jt}}}if(!he)if(W.variant==="reasoning"&&W.reasoning){if(!U)return;he=br(W)}else if(W.variant==="tool"&&W.toolCall){if(!K)return;he=Cr(W,e)}else if(W.variant==="approval"&&W.approval){if(e.approval===!1)return;he=xr(W,e)}else{let Z=(Pt=e.layout)==null?void 0:Pt.messages;Z!=null&&Z.renderUserMessage&&W.role==="user"?he=Z.renderUserMessage({message:W,config:e,streaming:!!W.streaming}):Z!=null&&Z.renderAssistantMessage&&W.role==="assistant"?he=Z.renderAssistantMessage({message:W,config:e,streaming:!!W.streaming}):he=Ss(W,f,Z,e.messageActions,dt,{loadingIndicatorRenderer:P,widgetConfig:e}),W.role!=="user"&&he&&Ar(he,W,e,M)}let Pe=document.createElement("div");Pe.className="tvw-flex",Pe.id=`wrapper-${W.id}`,Pe.setAttribute("data-wrapper-id",W.id),W.role==="user"&&Pe.classList.add("tvw-justify-end"),Pe.appendChild(he),A.appendChild(Pe)});let q=p.some(W=>W.role==="assistant"&&W.streaming),ge=p[p.length-1],me=(ge==null?void 0:ge.role)==="assistant"&&!ge.streaming&&ge.variant!=="approval";if(fn&&p.some(W=>W.role==="user")&&!q&&!me){let W={config:e,streaming:!0,location:"standalone",defaultRenderer:Vn},he=o.find(st=>st.renderLoadingIndicator),we=null;if(he!=null&&he.renderLoadingIndicator&&(we=he.renderLoadingIndicator(W)),we===null&&((fe=e.loadingIndicator)!=null&&fe.render)&&(we=e.loadingIndicator.render(W)),we===null&&(we=Vn()),we){let st=document.createElement("div"),Pe=((xe=e.loadingIndicator)==null?void 0:xe.showBubble)!==!1;st.className=Pe?["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(" "),st.setAttribute("data-typing-indicator","true"),st.appendChild(we);let ft=document.createElement("div");ft.className="tvw-flex",ft.id="wrapper-typing-indicator",ft.setAttribute("data-wrapper-id","typing-indicator"),ft.appendChild(st),A.appendChild(ft)}}if(!fn&&p.length>0){let W=p[p.length-1],he={config:e,lastMessage:W,messageCount:p.length},we=o.find(Pe=>Pe.renderIdleIndicator),st=null;if(we!=null&&we.renderIdleIndicator&&(st=we.renderIdleIndicator(he)),st===null&&((Te=e.loadingIndicator)!=null&&Te.renderIdle)&&(st=e.loadingIndicator.renderIdle(he)),st){let Pe=document.createElement("div"),ft=((te=e.loadingIndicator)==null?void 0:te.showBubble)!==!1;Pe.className=ft?["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(" "),Pe.setAttribute("data-idle-indicator","true"),Pe.appendChild(st);let Pt=document.createElement("div");Pt.className="tvw-flex",Pt.id="wrapper-idle-indicator",Pt.setAttribute("data-wrapper-id","idle-indicator"),Pt.appendChild(Pe),A.appendChild(Pt)}}_i(l,A),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let W=Ps();Rs(W)})})},Sn=()=>{y&&(I?(Ne.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"),Xe?Xe.element.style.display="none":Ge&&(Ge.style.display="none")):(Ne.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"),Xe?Xe.element.style.display="":Ge&&(Ge.style.display="")))},nt=(l,p="user")=>{if(!y||I===l)return;let f=I;I=l,Sn(),I&&(wn(),Cn(!0));let A={open:I,source:p,timestamp:Date.now()};I&&!f?s.emit("widget:opened",A):!I&&f&&s.emit("widget:closed",A),s.emit("widget:state",{open:I,launcherEnabled:y,voiceActive:Ee.active,streaming:M.isStreaming()})},Rn=l=>{X.disabled=l,F&&(F.disabled=l),hn.buttons.forEach(p=>{p.disabled=l})},Hn=()=>{Ee.active||de&&de.focus()};s.on("widget:opened",()=>{e.autoFocusInput&&setTimeout(()=>Hn(),200)});let es=()=>{var H,P,q,ge,me,fe,xe,Te,te,W,he,we,st,Pe;yt.textContent=(P=(H=e.copy)==null?void 0:H.welcomeTitle)!=null?P:"Hello \u{1F44B}",Kt.textContent=(ge=(q=e.copy)==null?void 0:q.welcomeSubtitle)!=null?ge:"Ask anything about your account or products.",de.placeholder=(fe=(me=e.copy)==null?void 0:me.inputPlaceholder)!=null?fe:"How can I help...",(Te=(xe=e.sendButton)==null?void 0:xe.useIcon)!=null&&Te||(X.textContent=(W=(te=e.copy)==null?void 0:te.sendButtonLabel)!=null?W:"Send");let p=(we=(he=e.theme)==null?void 0:he.inputFontFamily)!=null?we:"sans-serif",f=(Pe=(st=e.theme)==null?void 0:st.inputFontWeight)!=null?Pe:"400",A=ft=>{switch(ft){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'}};de.style.fontFamily=A(p),de.style.fontWeight=f};if(e.clientToken&&(e={...e,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{d(p=>({...p,sessionId:l}))}}),M=new ys(e,{onMessagesChanged(l){xn(Ue,l,z),M&&(l.some(H=>H.role==="user")?hn.render([],M,de,l):hn.render(e.suggestionChips,M,de,l,e.suggestionChipsConfig)),Cn(!fn),Hs(l);let p=[...l].reverse().find(A=>A.role==="user"),f=Ee.lastUserMessageId;p&&p.id!==f&&(Ee.lastUserMessageId=p.id,s.emit("user:message",p)),Ee.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Qn(l)},onStatusChanged(l){var A;let p=(A=e.statusIndicator)!=null?A:{},f=H=>{var P,q,ge,me;return H==="idle"?(P=p.idleText)!=null?P:Rt.idle:H==="connecting"?(q=p.connectingText)!=null?q:Rt.connecting:H==="connected"?(ge=p.connectedText)!=null?ge:Rt.connected:H==="error"?(me=p.errorText)!=null?me:Rt.error:Rt[H]};Tt.textContent=f(l)},onStreamingChanged(l){fn=l,Rn(l),M&&xn(Ue,M.getMessages(),z),l||Cn(!0)},onVoiceStatusChanged(l){var p,f;((f=(p=e.voiceRecognition)==null?void 0:p.provider)==null?void 0:f.type)==="runtype"&&l!=="listening"&&(Ee.active=!1,Tn(),Qt("system"),Ut())}}),((xt=(Ve=e.voiceRecognition)==null?void 0:Ve.provider)==null?void 0:xt.type)==="runtype")try{M.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}e.clientToken&&M.initClientSession().catch(l=>{e.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),O&&M.setSSEEventCallback((l,p)=>{O==null||O.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),u&&u.then(l=>{var p;l&&(l.metadata&&(a=Fr(l.metadata),b.syncFromMetadata()),(p=l.messages)!=null&&p.length&&M.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let ts=l=>{var H;l.preventDefault();let p=de.value.trim(),f=(H=oe==null?void 0:oe.hasAttachments())!=null?H:!1;if(!p&&!f)return;let A;f&&(A=[],A.push(...oe.getContentParts()),p&&A.push(fr(p))),de.value="",de.style.height="auto",M.sendMessage(p,{contentParts:A}),f&&oe.clearAttachments()},ns=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),X.click())},ss=async l=>{var f;if(((f=e.attachments)==null?void 0:f.enabled)!==!0||!oe)return;let p=Tl(l.clipboardData);p.length!==0&&(l.preventDefault(),await oe.handleFiles(p))},Ft=null,qt=!1,un=null,kt=null,rs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,An=(l="user")=>{var P,q,ge,me;if(qt||M.isStreaming())return;let p=rs();if(!p)return;Ft=new p;let A=(q=((P=e.voiceRecognition)!=null?P:{}).pauseDuration)!=null?q:2e3;Ft.continuous=!0,Ft.interimResults=!0,Ft.lang="en-US";let H=de.value;Ft.onresult=fe=>{let xe="",Te="";for(let W=0;W<fe.results.length;W++){let he=fe.results[W],we=he[0].transcript;he.isFinal?xe+=we+" ":Te=we}let te=H+xe+Te;de.value=te,un&&clearTimeout(un),(xe||Te)&&(un=window.setTimeout(()=>{let W=de.value.trim();W&&Ft&&qt&&(en(),de.value="",de.style.height="auto",M.sendMessage(W,{viaVoice:!0}))},A))},Ft.onerror=fe=>{fe.error!=="no-speech"&&en()},Ft.onend=()=>{if(qt){let fe=de.value.trim();fe&&fe!==H.trim()&&(de.value="",de.style.height="auto",M.sendMessage(fe,{viaVoice:!0})),en()}};try{if(Ft.start(),qt=!0,Ee.active=!0,l!=="system"&&(Ee.manuallyDeactivated=!1),Qt(l),Ut(),F){kt={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor};let fe=(ge=e.voiceRecognition)!=null?ge:{},xe=(me=fe.recordingBackgroundColor)!=null?me:"#ef4444",Te=fe.recordingIconColor,te=fe.recordingBorderColor;if(F.classList.add("tvw-voice-recording"),F.style.backgroundColor=xe,Te){F.style.color=Te;let W=F.querySelector("svg");W&&W.setAttribute("stroke",Te)}te&&(F.style.borderColor=te),F.setAttribute("aria-label","Stop voice recognition")}}catch{en("system")}},en=(l="user")=>{if(qt){if(qt=!1,un&&(clearTimeout(un),un=null),Ft){try{Ft.stop()}catch{}Ft=null}if(Ee.active=!1,Qt(l),Ut(),F){if(F.classList.remove("tvw-voice-recording"),kt){F.style.backgroundColor=kt.backgroundColor,F.style.color=kt.color,F.style.borderColor=kt.borderColor;let p=F.querySelector("svg");p&&p.setAttribute("stroke",kt.color||"currentColor"),kt=null}F.setAttribute("aria-label","Start voice recognition")}}},Bs=(l,p)=>{var Pe,ft,Pt,Z,je,rn,jt,tn;let f=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((Pe=l==null?void 0:l.provider)==null?void 0:Pe.type)==="runtype";if(!(f||A))return null;let P=g("div","tvw-send-button-wrapper"),q=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");q.type="button",q.setAttribute("aria-label","Start voice recognition");let ge=(ft=l==null?void 0:l.iconName)!=null?ft:"mic",me=(Pt=p==null?void 0:p.size)!=null?Pt:"40px",fe=(Z=l==null?void 0:l.iconSize)!=null?Z:me,xe=parseFloat(fe)||24,Te=(je=l==null?void 0:l.backgroundColor)!=null?je:p==null?void 0:p.backgroundColor,te=(rn=l==null?void 0:l.iconColor)!=null?rn:p==null?void 0:p.textColor;q.style.width=fe,q.style.height=fe,q.style.minWidth=fe,q.style.minHeight=fe,q.style.fontSize="18px",q.style.lineHeight="1";let W=te||"currentColor",he=ie(ge,xe,W,1.5);he?(q.appendChild(he),q.style.color=W):(q.textContent="\u{1F3A4}",q.style.color=W),Te?q.style.backgroundColor=Te:q.classList.add("tvw-bg-cw-primary"),te?q.style.color=te:!te&&!(p!=null&&p.textColor)&&q.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(q.style.borderWidth=l.borderWidth,q.style.borderStyle="solid"),l!=null&&l.borderColor&&(q.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(q.style.paddingLeft=l.paddingX,q.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(q.style.paddingTop=l.paddingY,q.style.paddingBottom=l.paddingY),P.appendChild(q);let we=(jt=l==null?void 0:l.tooltipText)!=null?jt:"Start voice recognition";if(((tn=l==null?void 0:l.showTooltip)!=null?tn:!1)&&we){let Mn=g("div","tvw-send-button-tooltip");Mn.textContent=we,P.appendChild(Mn)}return{micButton:q,micButtonWrapper:P}},En=()=>{var H,P;if(!F)return;kt={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor};let l=(H=e.voiceRecognition)!=null?H:{},p=(P=l.recordingBackgroundColor)!=null?P:"#ef4444",f=l.recordingIconColor,A=l.recordingBorderColor;if(F.classList.add("tvw-voice-recording"),F.style.backgroundColor=p,f){F.style.color=f;let q=F.querySelector("svg");q&&q.setAttribute("stroke",f)}A&&(F.style.borderColor=A),F.setAttribute("aria-label","Stop voice recognition")},Tn=()=>{var l,p,f;if(F){if(F.classList.remove("tvw-voice-recording"),kt){F.style.backgroundColor=(l=kt.backgroundColor)!=null?l:"",F.style.color=(p=kt.color)!=null?p:"",F.style.borderColor=(f=kt.borderColor)!=null?f:"";let A=F.querySelector("svg");A&&A.setAttribute("stroke",kt.color||"currentColor"),kt=null}F.setAttribute("aria-label","Start voice recognition")}},Bn=()=>{var l,p;if(((p=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){M.toggleVoice().then(()=>{Ee.active=M.isVoiceActive(),Ee.manuallyDeactivated=!M.isVoiceActive(),Ut(),Qt("user"),M.isVoiceActive()?En():Tn()});return}if(qt){let f=de.value.trim();Ee.manuallyDeactivated=!0,Ut(),en("user"),f&&(de.value="",de.style.height="auto",M.sendMessage(f))}else Ee.manuallyDeactivated=!1,Ut(),An("user")};F&&(F.addEventListener("click",Bn),Ye.push(()=>{var l,p;((p=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(M.isVoiceActive()&&M.toggleVoice(),Tn()):en("system"),F&&F.removeEventListener("click",Bn)}));let Fs=s.on("assistant:complete",()=>{Zn&&(Ee.active||Ee.manuallyDeactivated||Zn==="assistant"&&!Ee.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!Ee.active&&!Ee.manuallyDeactivated&&(((p=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?M.toggleVoice().then(()=>{Ee.active=M.isVoiceActive(),Qt("auto"),M.isVoiceActive()&&En()}):An("auto"))},600))});Ye.push(Fs);let $s=s.on("action:resubmit",()=>{setTimeout(()=>{M&&!M.isStreaming()&&M.continueConversation()},100)});Ye.push($s);let pn=()=>{nt(!I,"user")},Xe=null,Ge=null;if(y){let l=o.find(p=>p.renderLauncher);if(l!=null&&l.renderLauncher){let p=l.renderLauncher({config:e,defaultRenderer:()=>bs(e,pn).element,onToggle:pn});p&&(Ge=p)}Ge||(Xe=bs(e,pn))}Xe?n.appendChild(Xe.element):Ge&&n.appendChild(Ge),Sn(),hn.render(e.suggestionChips,M,de,void 0,e.suggestionChipsConfig),es(),Rn(M.isStreaming()),Cn(!0),Ls(),x&&(y?I&&setTimeout(()=>Hn(),200):setTimeout(()=>Hn(),0));let wn=()=>{var f,A,H,P,q,ge,me,fe;let l=(A=(f=e.launcher)==null?void 0:f.sidebarMode)!=null?A:!1,p=l||((P=(H=e.launcher)==null?void 0:H.fullHeight)!=null?P:!1);if(!y){ne.style.height="",ne.style.width="";return}if(!l){let xe=(ge=(q=e==null?void 0:e.launcher)==null?void 0:q.width)!=null?ge:e==null?void 0:e.launcherWidth,Te=xe!=null?xe:"min(400px, calc(100vw - 24px))";ne.style.width=Te,ne.style.maxWidth=Te}if(!p){let xe=window.innerHeight,Te=64,te=(fe=(me=e.launcher)==null?void 0:me.heightOffset)!=null?fe:0,W=Math.max(200,xe-Te),he=Math.min(640,W),we=Math.max(200,he-te);ne.style.height=`${we}px`}};wn(),window.addEventListener("resize",wn),Ye.push(()=>window.removeEventListener("resize",wn)),bn=Fe.scrollTop;let os=()=>{let l=Fe.scrollTop,p=Fe.scrollHeight,f=Fe.clientHeight,A=p-l-f,H=Math.abs(l-bn);if(bn=l,!Wn&&!(H<=Is)){if(!an&&A<Gn){cn=!1,an=!0;return}an&&A>Gn&&(cn=!0,Ln=Date.now()+ks,an=!1)}};Fe.addEventListener("scroll",os,{passive:!0}),Ye.push(()=>Fe.removeEventListener("scroll",os)),Ye.push(()=>{ln&&cancelAnimationFrame(ln)});let is=()=>{ee&&(sn&&(ee.removeEventListener("click",sn),sn=null),y?(ee.style.display="",sn=()=>{I=!1,Sn()},ee.addEventListener("click",sn)):ee.style.display="none")};is(),(()=>{let{clearChatButton:l}=be;l&&l.addEventListener("click",()=>{M.clearMessages();try{localStorage.removeItem(Kn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Kn}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Kn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}a={},b.syncFromMetadata(),O==null||O.clear(),Q==null||Q.update()})})(),vt.addEventListener("submit",ts),de.addEventListener("keydown",ns),de.addEventListener("paste",ss),Ye.push(()=>{vt.removeEventListener("submit",ts),de.removeEventListener("keydown",ns),de.removeEventListener("paste",ss)}),Ye.push(()=>{M.cancel()}),Xe?Ye.push(()=>{Xe==null||Xe.destroy()}):Ge&&Ye.push(()=>{Ge==null||Ge.remove()});let It={update(l){var qr,zr,Jr,Kr,Yr,Xr,Gr,Zr,Qr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,vo,yo,bo,Co,xo,So,Ao,Eo,To,Mo,ko,Io,Lo,Wo,Po,Ro,Ho,Bo,Fo,$o,Oo,No,Do,jo,_o,Vo,Uo,qo,zo,Jo,Ko,Yo,Xo,Go,Zo,Qo,ei,ti,ni,si,ri,oi,ii,ai,li,ci,di,ui,pi,gi,mi,hi,fi,wi,vi,yi,bi,Ci,xi,Si,Ai,Ei,Ti,Mi;let p=e.toolCall,f=e.colorScheme;e={...e,...l},Gt(),Ks(n,e),e.colorScheme!==f&&mn();let A=Ys.getForInstance(e.plugins);o.length=0,o.push(...A),y=(zr=(qr=e.launcher)==null?void 0:qr.enabled)!=null?zr:!0,S=(Kr=(Jr=e.launcher)==null?void 0:Jr.autoExpand)!=null?Kr:!1,U=(Xr=(Yr=e.features)==null?void 0:Yr.showReasoning)!=null?Xr:!0,K=(Zr=(Gr=e.features)==null?void 0:Gr.showToolCalls)!=null?Zr:!0;let H=j;if(j=(eo=(Qr=e.features)==null?void 0:Qr.showEventStreamToggle)!=null?eo:!1,j&&!H){if(O||(Y=new Es(se),O=new As(_,Y),Y.open().then(()=>O==null?void 0:O.restore()).catch(()=>{}),M.setSSEEventCallback((R,Me)=>{O.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:R,timestamp:Date.now(),payload:JSON.stringify(Me)})})),!D&&Ce){let R=(no=(to=e.features)==null?void 0:to.eventStream)==null?void 0:no.classNames,Me="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"+(R!=null&&R.toggleButton?" "+R.toggleButton:"");D=g("button",Me),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let Ze=ie("activity","18px","currentColor",1.5);Ze&&D.appendChild(Ze);let ve=be.clearChatButtonWrapper,He=be.closeButtonWrapper,wt=ve||He;wt&&wt.parentNode===Ce?Ce.insertBefore(D,wt):Ce.appendChild(D),D.addEventListener("click",()=>{ue?ce():Ke()})}}else!j&&H&&(ce(),D&&(D.remove(),D=null),O==null||O.clear(),Y==null||Y.destroy(),O=null,Y=null);if(((so=e.launcher)==null?void 0:so.enabled)===!1&&Xe&&(Xe.destroy(),Xe=null),((ro=e.launcher)==null?void 0:ro.enabled)===!1&&Ge&&(Ge.remove(),Ge=null),((oo=e.launcher)==null?void 0:oo.enabled)!==!1&&!Xe&&!Ge){let R=o.find(Me=>Me.renderLauncher);if(R!=null&&R.renderLauncher){let Me=R.renderLauncher({config:e,defaultRenderer:()=>bs(e,pn).element,onToggle:pn});Me&&(Ge=Me,n.appendChild(Ge))}Ge||(Xe=bs(e,pn),n.appendChild(Xe.element))}Xe&&Xe.update(e),bt&&((io=e.launcher)==null?void 0:io.title)!==void 0&&(bt.textContent=e.launcher.title),pe&&((ao=e.launcher)==null?void 0:ao.subtitle)!==void 0&&(pe.textContent=e.launcher.subtitle);let P=(lo=e.layout)==null?void 0:lo.header;if((P==null?void 0:P.layout)!==E&&Ce){let R=P?Cs(e,P,{showClose:y,onClose:()=>nt(!1,"user")}):yn({config:e,showClose:y,onClose:()=>nt(!1,"user")});Ce.replaceWith(R.header),Ce=R.header,Le=R.iconHolder,bt=R.headerTitle,pe=R.headerSubtitle,ee=R.closeButton,E=P==null?void 0:P.layout}else if(P&&(Le&&(Le.style.display=P.showIcon===!1?"none":""),bt&&(bt.style.display=P.showTitle===!1?"none":""),pe&&(pe.style.display=P.showSubtitle===!1?"none":""),ee&&(ee.style.display=P.showCloseButton===!1?"none":""),be.clearChatButtonWrapper)){let R=P.showClearChat;if(R!==void 0){be.clearChatButtonWrapper.style.display=R?"":"none";let{closeButtonWrapper:Me}=be;Me&&!Me.classList.contains("tvw-absolute")&&(R?Me.classList.remove("tvw-ml-auto"):Me.classList.add("tvw-ml-auto"))}}let ge=((co=e.layout)==null?void 0:co.showHeader)!==!1;Ce&&(Ce.style.display=ge?"":"none");let me=((uo=e.layout)==null?void 0:uo.showFooter)!==!1;qe&&(qe.style.display=me?"":"none"),y!==J?y?nt(S,"auto"):(I=!0,Sn()):S!==k&&nt(S,"auto"),k=S,J=y,wn(),is(),JSON.stringify(l.toolCall)!==JSON.stringify(p)&&M&&xn(Ue,M.getMessages(),z);let te=(po=e.launcher)!=null?po:{},W=(go=te.headerIconHidden)!=null?go:!1,he=(ho=(mo=e.layout)==null?void 0:mo.header)==null?void 0:ho.showIcon,we=W||he===!1,st=te.headerIconName,Pe=(fo=te.headerIconSize)!=null?fo:"48px";if(Le){let R=Re.querySelector(".tvw-border-b-cw-divider"),Me=R==null?void 0:R.querySelector(".tvw-flex-col");if(we)Le.style.display="none",R&&Me&&!R.contains(Me)&&R.insertBefore(Me,R.firstChild);else{if(Le.style.display="",Le.style.height=Pe,Le.style.width=Pe,R&&Me&&(R.contains(Le)?Le.nextSibling!==Me&&(Le.remove(),R.insertBefore(Le,Me)):R.insertBefore(Le,Me)),st){let ve=parseFloat(Pe)||24,He=ie(st,ve*.6,"#ffffff",2);He?Le.replaceChildren(He):Le.textContent=(wo=te.agentIconText)!=null?wo:"\u{1F4AC}"}else if(te.iconUrl){let ve=Le.querySelector("img");if(ve)ve.src=te.iconUrl,ve.style.height=Pe,ve.style.width=Pe;else{let He=document.createElement("img");He.src=te.iconUrl,He.alt="",He.className="tvw-rounded-xl tvw-object-cover",He.style.height=Pe,He.style.width=Pe,Le.replaceChildren(He)}}else{let ve=Le.querySelector("svg"),He=Le.querySelector("img");(ve||He)&&Le.replaceChildren(),Le.textContent=(vo=te.agentIconText)!=null?vo:"\u{1F4AC}"}let Ze=Le.querySelector("img");Ze&&(Ze.style.height=Pe,Ze.style.width=Pe)}}let ft=(bo=(yo=e.layout)==null?void 0:yo.header)==null?void 0:bo.showTitle,Pt=(xo=(Co=e.layout)==null?void 0:Co.header)==null?void 0:xo.showSubtitle;if(bt&&(bt.style.display=ft===!1?"none":""),pe&&(pe.style.display=Pt===!1?"none":""),ee){((Ao=(So=e.layout)==null?void 0:So.header)==null?void 0:Ao.showCloseButton)===!1?ee.style.display="none":ee.style.display="";let Me=(Eo=te.closeButtonSize)!=null?Eo:"32px",Ze=(To=te.closeButtonPlacement)!=null?To:"inline";ee.style.height=Me,ee.style.width=Me;let{closeButtonWrapper:ve}=be,He=Ze==="top-right",wt=ve==null?void 0:ve.classList.contains("tvw-absolute");if(ve&&He!==wt)if(ve.remove(),He)ve.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Re.style.position="relative",Re.appendChild(ve);else{let ke=(ko=(Mo=te.clearChat)==null?void 0:Mo.placement)!=null?ko:"inline",St=(Lo=(Io=te.clearChat)==null?void 0:Io.enabled)!=null?Lo:!0;ve.className=St&&ke==="inline"?"":"tvw-ml-auto";let _t=Re.querySelector(".tvw-border-b-cw-divider");_t&&_t.appendChild(ve)}if(te.closeButtonColor?(ee.style.color=te.closeButtonColor,ee.classList.remove("tvw-text-cw-muted")):(ee.style.color="",ee.classList.add("tvw-text-cw-muted")),te.closeButtonBackgroundColor?(ee.style.backgroundColor=te.closeButtonBackgroundColor,ee.classList.remove("hover:tvw-bg-gray-100")):(ee.style.backgroundColor="",ee.classList.add("hover:tvw-bg-gray-100")),te.closeButtonBorderWidth||te.closeButtonBorderColor){let ke=te.closeButtonBorderWidth||"0px",St=te.closeButtonBorderColor||"transparent";ee.style.border=`${ke} solid ${St}`,ee.classList.remove("tvw-border-none")}else ee.style.border="",ee.classList.add("tvw-border-none");te.closeButtonBorderRadius?(ee.style.borderRadius=te.closeButtonBorderRadius,ee.classList.remove("tvw-rounded-full")):(ee.style.borderRadius="",ee.classList.add("tvw-rounded-full")),te.closeButtonPaddingX?(ee.style.paddingLeft=te.closeButtonPaddingX,ee.style.paddingRight=te.closeButtonPaddingX):(ee.style.paddingLeft="",ee.style.paddingRight=""),te.closeButtonPaddingY?(ee.style.paddingTop=te.closeButtonPaddingY,ee.style.paddingBottom=te.closeButtonPaddingY):(ee.style.paddingTop="",ee.style.paddingBottom="");let Wt=(Wo=te.closeButtonIconName)!=null?Wo:"x",zt=(Po=te.closeButtonIconText)!=null?Po:"\xD7";ee.innerHTML="";let Ot=ie(Wt,"20px",te.closeButtonColor||"",2);Ot?ee.appendChild(Ot):ee.textContent=zt;let ct=(Ro=te.closeButtonTooltipText)!=null?Ro:"Close chat",Jt=(Ho=te.closeButtonShowTooltip)!=null?Ho:!0;if(ee.setAttribute("aria-label",ct),ve&&(ve._cleanupTooltip&&(ve._cleanupTooltip(),delete ve._cleanupTooltip),Jt&&ct)){let ke=null,St=()=>{if(ke||!ee)return;ke=g("div","tvw-clear-chat-tooltip"),ke.textContent=ct;let hs=g("div");hs.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(hs);let kn=ee.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${kn.left+kn.width/2}px`,ke.style.top=`${kn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},_t=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};ve.addEventListener("mouseenter",St),ve.addEventListener("mouseleave",_t),ee.addEventListener("focus",St),ee.addEventListener("blur",_t),ve._cleanupTooltip=()=>{_t(),ve&&(ve.removeEventListener("mouseenter",St),ve.removeEventListener("mouseleave",_t)),ee&&(ee.removeEventListener("focus",St),ee.removeEventListener("blur",_t))}}}let{clearChatButton:Z,clearChatButtonWrapper:je}=be;if(Z){let R=(Bo=te.clearChat)!=null?Bo:{},Me=(Fo=R.enabled)!=null?Fo:!0,Ze=(Oo=($o=e.layout)==null?void 0:$o.header)==null?void 0:Oo.showClearChat,ve=Ze!==void 0?Ze:Me,He=(No=R.placement)!=null?No:"inline";if(je){je.style.display=ve?"":"none";let{closeButtonWrapper:wt}=be;wt&&!wt.classList.contains("tvw-absolute")&&(ve?wt.classList.remove("tvw-ml-auto"):wt.classList.add("tvw-ml-auto"));let Wt=He==="top-right",zt=je.classList.contains("tvw-absolute");if(Wt!==zt&&ve){if(je.remove(),Wt)je.className="tvw-absolute tvw-top-4 tvw-z-50",je.style.right="48px",Re.style.position="relative",Re.appendChild(je);else{je.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",je.style.right="";let ct=Re.querySelector(".tvw-border-b-cw-divider"),Jt=be.closeButtonWrapper;ct&&Jt&&Jt.parentElement===ct?ct.insertBefore(je,Jt):ct&&ct.appendChild(je)}let Ot=be.closeButtonWrapper;Ot&&!Ot.classList.contains("tvw-absolute")&&(Wt?Ot.classList.add("tvw-ml-auto"):Ot.classList.remove("tvw-ml-auto"))}}if(ve){let wt=(Do=R.size)!=null?Do:"32px";Z.style.height=wt,Z.style.width=wt;let Wt=(jo=R.iconName)!=null?jo:"refresh-cw",zt=(_o=R.iconColor)!=null?_o:"";Z.innerHTML="";let Ot=ie(Wt,"20px",zt||"",2);if(Ot&&Z.appendChild(Ot),zt?(Z.style.color=zt,Z.classList.remove("tvw-text-cw-muted")):(Z.style.color="",Z.classList.add("tvw-text-cw-muted")),R.backgroundColor?(Z.style.backgroundColor=R.backgroundColor,Z.classList.remove("hover:tvw-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:tvw-bg-gray-100")),R.borderWidth||R.borderColor){let ke=R.borderWidth||"0px",St=R.borderColor||"transparent";Z.style.border=`${ke} solid ${St}`,Z.classList.remove("tvw-border-none")}else Z.style.border="",Z.classList.add("tvw-border-none");R.borderRadius?(Z.style.borderRadius=R.borderRadius,Z.classList.remove("tvw-rounded-full")):(Z.style.borderRadius="",Z.classList.add("tvw-rounded-full")),R.paddingX?(Z.style.paddingLeft=R.paddingX,Z.style.paddingRight=R.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),R.paddingY?(Z.style.paddingTop=R.paddingY,Z.style.paddingBottom=R.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let ct=(Vo=R.tooltipText)!=null?Vo:"Clear chat",Jt=(Uo=R.showTooltip)!=null?Uo:!0;if(Z.setAttribute("aria-label",ct),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),Jt&&ct)){let ke=null,St=()=>{if(ke||!Z)return;ke=g("div","tvw-clear-chat-tooltip"),ke.textContent=ct;let hs=g("div");hs.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(hs);let kn=Z.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${kn.left+kn.width/2}px`,ke.style.top=`${kn.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},_t=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};je.addEventListener("mouseenter",St),je.addEventListener("mouseleave",_t),Z.addEventListener("focus",St),Z.addEventListener("blur",_t),je._cleanupTooltip=()=>{_t(),je&&(je.removeEventListener("mouseenter",St),je.removeEventListener("mouseleave",_t)),Z&&(Z.removeEventListener("focus",St),Z.removeEventListener("blur",_t))}}}}let rn=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Xs],jt=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Jn.message,Jn.messageAndClick];b=Gs({parsers:rn,handlers:jt,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),z=la(e,b,le),M.updateConfig(e),xn(Ue,M.getMessages(),z),hn.render(e.suggestionChips,M,de,void 0,e.suggestionChipsConfig),es(),Rn(M.isStreaming());let tn=((qo=e.voiceRecognition)==null?void 0:qo.enabled)===!0,Mn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Os=((Jo=(zo=e.voiceRecognition)==null?void 0:zo.provider)==null?void 0:Jo.type)==="runtype";if(tn&&(Mn||Os))if(!F||!Qe){let R=Bs(e.voiceRecognition,e.sendButton);R&&(F=R.micButton,Qe=R.micButtonWrapper,Vt.insertBefore(Qe,at),F.addEventListener("click",Bn),F.disabled=M.isStreaming())}else{let R=(Ko=e.voiceRecognition)!=null?Ko:{},Me=(Yo=e.sendButton)!=null?Yo:{},Ze=(Xo=R.iconName)!=null?Xo:"mic",ve=(Go=Me.size)!=null?Go:"40px",He=(Zo=R.iconSize)!=null?Zo:ve,wt=parseFloat(He)||24;F.style.width=He,F.style.height=He,F.style.minWidth=He,F.style.minHeight=He;let Wt=(ei=(Qo=R.iconColor)!=null?Qo:Me.textColor)!=null?ei:"currentColor";F.innerHTML="";let zt=ie(Ze,wt,Wt,2);zt?F.appendChild(zt):F.textContent="\u{1F3A4}";let Ot=(ti=R.backgroundColor)!=null?ti:Me.backgroundColor;Ot?(F.style.backgroundColor=Ot,F.classList.remove("tvw-bg-cw-primary")):(F.style.backgroundColor="",F.classList.add("tvw-bg-cw-primary")),Wt?(F.style.color=Wt,F.classList.remove("tvw-text-white")):!Wt&&!Me.textColor&&(F.style.color="",F.classList.add("tvw-text-white")),R.borderWidth?(F.style.borderWidth=R.borderWidth,F.style.borderStyle="solid"):(F.style.borderWidth="",F.style.borderStyle=""),R.borderColor?F.style.borderColor=R.borderColor:F.style.borderColor="",R.paddingX?(F.style.paddingLeft=R.paddingX,F.style.paddingRight=R.paddingX):(F.style.paddingLeft="",F.style.paddingRight=""),R.paddingY?(F.style.paddingTop=R.paddingY,F.style.paddingBottom=R.paddingY):(F.style.paddingTop="",F.style.paddingBottom="");let ct=Qe==null?void 0:Qe.querySelector(".tvw-send-button-tooltip"),Jt=(ni=R.tooltipText)!=null?ni:"Start voice recognition";if(((si=R.showTooltip)!=null?si:!1)&&Jt)if(ct)ct.textContent=Jt,ct.style.display="";else{let St=document.createElement("div");St.className="tvw-send-button-tooltip",St.textContent=Jt,Qe==null||Qe.insertBefore(St,F)}else ct&&(ct.style.display="none");Qe.style.display="",F.disabled=M.isStreaming()}else F&&Qe&&(Qe.style.display="none",((oi=(ri=e.voiceRecognition)==null?void 0:ri.provider)==null?void 0:oi.type)==="runtype"?M.isVoiceActive()&&M.toggleVoice():qt&&en());if(((ii=e.attachments)==null?void 0:ii.enabled)===!0)if(!G||!N){let R=(ai=e.attachments)!=null?ai:{},Ze=(ci=((li=e.sendButton)!=null?li:{}).size)!=null?ci:"40px";$e||($e=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),$e.style.display="none",vt.insertBefore($e,de)),re||(re=document.createElement("input"),re.type="file",re.accept=((di=R.allowedTypes)!=null?di:vn).join(","),re.multiple=((ui=R.maxFiles)!=null?ui:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),vt.insertBefore(re,de)),G=g("div","tvw-send-button-wrapper"),N=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),N.type="button",N.setAttribute("aria-label",(pi=R.buttonTooltipText)!=null?pi:"Attach file");let ve=(gi=R.buttonIconName)!=null?gi:"paperclip",He=Ze,wt=parseFloat(He)||40,Wt=Math.round(wt*.6);N.style.width=He,N.style.height=He,N.style.minWidth=He,N.style.minHeight=He,N.style.fontSize="18px",N.style.lineHeight="1",N.style.backgroundColor="transparent",N.style.color="var(--cw-primary, #111827)",N.style.border="none",N.style.borderRadius="6px",N.style.transition="background-color 0.15s ease",N.addEventListener("mouseenter",()=>{N.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),N.addEventListener("mouseleave",()=>{N.style.backgroundColor="transparent"});let zt=ie(ve,Wt,"currentColor",1.5);zt?N.appendChild(zt):N.textContent="\u{1F4CE}",N.addEventListener("click",Jt=>{Jt.preventDefault(),re==null||re.click()}),G.appendChild(N);let Ot=(mi=R.buttonTooltipText)!=null?mi:"Attach file",ct=g("div","tvw-send-button-tooltip");ct.textContent=Ot,G.appendChild(ct),Mt.append(G),!oe&&re&&$e&&(oe=jn.fromConfig(R),oe.setPreviewsContainer($e),re.addEventListener("change",async()=>{oe&&(re!=null&&re.files)&&(await oe.handleFileSelect(re.files),re.value="")}))}else{G.style.display="";let R=(hi=e.attachments)!=null?hi:{};re&&(re.accept=((fi=R.allowedTypes)!=null?fi:vn).join(","),re.multiple=((wi=R.maxFiles)!=null?wi:4)>1),oe&&oe.updateConfig({allowedTypes:R.allowedTypes,maxFileSize:R.maxFileSize,maxFiles:R.maxFiles})}else G&&(G.style.display="none"),oe&&oe.clearAttachments();let pt=(vi=e.sendButton)!=null?vi:{},Fn=(yi=pt.useIcon)!=null?yi:!1,$n=(bi=pt.iconText)!=null?bi:"\u2191",Ur=pt.iconName,lr=(Ci=pt.tooltipText)!=null?Ci:"Send message",wa=(xi=pt.showTooltip)!=null?xi:!1,ps=(Si=pt.size)!=null?Si:"40px",Ns=pt.backgroundColor,on=pt.textColor;if(Fn){if(X.style.width=ps,X.style.height=ps,X.style.minWidth=ps,X.style.minHeight=ps,X.style.fontSize="18px",X.style.lineHeight="1",X.innerHTML="",Ur){let R=parseFloat(ps)||24,Me=on&&typeof on=="string"&&on.trim()?on.trim():"currentColor",Ze=ie(Ur,R,Me,2);Ze?(X.appendChild(Ze),X.style.color=Me):(X.textContent=$n,on?X.style.color=on:X.classList.add("tvw-text-white"))}else X.textContent=$n,on?X.style.color=on:X.classList.add("tvw-text-white");X.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Ns?(X.style.backgroundColor=Ns,X.classList.remove("tvw-bg-cw-primary")):X.classList.add("tvw-bg-cw-primary")}else X.textContent=(Ei=(Ai=e.copy)==null?void 0:Ai.sendButtonLabel)!=null?Ei:"Send",X.style.width="",X.style.height="",X.style.minWidth="",X.style.minHeight="",X.style.fontSize="",X.style.lineHeight="",X.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",Ns?(X.style.backgroundColor=Ns,X.classList.remove("tvw-bg-cw-accent")):X.classList.add("tvw-bg-cw-accent"),on?X.style.color=on:X.classList.add("tvw-text-white");pt.borderWidth?(X.style.borderWidth=pt.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),pt.borderColor?X.style.borderColor=pt.borderColor:X.style.borderColor="",pt.paddingX?(X.style.paddingLeft=pt.paddingX,X.style.paddingRight=pt.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),pt.paddingY?(X.style.paddingTop=pt.paddingY,X.style.paddingBottom=pt.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let gs=at==null?void 0:at.querySelector(".tvw-send-button-tooltip");if(wa&&lr)if(gs)gs.textContent=lr,gs.style.display="";else{let R=document.createElement("div");R.className="tvw-send-button-tooltip",R.textContent=lr,at==null||at.insertBefore(R,X)}else gs&&(gs.style.display="none");let ms=(Ti=e.statusIndicator)!=null?Ti:{},va=(Mi=ms.visible)!=null?Mi:!0;if(Tt.style.display=va?"":"none",M){let R=M.getStatus(),Me=Ze=>{var ve,He,wt,Wt;return Ze==="idle"?(ve=ms.idleText)!=null?ve:Rt.idle:Ze==="connecting"?(He=ms.connectingText)!=null?He:Rt.connecting:Ze==="connected"?(wt=ms.connectedText)!=null?wt:Rt.connected:Ze==="error"?(Wt=ms.errorText)!=null?Wt:Rt.error:Rt[Ze]};Tt.textContent=Me(R)}},open(){y&&nt(!0,"api")},close(){y&&nt(!1,"api")},toggle(){y&&nt(!I,"api")},clearChat(){M.clearMessages();try{localStorage.removeItem(Kn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Kn}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Kn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(f=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}a={},b.syncFromMetadata(),O==null||O.clear(),Q==null||Q.update()},setMessage(l){return!de||M.isStreaming()?!1:(!I&&y&&nt(!0,"system"),de.value=l,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(M.isStreaming())return!1;let p=(l==null?void 0:l.trim())||de.value.trim();return p?(!I&&y&&nt(!0,"system"),de.value="",de.style.height="auto",M.sendMessage(p),!0):!1},startVoiceRecognition(){var p,f;return M.isStreaming()?!1:((f=(p=e.voiceRecognition)==null?void 0:p.provider)==null?void 0:f.type)==="runtype"?(M.isVoiceActive()||(!I&&y&&nt(!0,"system"),Ee.manuallyDeactivated=!1,Ut(),M.toggleVoice().then(()=>{Ee.active=M.isVoiceActive(),Qt("user"),M.isVoiceActive()&&En()})),!0):qt?!0:rs()?(!I&&y&&nt(!0,"system"),Ee.manuallyDeactivated=!1,Ut(),An("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?M.isVoiceActive()?(M.toggleVoice().then(()=>{Ee.active=!1,Ee.manuallyDeactivated=!0,Ut(),Qt("user"),Tn()}),!0):!1:qt?(Ee.manuallyDeactivated=!0,Ut(),en("user"),!0):!1},injectMessage(l){return!I&&y&&nt(!0,"system"),M.injectMessage(l)},injectAssistantMessage(l){!I&&y&&nt(!0,"system");let p=M.injectAssistantMessage(l);return T&&(T=!1,B&&(clearTimeout(B),B=null),setTimeout(()=>{M&&!M.isStreaming()&&M.continueConversation()},100)),p},injectUserMessage(l){return!I&&y&&nt(!0,"system"),M.injectUserMessage(l)},injectSystemMessage(l){return!I&&y&&nt(!0,"system"),M.injectSystemMessage(l)},injectMessageBatch(l){return!I&&y&&nt(!0,"system"),M.injectMessageBatch(l)},injectTestMessage(l){!I&&y&&nt(!0,"system"),M.injectTestEvent(l)},async connectStream(l,p){return M.connectStream(l,p)},__pushEventStreamEvent(l){O&&O.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!j||!O||Ke()},hideEventStream(){ue&&ce()},isEventStreamVisible(){return ue},focusInput(){return y&&!I||!de?!1:(de.focus(),!0)},async resolveApproval(l,p){let A=M.getMessages().find(H=>{var P;return H.variant==="approval"&&((P=H.approval)==null?void 0:P.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return M.resolveApproval(A.approval,p)},getMessages(){return M.getMessages()},getStatus(){return M.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){d(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return y&&I},isVoiceActive(){return Ee.active},getState(){return{open:y&&I,launcherEnabled:y,voiceActive:Ee.active,streaming:M.isStreaming()}},showCSATFeedback(l){!I&&y&&nt(!0,"system");let p=Ue.querySelector(".tvw-feedback-container");p&&p.remove();let f=Hr({onSubmit:async(A,H)=>{var P;M.isClientTokenMode()&&await M.submitCSATFeedback(A,H),(P=l==null?void 0:l.onSubmit)==null||P.call(l,A,H)},onDismiss:l==null?void 0:l.onDismiss,...l});Ue.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!I&&y&&nt(!0,"system");let p=Ue.querySelector(".tvw-feedback-container");p&&p.remove();let f=Br({onSubmit:async(A,H)=>{var P;M.isClientTokenMode()&&await M.submitNPSFeedback(A,H),(P=l==null?void 0:l.onSubmit)==null||P.call(l,A,H)},onDismiss:l==null?void 0:l.onDismiss,...l});Ue.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return M.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return M.submitNPSFeedback(l,p)},destroy(){Ye.forEach(l=>l()),Ne.remove(),Xe==null||Xe.destroy(),Ge==null||Ge.remove(),sn&&ee.removeEventListener("click",sn)}};if((((Dt=r==null?void 0:r.debugTools)!=null?Dt:!1)||!!e.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:It,getMessages:It.getMessages,getStatus:It.getStatus,getMetadata:It.getPersistentMetadata,updateMetadata:It.updatePersistentMetadata,clearHistory:()=>It.clearChat(),setVoiceActive:f=>f?It.startVoiceRecognition():It.stopVoiceRecognition()};window.AgentWidgetBrowser=p,Ye.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),p=f=>{let A=f.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&It.focusInput()};if(window.addEventListener("persona:focusInput",p),Ye.push(()=>{window.removeEventListener("persona:focusInput",p)}),j){let f=H=>{let P=H.detail;(!(P!=null&&P.instanceId)||P.instanceId===l)&&It.showEventStream()},A=H=>{let P=H.detail;(!(P!=null&&P.instanceId)||P.instanceId===l)&&It.hideEventStream()};window.addEventListener("persona:showEventStream",f),window.addEventListener("persona:hideEventStream",A),Ye.push(()=>{window.removeEventListener("persona:showEventStream",f),window.removeEventListener("persona:hideEventStream",A)})}}let $t=Ml(e.persistState);if($t&&y){let l=kl($t.storage),p=`${$t.keyPrefix}widget-open`,f=`${$t.keyPrefix}widget-voice`,A=`${$t.keyPrefix}widget-voice-mode`;if(l){let H=((Xt=$t.persist)==null?void 0:Xt.openState)&&l.getItem(p)==="true",P=((Dr=$t.persist)==null?void 0:Dr.voiceState)&&l.getItem(f)==="true",q=((jr=$t.persist)==null?void 0:jr.voiceState)&&l.getItem(A)==="true";if(H&&setTimeout(()=>{It.open(),setTimeout(()=>{var ge;if(P||q)It.startVoiceRecognition();else if((ge=$t.persist)!=null&&ge.focusInput){let me=n.querySelector("textarea");me&&me.focus()}},100)},0),(_r=$t.persist)!=null&&_r.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Vr=$t.persist)!=null&&Vr.voiceState&&(s.on("voice:state",ge=>{l.setItem(f,ge.active?"true":"false")}),s.on("user:message",ge=>{l.setItem(A,ge.viaVoice?"true":"false")})),$t.clearOnChatClear){let ge=()=>{l.removeItem(p),l.removeItem(f),l.removeItem(A)},me=()=>ge();window.addEventListener("persona:clear-chat",me),Ye.push(()=>{window.removeEventListener("persona:clear-chat",me)})}}}return It};var Or={},Il=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},Ll=()=>{try{if(typeof Or!="undefined"&&Or.url)return new URL("../widget.css",Or.url).href}catch{}return null},ca=n=>{let t=Ll(),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)}},da=n=>{var c,v,d,m;let t=Il(n.target),r=document.createElement("div");r.className="persona-host";let e=(d=(v=(c=n.config)==null?void 0:c.launcher)==null?void 0:v.enabled)!=null?d:!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),ca(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),ca(r);t.id&&s.setAttribute("data-persona-instance",t.id);let a=$r(s,n.config,{debugTools:n.debugTools});(m=n.onReady)==null||m.call(n);let u={...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]=u),u};var ua={name:"@runtypelabs/persona",version:"1.47.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 Yn=ua.version;function gn(n){if(n!==void 0)return typeof n=="string"?n:Array.isArray(n)?`[${n.map(t=>t.toString()).join(", ")}]`:n.toString()}function Pl(n){if(n)return{getHeaders:gn(n.getHeaders),onFeedback:gn(n.onFeedback),onCopy:gn(n.onCopy),requestMiddleware:gn(n.requestMiddleware),actionHandlers:gn(n.actionHandlers),actionParsers:gn(n.actionParsers),postprocessMessage:gn(n.postprocessMessage),contextProviders:gn(n.contextProviders),streamParser:gn(n.streamParser)}}var pa=`({ 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 ya}from"marked";var ba=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
- }`,ga=`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 ya}from"marked";var ba=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
- }`,ma=`(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 ya}from"marked";var ba=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
- }`,ha=`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 ya}from"marked";var ba=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
- }`,Rl=`(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
- }`,Hl=`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 Bl(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 Zs(n){var t,r;return(r=(t=n.parserType)!=null?t:Bl(n.streamParser))!=null?r:"plain"}function Qs(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 er(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 tr(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 nr(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,u])=>{typeof u=="string"?r.push(`${t} ${a}: "${u}",`):typeof u=="boolean"&&r.push(`${t} ${a}: ${u},`)}),r.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([u])=>u!=="format")&&(r.push(`${t} timestamp: {`),Object.entries(i).forEach(([u,c])=>{u!=="format"&&(typeof c=="string"?r.push(`${t} ${u}: "${c}",`):typeof c=="boolean"&&r.push(`${t} ${u}: ${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 Nr(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 Fl(n,t="esm",r){let e={...n};delete e.postprocessMessage,delete e.initialMessages;let o=r?{...r,hooks:Pl(r.hooks)}:void 0;return t==="esm"?$l(e,o):t==="script-installer"?Dl(e):t==="script-advanced"?_l(e,o):t==="react-component"?Ol(e,o):t==="react-advanced"?Nl(e,o):jl(e,o)}function $l(n,t){let r=t==null?void 0:t.hooks,e=Zs(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(...Qs(n," ")),s.push(...er(n," ",r)),s.push(...tr(n," ")),s.push(...nr(n," ")),s.push(...Nr(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 Ol(n,t){let r=t==null?void 0:t.hooks,e=Zs(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(...Qs(n," ")),s.push(...er(n," ",r)),s.push(...tr(n," ")),s.push(...nr(n," ")),s.push(...Nr(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 Nl(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(...Qs(n," ")),e.push(...er(n," ",r)),e.push(...tr(n," ")),e.push(...nr(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(${Rl}),`)),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(` ${pa}`),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(` ${pa}`),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(` ${ma}`),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(` ${ma}`),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 fa(n){var o;let t=Zs(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,u])=>{a!=="render"&&(typeof u=="string"||typeof u=="boolean")&&(i[a]=u)}),Object.keys(i).length>0&&(s.header=i)}if(n.layout.messages){let i={};Object.entries(n.layout.messages).forEach(([a,u])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof u=="object"&&u!==null)i.avatar=u;else if(a==="timestamp"&&typeof u=="object"&&u!==null){let c={};Object.entries(u).forEach(([v,d])=>{v!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[v]=d)}),Object.keys(c).length>0&&(i.timestamp=c)}else(typeof u=="string"||typeof u=="boolean")&&(i[a]=u)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(e.layout=s)}return e}function Dl(n){let t=fa(n),r=JSON.stringify(t,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Yn}/dist/install.global.js" data-config='${r}'></script>`}function jl(n,t){let r=t==null?void 0:t.hooks,e=Zs(n),o=e!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Yn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Yn}/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(...Qs(n," ")),s.push(...er(n," ",r)),s.push(...tr(n," ")),s.push(...nr(n," ")),s.push(...Nr(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 _l(n,t){let r=t==null?void 0:t.hooks,e=fa(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@${Yn}/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(${Hl});`),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(` ${ga}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${ga}`),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(` ${ha}`),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(` ${ha}`),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 bu=da;export{On as AgentWidgetClient,ys as AgentWidgetSession,jn as AttachmentManager,ra as DEFAULT_DARK_THEME,sa as DEFAULT_LIGHT_THEME,it as DEFAULT_WIDGET_CONFIG,Yn as VERSION,_n as attachHeaderToContainer,xs as buildComposer,Vi as buildDefaultHeader,qi as buildExpandedHeader,yn as buildHeader,Cs as buildHeaderWithLayout,Ui as buildMinimalHeader,Ts as componentRegistry,Gs as createActionManager,$r as createAgentExperience,wr as createBestAvailableVoiceProvider,el as createBubbleWithLayout,Hr as createCSATFeedback,xl as createComponentMiddleware,Lr as createComponentStreamParser,xa as createDirectivePostprocessor,Ma as createFlexibleJsonStreamParser,Ba as createImagePart,pr as createJsonStreamParser,kr as createLocalStorageAdapter,Ds as createMarkdownProcessor,js as createMarkdownProcessorFromConfig,Gi as createMessageActions,Br as createNPSFeedback,dr as createPlainTextParser,ur as createRegexJsonParser,Ss as createStandardBubble,fr as createTextPart,Vn as createTypingIndicator,Dn as createVoiceProvider,gr as createXmlParser,bu as default,Jn as defaultActionHandlers,Xs as defaultJsonActionParser,Sa as directivePostprocessor,cr as escapeHtml,Rr as extractComponentDirectiveFromMessage,Fa as fileToImagePart,Nn as generateAssistantMessageId,Fl as generateCodeSnippet,La as generateMessageId,ws as generateUserMessageId,Pa as getDisplayText,zi as getHeaderLayout,Ha as getImageParts,Pr as hasComponentDirective,Ra as hasImages,yr as headerLayouts,da as initAgentWidget,Cl as isComponentDirectiveType,zs as isVoiceSupported,Ii as markdownPostprocessor,Tr as mergeWithDefaults,Wa as normalizeContent,Ys as pluginRegistry,Wr as renderComponentDirective,Xi as renderLoadingIndicatorWithFallback,$a 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