@runtypelabs/persona 3.21.2 → 3.22.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 (59) hide show
  1. package/README.md +67 -0
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-CWPIj66R.d.cts → types-BZVr1YOV.d.cts} +10 -0
  5. package/dist/animations/{types-CWPIj66R.d.ts → types-BZVr1YOV.d.ts} +10 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/index.cjs +50 -43
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +474 -6
  11. package/dist/index.d.ts +474 -6
  12. package/dist/index.global.js +98 -88
  13. package/dist/index.global.js.map +1 -1
  14. package/dist/index.js +48 -41
  15. package/dist/index.js.map +1 -1
  16. package/dist/smart-dom-reader.cjs +1875 -0
  17. package/dist/smart-dom-reader.d.cts +4521 -0
  18. package/dist/smart-dom-reader.d.ts +4521 -0
  19. package/dist/smart-dom-reader.js +1848 -0
  20. package/dist/theme-editor.cjs +2282 -90
  21. package/dist/theme-editor.d.cts +348 -1
  22. package/dist/theme-editor.d.ts +348 -1
  23. package/dist/theme-editor.js +2267 -90
  24. package/package.json +9 -2
  25. package/src/client.test.ts +165 -0
  26. package/src/client.ts +144 -23
  27. package/src/components/composer-parts.test.ts +34 -0
  28. package/src/components/composer-parts.ts +9 -6
  29. package/src/index.ts +26 -0
  30. package/src/session.test.ts +258 -0
  31. package/src/session.ts +886 -30
  32. package/src/session.webmcp.test.ts +815 -0
  33. package/src/smart-dom-reader.test.ts +135 -0
  34. package/src/smart-dom-reader.ts +135 -0
  35. package/src/theme-editor/color-utils.test.ts +59 -0
  36. package/src/theme-editor/color-utils.ts +38 -2
  37. package/src/theme-editor/index.ts +35 -0
  38. package/src/theme-editor/webmcp/coerce.test.ts +86 -0
  39. package/src/theme-editor/webmcp/coerce.ts +286 -0
  40. package/src/theme-editor/webmcp/index.ts +45 -0
  41. package/src/theme-editor/webmcp/summary.ts +324 -0
  42. package/src/theme-editor/webmcp/tools.test.ts +205 -0
  43. package/src/theme-editor/webmcp/tools.ts +795 -0
  44. package/src/theme-editor/webmcp/types.ts +87 -0
  45. package/src/types.ts +186 -0
  46. package/src/ui.composer-keyboard.test.ts +229 -0
  47. package/src/ui.ts +127 -5
  48. package/src/utils/composer-history.test.ts +128 -0
  49. package/src/utils/composer-history.ts +113 -0
  50. package/src/utils/message-fingerprint.test.ts +20 -0
  51. package/src/utils/message-fingerprint.ts +2 -0
  52. package/src/utils/smart-dom-adapter.test.ts +257 -0
  53. package/src/utils/smart-dom-adapter.ts +217 -0
  54. package/{LICENSE → src/vendor/smart-dom-reader/LICENSE} +2 -2
  55. package/src/vendor/smart-dom-reader/README.md +61 -0
  56. package/src/vendor/smart-dom-reader/index.d.ts +476 -0
  57. package/src/vendor/smart-dom-reader/index.js +1618 -0
  58. package/src/webmcp-bridge.test.ts +429 -0
  59. package/src/webmcp-bridge.ts +547 -0
package/dist/index.js CHANGED
@@ -1,11 +1,18 @@
1
- import{Marked as Yu}from"marked";var Zu=e=>{if(e)return e},ca=e=>{var o,s;let n=e==null?void 0:e.markedOptions,t=new Yu({gfm:(o=n==null?void 0:n.gfm)!=null?o:!0,breaks:(s=n==null?void 0:n.breaks)!=null?s:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=Zu(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},Fo=e=>e?ca({markedOptions:e.options,renderer:e.renderer}):ca(),em=ca(),Yd=e=>em(e),Oo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Zd=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Xd=e=>`%%FORM_PLACEHOLDER_${e}%%`,ep=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Xd(n.length);return n.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Xd(n.length);return n.push({token:s,type:o}),s}),t},tm=e=>{let n=Fo(e);return t=>{let r=[],o=ep(t,r),s=n(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Zd(i)}"></div>`;s=s.replace(d,u)}),s}},nm=e=>{let n=[],t=ep(e,n),r=Yd(t);return n.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Zd(s)}"></div>`;r=r.replace(a,d)}),r};import rm from"dompurify";var om={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},sm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,tp=()=>{let e=rm(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(n,t)=>{if(t.attrName==="src"||t.attrName==="href"){let r=t.attrValue;r.toLowerCase().startsWith("data:")&&!sm.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,om)},xs=e=>e===!1?null:typeof e=="function"?e:tp();import{parse as np,STR as rp,OBJ as op}from"partial-json";var da=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),$o=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)}},am=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},sp=e=>e.status==="complete"?am(e):e.status==="pending"?"Waiting":"",im=e=>{var o,s,a;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var ap=e=>e.status==="complete"?im(e):"Using tool...",pa=e=>{let n=e/1e3;return n<.1?"<0.1s":n>=10?`${Math.round(n)}s`:`${n.toFixed(1).replace(/\.0$/,"")}s`},Cs=e=>{var t,r,o;let n=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return pa(n)},ua=e=>{var t,r,o;let n=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return pa(n)},ai=(e,n,t)=>{var s;if(!n)return t;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=Cs(e);return n.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},ma=(e,n)=>{let t=e.replace(/\{toolName\}/g,n),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&vs(r,t.slice(s,a.index),[]),a[1]!==void 0?vs(r,a[1],["bold"]):a[2]!==void 0?vs(r,a[2],["italic"]):a[3]!==void 0&&vs(r,a[3],["dim"]),s=a.index+a[0].length;return s<t.length&&vs(r,t.slice(s),[]),r},vs=(e,n,t)=>{let r=n.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:t}),o<r.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},lm=()=>{let e=null,n=0,t=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
3
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(e=s),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},wo=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},ii=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},li=()=>{var n;let e=lm();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},ci=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let o=np(t,rp|op);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?da(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=da(o.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},cm=e=>{let n=null,t=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?da(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?da(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=t)return n!==null?{text:n,raw:s}:null;try{let i=np(s,rp|op),d=o(i);d!==null&&(n=d)}catch{}return t=s.length,{text:n||"",raw:s}},close:()=>{}}},di=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var ga=class{constructor(n,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=n,this.gapTimeoutMs=t}push(n,t){var s,a,i;let r=(i=(s=t==null?void 0:t.seq)!=null?s:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(n,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(n,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(n,t);return}let o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(r,{payloadType:n,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let n=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(n.payloadType,n.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let n=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of n)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);n.length>0&&(this.nextExpectedSeq=n[n.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var dm="https://api.runtype.com/v1/dispatch",fa="https://api.runtype.com";function pm(e){var s,a;let n=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[n];if(r)return`attachment.${r}`;let o=n.indexOf("/");if(o>0){let i=(a=(s=n.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var pi=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 um(e){switch(e){case"json":return ci;case"regex-json":return li;case"xml":return di;default:return ii}}var ip=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function mm(e,n){if(!e)return n;let t=e.trim(),r=n.trim();if(t.length===0)return n;if(r.length===0)return e;let o=ip(t);if(!ip(r))return e;if(!o||r===t||r.startsWith(t))return n;let a=wo(e);return wo(n)!==null&&a===null?n:e}var _o=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,o;this.apiUrl=(t=n.apiUrl)!=null?t:dm,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:um(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;let t=((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fa;return n==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let n=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fa}/v1/client/feedback`}async sendFeedback(n){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:n,comment:t})}async submitNPSFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var o,s,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let g=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:g}),g}let l=await this.buildPayload(n.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(pi).map(g=>{var C,x,T;return{id:g.id,role:g.role,content:(T=(x=(C=g.contentParts)!=null?C:g.llmContent)!=null?x:g.rawContent)!=null?T:g.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.signal});if(!f.ok){let g=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let x=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:x}),x}if(f.status===429){let x=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:x}),x}let C=new Error(g.error||"Failed to send message");throw t({type:"error",error:C}),C}if(!f.body){let g=new Error("No response body received");throw t({type:"error",error:g}),g}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&t({type:"error",error:l}),l}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||fa}/v1/agents/${n.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var i,d;let s=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,""))||fa}/resume`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(s,{method:"POST",headers:a,body:JSON.stringify({executionId:n,toolOutputs:t,streamResponse:(d=r==null?void 0:r.streamResponse)!=null?d:!0})})}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(pi).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let a=new Date(o.createdAt).getTime(),i=new Date(s.createdAt).getTime();return a-i}).map(o=>{var s,a,i;return{role:o.role,content:(i=(a=(s=o.contentParts)!=null?s:o.llmContent)!=null?a:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(r.context=o)}return r}async buildPayload(n){let r={messages:n.slice().filter(pi).sort((o,s)=>{let a=new Date(o.createdAt).getTime(),i=new Date(s.createdAt).getTime();return a-i}).map(o=>{var s,a,i;return{role:o.role,content:(i=(a=(s=o.contentParts)!=null?s:o.llmContent)!=null?a:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(r.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...r},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return r}async handleCustomSSEEvent(n,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let d=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return r.current=p,o(p),p},l=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,o(u)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,t,r){var Vt,vr,dr,je;let o=n.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=U=>{let Ce=U.reasoning?{...U.reasoning,chunks:[...U.reasoning.chunks]}:void 0,He=U.toolCall?{...U.toolCall,chunks:U.toolCall.chunks?[...U.toolCall.chunks]:void 0}:void 0,Be=U.tools?U.tools.map($e=>({...$e,chunks:$e.chunks?[...$e.chunks]:void 0})):void 0;return{...U,reasoning:Ce,toolCall:He,tools:Be}},p=U=>{t({type:"message",message:u(U)})},f=null,g=null,C={current:null},x={current:null},T=!1,A=new Map,k=new Map,B=new Map,D=new Map,L={lastId:null,byStep:new Map},S={lastId:null,byCall:new Map},F=(U,Ce,He="")=>`${U}::${Ce}::${He}`,$=(U,Ce)=>`${U}::${Ce}::`,j=(U,Ce,He,Be)=>{let $e=F(U,Ce,He),lt=B.get($e);if(lt)return lt;let et=He?`-${He}`:"",Ct={id:`nested-${U}-${Ce}${et}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...He?{partId:He}:{},agentMetadata:{executionId:Be,parentToolId:U,parentStepId:Ce}};return B.set($e,Ct),p(Ct),Ct},W=U=>{if(U==null)return null;try{return String(U)}catch{return null}},O=U=>{var Ce,He,Be,$e,lt;return W((lt=($e=(Be=(He=(Ce=U.stepId)!=null?Ce:U.step_id)!=null?He:U.step)!=null?Be:U.parentId)!=null?$e:U.flowStepId)!=null?lt:U.flow_step_id)},V=U=>{var Ce,He,Be,$e,lt,et,Ct;return W((Ct=(et=(lt=($e=(Be=(He=(Ce=U.callId)!=null?Ce:U.call_id)!=null?He:U.requestId)!=null?Be:U.request_id)!=null?$e:U.toolCallId)!=null?lt:U.tool_call_id)!=null?et:U.stepId)!=null?Ct:U.step_id)},oe=r,Pe=!1,ke=()=>{if(f)return f;let U;return!Pe&&oe?(U=oe,Pe=!0):oe&&x.current?U=`${oe}_${x.current}`:U=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:U,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},Ge=(U,Ce)=>{L.lastId=Ce,U&&L.byStep.set(U,Ce)},de=(U,Ce)=>{var lt;let He=(lt=U.reasoningId)!=null?lt:U.id,Be=O(U);if(He){let et=String(He);return Ge(Be,et),et}if(Be){let et=L.byStep.get(Be);if(et)return L.lastId=et,et}if(L.lastId&&!Ce)return L.lastId;if(!Ce)return null;let $e=`reason-${l()}`;return Ge(Be,$e),$e},pe=U=>{let Ce=A.get(U);if(Ce)return Ce;let He={id:`reason-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"streaming",chunks:[]}};return A.set(U,He),p(He),He},Me=(U,Ce)=>{S.lastId=Ce,U&&S.byCall.set(U,Ce)},_e=new Set,ee=new Map,Ae=new Set,Q=new Map,ae=U=>{if(!U)return!1;let Ce=U.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ce==="emit_artifact_markdown"||Ce==="emit_artifact_component"},Re=(U,Ce)=>{var lt;let He=(lt=U.toolId)!=null?lt:U.id,Be=V(U);if(He){let et=String(He);return Me(Be,et),et}if(Be){let et=S.byCall.get(Be);if(et)return S.lastId=et,et}if(S.lastId&&!Ce)return S.lastId;if(!Ce)return null;let $e=`tool-${l()}`;return Me(Be,$e),$e},ce=U=>{let Ce=k.get(U);if(Ce)return Ce;let He={id:`tool-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:U,status:"pending"}};return k.set(U,He),p(He),He},We=U=>{if(typeof U=="number"&&Number.isFinite(U))return U;if(typeof U=="string"){let Ce=Number(U);if(!Number.isNaN(Ce)&&Number.isFinite(Ce))return Ce;let He=Date.parse(U);if(!Number.isNaN(He))return He}return Date.now()},Ze=U=>{if(typeof U=="string")return U;if(U==null)return"";try{return JSON.stringify(U)}catch{return String(U)}},J=new Map,se=new Map,Fe=new Map,K=new Map,z=null,xe=(U,Ce,He)=>{var Ct;let Be=Fe.get(U);Be||(Be=[],Fe.set(U,Be));let $e=0,lt=Be.length;for(;$e<lt;){let Ut=$e+lt>>>1;Be[Ut].seq<Ce?$e=Ut+1:lt=Ut}((Ct=Be[$e])==null?void 0:Ct.seq)===Ce?Be[$e]={seq:Ce,text:He}:Be.splice($e,0,{seq:Ce,text:He});let et="";for(let Ut=0;Ut<Be.length;Ut++)et+=Be[Ut].text;return et},Oe=(U,Ce)=>{let He=Ze(Ce),Be=se.get(U.id),$e=mm(Be,He);U.rawContent=$e;let lt=J.get(U.id),et=me=>{var qe;let ct=(qe=U.content)!=null?qe:"";me.trim()!==""&&(ct.trim().length===0||me.startsWith(ct)||me.trimStart().startsWith(ct.trim()))&&(U.content=me)},Ct=()=>{var me;if(lt){let ct=(me=lt.close)==null?void 0:me.call(lt);ct instanceof Promise&&ct.catch(()=>{})}J.delete(U.id),se.delete(U.id),U.streaming=!1,p(U)};if(!lt){et(He),Ct();return}let Ut=wo($e);if(Ut!==null&&Ut.trim()!==""){et(Ut),Ct();return}let P=me=>{var It;let ct=typeof me=="string"?me:(It=me==null?void 0:me.text)!=null?It:null;if(ct!==null&&ct.trim()!=="")return ct;let qe=lt.getExtractedText();return qe!==null&&qe.trim()!==""?qe:He},fe;try{fe=lt.processChunk($e)}catch{et(He),Ct();return}if(fe instanceof Promise){fe.then(me=>{et(P(me)),Ct()}).catch(()=>{et(He),Ct()});return}et(P(fe)),Ct()},ne=[],Se=!1,be,Ht=()=>{Se||(Se=!0,queueMicrotask(()=>{Se=!1,be()}))},Le=new ga((U,Ce)=>{ne.push({payloadType:U,payload:Ce}),Ht()}),te=null,sn=new Map,Nt=(Vt=this.config.iterationDisplay)!=null?Vt:"separate";for(be=()=>{var U,Ce,He,Be,$e,lt,et,Ct,Ut,P,fe,me,ct,qe,It,an,wt,bt,Mt,pt,Jt,Cr,jn,Br,vt,pr,ur,wr,Yn,mt,ao,mr,io,Sn,ko,Dr,Ar,yt,In,Wn,hn,kt,Un,qn,Rn,Nr,Sr,Fr,Hn,Wt,yn,zn,Or,Er,$r,gr,Bn,Zn,gt,Kt,Gt,Dn,_r,Vn,er,Nn,_,le,Fn,tr,fr,ns,nr,rr,or,Tr,lo,qs,rs,zs,Lo,ut,os,Jn,En,Vs,Js,Po,Mr,Ks,co,ss,kr,as,jr,Ur,Gs,Qs,si,po,qr,Xs,is,zr,Ys,ls,Vr,cs,Zs,Lr,ea,Jr,Rt,Io,Wo,ds,hr,ta,ps,us,ms,gs,bn,On,Pr,tt,fs,uo,sr,na,Ro,Ho,mo,Kr,ra,oa,ar,go;for(let Bo=0;Bo<ne.length;Bo++){let Ve=ne[Bo].payloadType,v=ne[Bo].payload;if(Ve==="reason_start"){let R=(U=de(v,!0))!=null?U:`reason-${l()}`,w=pe(R);w.reasoning=(Ce=w.reasoning)!=null?Ce:{id:R,status:"streaming",chunks:[]},w.reasoning.startedAt=(Be=w.reasoning.startedAt)!=null?Be:We((He=v.startedAt)!=null?He:v.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",p(w)}else if(Ve==="reason_delta"||Ve==="reason_chunk"){let R=(lt=($e=de(v,!1))!=null?$e:de(v,!0))!=null?lt:`reason-${l()}`,w=pe(R);w.reasoning=(et=w.reasoning)!=null?et:{id:R,status:"streaming",chunks:[]},w.reasoning.startedAt=(Ut=w.reasoning.startedAt)!=null?Ut:We((Ct=v.startedAt)!=null?Ct:v.timestamp);let G=(me=(fe=(P=v.reasoningText)!=null?P:v.text)!=null?fe:v.delta)!=null?me:"";if(G&&v.hidden!==!0){let re=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(re!==void 0){let X=xe(R,re,String(G));w.reasoning.chunks=[X]}else w.reasoning.chunks.push(String(G))}if(w.reasoning.status=v.done?"complete":"streaming",v.done){w.reasoning.completedAt=We((ct=v.completedAt)!=null?ct:v.timestamp);let re=(qe=w.reasoning.startedAt)!=null?qe:Date.now();w.reasoning.durationMs=Math.max(0,((It=w.reasoning.completedAt)!=null?It:Date.now())-re)}w.streaming=w.reasoning.status!=="complete",p(w)}else if(Ve==="reason_complete"){let R=(wt=(an=de(v,!1))!=null?an:de(v,!0))!=null?wt:`reason-${l()}`,w=A.get(R);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=We((bt=v.completedAt)!=null?bt:v.timestamp);let re=(Mt=w.reasoning.startedAt)!=null?Mt:Date.now();w.reasoning.durationMs=Math.max(0,((pt=w.reasoning.completedAt)!=null?pt:Date.now())-re),w.streaming=!1,p(w)}let G=O(v);G&&L.byStep.delete(G)}else if(Ve==="tool_start"){let R=(Jt=Re(v,!0))!=null?Jt:`tool-${l()}`,w=(Cr=v.toolName)!=null?Cr:v.name;if(ae(w)){_e.add(R);continue}let G=ce(R),re=(jn=G.toolCall)!=null?jn:{id:R,status:"pending"};re.name=w!=null?w:re.name,re.status="running",v.args!==void 0?re.args=v.args:v.parameters!==void 0&&(re.args=v.parameters),re.startedAt=(vt=re.startedAt)!=null?vt:We((Br=v.startedAt)!=null?Br:v.timestamp),re.completedAt=void 0,re.durationMs=void 0,G.toolCall=re,G.streaming=!0;let X=v.agentContext;(X||v.executionId)&&(G.agentMetadata={executionId:(pr=X==null?void 0:X.executionId)!=null?pr:v.executionId,iteration:(ur=X==null?void 0:X.iteration)!=null?ur:v.iteration}),p(G)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let R=(Yn=(wr=Re(v,!1))!=null?wr:Re(v,!0))!=null?Yn:`tool-${l()}`;if(_e.has(R))continue;let w=ce(R),G=(mt=w.toolCall)!=null?mt:{id:R,status:"running"};G.startedAt=(mr=G.startedAt)!=null?mr:We((ao=v.startedAt)!=null?ao:v.timestamp);let re=(ko=(Sn=(io=v.text)!=null?io:v.delta)!=null?Sn:v.message)!=null?ko:"";re&&(G.chunks=(Dr=G.chunks)!=null?Dr:[],G.chunks.push(String(re))),G.status="running",w.toolCall=G,w.streaming=!0;let X=v.agentContext;(X||v.executionId)&&(w.agentMetadata=(In=w.agentMetadata)!=null?In:{executionId:(Ar=X==null?void 0:X.executionId)!=null?Ar:v.executionId,iteration:(yt=X==null?void 0:X.iteration)!=null?yt:v.iteration}),p(w)}else if(Ve==="tool_complete"){let R=(hn=(Wn=Re(v,!1))!=null?Wn:Re(v,!0))!=null?hn:`tool-${l()}`;if(_e.has(R)){_e.delete(R);continue}let w=ce(R),G=(kt=w.toolCall)!=null?kt:{id:R,status:"running"};G.status="complete",v.result!==void 0&&(G.result=v.result),typeof v.duration=="number"&&(G.duration=v.duration),G.completedAt=We((Un=v.completedAt)!=null?Un:v.timestamp);let re=(qn=v.duration)!=null?qn:v.executionTime;if(typeof re=="number")G.durationMs=re;else{let De=(Rn=G.startedAt)!=null?Rn:Date.now();G.durationMs=Math.max(0,((Nr=G.completedAt)!=null?Nr:Date.now())-De)}w.toolCall=G,w.streaming=!1;let X=v.agentContext;(X||v.executionId)&&(w.agentMetadata=(Hn=w.agentMetadata)!=null?Hn:{executionId:(Sr=X==null?void 0:X.executionId)!=null?Sr:v.executionId,iteration:(Fr=X==null?void 0:X.iteration)!=null?Fr:v.iteration}),p(w);let Je=V(v);Je&&S.byCall.delete(Je)}else if(Ve==="step_await"&&v.awaitReason==="local_tool_required"&&v.toolName){let R=(Wt=v.toolId)!=null?Wt:`local-${l()}`,w=ce(R),G=(yn=w.toolCall)!=null?yn:{id:R,status:"pending"};G.name=v.toolName,G.args=v.parameters,G.status="complete",G.chunks=(zn=G.chunks)!=null?zn:[],G.startedAt=(Er=G.startedAt)!=null?Er:We((Or=v.startedAt)!=null?Or:v.timestamp),G.completedAt=($r=G.completedAt)!=null?$r:G.startedAt,w.toolCall=G,w.streaming=!1,w.agentMetadata={...w.agentMetadata,executionId:(Bn=v.executionId)!=null?Bn:(gr=w.agentMetadata)==null?void 0:gr.executionId,awaitingLocalTool:!0},p(w)}else if(Ve==="text_start"){if((Zn=v.toolContext)!=null&&Zn.toolId)continue;let R=v.partId;if(R!==void 0&&x.current!==null&&R!==x.current){let w=f;w&&(w.streaming=!1,p(w),z=w,f=null,T=!0)}R!==void 0&&(x.current=R)}else if(Ve==="text_end"){if((gt=v.toolContext)!=null&&gt.toolId)continue;let R=f;R&&(R.streaming=!1,p(R),z=R,f=null,T=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let R=v.stepType,w=v.executionType;if(R==="tool"||w==="context")continue;let G=v.toolContext;if(G!=null&&G.toolId){let De=String((Gt=(Kt=v.id)!=null?Kt:G.stepId)!=null?Gt:`step-${l()}`),nt=v.partId!==void 0&&v.partId!==null?String(v.partId):"",Xe=`${G.toolId}::${De}`,St=D.get(Xe);if(nt!==""&&St!==void 0&&St!==""&&St!==nt){let ft=B.get(F(G.toolId,De,St));ft&&ft.streaming!==!1&&(ft.streaming=!1,p(ft))}nt!==""&&D.set(Xe,nt);let Lt=j(G.toolId,De,nt,G.executionId),Yt=(er=(Vn=(_r=(Dn=v.text)!=null?Dn:v.delta)!=null?_r:v.content)!=null?Vn:v.chunk)!=null?er:"";Yt&&(Lt.content+=String(Yt),Lt.streaming=!0,p(Lt)),v.isComplete&&(Lt.streaming=!1,p(Lt));continue}let re=v.partId;if(re!==void 0&&x.current!==null&&re!==x.current){let De=f;De&&(De.streaming=!1,p(De),z=De,f=null,T=!0)}re!==void 0&&(x.current=re);let X=re!==void 0&&(Nn=K.get(re))!=null?Nn:ke();re!==void 0&&(X.partId||(X.partId=re),K.set(re,X));let Je=(tr=(Fn=(le=(_=v.text)!=null?_:v.delta)!=null?le:v.content)!=null?Fn:v.chunk)!=null?tr:"";if(Je){let De=typeof v.seq=="number"?v.seq:void 0,nt=re!=null?re:X.id,Xe=De!==void 0?xe(nt,De,String(Je)):((fr=se.get(X.id))!=null?fr:"")+Je;X.rawContent=Xe,J.has(X.id)||J.set(X.id,this.createStreamParser());let St=J.get(X.id),Lt=Xe.trim().startsWith("{")||Xe.trim().startsWith("[");if(Lt&&se.set(X.id,Xe),St.__isPlainTextParser===!0){X.content=De!==void 0?Xe:X.content+Je,se.delete(X.id),J.delete(X.id),X.rawContent=void 0,p(X);continue}let ft=St.processChunk(Xe);if(ft instanceof Promise)ft.then(Et=>{var pn;let tn=typeof Et=="string"?Et:(pn=Et==null?void 0:Et.text)!=null?pn:null;if(tn!==null&&tn.trim()!=="")X.content=tn,p(X);else if(!Lt&&!Xe.trim().startsWith("<")){let ln=f,Ft=ln&&ln.id===X.id?ln:X;Ft.id===X.id&&(Ft.content=De!==void 0?Xe:Ft.content+Je,se.delete(Ft.id),J.delete(Ft.id),Ft.rawContent=void 0,p(Ft))}}).catch(()=>{X.content=De!==void 0?Xe:X.content+Je,se.delete(X.id),J.delete(X.id),X.rawContent=void 0,p(X)});else{let Et=typeof ft=="string"?ft:(ns=ft==null?void 0:ft.text)!=null?ns:null;Et!==null&&Et.trim()!==""?(X.content=Et,p(X)):!Lt&&!Xe.trim().startsWith("<")&&(X.content=De!==void 0?Xe:X.content+Je,se.delete(X.id),J.delete(X.id),X.rawContent=void 0,p(X))}}if(v.isComplete){let De=(rr=(nr=v.result)==null?void 0:nr.response)!=null?rr:X.content;if(De){let nt=se.get(X.id),Xe=nt!=null?nt:Ze(De);X.rawContent=Xe;let St=J.get(X.id),Lt=null,Yt=!1;if(St&&(Lt=St.getExtractedText(),Lt===null&&(Lt=wo(Xe)),Lt===null)){let ft=St.processChunk(Xe);ft instanceof Promise?(Yt=!0,ft.then(Et=>{var pn;let tn=typeof Et=="string"?Et:(pn=Et==null?void 0:Et.text)!=null?pn:null;if(tn!==null){let ln=f;ln&&ln.id===X.id&&(ln.content=tn,ln.streaming=!1,J.delete(ln.id),se.delete(ln.id),p(ln))}})):Lt=typeof ft=="string"?ft:(or=ft==null?void 0:ft.text)!=null?or:null}if(!Yt){Lt!==null&&Lt.trim()!==""?X.content=Lt:se.has(X.id)||(X.content=Ze(De));let ft=J.get(X.id);if(ft){let Et=(Tr=ft.close)==null?void 0:Tr.call(ft);Et instanceof Promise&&Et.catch(()=>{}),J.delete(X.id)}se.delete(X.id),X.streaming=!1,p(X)}}}}else if(Ve==="step_complete"){let R=v.stepType,w=v.executionType;if(R==="tool"||w==="context")continue;let G=v.toolContext;if(G!=null&&G.toolId){let De=String((qs=(lo=v.id)!=null?lo:G.stepId)!=null?qs:"");if(De){let nt=$(G.toolId,De);for(let[Xe,St]of B)Xe.startsWith(nt)&&St.streaming!==!1&&(St.streaming=!1,p(St));D.delete(`${G.toolId}::${De}`)}continue}let re=v.stopReason;if(T){if(f!==null){let Xe=f;re&&(Xe.stopReason=re),J.delete(Xe.id),se.delete(Xe.id),Xe.streaming!==!1&&(Xe.streaming=!1,p(Xe))}let De=(rs=v.result)==null?void 0:rs.response,nt=z;nt&&(re&&(nt.stopReason=re),De!=null?Oe(nt,De):(J.delete(nt.id),se.delete(nt.id))),z=null;continue}let X=(zs=v.result)==null?void 0:zs.response,Je=ke();if(re&&(Je.stopReason=re),X!=null){let De=J.get(Je.id),nt=!1,Xe=!1;if(De){let St=De.getExtractedText(),Lt=se.get(Je.id),Yt=Lt!=null?Lt:Ze(X);if(Je.rawContent=Yt,St!==null&&St.trim()!=="")Je.content=St,nt=!0;else{let ft=wo(Yt);if(ft!==null)Je.content=ft,nt=!0;else{let Et=De.processChunk(Yt);if(Et instanceof Promise)Xe=!0,Et.then(tn=>{var ln;let pn=typeof tn=="string"?tn:(ln=tn==null?void 0:tn.text)!=null?ln:null;if(pn!==null&&pn.trim()!==""){let Ft=f;Ft&&Ft.id===Je.id&&(Ft.content=pn,Ft.streaming=!1,J.delete(Ft.id),se.delete(Ft.id),p(Ft))}else{let Ft=De.getExtractedText(),Tn=f;Tn&&Tn.id===Je.id&&(Ft!==null&&Ft.trim()!==""?Tn.content=Ft:se.has(Tn.id)||(Tn.content=Ze(X)),Tn.streaming=!1,J.delete(Tn.id),se.delete(Tn.id),p(Tn))}});else{let tn=typeof Et=="string"?Et:(Lo=Et==null?void 0:Et.text)!=null?Lo:null;if(tn!==null&&tn.trim()!=="")Je.content=tn,nt=!0;else{let pn=De.getExtractedText();pn!==null&&pn.trim()!==""&&(Je.content=pn,nt=!0)}}}}}if(!Xe){if(!Je.rawContent){let St=se.get(Je.id);Je.rawContent=St!=null?St:Ze(X)}if(!nt&&!se.has(Je.id)&&(Je.content=Ze(X)),De){let St=(ut=De.close)==null?void 0:ut.call(De);St instanceof Promise&&St.catch(()=>{})}J.delete(Je.id),se.delete(Je.id),Je.streaming=!1,p(Je)}}else J.delete(Je.id),se.delete(Je.id),Je.streaming=!1,p(Je)}else if(Ve==="flow_complete"){let R=(os=v.result)==null?void 0:os.response;if(T){if(f!==null){let w=f;J.delete(w.id),se.delete(w.id),w.streaming!==!1&&(w.streaming=!1,p(w))}}else if(R!=null){let w=ke(),G=se.get(w.id),re=G!=null?G:Ze(R);w.rawContent=re;let X=Ze(R),Je=J.get(w.id);if(Je){let Xe=wo(re);if(Xe!==null)X=Xe;else{let St=Je.processChunk(re);St instanceof Promise&&St.then(Yt=>{var Et;let ft=typeof Yt=="string"?Yt:(Et=Yt==null?void 0:Yt.text)!=null?Et:null;ft!==null&&(w.content=ft,w.streaming=!1,p(w))});let Lt=Je.getExtractedText();Lt!==null&&(X=Lt)}}J.delete(w.id),se.delete(w.id);let De=X!==w.content,nt=w.streaming!==!1;De&&(w.content=X),w.streaming=!1,(De||nt)&&p(w)}else if(f!==null){let w=f;J.delete(w.id),se.delete(w.id),w.streaming!==!1&&(w.streaming=!1,p(w))}t({type:"status",status:"idle"})}else if(Ve==="agent_start")te={executionId:v.executionId,agentId:(Jn=v.agentId)!=null?Jn:"virtual",agentName:(En=v.agentName)!=null?En:"",status:"running",currentIteration:0,maxTurns:(Vs=v.maxTurns)!=null?Vs:1,startedAt:We(v.startedAt)};else if(Ve==="agent_iteration_start"){if(te&&(te.currentIteration=v.iteration),Nt==="separate"&&v.iteration>1){let R=f;R&&(R.streaming=!1,p(R),sn.set(v.iteration-1,R),f=null)}}else if(Ve==="agent_turn_start")g=null;else if(Ve==="agent_turn_delta"){if(v.contentType==="text"){let R=ke();R.content+=(Js=v.delta)!=null?Js:"",R.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:v.turnId,agentName:te==null?void 0:te.agentName},g=R,p(R)}else if(v.contentType==="thinking"){let R=(Po=v.turnId)!=null?Po:`agent-think-${v.iteration}`,w=pe(R);w.reasoning=(Mr=w.reasoning)!=null?Mr:{id:R,status:"streaming",chunks:[]},w.reasoning.chunks.push((Ks=v.delta)!=null?Ks:""),w.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:v.turnId},p(w)}else if(v.contentType==="tool_input"){let R=(co=v.toolCallId)!=null?co:S.lastId;if(R){let w=k.get(R);w!=null&&w.toolCall&&(w.toolCall.chunks=(ss=w.toolCall.chunks)!=null?ss:[],w.toolCall.chunks.push((kr=v.delta)!=null?kr:""),p(w))}}}else if(Ve==="agent_turn_complete"){let R=v.turnId;if(R){let re=A.get(R);if(re!=null&&re.reasoning){re.reasoning.status="complete",re.reasoning.completedAt=We(v.completedAt);let X=(as=re.reasoning.startedAt)!=null?as:Date.now();re.reasoning.durationMs=Math.max(0,((jr=re.reasoning.completedAt)!=null?jr:Date.now())-X),re.streaming=!1,p(re)}}let w=v.stopReason,G=f!=null?f:g;if(w&&G!==null){let re=v.turnId;(!re||((Ur=G.agentMetadata)==null?void 0:Ur.turnId)===re)&&(G.stopReason=w,p(G))}}else if(Ve==="agent_tool_start"){f&&(f.streaming=!1,p(f),f=null);let R=(Gs=v.toolCallId)!=null?Gs:`agent-tool-${l()}`;Me(V(v),R);let w=ce(R),G=(Qs=w.toolCall)!=null?Qs:{id:R,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};G.name=(po=(si=v.toolName)!=null?si:v.name)!=null?po:G.name,G.status="running",v.parameters!==void 0&&(G.args=v.parameters),G.startedAt=We((qr=v.startedAt)!=null?qr:v.timestamp),w.toolCall=G,w.streaming=!0,w.agentMetadata={executionId:v.executionId,iteration:v.iteration},p(w)}else if(Ve==="agent_tool_delta"){let R=(Xs=v.toolCallId)!=null?Xs:S.lastId;if(R){let w=(is=k.get(R))!=null?is:ce(R);w.toolCall&&(w.toolCall.chunks=(zr=w.toolCall.chunks)!=null?zr:[],w.toolCall.chunks.push((Ys=v.delta)!=null?Ys:""),w.toolCall.status="running",w.streaming=!0,p(w))}}else if(Ve==="agent_tool_complete"){let R=(ls=v.toolCallId)!=null?ls:S.lastId;if(R){let w=(Vr=k.get(R))!=null?Vr:ce(R);if(w.toolCall){w.toolCall.status="complete",v.result!==void 0&&(w.toolCall.result=v.result),typeof v.executionTime=="number"&&(w.toolCall.durationMs=v.executionTime),w.toolCall.completedAt=We((cs=v.completedAt)!=null?cs:v.timestamp),w.streaming=!1,p(w);let G=V(v);G&&S.byCall.delete(G)}}}else if(Ve==="agent_media"){let R=Array.isArray(v.media)?v.media:[],w=[];for(let G of R){if(!G||typeof G!="object")continue;let re=G,X=typeof re.type=="string"?re.type:void 0,Je=typeof re.mediaType=="string"?re.mediaType.toLowerCase():"",De=null,nt="";if(X==="media"){let Xe=typeof re.data=="string"?re.data:void 0;if(!Xe)continue;nt=Je.length>0?Je:"application/octet-stream",De=`data:${nt};base64,${Xe}`}else if(X==="image-url"){let Xe=typeof re.url=="string"?re.url:void 0;if(!Xe)continue;nt=Je,De=Xe}else if(X==="file-url"){let Xe=typeof re.url=="string"?re.url:void 0;if(!Xe)continue;nt=Je,De=Xe}else continue;if(De)if(X==="image-url"||nt.startsWith("image/"))w.push({type:"image",image:De,...nt?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))w.push({type:"audio",audio:De,mimeType:nt});else if(nt.startsWith("video/"))w.push({type:"video",video:De,mimeType:nt});else{let Xe=nt||"application/octet-stream";w.push({type:"file",data:De,mimeType:Xe,filename:pm(Xe)})}}if(w.length>0){let G=l(),re=v.toolCallId,Je={id:`agent-media-${typeof re=="string"&&re.length>0?`${re}-${G}`:String(G)}`,role:"assistant",content:"",contentParts:w,createdAt:new Date().toISOString(),streaming:!1,sequence:G,agentMetadata:{executionId:v.executionId,iteration:v.iteration}};p(Je);let De=f;De&&(De.streaming=!1,p(De)),f=null,C.current=null}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let R=`agent-reflection-${v.executionId}-${v.iteration}`,w={id:R,role:"assistant",content:(Zs=v.reflection)!=null?Zs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:R,status:"complete",chunks:[(Lr=v.reflection)!=null?Lr:""]},agentMetadata:{executionId:v.executionId,iteration:v.iteration}};p(w)}else if(Ve==="agent_complete"){te&&(te.status=v.success?"complete":"error",te.completedAt=We(v.completedAt),te.stopReason=v.stopReason);let R=f;R&&(R.streaming=!1,p(R)),t({type:"status",status:"idle"})}else if(Ve==="agent_error"){let R=typeof v.error=="string"?v.error:(Jr=(ea=v.error)==null?void 0:ea.message)!=null?Jr:"Agent execution error";v.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",R):t({type:"error",error:new Error(R)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let R=(Rt=v.approvalId)!=null?Rt:`approval-${l()}`,w={id:`approval-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:R,status:"pending",agentId:(Io=te==null?void 0:te.agentId)!=null?Io:"virtual",executionId:(ds=(Wo=v.executionId)!=null?Wo:te==null?void 0:te.executionId)!=null?ds:"",toolName:(hr=v.toolName)!=null?hr:"",toolType:v.toolType,description:(ps=v.description)!=null?ps:`Execute ${(ta=v.toolName)!=null?ta:"tool"}`,parameters:v.parameters}};p(w)}else if(Ve==="step_await"&&v.awaitReason==="approval_required"){let R=(us=v.approvalId)!=null?us:`approval-${l()}`,w={id:`approval-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:R,status:"pending",agentId:(ms=te==null?void 0:te.agentId)!=null?ms:"virtual",executionId:(bn=(gs=v.executionId)!=null?gs:te==null?void 0:te.executionId)!=null?bn:"",toolName:(On=v.toolName)!=null?On:"",toolType:v.toolType,description:(tt=v.description)!=null?tt:`Execute ${(Pr=v.toolName)!=null?Pr:"tool"}`,parameters:v.parameters}};p(w)}else if(Ve==="agent_approval_complete"){let R=v.approvalId;if(R){let G={id:`approval-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:R,status:(fs=v.decision)!=null?fs:"approved",agentId:(uo=te==null?void 0:te.agentId)!=null?uo:"virtual",executionId:(na=(sr=v.executionId)!=null?sr:te==null?void 0:te.executionId)!=null?na:"",toolName:(Ro=v.toolName)!=null?Ro:"",description:(Ho=v.description)!=null?Ho:"",resolvedAt:Date.now()}};p(G)}}else if(Ve==="artifact_start"||Ve==="artifact_delta"||Ve==="artifact_update"||Ve==="artifact_complete"){if(Ve==="artifact_start"){let R=v.artifactType,w=String(v.id),G=typeof v.title=="string"?v.title:void 0;if(t({type:"artifact_start",id:w,artifactType:R,title:G,component:typeof v.component=="string"?v.component:void 0}),Q.set(w,{markdown:"",title:G}),!Ae.has(w)){Ae.add(w);let re={id:`artifact-ref-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:w,title:G,artifactType:R,status:"streaming"}})};ee.set(w,re),p(re)}}else if(Ve==="artifact_delta"){let R=String(v.id),w=typeof v.delta=="string"?v.delta:String((mo=v.delta)!=null?mo:"");t({type:"artifact_delta",id:R,artDelta:w});let G=Q.get(R);G&&(G.markdown+=w)}else if(Ve==="artifact_update"){let R=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};t({type:"artifact_update",id:String(v.id),props:R,component:typeof v.component=="string"?v.component:void 0})}else if(Ve==="artifact_complete"){let R=String(v.id);t({type:"artifact_complete",id:R});let w=ee.get(R);if(w){w.streaming=!1;try{let G=JSON.parse((Kr=w.rawContent)!=null?Kr:"{}");if(G.props){G.props.status="complete";let re=Q.get(R);re!=null&&re.markdown&&(G.props.markdown=re.markdown)}w.rawContent=JSON.stringify(G)}catch{}Q.delete(R),p(w),ee.delete(R)}}}else if(Ve==="transcript_insert"){let R=v.message;if(!R||typeof R!="object")continue;let w=String((ra=R.id)!=null?ra:`msg-${l()}`),G=R.role,X={id:w,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof R.content=="string"?R.content:"",rawContent:typeof R.rawContent=="string"?R.rawContent:void 0,createdAt:typeof R.createdAt=="string"?R.createdAt:new Date().toISOString(),streaming:R.streaming===!0,...typeof R.variant=="string"?{variant:R.variant}:{},sequence:l()};if(p(X),X.rawContent)try{let Je=JSON.parse(X.rawContent),De=(oa=Je==null?void 0:Je.props)==null?void 0:oa.artifactId;typeof De=="string"&&Ae.add(De)}catch{}f=null,C.current=null,J.delete(w),se.delete(w)}else if(Ve==="error"||Ve==="step_error"||Ve==="dispatch_error"||Ve==="flow_error"){let R=null;if(v.error instanceof Error)R=v.error;else if(Ve==="dispatch_error"){let w=(ar=v.message)!=null?ar:v.error;w!=null&&w!==""&&(R=new Error(String(w)))}else if(Ve==="step_error"||Ve==="flow_error"){let w=v.error;typeof w=="string"&&w!==""?R=new Error(w):w!=null&&typeof w=="object"&&"message"in w&&(R=new Error(String((go=w.message)!=null?go:w)))}else Ve==="error"&&v.error!=null&&v.error!==""&&(R=new Error(String(v.error)));if(R){t({type:"error",error:R});let w=f;w&&w.streaming&&(w.streaming=!1,p(w)),t({type:"status",status:"idle"})}}}}}ne.length=0};;){let{done:U,value:Ce}=await o.read();if(U)break;a+=s.decode(Ce,{stream:!0});let He=a.split(`
1
+ import{Marked as ym}from"marked";var bm=e=>{if(e)return e},fa=e=>{var s,o;let n=e==null?void 0:e.markedOptions,t=new ym({gfm:(s=n==null?void 0:n.gfm)!=null?s:!0,breaks:(o=n==null?void 0:n.breaks)!=null?o:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=bm(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},Oo=e=>e?fa({markedOptions:e.options,renderer:e.renderer}):fa(),xm=fa(),gp=e=>xm(e),Fo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),fp=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),mp=e=>`%%FORM_PLACEHOLDER_${e}%%`,hp=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=mp(n.length);return n.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=mp(n.length);return n.push({token:o,type:s}),o}),t},vm=e=>{let n=Oo(e);return t=>{let r=[],s=hp(t,r),o=n(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${fp(i)}"></div>`;o=o.replace(d,u)}),o}},wm=e=>{let n=[],t=hp(e,n),r=gp(t);return n.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${fp(o)}"></div>`;r=r.replace(a,d)}),r};import Cm from"dompurify";var Am={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},Sm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,yp=()=>{let e=Cm(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(n,t)=>{if(t.attrName==="src"||t.attrName==="href"){let r=t.attrValue;r.toLowerCase().startsWith("data:")&&!Sm.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,Am)},Cs=e=>e===!1?null:typeof e=="function"?e:yp();var ya="webmcp:",ha={warn(e,...n){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...n)}},As=class{constructor(n){this.config=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=n.onConfirm)!=null?t:null,this.timeoutMs=3e4}setConfirmHandler(n){this.confirmHandler=n}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let n=this.getModelContext();if(!n)return[];let t;try{t=await n.getTools()}catch(s){return ha.warn("getTools() threw \u2014 shipping an empty WebMCP snapshot.",s),[]}let r=typeof location!="undefined"?location.origin:"";return t.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let o={name:s.name,description:s.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Tm(s.inputSchema);return a&&(o.parametersSchema=a),o})}async executeToolCall(n,t,r){if(await this.ensureReady(),this.config.enabled!==!0)return ir("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let m=typeof document!="undefined"&&!!document.modelContext;return ir(m?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let o=bp(n),a;try{a=await s.getTools()}catch(m){let v=m instanceof Error?m.message:String(m);return ir(`Failed to read WebMCP registry: ${v}`)}let i=a.find(m=>m.name===o);if(!i)return ir(`WebMCP tool not registered on this page: ${o}`);if(!this.passesClientAllowlist(o))return ir(`WebMCP tool not allowed by client allowlist: ${o}`);if(r!=null&&r.aborted)return ir("Aborted by cancel()");let d={toolName:o,args:t,description:i.description,reason:"gate"};if(!await this.requestConfirm(d))return ir("User declined the tool call.");if(r!=null&&r.aborted)return ir("Aborted by cancel()");let l=new AbortController,u=!1,p=setTimeout(()=>{u=!0,l.abort()},this.timeoutMs),f=()=>l.abort();r&&(r.aborted?l.abort():r.addEventListener("abort",f,{once:!0}));try{let m=await s.executeTool(i,Pm(t),{signal:l.signal});return Mm(m)}catch(m){if(u)return ir(`WebMCP tool '${o}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return ir("Aborted by cancel()");let v=m instanceof Error?m.message:String(m);return ir(v)}finally{clearTimeout(p),r&&r.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{(await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(n){ha.warn("Failed to load @mcp-b/webmcp-polyfill \u2014 WebMCP consumption disabled.",n),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let n=document.modelContext;if(!n||typeof n!="object")return null;let t=n;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ha.warn("document.modelContext is present but does not expose getTools()/executeTool() \u2014 WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):n}async requestConfirm(n){var r;let t=(r=this.confirmHandler)!=null?r:km;try{return await t(n)}catch(s){return ha.warn(`Confirm handler threw for WebMCP tool '${n.toolName}'; declining.`,s),!1}}passesClientAllowlist(n){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(r=>Em(n,r))}},bp=e=>e.startsWith(ya)?e.slice(ya.length):e,ba=e=>e.startsWith(ya),Em=(e,n)=>{if(n==="*")return!0;let t=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(e)},Tm=e=>{if(!(e===void 0||e===""))try{let n=JSON.parse(e);return n!==null&&typeof n=="object"?n:void 0}catch{return}},Mm=e=>{if(e==null)return{content:[{type:"text",text:""}]};let n;try{n=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return n!==null&&typeof n=="object"&&Array.isArray(n.content)?n:{content:[{type:"text",text:typeof n=="string"?n:Im(n)}]}},ir=e=>({isError:!0,content:[{type:"text",text:e}]}),km=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let n=Lm(e.args),t=`Allow the AI to call ${e.toolName}`+(n?`
5
2
 
6
- `);a=(vr=He.pop())!=null?vr:"";for(let Be of He){let $e=Be.split(`
7
- `),lt="message",et="";for(let P of $e)P.startsWith("event:")?lt=P.replace("event:","").trim():P.startsWith("data:")&&(et+=P.replace("data:","").trim());if(!et)continue;let Ct;try{Ct=JSON.parse(et)}catch(P){t({type:"error",error:P instanceof Error?P:new Error("Failed to parse chat stream payload")});continue}let Ut=lt!=="message"?lt:(dr=Ct.type)!=null?dr:"message";if((je=this.onSSEEvent)==null||je.call(this,Ut,Ct),this.parseSSEEvent){C.current=f;let P=await this.handleCustomSSEEvent(Ct,t,C,p,l,x);if(C.current&&C.current!==f&&(f=C.current),P)continue}Le.push(Ut,Ct),be()}}Le.flushPending(),be(),Le.destroy()}};function gm(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function ws(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function jo(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var ha="[Image]";function fm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function hm(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function ym(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function bm(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function ya(e){return{type:"text",text:e}}function xm(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function vm(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Cm(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var lp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],wm=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Rr=[...lp,...wm];function Am(e){return lp.includes(e)||e.startsWith("image/")}function ba(e){return Am(e.type)}async function cp(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;ba(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function dp(e,n=Rr,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Sm(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function pp(e,n){let t=Sm(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var xa=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),o=this.pcmToFloat32(t),s=r.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=r.createBufferSource();a.buffer=s,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),o=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let s=0;s<t;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}};var va=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,o,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];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 As=class{constructor(n){this.config=n;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new va;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",a=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${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((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let C=!1,x=A=>{C||(C=!0,clearTimeout(T),g(new Error(A)))},T=setTimeout(()=>x("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(T),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",A=>{if(!A.wasClean&&!C){let k=A.code!==1006?` (code ${A.code})`:"";x("WebSocket connection failed"+k+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(n.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new xa(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var n,t,r,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(o=(r=this.config)==null?void 0:r.silenceThreshold)!=null?o:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),o=this.getFormatFromMimeType(n.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:o,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:s}))}catch(r){this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];t(a)},o.onerror=r,o.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let l=0;l<t.length;l++)r[l]=t.charCodeAt(l);let o=n.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([r],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Ao=class{constructor(n={}){this.config=n;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(n=>n("connected"))}async startListening(){var n,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Uo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new As(e.runtype);case"browser":if(!Ao.isSupported())throw new Error("Browser speech recognition not supported");return new Ao(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ui(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Uo({type:"runtype",runtype:e.runtype});if(Ao.isSupported())return Uo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ca(e){try{return ui(e),!0}catch{return!1}}var Ss=class e{constructor(n={},t){this.config=n;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=n=>{var t,r,o,s,a,i,d;n.type==="message"?(this.upsertMessage(n.message),(t=n.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(r=n.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r,o;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new _o(n);for(let s of(o=n.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});n.initialSelectedArtifactId!=null&&(this.selectedArtifactId=n.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return Ca((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,o;try{let s=n||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Uo(s);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,f,g,C,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=l.text)!=null&&g.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let T=(x=this.pendingVoiceAssistantMessageId)!=null?x:(C=[...this.messages].reverse().find(A=>A.role==="assistant"))==null?void 0:C.id;T&&this.ttsSpokenMessageIds.add(T)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),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(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,l,u;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((o=n.runtype)==null?void 0:o.clientToken)||"",host:(s=n.runtype)==null?void 0:s.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=n.browser)==null?void 0:l.language)||"en-US",continuous:(u=n.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new _o(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=n,g={id:a!=null?a:t==="user"?ws():t==="assistant"?jo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(g),g}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:f,rawContent:g}=r,x={id:d!=null?d:o==="user"?ws():o==="assistant"?jo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(n){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=n,l={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(n,t){var l,u,p,f,g;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort();let o=ws(),s=jo(),a={id:o,role:"user",content:r||ha,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(C){let x=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!x){let T={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(T)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(C instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,C):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(C))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=jo();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(l){let u={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(u),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l)))}}async connectStream(n,t){var o,s,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(n,t){var d,l,u,p;let r=`approval-${n.id}`,o={...n,status:t,resolvedAt:Date.now()},s={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):f=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),f){let g=null;if(f instanceof Response){if(!f.ok){let C=await f.json().catch(()=>null);throw new Error((l=C==null?void 0:C.error)!=null?l:`Approval request failed: ${f.status}`)}g=f.body}else f instanceof ReadableStream&&(g=f);g?await this.connectStream(g,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let g=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||(p=(u=this.callbacks).onError)==null||p.call(u,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(n,t){let r=this.messages.find(o=>o.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(o=>o.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(n,t){var u,p,f,g,C,x,T,A,k,B,D,L;let r=this.messages.find(S=>S.id===n.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(p=n.agentMetadata)==null?void 0:p.executionId,s=(f=n.toolCall)==null?void 0:f.name;if(!o||!s){(C=(g=this.callbacks).onError)==null||C.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let S=(x=n.toolCall)==null?void 0:x.args,F=Array.isArray(S==null?void 0:S.questions)?S.questions:[];if(F.length===1){let $=typeof((T=F[0])==null?void 0:T.question)=="string"?F[0].question:"";$&&(a={[$]:t})}}this.markAskUserQuestionResolved(n,a),(A=this.abortController)==null||A.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=n.toolCall.id,d=(k=n.toolCall)==null?void 0:k.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let S=typeof t=="string"?t:Object.entries(t).map(([F,$])=>`${F}: ${Array.isArray($)?$.join(", "):$}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let S=a!=null?a:{};l.forEach((F,$)=>{let j=typeof(F==null?void 0:F.question)=="string"?F.question:"";if(!j)return;let W=S[j],O=Array.isArray(W)?W.join(", "):typeof W=="string"?W:"";this.appendMessage({id:`ask-user-q-${i}-${$}`,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${$}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let S=await this.client.resumeFlow(o,{[s]:t});if(!S.ok){let F=await S.json().catch(()=>null);throw new Error((B=F==null?void 0:F.error)!=null?B:`Resume failed: ${S.status}`)}S.body?await this.connectStream(S.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(S){let F=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));this.setStreaming(!1),this.abortController=null,F||(L=(D=this.callbacks).onError)==null||L.call(D,S instanceof Error?S:new Error(String(S)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var o;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(o=n.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let o=this.artifacts.get(n.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let o=this.artifacts.get(n.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...n.props},n.component&&(o.component=n.component));break}case"artifact_complete":{let o=this.artifacts.get(n.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(n,t=null){this.artifacts.clear();for(let r of n)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=r.content;o.trim()&&this.speak(o,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(n),s=r.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=t.pickVoice?t.pickVoice(s):e.pickBestVoice(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),setTimeout(()=>r.speak(o),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let s=n.find(a=>a.name===o);if(s)return s}return(r=n.find(o=>o.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var i;if(s!==r)return o;let a={...o,...t};return((i=o.agentMetadata)==null?void 0:i.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var d,l;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},br=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};import{Activity as Em,ArrowDown as Tm,ArrowUp as Mm,ArrowUpRight as km,Bot as Lm,ChevronDown as Pm,ChevronUp as Im,ChevronRight as Wm,ChevronLeft as Rm,Check as Hm,Clipboard as Bm,ClipboardCopy as Dm,Copy as Nm,File as Fm,FileCode as Om,FileSpreadsheet as $m,FileText as _m,ImagePlus as jm,Loader as Um,LoaderCircle as qm,Mic as zm,Paperclip as Vm,RefreshCw as Jm,Search as Km,Send as Gm,ShieldAlert as Qm,ShieldCheck as Xm,ShieldX as Ym,Square as Zm,ThumbsDown as eg,ThumbsUp as tg,Upload as ng,Volume2 as rg,X as og,User as sg,Mail as ag,Phone as ig,Calendar as lg,Clock as cg,Building as dg,MapPin as pg,Lock as ug,Key as mg,CreditCard as gg,AtSign as fg,Hash as hg,Globe as yg,Link as bg,CircleCheck as xg,CircleX as vg,TriangleAlert as Cg,Info as wg,Ban as Ag,Shield as Sg,ArrowLeft as Eg,ArrowRight as Tg,ExternalLink as Mg,Ellipsis as kg,EllipsisVertical as Lg,Menu as Pg,House as Ig,Plus as Wg,Minus as Rg,Pencil as Hg,Trash as Bg,Trash2 as Dg,Save as Ng,Download as Fg,Share as Og,Funnel as $g,Settings as _g,RotateCw as jg,Maximize as Ug,Minimize as qg,ShoppingCart as zg,ShoppingBag as Vg,Package as Jg,Truck as Kg,Tag as Gg,Gift as Qg,Receipt as Xg,Wallet as Yg,Store as Zg,DollarSign as ef,Percent as tf,Play as nf,Pause as rf,VolumeX as of,Camera as sf,Image as af,Film as lf,Headphones as cf,MessageCircle as df,MessageSquare as pf,Bell as uf,Heart as mf,Star as gf,Eye as ff,EyeOff as hf,Bookmark as yf,CalendarDays as bf,History as xf,Timer as vf,Folder as Cf,FolderOpen as wf,Files as Af,Sparkles as Sf,Zap as Ef,Sun as Tf,Moon as Mf,Flag as kf,Monitor as Lf,Smartphone as Pf}from"lucide";var If={activity:Em,"arrow-down":Tm,"arrow-up":Mm,"arrow-up-right":km,bot:Lm,"chevron-down":Pm,"chevron-up":Im,"chevron-right":Wm,"chevron-left":Rm,check:Hm,clipboard:Bm,"clipboard-copy":Dm,copy:Nm,file:Fm,"file-code":Om,"file-spreadsheet":$m,"file-text":_m,"image-plus":jm,loader:Um,"loader-circle":qm,mic:zm,paperclip:Vm,"refresh-cw":Jm,search:Km,send:Gm,"shield-alert":Qm,"shield-check":Xm,"shield-x":Ym,square:Zm,"thumbs-down":eg,"thumbs-up":tg,upload:ng,"volume-2":rg,x:og,user:sg,mail:ag,phone:ig,calendar:lg,clock:cg,building:dg,"map-pin":pg,lock:ug,key:mg,"credit-card":gg,"at-sign":fg,hash:hg,globe:yg,link:bg,"circle-check":xg,"circle-x":vg,"triangle-alert":Cg,info:wg,ban:Ag,shield:Sg,"arrow-left":Eg,"arrow-right":Tg,"external-link":Mg,ellipsis:kg,"ellipsis-vertical":Lg,menu:Pg,house:Ig,plus:Wg,minus:Rg,pencil:Hg,trash:Bg,"trash-2":Dg,save:Ng,download:Fg,share:Og,funnel:$g,settings:_g,"rotate-cw":jg,maximize:Ug,minimize:qg,"shopping-cart":zg,"shopping-bag":Vg,package:Jg,truck:Kg,tag:Gg,gift:Qg,receipt:Xg,wallet:Yg,store:Zg,"dollar-sign":ef,percent:tf,play:nf,pause:rf,"volume-x":of,camera:sf,image:af,film:lf,headphones:cf,"message-circle":df,"message-square":pf,bell:uf,heart:mf,star:gf,eye:ff,"eye-off":hf,bookmark:yf,"calendar-days":bf,history:xf,timer:vf,folder:Cf,"folder-open":wf,files:Af,sparkles:Sf,zap:Ef,sun:Tf,moon:Mf,flag:kf,monitor:Lf,smartphone:Pf},ge=(e,n=24,t="currentColor",r=2)=>{let o=If[e];return o?Wf(o,n,t,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Wf(e,n,t,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),o.appendChild(d)}),o}var wa={allowedTypes:Rr,maxFileSize:10*1024*1024,maxFiles:4};function Rf(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Hf(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-code":"file"}var qo=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:wa.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:wa.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:wa.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:wa.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,o,s,a,i,d;if(n.length){for(let l of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,l,"count");continue}let u=dp(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(o=u.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,p);continue}try{let p=await cp(l),f=ba(l)?URL.createObjectURL(l):null,g={id:Rf(),file:l,previewUrl:f,contentPart:p};this.attachments.push(g),this.renderPreview(g)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(n){var s,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=ba(n.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=h("img");a.src=n.previewUrl,a.alt=n.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Hf(n.file.type),d=ge(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=pp(n.file.type,n.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let o=h("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=ge("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var up=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Es(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];up(s)&&up(o)?t[r]=Es(s,o):t[r]=o}return t}var Gn="min(440px, calc(100vw - 24px))",mi="440px",$t={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Gn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{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:void 0,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",borderColor:void 0,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:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},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 mp(e,n){if(!(!e&&!n))return e?n?Es(e,n):e:n}function gi(e){var n,t,r,o,s,a,i,d,l,u,p,f,g,C,x,T,A,k,B,D,L;return e?{...$t,...e,theme:mp($t.theme,e.theme),darkTheme:mp($t.darkTheme,e.darkTheme),launcher:{...$t.launcher,...e.launcher,dock:{...(n=$t.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=$t.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...$t.copy,...e.copy},sendButton:{...$t.sendButton,...e.sendButton},statusIndicator:{...$t.statusIndicator,...e.statusIndicator},voiceRecognition:{...$t.voiceRecognition,...e.voiceRecognition},features:(()=>{var pe,Me,_e,ee,Ae,Q,ae,Re;let S=(pe=$t.features)==null?void 0:pe.artifacts,F=(Me=e.features)==null?void 0:Me.artifacts,$=(_e=$t.features)==null?void 0:_e.scrollToBottom,j=(ee=e.features)==null?void 0:ee.scrollToBottom,W=(Ae=$t.features)==null?void 0:Ae.streamAnimation,O=(Q=e.features)==null?void 0:Q.streamAnimation,V=(ae=$t.features)==null?void 0:ae.askUserQuestion,oe=(Re=e.features)==null?void 0:Re.askUserQuestion,Pe=S===void 0&&F===void 0?void 0:{...S,...F,layout:{...S==null?void 0:S.layout,...F==null?void 0:F.layout}},ke=$===void 0&&j===void 0?void 0:{...$,...j},Ge=W===void 0&&O===void 0?void 0:{...W,...O},de=V===void 0&&oe===void 0?void 0:{...V,...oe,styles:{...V==null?void 0:V.styles,...oe==null?void 0:oe.styles}};return{...$t.features,...e.features,...ke!==void 0?{scrollToBottom:ke}:{},...Pe!==void 0?{artifacts:Pe}:{},...Ge!==void 0?{streamAnimation:Ge}:{},...de!==void 0?{askUserQuestion:de}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:$t.suggestionChips,suggestionChipsConfig:{...$t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...$t.layout,...e.layout,header:{...(a=$t.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=$t.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=$t.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(x=(C=$t.layout)==null?void 0:C.messages)==null?void 0:x.timestamp,...(A=(T=e.layout)==null?void 0:T.messages)==null?void 0:A.timestamp}},slots:{...(k=$t.layout)==null?void 0:k.slots,...(B=e.layout)==null?void 0:B.slots}},markdown:{...$t.markdown,...e.markdown,options:{...(D=$t.markdown)==null?void 0:D.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...$t.messageActions,...e.messageActions}}:$t}var gp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},fp={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},hp={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Gn,maxWidth:mi,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function zo(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?zo(e,r):r}function fi(e){let n={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=zo(e,a);d!==void 0&&(n[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function yp(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function bp(e,n){let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=bp(s,o):t[r]=o}return t}function Bf(e,n){return n?bp(e,n):e}function Ts(e,n={}){var o,s,a,i,d,l,u,p,f,g,C,x,T;let t={palette:gp,semantic:fp,components:hp},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(C=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:C.feedback}},spacing:{...t.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:Bf(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let A=yp(r);if(!A.valid)throw new Error(`Theme validation failed: ${A.errors.map(k=>k.message).join(", ")}`)}if(n.plugins)for(let A of n.plugins)r=A.transform(r);return r}function hi(e){var x,T,A,k,B,D,L,S,F,$,j,W,O,V,oe,Pe,ke,Ge,de,pe,Me,_e,ee,Ae,Q,ae,Re,ce,We,Ze,J,se,Fe,K,z,xe,Oe,ne,Se,be,Ht,Le,te,sn,Nt,Vt,vr,dr,je,U,Ce,He,Be,$e,lt,et,Ct,Ut,P,fe,me,ct,qe,It,an,wt,bt,Mt,pt,Jt,Cr,jn,Br,vt,pr,ur,wr,Yn,mt,ao,mr,io,Sn,ko,Dr,Ar,yt,In,Wn,hn,kt,Un,qn,Rn,Nr,Sr,Fr,Hn,Wt,yn,zn,Or,Er,$r,gr,Bn,Zn,gt,Kt,Gt,Dn,_r,Vn,er,Nn,_;let n=fi(e),t={};for(let[le,Fn]of Object.entries(n)){let tr=le.replace(/\./g,"-");t[`--persona-${tr}`]=Fn.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(T=t["--persona-semantic-colors-secondary"])!=null?T:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(A=t["--persona-semantic-colors-accent"])!=null?A:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(k=t["--persona-semantic-colors-surface"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(B=t["--persona-semantic-colors-background"])!=null?B:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(D=t["--persona-semantic-colors-container"])!=null?D:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(L=t["--persona-semantic-colors-text"])!=null?L:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(S=t["--persona-semantic-colors-text-muted"])!=null?S:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(F=t["--persona-semantic-colors-text-inverse"])!=null?F:t["--persona-palette-colors-gray-50"],t["--persona-border"]=($=t["--persona-semantic-colors-border"])!=null?$:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(j=t["--persona-semantic-colors-divider"])!=null?j:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(W=t["--persona-components-voice-recording-indicator"])!=null?W:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(O=t["--persona-components-voice-recording-background"])!=null?O:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(V=t["--persona-components-voice-processing-icon"])!=null?V:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(oe=t["--persona-components-voice-speaking-icon"])!=null?oe:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Pe=t["--persona-components-approval-requested-background"])!=null?Pe:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(ke=t["--persona-components-approval-requested-border"])!=null?ke:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ge=t["--persona-components-approval-requested-text"])!=null?Ge:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(de=t["--persona-components-approval-approve-background"])!=null?de:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(pe=t["--persona-components-approval-deny-background"])!=null?pe:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Me=t["--persona-components-attachment-image-background"])!=null?Me:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(_e=t["--persona-components-attachment-image-border"])!=null?_e:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ee=t["--persona-semantic-typography-fontFamily"])!=null?ee:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Ae=t["--persona-semantic-typography-fontSize"])!=null?Ae:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(Q=t["--persona-semantic-typography-fontWeight"])!=null?Q:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ae=t["--persona-semantic-typography-lineHeight"])!=null?ae:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(Re=t["--persona-palette-radius-sm"])!=null?Re:"0.125rem",t["--persona-radius-md"]=(ce=t["--persona-palette-radius-md"])!=null?ce:"0.375rem",t["--persona-radius-lg"]=(We=t["--persona-palette-radius-lg"])!=null?We:"0.5rem",t["--persona-radius-xl"]=(Ze=t["--persona-palette-radius-xl"])!=null?Ze:"0.75rem",t["--persona-radius-full"]=(J=t["--persona-palette-radius-full"])!=null?J:"9999px",t["--persona-launcher-radius"]=(Fe=(se=t["--persona-components-launcher-borderRadius"])!=null?se:t["--persona-palette-radius-full"])!=null?Fe:"9999px",t["--persona-launcher-bg"]=(K=t["--persona-components-launcher-background"])!=null?K:t["--persona-primary"],t["--persona-launcher-fg"]=(z=t["--persona-components-launcher-foreground"])!=null?z:t["--persona-text-inverse"],t["--persona-launcher-border"]=(xe=t["--persona-components-launcher-border"])!=null?xe:t["--persona-border"],t["--persona-button-primary-bg"]=(Oe=t["--persona-components-button-primary-background"])!=null?Oe:t["--persona-primary"],t["--persona-button-primary-fg"]=(ne=t["--persona-components-button-primary-foreground"])!=null?ne:t["--persona-text-inverse"],t["--persona-button-radius"]=(be=(Se=t["--persona-components-button-primary-borderRadius"])!=null?Se:t["--persona-palette-radius-full"])!=null?be:"9999px",t["--persona-panel-radius"]=(Le=(Ht=t["--persona-components-panel-borderRadius"])!=null?Ht:t["--persona-radius-xl"])!=null?Le:"0.75rem",t["--persona-panel-border"]=(te=t["--persona-components-panel-border"])!=null?te:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Nt=(sn=t["--persona-components-panel-shadow"])!=null?sn:t["--persona-palette-shadows-xl"])!=null?Nt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(vr=(Vt=t["--persona-components-input-borderRadius"])!=null?Vt:t["--persona-radius-lg"])!=null?vr:"0.5rem",t["--persona-message-user-radius"]=(je=(dr=t["--persona-components-message-user-borderRadius"])!=null?dr:t["--persona-radius-lg"])!=null?je:"0.5rem",t["--persona-message-assistant-radius"]=(Ce=(U=t["--persona-components-message-assistant-borderRadius"])!=null?U:t["--persona-radius-lg"])!=null?Ce:"0.5rem",t["--persona-header-bg"]=(He=t["--persona-components-header-background"])!=null?He:t["--persona-surface"],t["--persona-header-border"]=(Be=t["--persona-components-header-border"])!=null?Be:t["--persona-divider"],t["--persona-header-icon-bg"]=($e=t["--persona-components-header-iconBackground"])!=null?$e:t["--persona-primary"],t["--persona-header-icon-fg"]=(lt=t["--persona-components-header-iconForeground"])!=null?lt:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(et=t["--persona-components-header-titleForeground"])!=null?et:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Ct=t["--persona-components-header-subtitleForeground"])!=null?Ct:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(Ut=t["--persona-components-header-actionIconForeground"])!=null?Ut:t["--persona-muted"];let r=(P=e.components)==null?void 0:P.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(fe=e.components)==null?void 0:fe.introCard;t["--persona-intro-card-bg"]=(me=t["--persona-components-introCard-background"])!=null?me:t["--persona-surface"],t["--persona-intro-card-radius"]=(ct=t["--persona-components-introCard-borderRadius"])!=null?ct:"1rem",t["--persona-intro-card-padding"]=(qe=t["--persona-components-introCard-padding"])!=null?qe:"1.5rem",t["--persona-intro-card-shadow"]=(an=(It=o==null?void 0:o.shadow)!=null?It:t["--persona-components-introCard-shadow"])!=null?an:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(wt=t["--persona-components-input-background"])!=null?wt:t["--persona-surface"],t["--persona-input-placeholder"]=(bt=t["--persona-components-input-placeholder"])!=null?bt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Mt=t["--persona-components-message-user-background"])!=null?Mt:t["--persona-accent"],t["--persona-message-user-text"]=(pt=t["--persona-components-message-user-text"])!=null?pt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Jt=t["--persona-components-message-user-shadow"])!=null?Jt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Cr=t["--persona-components-message-assistant-background"])!=null?Cr:t["--persona-surface"],t["--persona-message-assistant-text"]=(jn=t["--persona-components-message-assistant-text"])!=null?jn:t["--persona-text"],t["--persona-message-assistant-border"]=(Br=t["--persona-components-message-assistant-border"])!=null?Br:t["--persona-border"],t["--persona-message-assistant-shadow"]=(vt=t["--persona-components-message-assistant-shadow"])!=null?vt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(ur=(pr=t["--persona-components-scrollToBottom-background"])!=null?pr:t["--persona-button-primary-bg"])!=null?ur:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Yn=(wr=t["--persona-components-scrollToBottom-foreground"])!=null?wr:t["--persona-button-primary-fg"])!=null?Yn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(mt=t["--persona-components-scrollToBottom-border"])!=null?mt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(ao=t["--persona-components-scrollToBottom-size"])!=null?ao:"40px",t["--persona-scroll-to-bottom-radius"]=(Sn=(io=(mr=t["--persona-components-scrollToBottom-borderRadius"])!=null?mr:t["--persona-button-radius"])!=null?io:t["--persona-radius-full"])!=null?Sn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Dr=(ko=t["--persona-components-scrollToBottom-shadow"])!=null?ko:t["--persona-palette-shadows-sm"])!=null?Dr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Ar=t["--persona-components-scrollToBottom-padding"])!=null?Ar:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(yt=t["--persona-components-scrollToBottom-gap"])!=null?yt:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Wn=(In=t["--persona-components-scrollToBottom-fontSize"])!=null?In:t["--persona-palette-typography-fontSize-sm"])!=null?Wn:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(hn=t["--persona-components-scrollToBottom-iconSize"])!=null?hn:"14px",t["--persona-tool-bubble-shadow"]=(kt=t["--persona-components-toolBubble-shadow"])!=null?kt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Un=t["--persona-components-reasoningBubble-shadow"])!=null?Un:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(qn=t["--persona-components-composer-shadow"])!=null?qn:"none",t["--persona-md-inline-code-bg"]=(Rn=t["--persona-components-markdown-inlineCode-background"])!=null?Rn:t["--persona-container"],t["--persona-md-inline-code-color"]=(Nr=t["--persona-components-markdown-inlineCode-foreground"])!=null?Nr:t["--persona-text"],t["--persona-md-link-color"]=(Fr=(Sr=t["--persona-components-markdown-link-foreground"])!=null?Sr:t["--persona-accent"])!=null?Fr:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=(Hn=t["--persona-components-markdown-codeBlock-background"])!=null?Hn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Wt=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Wt:t["--persona-border"],t["--persona-md-code-block-text-color"]=(yn=t["--persona-components-markdown-codeBlock-textColor"])!=null?yn:"inherit",t["--persona-md-table-header-bg"]=(zn=t["--persona-components-markdown-table-headerBackground"])!=null?zn:t["--persona-container"],t["--persona-md-table-border-color"]=(Or=t["--persona-components-markdown-table-borderColor"])!=null?Or:t["--persona-border"],t["--persona-md-hr-color"]=(Er=t["--persona-components-markdown-hr-color"])!=null?Er:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=($r=t["--persona-components-markdown-blockquote-borderColor"])!=null?$r:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(gr=t["--persona-components-markdown-blockquote-background"])!=null?gr:"transparent",t["--persona-md-blockquote-text-color"]=(Bn=t["--persona-components-markdown-blockquote-textColor"])!=null?Bn:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Zn=t["--persona-components-collapsibleWidget-container"])!=null?Zn:t["--persona-surface"],t["--cw-surface"]=(gt=t["--persona-components-collapsibleWidget-surface"])!=null?gt:t["--persona-surface"],t["--cw-border"]=(Kt=t["--persona-components-collapsibleWidget-border"])!=null?Kt:t["--persona-border"],t["--persona-message-border"]=(Gt=t["--persona-components-message-border"])!=null?Gt:t["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let f=u==null?void 0:u.labelButton;f&&(f.background&&(t["--persona-label-btn-bg"]=f.background),f.border&&(t["--persona-label-btn-border"]=f.border),f.color&&(t["--persona-label-btn-color"]=f.color),f.padding&&(t["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(t["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(t["--persona-label-btn-gap"]=f.gap));let g=u==null?void 0:u.toggleGroup;g&&(g.gap&&(t["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(t["--persona-toggle-group-radius"]=g.borderRadius));let C=u==null?void 0:u.artifact;if(C!=null&&C.toolbar){let le=C.toolbar;le.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=le.iconHoverColor),le.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=le.iconHoverBackground),le.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=le.iconPadding),le.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=le.iconBorderRadius),le.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=le.iconBorder),le.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=le.toggleGroupGap),le.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=le.toggleBorderRadius),le.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=le.copyBackground),le.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=le.copyBorder),le.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=le.copyColor),le.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=le.copyBorderRadius),le.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=le.copyPadding),le.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=le.copyMenuBackground,t["--persona-dropdown-bg"]=(Dn=t["--persona-dropdown-bg"])!=null?Dn:le.copyMenuBackground),le.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=le.copyMenuBorder,t["--persona-dropdown-border"]=(_r=t["--persona-dropdown-border"])!=null?_r:le.copyMenuBorder),le.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=le.copyMenuShadow,t["--persona-dropdown-shadow"]=(Vn=t["--persona-dropdown-shadow"])!=null?Vn:le.copyMenuShadow),le.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=le.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(er=t["--persona-dropdown-radius"])!=null?er:le.copyMenuBorderRadius),le.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=le.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Nn=t["--persona-dropdown-item-hover-bg"])!=null?Nn:le.copyMenuItemHoverBackground),le.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=le.iconBackground),le.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=le.toolbarBorder)}if(C!=null&&C.tab){let le=C.tab;le.background&&(t["--persona-artifact-tab-bg"]=le.background),le.activeBackground&&(t["--persona-artifact-tab-active-bg"]=le.activeBackground),le.activeBorder&&(t["--persona-artifact-tab-active-border"]=le.activeBorder),le.borderRadius&&(t["--persona-artifact-tab-radius"]=le.borderRadius),le.textColor&&(t["--persona-artifact-tab-color"]=le.textColor),le.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=le.hoverBackground),le.listBackground&&(t["--persona-artifact-tab-list-bg"]=le.listBackground),le.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=le.listBorderColor),le.listPadding&&(t["--persona-artifact-tab-list-padding"]=le.listPadding)}if(C!=null&&C.pane){let le=C.pane;if(le.toolbarBackground){let Fn=(_=zo(e,le.toolbarBackground))!=null?_:le.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Fn}}return t}var Df={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Nf={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},xp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Aa=()=>{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"},Ff=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Aa()},vp=e=>Ff(e),Of=e=>Ts(e),$f=e=>{var t;let n=Ts(void 0,{validate:!1});return Ts({...e,palette:{...n.palette,colors:{...Nf.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Ms=e=>{let n=vp(e),t=xp(e==null?void 0:e.theme),r=xp(e==null?void 0:e.darkTheme);return n==="dark"?$f(Es(t!=null?t:{},r!=null?r:{})):Of(t)},_f=e=>hi(e),So=(e,n)=>{var s;let t=Ms(n),r=_f(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let o=(s=n==null?void 0:n.toolCall)==null?void 0:s.shadow;o!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},yi=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Aa())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Aa());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};import{Idiomorph as jf}from"idiomorph";var Sa=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;jf.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};function Cp(e,n){var t,r,o,s,a,i,d,l,u,p,f,g,C,x,T,A,k,B,D,L,S,F,$,j,W,O,V,oe,Pe,ke;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(C=(g=e.toolCall)==null?void 0:g.status)!=null?C:"",(T=(x=e.toolCall)==null?void 0:x.name)!=null?T:"",(B=(k=(A=e.toolCall)==null?void 0:A.chunks)==null?void 0:k.length)!=null?B:0,(F=(S=(L=(D=e.toolCall)==null?void 0:D.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?F:"",typeof(($=e.toolCall)==null?void 0:$.args)=="string"?e.toolCall.args.length:(j=e.toolCall)!=null&&j.args?JSON.stringify(e.toolCall.args).length:0,(V=(O=(W=e.reasoning)==null?void 0:W.chunks)==null?void 0:O.length)!=null?V:0,(Pe=(oe=e.contentParts)==null?void 0:oe.length)!=null?Pe:0,(ke=e.stopReason)!=null?ke:"",n].join("\0")}function wp(){return new Map}function Ap(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Sp(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function Ep(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function Ea(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function ks(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ls(e,n){return ks(e)-e.scrollTop<=n}function Ta(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-r;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:t}:!n&&o&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:n&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:n&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Ma(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return n&&t<0?"pause":!n&&o&&t>0&&r?"resume":"none"}var gn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},fn=1e5,Qr=fn+1;var Ps={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Uf=["pre","code","a","script","style"],ka=e=>{var n,t,r,o,s;return{type:(n=e==null?void 0:e.type)!=null?n:Ps.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:Ps.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Ps.speed,duration:(o=e==null?void 0:e.duration)!=null?o:Ps.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:Ps.buffer}},Mp=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Is=new Map;for(let e of Mp)Is.set(e.name,e);var qf=e=>{Is.set(e.name,e)},zf=e=>{Mp.some(n=>n.name===e)||Is.delete(e)},Vf=()=>Array.from(Is.keys()),Ws=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=Is.get(e))!=null?r:null},La=(e,n,t,r,o)=>{if(!o)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(n==="line"){let s=e.lastIndexOf(`
8
- `);return s<0?"":e.slice(0,s)}return e},Jf=(e,n,t,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=n,o},Kf=(e,n,t,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=n,o},bi=/\s/,Gf=(e,n)=>{let t=e.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(n.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Qf=(e,n,t)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(bi.test(s[i])){let l=i;for(;l<s.length&&bi.test(s[l]);)l+=1;a.appendChild(r.createTextNode(s.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<s.length&&!bi.test(s[u]);)l.appendChild(Jf(r,s[u],n,t.value)),t.value+=1,u+=1;a.appendChild(l),i=u}o.replaceChild(a,e)},Xf=(e,n,t)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(Kf(r,l,n,t.value)),t.value+=1));o.replaceChild(a,e)},Rs=(e,n,t,r)=>{var p,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((p=r==null?void 0:r.skipTags)!=null?p:Uf).map(g=>g.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Gf(d,s)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},u=n==="char"?Qf:Xf;for(let g of i)u(g,t,l);return o.innerHTML},Pa=(e=document)=>{let n=e.createElement("span");return n.className="persona-stream-caret",n.setAttribute("aria-hidden","true"),n.setAttribute("data-preserve-animation","stream-caret"),n},Hs=(e=document)=>{let n=e.createElement("div");n.className="persona-stream-skeleton",n.setAttribute("data-preserve-animation","stream-skeleton"),n.setAttribute("aria-hidden","true");let t=e.createElement("div");return t.className="persona-stream-skeleton-line",n.appendChild(t),n},Tp=new WeakMap,Yf=(e,n)=>{var s;if(!e.styles)return;let t=Tp.get(n);if(t||(t=new Set,Tp.set(n,t)),t.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(n.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(e.name)}t.add(e.name);let o=(n instanceof ShadowRoot?n.ownerDocument:(s=n.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,n.appendChild(o)},xi=new WeakMap,Zf=(e,n)=>{if(!e.onAttach)return;let t=xi.get(n);if(t||(t=new Map,xi.set(n,t)),t.has(e.name))return;let r=e.onAttach(n);t.set(e.name,r)},kp=e=>{let n=xi.get(e);if(n){for(let t of n.values())typeof t=="function"&&t();n.clear()}},vi=(e,n)=>{Yf(e,n),Zf(e,n)};function Ci(e,n=fn){let t=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(n),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=r,e.style.isolation=o}}var Bs=0,Xr=null;function wi(e=document){var t;if(Bs++,Bs===1){let r=e.body,s=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Xr={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let n=!1;return()=>{var r;if(!n&&(n=!0,Bs=Math.max(0,Bs-1),Bs===0&&Xr)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=Xr.originalOverflow,o.style.position=Xr.originalPosition,o.style.top=Xr.originalTop,o.style.width=Xr.originalWidth,s.scrollTo(0,Xr.scrollY),Xr=null}}}var Ia={side:"right",width:"420px",animate:!0,reveal:"resize"},on=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},Yr=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="composer-bar"},lr=e=>{var t,r,o,s,a;let n=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(r=n==null?void 0:n.side)!=null?r:Ia.side,width:(o=n==null?void 0:n.width)!=null?o:Ia.width,animate:(s=n==null?void 0:n.animate)!=null?s:Ia.animate,reveal:(a=n==null?void 0:n.reveal)!=null?a:Ia.reveal}};var cr={"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 Ds=(e,n)=>{let t=h("button");t.type="button",t.innerHTML=`
3
+ Arguments:
4
+ ${n}`:"")+(e.description?`
5
+
6
+ ${e.description}`:"");return window.confirm(t)},Lm=e=>{if(e==null)return"";try{let n=JSON.stringify(e,null,2);return n.length>500?n.slice(0,500)+"\u2026":n}catch{return String(e)}},Pm=e=>{if(e===void 0)return"{}";try{let n=JSON.stringify(e);return n===void 0?"{}":n}catch{return"{}"}},Im=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as xp,STR as vp,OBJ as wp}from"partial-json";var xa=e=>e.replace(/\\n/g,`
7
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),$o=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)}},Wm=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Cp=e=>e.status==="complete"?Wm(e):e.status==="pending"?"Waiting":"",Rm=e=>{var s,o,a;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var Ap=e=>e.status==="complete"?Rm(e):"Using tool...",va=e=>{let n=e/1e3;return n<.1?"<0.1s":n>=10?`${Math.round(n)}s`:`${n.toFixed(1).replace(/\.0$/,"")}s`},Es=e=>{var t,r,s;let n=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return va(n)},wa=e=>{var t,r,s;let n=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return va(n)},yi=(e,n,t)=>{var o;if(!n)return t;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Es(e);return n.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Ca=(e,n)=>{let t=e.replace(/\{toolName\}/g,n),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&Ss(r,t.slice(o,a.index),[]),a[1]!==void 0?Ss(r,a[1],["bold"]):a[2]!==void 0?Ss(r,a[2],["italic"]):a[3]!==void 0&&Ss(r,a[3],["dim"]),o=a.index+a[0].length;return o<t.length&&Ss(r,t.slice(o),[]),r},Ss=(e,n,t)=>{let r=n.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:t}),s<r.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},Hm=()=>{let e=null,n=0,t=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
8
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Co=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},bi=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},xi=()=>{var n;let e=Hm();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},vi=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=xp(t,vp|wp);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?xa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=xa(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Bm=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?xa(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?xa(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=xp(o,vp|wp),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},wi=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var Aa=class{constructor(n,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=n,this.gapTimeoutMs=t}push(n,t){var o,a,i;let r=(i=(o=t==null?void 0:t.seq)!=null?o:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(n,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(n,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(n,t);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:n,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let n=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(n.payloadType,n.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let n=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of n)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);n.length>0&&(this.nextExpectedSeq=n[n.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Dm="https://api.runtype.com/v1/dispatch",Sa="https://api.runtype.com";function Nm(e){var o,a;let n=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[n];if(r)return`attachment.${r}`;let s=n.indexOf("/");if(s>0){let i=(a=(o=n.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Ci=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 Om(e){switch(e){case"json":return vi;case"regex-json":return xi;case"xml":return wi;default:return bi}}var Sp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Fm(e,n){if(!e)return n;let t=e.trim(),r=n.trim();if(t.length===0)return n;if(r.length===0)return e;let s=Sp(t);if(!Sp(r))return e;if(!s||r===t||r.startsWith(t))return n;let a=Co(e);return Co(n)!==null&&a===null?n:e}var _o=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,s,o;this.apiUrl=(t=n.apiUrl)!=null?t:Dm,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:Om(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders,this.webMcpBridge=((o=n.webmcp)==null?void 0:o.enabled)===!0?new As(n.webmcp):null}setSSEEventCallback(n){this.onSSEEvent=n}setWebMcpConfirmHandler(n){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(n)}isWebMcpOperational(){var n;return((n=this.webMcpBridge)==null?void 0:n.isOperational())===!0}executeWebMcpToolCall(n,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(n,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/client/${n}`}getClientSession(){return this.clientSession}async initSession(){var n,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/client/feedback`}async sendFeedback(n){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:n,comment:t})}async submitNPSFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let l=await this.buildPayload(n.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(Ci).map(m=>{var v,x,S;return{id:m.id,role:m.role,content:(S=(x=(v=m.contentParts)!=null?v:m.llmContent)!=null?x:m.rawContent)!=null?S:m.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},...l.clientTools&&l.clientTools.length>0&&{clientTools:l.clientTools}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.signal});if(!f.ok){let m=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let x=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:x}),x}if(f.status===429){let x=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:x}),x}let v=new Error(m.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!f.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&t({type:"error",error:l}),l}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/agents/${n.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(n,t,r){var l,u;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Sa}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:n,toolOutputs:t,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(n){var o;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(Ci).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:n,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(n){var o;let r={messages:n.slice().filter(Ci).sort((a,i)=>{let d=new Date(a.createdAt).getTime(),l=new Date(i.createdAt).getTime();return d-l}).map(a=>{var i,d,l;return{role:a.role,content:(l=(d=(i=a.contentParts)!=null?i:a.llmContent)!=null?d:a.rawContent)!=null?l:a.content,createdAt:a.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch());if(s&&s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let d=await i({messages:n,config:this.config});d&&typeof d=="object"&&Object.assign(a,d)}catch(d){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",d)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let i=a;return r.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=r.clientTools),i}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(n,t,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let d=u=>{let p={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...u!==void 0&&{partId:u}};return r.current=p,s(p),p},l=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,s(u)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,t,r){var zt,vr,dr,Ue;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=U=>{let Ae=U.reasoning?{...U.reasoning,chunks:[...U.reasoning.chunks]}:void 0,Be=U.toolCall?{...U.toolCall,chunks:U.toolCall.chunks?[...U.toolCall.chunks]:void 0}:void 0,De=U.tools?U.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...U,reasoning:Ae,toolCall:Be,tools:De}},p=U=>{t({type:"message",message:u(U)})},f=null,m=null,v={current:null},x={current:null},S=!1,A=new Map,k=new Map,R=new Map,H=new Map,L={lastId:null,byStep:new Map},w={lastId:null,byCall:new Map},B=(U,Ae,Be="")=>`${U}::${Ae}::${Be}`,F=(U,Ae)=>`${U}::${Ae}::`,$=(U,Ae,Be,De)=>{let _e=B(U,Ae,Be),ct=R.get(_e);if(ct)return ct;let nt=Be?`-${Be}`:"",Ct={id:`nested-${U}-${Ae}${nt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Be?{partId:Be}:{},agentMetadata:{executionId:De,parentToolId:U,parentStepId:Ae}};return R.set(_e,Ct),p(Ct),Ct},W=U=>{if(U==null)return null;try{return String(U)}catch{return null}},O=U=>{var Ae,Be,De,_e,ct;return W((ct=(_e=(De=(Be=(Ae=U.stepId)!=null?Ae:U.step_id)!=null?Be:U.step)!=null?De:U.parentId)!=null?_e:U.flowStepId)!=null?ct:U.flow_step_id)},V=U=>{var Ae,Be,De,_e,ct,nt,Ct;return W((Ct=(nt=(ct=(_e=(De=(Be=(Ae=U.callId)!=null?Ae:U.call_id)!=null?Be:U.requestId)!=null?De:U.request_id)!=null?_e:U.toolCallId)!=null?ct:U.tool_call_id)!=null?nt:U.stepId)!=null?Ct:U.step_id)},oe=r,Ie=!1,Pe=()=>{if(f)return f;let U;return!Ie&&oe?(U=oe,Ie=!0):oe&&x.current?U=`${oe}_${x.current}`:U=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:U,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},p(f),f},ze=(U,Ae)=>{L.lastId=Ae,U&&L.byStep.set(U,Ae)},pe=(U,Ae)=>{var ct;let Be=(ct=U.reasoningId)!=null?ct:U.id,De=O(U);if(Be){let nt=String(Be);return ze(De,nt),nt}if(De){let nt=L.byStep.get(De);if(nt)return L.lastId=nt,nt}if(L.lastId&&!Ae)return L.lastId;if(!Ae)return null;let _e=`reason-${l()}`;return ze(De,_e),_e},ce=U=>{let Ae=A.get(U);if(Ae)return Ae;let Be={id:`reason-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"streaming",chunks:[]}};return A.set(U,Be),p(Be),Be},Ee=(U,Ae)=>{w.lastId=Ae,U&&w.byCall.set(U,Ae)},je=new Set,te=new Map,xe=new Set,G=new Map,ae=U=>{if(!U)return!1;let Ae=U.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ae==="emit_artifact_markdown"||Ae==="emit_artifact_component"},He=(U,Ae)=>{var ct;let Be=(ct=U.toolId)!=null?ct:U.id,De=V(U);if(Be){let nt=String(Be);return Ee(De,nt),nt}if(De){let nt=w.byCall.get(De);if(nt)return w.lastId=nt,nt}if(w.lastId&&!Ae)return w.lastId;if(!Ae)return null;let _e=`tool-${l()}`;return Ee(De,_e),_e},ue=U=>{let Ae=k.get(U);if(Ae)return Ae;let Be={id:`tool-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:U,status:"pending"}};return k.set(U,Be),p(Be),Be},Re=U=>{if(typeof U=="number"&&Number.isFinite(U))return U;if(typeof U=="string"){let Ae=Number(U);if(!Number.isNaN(Ae)&&Number.isFinite(Ae))return Ae;let Be=Date.parse(U);if(!Number.isNaN(Be))return Be}return Date.now()},tt=U=>{if(typeof U=="string")return U;if(U==null)return"";try{return JSON.stringify(U)}catch{return String(U)}},K=new Map,se=new Map,Oe=new Map,J=new Map,z=null,we=(U,Ae,Be)=>{var Ct;let De=Oe.get(U);De||(De=[],Oe.set(U,De));let _e=0,ct=De.length;for(;_e<ct;){let jt=_e+ct>>>1;De[jt].seq<Ae?_e=jt+1:ct=jt}((Ct=De[_e])==null?void 0:Ct.seq)===Ae?De[_e]={seq:Ae,text:Be}:De.splice(_e,0,{seq:Ae,text:Be});let nt="";for(let jt=0;jt<De.length;jt++)nt+=De[jt].text;return nt},$e=(U,Ae)=>{let Be=tt(Ae),De=se.get(U.id),_e=Fm(De,Be);U.rawContent=_e;let ct=K.get(U.id),nt=ge=>{var Ke;let dt=(Ke=U.content)!=null?Ke:"";ge.trim()!==""&&(dt.trim().length===0||ge.startsWith(dt)||ge.trimStart().startsWith(dt.trim()))&&(U.content=ge)},Ct=()=>{var ge;if(ct){let dt=(ge=ct.close)==null?void 0:ge.call(ct);dt instanceof Promise&&dt.catch(()=>{})}K.delete(U.id),se.delete(U.id),U.streaming=!1,p(U)};if(!ct){nt(Be),Ct();return}let jt=Co(_e);if(jt!==null&&jt.trim()!==""){nt(jt),Ct();return}let P=ge=>{var It;let dt=typeof ge=="string"?ge:(It=ge==null?void 0:ge.text)!=null?It:null;if(dt!==null&&dt.trim()!=="")return dt;let Ke=ct.getExtractedText();return Ke!==null&&Ke.trim()!==""?Ke:Be},he;try{he=ct.processChunk(_e)}catch{nt(Be),Ct();return}if(he instanceof Promise){he.then(ge=>{nt(P(ge)),Ct()}).catch(()=>{nt(Be),Ct()});return}nt(P(he)),Ct()},ne=[],Te=!1,ve,Ht=()=>{Te||(Te=!0,queueMicrotask(()=>{Te=!1,ve()}))},ie=new Aa((U,Ae)=>{ne.push({payloadType:U,payload:Ae}),Ht()}),re=null,sn=new Map,Nt=(zt=this.config.iterationDisplay)!=null?zt:"separate";for(ve=()=>{var U,Ae,Be,De,_e,ct,nt,Ct,jt,P,he,ge,dt,Ke,It,an,At,bt,Mt,ut,Vt,wr,_n,Br,vt,pr,ur,Cr,Qn,gt,io,mr,lo,Sn,ko,Dr,Ar,yt,Pn,In,fn,kt,jn,Un,Wn,Nr,Sr,Or,Rn,Wt,hn,qn,Fr,Er,$r,gr,Hn,Zn,ft,Kt,Jt,Bn,_r,zn,er,Dn,_,de,Nn,tr,fr,ns,nr,rr,or,Tr,co,Js,rs,Gs,Lo,mt,os,Vn,En,Xs,Ys,Po,Mr,Qs,po,ss,kr,as,jr,Ur,Zs,ea,fi,uo,qr,ta,is,zr,na,ls,Vr,cs,ra,Lr,oa,Kr,Rt,Io,Wo,ds,hr,sa,ps,us,aa,Ro,Ho,mo,ia,la,ms,gs,fs,hs,yn,On,Pr,rt,ys,go,sr,ca;for(let Jr=0;Jr<ne.length;Jr++){let Ve=ne[Jr].payloadType,C=ne[Jr].payload;if(Ve==="reason_start"){let j=(U=pe(C,!0))!=null?U:`reason-${l()}`,M=ce(j);M.reasoning=(Ae=M.reasoning)!=null?Ae:{id:j,status:"streaming",chunks:[]},M.reasoning.startedAt=(De=M.reasoning.startedAt)!=null?De:Re((Be=C.startedAt)!=null?Be:C.timestamp),M.reasoning.completedAt=void 0,M.reasoning.durationMs=void 0,M.streaming=!0,M.reasoning.status="streaming",p(M)}else if(Ve==="reason_delta"||Ve==="reason_chunk"){let j=(ct=(_e=pe(C,!1))!=null?_e:pe(C,!0))!=null?ct:`reason-${l()}`,M=ce(j);M.reasoning=(nt=M.reasoning)!=null?nt:{id:j,status:"streaming",chunks:[]},M.reasoning.startedAt=(jt=M.reasoning.startedAt)!=null?jt:Re((Ct=C.startedAt)!=null?Ct:C.timestamp);let Z=(ge=(he=(P=C.reasoningText)!=null?P:C.text)!=null?he:C.delta)!=null?ge:"";if(Z&&C.hidden!==!0){let X=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(X!==void 0){let Y=we(j,X,String(Z));M.reasoning.chunks=[Y]}else M.reasoning.chunks.push(String(Z))}if(M.reasoning.status=C.done?"complete":"streaming",C.done){M.reasoning.completedAt=Re((dt=C.completedAt)!=null?dt:C.timestamp);let X=(Ke=M.reasoning.startedAt)!=null?Ke:Date.now();M.reasoning.durationMs=Math.max(0,((It=M.reasoning.completedAt)!=null?It:Date.now())-X)}M.streaming=M.reasoning.status!=="complete",p(M)}else if(Ve==="reason_complete"){let j=(At=(an=pe(C,!1))!=null?an:pe(C,!0))!=null?At:`reason-${l()}`,M=A.get(j);if(M!=null&&M.reasoning){M.reasoning.status="complete",M.reasoning.completedAt=Re((bt=C.completedAt)!=null?bt:C.timestamp);let X=(Mt=M.reasoning.startedAt)!=null?Mt:Date.now();M.reasoning.durationMs=Math.max(0,((ut=M.reasoning.completedAt)!=null?ut:Date.now())-X),M.streaming=!1,p(M)}let Z=O(C);Z&&L.byStep.delete(Z)}else if(Ve==="tool_start"){let j=(Vt=He(C,!0))!=null?Vt:`tool-${l()}`,M=(wr=C.toolName)!=null?wr:C.name;if(ae(M)){je.add(j);continue}let Z=ue(j),X=(_n=Z.toolCall)!=null?_n:{id:j,status:"pending"};X.name=M!=null?M:X.name,X.status="running",C.args!==void 0?X.args=C.args:C.parameters!==void 0&&(X.args=C.parameters),X.startedAt=(vt=X.startedAt)!=null?vt:Re((Br=C.startedAt)!=null?Br:C.timestamp),X.completedAt=void 0,X.durationMs=void 0,Z.toolCall=X,Z.streaming=!0;let Y=C.agentContext;(Y||C.executionId)&&(Z.agentMetadata={executionId:(pr=Y==null?void 0:Y.executionId)!=null?pr:C.executionId,iteration:(ur=Y==null?void 0:Y.iteration)!=null?ur:C.iteration}),p(Z)}else if(Ve==="tool_chunk"||Ve==="tool_delta"){let j=(Qn=(Cr=He(C,!1))!=null?Cr:He(C,!0))!=null?Qn:`tool-${l()}`;if(je.has(j))continue;let M=ue(j),Z=(gt=M.toolCall)!=null?gt:{id:j,status:"running"};Z.startedAt=(mr=Z.startedAt)!=null?mr:Re((io=C.startedAt)!=null?io:C.timestamp);let X=(ko=(Sn=(lo=C.text)!=null?lo:C.delta)!=null?Sn:C.message)!=null?ko:"";X&&(Z.chunks=(Dr=Z.chunks)!=null?Dr:[],Z.chunks.push(String(X))),Z.status="running",M.toolCall=Z,M.streaming=!0;let Y=C.agentContext;(Y||C.executionId)&&(M.agentMetadata=(Pn=M.agentMetadata)!=null?Pn:{executionId:(Ar=Y==null?void 0:Y.executionId)!=null?Ar:C.executionId,iteration:(yt=Y==null?void 0:Y.iteration)!=null?yt:C.iteration}),p(M)}else if(Ve==="tool_complete"){let j=(fn=(In=He(C,!1))!=null?In:He(C,!0))!=null?fn:`tool-${l()}`;if(je.has(j)){je.delete(j);continue}let M=ue(j),Z=(kt=M.toolCall)!=null?kt:{id:j,status:"running"};Z.status="complete",C.result!==void 0&&(Z.result=C.result),typeof C.duration=="number"&&(Z.duration=C.duration),Z.completedAt=Re((jn=C.completedAt)!=null?jn:C.timestamp);let X=(Un=C.duration)!=null?Un:C.executionTime;if(typeof X=="number")Z.durationMs=X;else{let Fe=(Wn=Z.startedAt)!=null?Wn:Date.now();Z.durationMs=Math.max(0,((Nr=Z.completedAt)!=null?Nr:Date.now())-Fe)}M.toolCall=Z,M.streaming=!1;let Y=C.agentContext;(Y||C.executionId)&&(M.agentMetadata=(Rn=M.agentMetadata)!=null?Rn:{executionId:(Sr=Y==null?void 0:Y.executionId)!=null?Sr:C.executionId,iteration:(Or=Y==null?void 0:Y.iteration)!=null?Or:C.iteration}),p(M);let Ye=V(C);Ye&&w.byCall.delete(Ye)}else if(Ve==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let j=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,M=(Wt=j!=null?j:C.toolId)!=null?Wt:`local-${l()}`,Z=ue(M),X=(hn=Z.toolCall)!=null?hn:{id:M,status:"pending"};X.name=C.toolName,X.args=C.parameters,X.status="complete",X.chunks=(qn=X.chunks)!=null?qn:[],X.startedAt=(Er=X.startedAt)!=null?Er:Re((Fr=C.startedAt)!=null?Fr:C.timestamp),X.completedAt=($r=X.completedAt)!=null?$r:X.startedAt,Z.toolCall=X,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(Hn=C.executionId)!=null?Hn:(gr=Z.agentMetadata)==null?void 0:gr.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},p(Z)}else if(Ve==="text_start"){if((Zn=C.toolContext)!=null&&Zn.toolId)continue;let j=C.partId;if(j!==void 0&&x.current!==null&&j!==x.current){let M=f;M&&(M.streaming=!1,p(M),z=M,f=null,S=!0)}j!==void 0&&(x.current=j)}else if(Ve==="text_end"){if((ft=C.toolContext)!=null&&ft.toolId)continue;let j=f;j&&(j.streaming=!1,p(j),z=j,f=null,S=!0)}else if(Ve==="step_chunk"||Ve==="step_delta"){let j=C.stepType,M=C.executionType;if(j==="tool"||M==="context")continue;let Z=C.toolContext;if(Z!=null&&Z.toolId){let Fe=String((Jt=(Kt=C.id)!=null?Kt:Z.stepId)!=null?Jt:`step-${l()}`),Ze=C.partId!==void 0&&C.partId!==null?String(C.partId):"",Me=`${Z.toolId}::${Fe}`,Ge=H.get(Me);if(Ze!==""&&Ge!==void 0&&Ge!==""&&Ge!==Ze){let wt=R.get(B(Z.toolId,Fe,Ge));wt&&wt.streaming!==!1&&(wt.streaming=!1,p(wt))}Ze!==""&&H.set(Me,Ze);let Lt=$(Z.toolId,Fe,Ze,Z.executionId),en=(er=(zn=(_r=(Bn=C.text)!=null?Bn:C.delta)!=null?_r:C.content)!=null?zn:C.chunk)!=null?er:"";en&&(Lt.content+=String(en),Lt.streaming=!0,p(Lt)),C.isComplete&&(Lt.streaming=!1,p(Lt));continue}let X=C.partId;if(X!==void 0&&x.current!==null&&X!==x.current){let Fe=f;Fe&&(Fe.streaming=!1,p(Fe),z=Fe,f=null,S=!0)}X!==void 0&&(x.current=X);let Y=X!==void 0&&(Dn=J.get(X))!=null?Dn:Pe();X!==void 0&&(Y.partId||(Y.partId=X),J.set(X,Y));let Ye=(tr=(Nn=(de=(_=C.text)!=null?_:C.delta)!=null?de:C.content)!=null?Nn:C.chunk)!=null?tr:"";if(Ye){let Fe=typeof C.seq=="number"?C.seq:void 0,Ze=X!=null?X:Y.id,Me=Fe!==void 0?we(Ze,Fe,String(Ye)):((fr=se.get(Y.id))!=null?fr:"")+Ye;Y.rawContent=Me,K.has(Y.id)||K.set(Y.id,this.createStreamParser());let Ge=K.get(Y.id),Lt=Me.trim().startsWith("{")||Me.trim().startsWith("[");if(Lt&&se.set(Y.id,Me),Ge.__isPlainTextParser===!0){Y.content=Fe!==void 0?Me:Y.content+Ye,se.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y);continue}let wt=Ge.processChunk(Me);if(wt instanceof Promise)wt.then(Et=>{var dn;let tn=typeof Et=="string"?Et:(dn=Et==null?void 0:Et.text)!=null?dn:null;if(tn!==null&&tn.trim()!=="")Y.content=tn,p(Y);else if(!Lt&&!Me.trim().startsWith("<")){let bn=f,Gt=bn&&bn.id===Y.id?bn:Y;Gt.id===Y.id&&(Gt.content=Fe!==void 0?Me:Gt.content+Ye,se.delete(Gt.id),K.delete(Gt.id),Gt.rawContent=void 0,p(Gt))}}).catch(()=>{Y.content=Fe!==void 0?Me:Y.content+Ye,se.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y)});else{let Et=typeof wt=="string"?wt:(ns=wt==null?void 0:wt.text)!=null?ns:null;Et!==null&&Et.trim()!==""?(Y.content=Et,p(Y)):!Lt&&!Me.trim().startsWith("<")&&(Y.content=Fe!==void 0?Me:Y.content+Ye,se.delete(Y.id),K.delete(Y.id),Y.rawContent=void 0,p(Y))}}if(C.isComplete){let Fe=(rr=(nr=C.result)==null?void 0:nr.response)!=null?rr:Y.content;if(Fe){let Ze=se.get(Y.id),Me=Ze!=null?Ze:tt(Fe);Y.rawContent=Me;let Ge=K.get(Y.id),Lt=null,en=!1;if(Ge&&(Lt=Ge.getExtractedText(),Lt===null&&(Lt=Co(Me)),Lt===null)){let wt=Ge.processChunk(Me);wt instanceof Promise?(en=!0,wt.then(Et=>{var dn;let tn=typeof Et=="string"?Et:(dn=Et==null?void 0:Et.text)!=null?dn:null;if(tn!==null){let bn=f;bn&&bn.id===Y.id&&(bn.content=tn,bn.streaming=!1,K.delete(bn.id),se.delete(bn.id),p(bn))}})):Lt=typeof wt=="string"?wt:(or=wt==null?void 0:wt.text)!=null?or:null}if(!en){Lt!==null&&Lt.trim()!==""?Y.content=Lt:se.has(Y.id)||(Y.content=tt(Fe));let wt=K.get(Y.id);if(wt){let Et=(Tr=wt.close)==null?void 0:Tr.call(wt);Et instanceof Promise&&Et.catch(()=>{}),K.delete(Y.id)}se.delete(Y.id),Y.streaming=!1,p(Y)}}}}else if(Ve==="step_complete"){let j=C.stepType,M=C.executionType;if(j==="tool"||M==="context")continue;let Z=C.toolContext;if(Z!=null&&Z.toolId){let Fe=String((Js=(co=C.id)!=null?co:Z.stepId)!=null?Js:"");if(Fe){let Ze=F(Z.toolId,Fe);for(let[Me,Ge]of R)Me.startsWith(Ze)&&Ge.streaming!==!1&&(Ge.streaming=!1,p(Ge));H.delete(`${Z.toolId}::${Fe}`)}continue}let X=C.stopReason;if(S){if(f!==null){let Me=f;X&&(Me.stopReason=X),K.delete(Me.id),se.delete(Me.id),Me.streaming!==!1&&(Me.streaming=!1,p(Me))}let Fe=(rs=C.result)==null?void 0:rs.response,Ze=z;Ze&&(X&&(Ze.stopReason=X),Fe!=null?$e(Ze,Fe):(K.delete(Ze.id),se.delete(Ze.id))),z=null;continue}let Y=(Gs=C.result)==null?void 0:Gs.response,Ye=Pe();if(X&&(Ye.stopReason=X),Y!=null){let Fe=K.get(Ye.id),Ze=!1,Me=!1;if(Fe){let Ge=Fe.getExtractedText(),Lt=se.get(Ye.id),en=Lt!=null?Lt:tt(Y);if(Ye.rawContent=en,Ge!==null&&Ge.trim()!=="")Ye.content=Ge,Ze=!0;else{let wt=Co(en);if(wt!==null)Ye.content=wt,Ze=!0;else{let Et=Fe.processChunk(en);if(Et instanceof Promise)Me=!0,Et.then(tn=>{var bn;let dn=typeof tn=="string"?tn:(bn=tn==null?void 0:tn.text)!=null?bn:null;if(dn!==null&&dn.trim()!==""){let Gt=f;Gt&&Gt.id===Ye.id&&(Gt.content=dn,Gt.streaming=!1,K.delete(Gt.id),se.delete(Gt.id),p(Gt))}else{let Gt=Fe.getExtractedText(),Kn=f;Kn&&Kn.id===Ye.id&&(Gt!==null&&Gt.trim()!==""?Kn.content=Gt:se.has(Kn.id)||(Kn.content=tt(Y)),Kn.streaming=!1,K.delete(Kn.id),se.delete(Kn.id),p(Kn))}});else{let tn=typeof Et=="string"?Et:(Lo=Et==null?void 0:Et.text)!=null?Lo:null;if(tn!==null&&tn.trim()!=="")Ye.content=tn,Ze=!0;else{let dn=Fe.getExtractedText();dn!==null&&dn.trim()!==""&&(Ye.content=dn,Ze=!0)}}}}}if(!Me){if(!Ye.rawContent){let Ge=se.get(Ye.id);Ye.rawContent=Ge!=null?Ge:tt(Y)}if(!Ze&&!se.has(Ye.id)&&(Ye.content=tt(Y)),Fe){let Ge=(mt=Fe.close)==null?void 0:mt.call(Fe);Ge instanceof Promise&&Ge.catch(()=>{})}K.delete(Ye.id),se.delete(Ye.id),Ye.streaming=!1,p(Ye)}}else K.delete(Ye.id),se.delete(Ye.id),Ye.streaming=!1,p(Ye)}else if(Ve==="flow_complete"){let j=(os=C.result)==null?void 0:os.response;if(S){if(f!==null){let M=f;K.delete(M.id),se.delete(M.id),M.streaming!==!1&&(M.streaming=!1,p(M))}}else if(j!=null){let M=Pe(),Z=se.get(M.id),X=Z!=null?Z:tt(j);M.rawContent=X;let Y=tt(j),Ye=K.get(M.id);if(Ye){let Me=Co(X);if(Me!==null)Y=Me;else{let Ge=Ye.processChunk(X);Ge instanceof Promise&&Ge.then(en=>{var Et;let wt=typeof en=="string"?en:(Et=en==null?void 0:en.text)!=null?Et:null;wt!==null&&(M.content=wt,M.streaming=!1,p(M))});let Lt=Ye.getExtractedText();Lt!==null&&(Y=Lt)}}K.delete(M.id),se.delete(M.id);let Fe=Y!==M.content,Ze=M.streaming!==!1;Fe&&(M.content=Y),M.streaming=!1,(Fe||Ze)&&p(M)}else if(f!==null){let M=f;K.delete(M.id),se.delete(M.id),M.streaming!==!1&&(M.streaming=!1,p(M))}t({type:"status",status:"idle"})}else if(Ve==="agent_start")re={executionId:C.executionId,agentId:(Vn=C.agentId)!=null?Vn:"virtual",agentName:(En=C.agentName)!=null?En:"",status:"running",currentIteration:0,maxTurns:(Xs=C.maxTurns)!=null?Xs:1,startedAt:Re(C.startedAt)};else if(Ve==="agent_iteration_start"){if(re&&(re.currentIteration=C.iteration),Nt==="separate"&&C.iteration>1){let j=f;j&&(j.streaming=!1,p(j),sn.set(C.iteration-1,j),f=null)}}else if(Ve==="agent_turn_start")m=null;else if(Ve==="agent_turn_delta"){if(C.contentType==="text"){let j=Pe();j.content+=(Ys=C.delta)!=null?Ys:"",j.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:re==null?void 0:re.agentName},m=j,p(j)}else if(C.contentType==="thinking"){let j=(Po=C.turnId)!=null?Po:`agent-think-${C.iteration}`,M=ce(j);M.reasoning=(Mr=M.reasoning)!=null?Mr:{id:j,status:"streaming",chunks:[]},M.reasoning.chunks.push((Qs=C.delta)!=null?Qs:""),M.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},p(M)}else if(C.contentType==="tool_input"){let j=(po=C.toolCallId)!=null?po:w.lastId;if(j){let M=k.get(j);M!=null&&M.toolCall&&(M.toolCall.chunks=(ss=M.toolCall.chunks)!=null?ss:[],M.toolCall.chunks.push((kr=C.delta)!=null?kr:""),p(M))}}}else if(Ve==="agent_turn_complete"){let j=C.turnId;if(j){let X=A.get(j);if(X!=null&&X.reasoning){X.reasoning.status="complete",X.reasoning.completedAt=Re(C.completedAt);let Y=(as=X.reasoning.startedAt)!=null?as:Date.now();X.reasoning.durationMs=Math.max(0,((jr=X.reasoning.completedAt)!=null?jr:Date.now())-Y),X.streaming=!1,p(X)}}let M=C.stopReason,Z=f!=null?f:m;if(M&&Z!==null){let X=C.turnId;(!X||((Ur=Z.agentMetadata)==null?void 0:Ur.turnId)===X)&&(Z.stopReason=M,p(Z))}}else if(Ve==="agent_tool_start"){f&&(f.streaming=!1,p(f),f=null);let j=(Zs=C.toolCallId)!=null?Zs:`agent-tool-${l()}`;Ee(V(C),j);let M=ue(j),Z=(ea=M.toolCall)!=null?ea:{id:j,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};Z.name=(uo=(fi=C.toolName)!=null?fi:C.name)!=null?uo:Z.name,Z.status="running",C.parameters!==void 0&&(Z.args=C.parameters),Z.startedAt=Re((qr=C.startedAt)!=null?qr:C.timestamp),M.toolCall=Z,M.streaming=!0,M.agentMetadata={executionId:C.executionId,iteration:C.iteration},p(M)}else if(Ve==="agent_tool_delta"){let j=(ta=C.toolCallId)!=null?ta:w.lastId;if(j){let M=(is=k.get(j))!=null?is:ue(j);M.toolCall&&(M.toolCall.chunks=(zr=M.toolCall.chunks)!=null?zr:[],M.toolCall.chunks.push((na=C.delta)!=null?na:""),M.toolCall.status="running",M.streaming=!0,p(M))}}else if(Ve==="agent_tool_complete"){let j=(ls=C.toolCallId)!=null?ls:w.lastId;if(j){let M=(Vr=k.get(j))!=null?Vr:ue(j);if(M.toolCall){M.toolCall.status="complete",C.result!==void 0&&(M.toolCall.result=C.result),typeof C.executionTime=="number"&&(M.toolCall.durationMs=C.executionTime),M.toolCall.completedAt=Re((cs=C.completedAt)!=null?cs:C.timestamp),M.streaming=!1,p(M);let Z=V(C);Z&&w.byCall.delete(Z)}}}else if(Ve==="agent_media"){let j=Array.isArray(C.media)?C.media:[],M=[];for(let Z of j){if(!Z||typeof Z!="object")continue;let X=Z,Y=typeof X.type=="string"?X.type:void 0,Ye=typeof X.mediaType=="string"?X.mediaType.toLowerCase():"",Fe=null,Ze="";if(Y==="media"){let Me=typeof X.data=="string"?X.data:void 0;if(!Me)continue;Ze=Ye.length>0?Ye:"application/octet-stream",Fe=`data:${Ze};base64,${Me}`}else if(Y==="image-url"){let Me=typeof X.url=="string"?X.url:void 0;if(!Me)continue;Ze=Ye,Fe=Me}else if(Y==="file-url"){let Me=typeof X.url=="string"?X.url:void 0;if(!Me)continue;Ze=Ye,Fe=Me}else continue;if(Fe)if(Y==="image-url"||Ze.startsWith("image/"))M.push({type:"image",image:Fe,...Ze?{mimeType:Ze}:{}});else if(Ze.startsWith("audio/"))M.push({type:"audio",audio:Fe,mimeType:Ze});else if(Ze.startsWith("video/"))M.push({type:"video",video:Fe,mimeType:Ze});else{let Me=Ze||"application/octet-stream";M.push({type:"file",data:Fe,mimeType:Me,filename:Nm(Me)})}}if(M.length>0){let Z=l(),X=C.toolCallId,Ye={id:`agent-media-${typeof X=="string"&&X.length>0?`${X}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:M,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(Ye);let Fe=f;Fe&&(Fe.streaming=!1,p(Fe)),f=null,v.current=null}}else if(Ve!=="agent_iteration_complete"){if(Ve==="agent_reflection"||Ve==="agent_reflect"){let j=`agent-reflection-${C.executionId}-${C.iteration}`,M={id:j,role:"assistant",content:(ra=C.reflection)!=null?ra:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:j,status:"complete",chunks:[(Lr=C.reflection)!=null?Lr:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(M)}else if(Ve==="agent_complete"){re&&(re.status=C.success?"complete":"error",re.completedAt=Re(C.completedAt),re.stopReason=C.stopReason);let j=f;j&&(j.streaming=!1,p(j)),t({type:"status",status:"idle"})}else if(Ve==="agent_error"){let j=typeof C.error=="string"?C.error:(Kr=(oa=C.error)==null?void 0:oa.message)!=null?Kr:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",j):t({type:"error",error:new Error(j)})}else if(Ve!=="agent_ping"){if(Ve==="agent_approval_start"){let j=(Rt=C.approvalId)!=null?Rt:`approval-${l()}`,M={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(Io=re==null?void 0:re.agentId)!=null?Io:"virtual",executionId:(ds=(Wo=C.executionId)!=null?Wo:re==null?void 0:re.executionId)!=null?ds:"",toolName:(hr=C.toolName)!=null?hr:"",toolType:C.toolType,description:(ps=C.description)!=null?ps:`Execute ${(sa=C.toolName)!=null?sa:"tool"}`,parameters:C.parameters}};p(M)}else if(Ve==="step_await"&&C.awaitReason==="approval_required"){let j=(us=C.approvalId)!=null?us:`approval-${l()}`,M={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:"pending",agentId:(aa=re==null?void 0:re.agentId)!=null?aa:"virtual",executionId:(Ho=(Ro=C.executionId)!=null?Ro:re==null?void 0:re.executionId)!=null?Ho:"",toolName:(mo=C.toolName)!=null?mo:"",toolType:C.toolType,description:(la=C.description)!=null?la:`Execute ${(ia=C.toolName)!=null?ia:"tool"}`,parameters:C.parameters}};p(M)}else if(Ve==="agent_approval_complete"){let j=C.approvalId;if(j){let Z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:j,status:(ms=C.decision)!=null?ms:"approved",agentId:(gs=re==null?void 0:re.agentId)!=null?gs:"virtual",executionId:(hs=(fs=C.executionId)!=null?fs:re==null?void 0:re.executionId)!=null?hs:"",toolName:(yn=C.toolName)!=null?yn:"",description:(On=C.description)!=null?On:"",resolvedAt:Date.now()}};p(Z)}}else if(Ve==="artifact_start"||Ve==="artifact_delta"||Ve==="artifact_update"||Ve==="artifact_complete"){if(Ve==="artifact_start"){let j=C.artifactType,M=String(C.id),Z=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:M,artifactType:j,title:Z,component:typeof C.component=="string"?C.component:void 0}),G.set(M,{markdown:"",title:Z}),!xe.has(M)){xe.add(M);let X={id:`artifact-ref-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:M,title:Z,artifactType:j,status:"streaming"}})};te.set(M,X),p(X)}}else if(Ve==="artifact_delta"){let j=String(C.id),M=typeof C.delta=="string"?C.delta:String((Pr=C.delta)!=null?Pr:"");t({type:"artifact_delta",id:j,artDelta:M});let Z=G.get(j);Z&&(Z.markdown+=M)}else if(Ve==="artifact_update"){let j=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:j,component:typeof C.component=="string"?C.component:void 0})}else if(Ve==="artifact_complete"){let j=String(C.id);t({type:"artifact_complete",id:j});let M=te.get(j);if(M){M.streaming=!1;try{let Z=JSON.parse((rt=M.rawContent)!=null?rt:"{}");if(Z.props){Z.props.status="complete";let X=G.get(j);X!=null&&X.markdown&&(Z.props.markdown=X.markdown)}M.rawContent=JSON.stringify(Z)}catch{}G.delete(j),p(M),te.delete(j)}}}else if(Ve==="transcript_insert"){let j=C.message;if(!j||typeof j!="object")continue;let M=String((ys=j.id)!=null?ys:`msg-${l()}`),Z=j.role,Y={id:M,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:l()};if(p(Y),Y.rawContent)try{let Ye=JSON.parse(Y.rawContent),Fe=(go=Ye==null?void 0:Ye.props)==null?void 0:go.artifactId;typeof Fe=="string"&&xe.add(Fe)}catch{}f=null,v.current=null,K.delete(M),se.delete(M)}else if(Ve==="error"||Ve==="step_error"||Ve==="dispatch_error"||Ve==="flow_error"){let j=null;if(C.error instanceof Error)j=C.error;else if(Ve==="dispatch_error"){let M=(sr=C.message)!=null?sr:C.error;M!=null&&M!==""&&(j=new Error(String(M)))}else if(Ve==="step_error"||Ve==="flow_error"){let M=C.error;typeof M=="string"&&M!==""?j=new Error(M):M!=null&&typeof M=="object"&&"message"in M&&(j=new Error(String((ca=M.message)!=null?ca:M)))}else Ve==="error"&&C.error!=null&&C.error!==""&&(j=new Error(String(C.error)));if(j){t({type:"error",error:j});let M=f;M&&M.streaming&&(M.streaming=!1,p(M)),t({type:"status",status:"idle"})}}}}}ne.length=0};;){let{done:U,value:Ae}=await s.read();if(U)break;a+=o.decode(Ae,{stream:!0});let Be=a.split(`
10
+
11
+ `);a=(vr=Be.pop())!=null?vr:"";for(let De of Be){let _e=De.split(`
12
+ `),ct="message",nt="";for(let P of _e)P.startsWith("event:")?ct=P.replace("event:","").trim():P.startsWith("data:")&&(nt+=P.replace("data:","").trim());if(!nt)continue;let Ct;try{Ct=JSON.parse(nt)}catch(P){t({type:"error",error:P instanceof Error?P:new Error("Failed to parse chat stream payload")});continue}let jt=ct!=="message"?ct:(dr=Ct.type)!=null?dr:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,jt,Ct),this.parseSSEEvent){v.current=f;let P=await this.handleCustomSSEEvent(Ct,t,v,p,l,x);if(v.current&&v.current!==f&&(f=v.current),P)continue}ie.push(jt,Ct),ve()}}ie.flushPending(),ve(),ie.destroy()}};function $m(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Ts(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function jo(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Ea="[Image]";function _m(e){return typeof e=="string"?[{type:"text",text:e}]:e}function jm(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Um(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function qm(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Ta(e){return{type:"text",text:e}}function zm(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function Vm(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Km(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Ep=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Jm=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Rr=[...Ep,...Jm];function Gm(e){return Ep.includes(e)||e.startsWith("image/")}function Ma(e){return Gm(e.type)}async function Tp(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Ma(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Mp(e,n=Rr,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Xm(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function kp(e,n){let t=Xm(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var ka=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(t),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var La=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Ms=class{constructor(n){this.config=n;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new La;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,x=A=>{v||(v=!0,clearTimeout(S),m(new Error(A)))},S=setTimeout(()=>x("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(S),f())},{once:!0}),this.ws.addEventListener("error",()=>{x("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",A=>{if(!A.wasClean&&!v){let k=A.code!==1006?` (code ${A.code})`:"";x("WebSocket connection failed"+k+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ka(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var n,t,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let l=0;l<t.length;l++)r[l]=t.charCodeAt(l);let s=n.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Ao=class{constructor(n={}){this.config=n;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(n=>n("connected"))}async startListening(){var n,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Uo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ms(e.runtype);case"browser":if(!Ao.isSupported())throw new Error("Browser speech recognition not supported");return new Ao(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ai(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Uo({type:"runtype",runtype:e.runtype});if(Ao.isSupported())return Uo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Pa(e){try{return Ai(e),!0}catch{return!1}}function Lp(e,n){let t=e instanceof Error?e:new Error(String(e));if(typeof n=="string")return n;if(typeof n=="function")return n(t);let r="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return t.message?`${r}
13
+
14
+ _Details: ${t.message}_`:r}var ks=class e{constructor(n={},t){this.config=n;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=n=>{var t,r,s,o,a,i,d,l;if(n.type==="message"){this.upsertMessage(n.message);let u=n.message.toolCall;((t=n.message.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&(u!=null&&u.name)&&ba(u.name)&&this.enqueueWebMcpAwait(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(s=n.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})}else if(n.type==="status"){if(this.setStatus(n.status),n.status==="connecting")this.setStreaming(!0);else if(n.status==="idle"||n.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((a=this.agentExecution)==null?void 0:a.status)==="running"&&(n.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else n.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(l=(d=this.callbacks).onError)==null||l.call(d,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r,s;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(o=>{var a;return{...o,sequence:(a=o.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new _o(n),this.wireDefaultWebMcpConfirm();for(let o of(s=n.initialArtifacts)!=null?s:[])this.artifacts.set(o.id,{...o,status:"complete"});n.initialSelectedArtifactId!=null&&(this.selectedArtifactId=n.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return Pa((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Uo(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let l=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=l.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(l=>{var u,p,f,m,v,x;if(l.provider==="browser")l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0});else if(l.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=l.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=l.transcript)!=null&&p.trim()&&this.injectUserMessage({content:l.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=l.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=l.text)!=null&&m.trim()&&this.injectAssistantMessage({content:l.text.trim()});{let S=(x=this.pendingVoiceAssistantMessageId)!=null?x:(v=[...this.messages].reverse().find(A=>A.role==="assistant"))==null?void 0:v.id;S&&this.ttsSpokenMessageIds.add(S)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),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(l=>{var u,p;this.voiceStatus=l,this.voiceActive=l==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,l)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,d,l,u;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((l=n.browser)==null?void 0:l.language)||"en-US",continuous:(u=n.browser)==null?void 0:u.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new _o(this.config),this.wireDefaultWebMcpConfirm(),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:u,rawContent:p}=n,m={id:a!=null?a:t==="user"?Ts():t==="assistant"?jo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u},...p!==void 0&&{rawContent:p}};return this.upsertMessage(m),m}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:u,streaming:p=!1,voiceProcessing:f,rawContent:m}=r,x={id:d!=null?d:s==="user"?Ts():s==="assistant"?jo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:l!=null?l:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...m!==void 0&&{rawContent:m}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(n){let{component:t,props:r={},text:s="",llmContent:o,id:a,createdAt:i,sequence:d}=n,l={text:s,component:t,props:r};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(l),...o!==void 0&&{llmContent:o},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(n,t){var l,u,p,f,m;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let s=Ts(),o=jo(),a={id:s,role:"user",content:r||Ea,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let S=Lp(v,this.config.errorMessage);if(S){let A={id:o,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(A)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=jo();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(l){let u=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!u){let p=Lp(l,this.config.errorMessage);if(p){let f={id:n,role:"assistant",createdAt:new Date().toISOString(),content:p,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(l instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(n,t){var s,o,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let n=this.config.webmcp;(n==null?void 0:n.enabled)===!0&&!n.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(n){var s,o,a;try{if(((o=(s=this.config.webmcp)==null?void 0:s.autoApprove)==null?void 0:o.call(s,n))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:n.toolName,toolType:"webmcp",description:(a=n.description)!=null?a:`Allow the assistant to run ${n.toolName}?`,parameters:n.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(n,t){let r=this.webMcpApprovalResolvers.get(n);if(!r)return;this.webMcpApprovalResolvers.delete(n);let s=this.messages.find(o=>o.id===n);s!=null&&s.approval&&this.upsertMessage({...s,approval:{...s.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(n,t){var d,l,u,p;let r=`approval-${n.id}`,s={...n,status:t,resolvedAt:Date.now()},o={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o),(d=this.abortController)==null||d.abort(),this.abortController=new AbortController,this.setStreaming(!0);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let f;if(i?f=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):f=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),f){let m=null;if(f instanceof Response){if(!f.ok){let v=await f.json().catch(()=>null);throw new Error((l=v==null?void 0:v.error)!=null?l:`Approval request failed: ${f.status}`)}m=f.body}else f instanceof ReadableStream&&(m=f);m?await this.connectStream(m,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(f){let m=f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||(p=(u=this.callbacks).onError)==null||p.call(u,f instanceof Error?f:new Error(String(f)))}}persistAskUserQuestionProgress(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(n,t){let r=this.messages.find(s=>s.id===n.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(n,t){var u,p,f,m,v,x,S,A,k,R,H,L;let r=this.messages.find(w=>w.id===n.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let s=(p=n.agentMetadata)==null?void 0:p.executionId,o=(f=n.toolCall)==null?void 0:f.name;if(!s||!o){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let w=(x=n.toolCall)==null?void 0:x.args,B=Array.isArray(w==null?void 0:w.questions)?w.questions:[];if(B.length===1){let F=typeof((S=B[0])==null?void 0:S.question)=="string"?B[0].question:"";F&&(a={[F]:t})}}this.markAskUserQuestionResolved(n,a),(A=this.abortController)==null||A.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=n.toolCall.id,d=(k=n.toolCall)==null?void 0:k.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let w=typeof t=="string"?t:Object.entries(t).map(([B,F])=>`${B}: ${Array.isArray(F)?F.join(", "):F}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:w,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let w=a!=null?a:{};l.forEach((B,F)=>{let $=typeof(B==null?void 0:B.question)=="string"?B.question:"";if(!$)return;let W=w[$],O=Array.isArray(W)?W.join(", "):typeof W=="string"?W:"";this.appendMessage({id:`ask-user-q-${i}-${F}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${F}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let w=await this.client.resumeFlow(s,{[o]:t});if(!w.ok){let B=await w.json().catch(()=>null);throw new Error((R=B==null?void 0:B.error)!=null?R:`Resume failed: ${w.status}`)}w.body?await this.connectStream(w.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(w){let B=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,B||(L=(H=this.callbacks).onError)==null||L.call(H,w instanceof Error?w:new Error(String(w)))}}enqueueWebMcpAwait(n){var o,a;let t=(o=n.agentMetadata)==null?void 0:o.executionId,r=(a=n.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(n)});return}let s=this.webMcpAwaitBatches.get(t);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,s)),!s.seen.has(r)&&(s.seen.add(r),s.snapshots.push(n))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let n=this.webMcpEpoch;queueMicrotask(()=>{if(n===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(n){let t=this.webMcpAwaitBatches.get(n);if(!t)return;this.webMcpAwaitBatches.delete(n);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(n,r)}async resolveWebMcpToolCallBatch(n,t){var i,d,l;let r=[],s=[],o=new AbortController;this.webMcpResolveControllers.add(o),this.setStreaming(!0);let a=await Promise.all(t.map(async u=>{var k,R,H,L,w,B,F;let p=(k=u.toolCall)==null?void 0:k.name,f=(R=u.toolCall)==null?void 0:R.id;if(!p||!f)return null;let m=`${n}:${f}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m))return null;this.webMcpInflightKeys.add(m),r.push(m),this.upsertMessage({...u,agentMetadata:{...u.agentMetadata,awaitingLocalTool:!1}});let v=new AbortController;this.webMcpResolveControllers.add(v),s.push(v);let x=(L=(H=u.agentMetadata)==null?void 0:H.webMcpToolCallId)!=null?L:p,S=this.client.executeWebMcpToolCall(p,(w=u.toolCall)==null?void 0:w.args,v.signal),A;if(!S)A={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{A=await S}catch($){return $ instanceof Error&&($.name==="AbortError"||$.message.includes("aborted")||$.message.includes("abort"))||(F=(B=this.callbacks).onError)==null||F.call(B,$ instanceof Error?$:new Error(String($))),this.webMcpInflightKeys.delete(m),null}return v.signal.aborted?(this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:x,output:A}}));try{let u=a.filter(m=>m!==null);if(u.length===0)return;let p={};for(let m of u)p[m.resumeKey]=m.output;let f=await this.client.resumeFlow(n,p,{signal:o.signal});if(!f.ok){let m=await f.json().catch(()=>null);throw new Error((i=m==null?void 0:m.error)!=null?i:`Resume failed: ${f.status}`)}for(let m of u)this.webMcpResolvedKeys.add(m.dedupeKey);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(u){u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))||(l=(d=this.callbacks).onError)==null||l.call(d,u instanceof Error?u:new Error(String(u)))}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of s)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(o),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(n){var u,p,f,m,v,x,S,A,k,R,H,L;let t=(u=n.agentMetadata)==null?void 0:u.executionId,r=(p=n.toolCall)==null?void 0:p.name,s=(f=n.toolCall)==null?void 0:f.id;if(!t){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("WebMCP step_await missing executionId \u2014 dispatch left paused."));return}if(!r)return;if(!s){let w=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w))return;this.webMcpInflightKeys.add(w);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id \u2014 cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(w)}catch(B){(S=(x=this.callbacks).onError)==null||S.call(x,B instanceof Error?B:new Error(String(B)))}finally{this.webMcpInflightKeys.delete(w)}return}let o=`${t}:${s}`;if(this.webMcpInflightKeys.has(o)||this.webMcpResolvedKeys.has(o))return;this.webMcpInflightKeys.add(o),this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1}});let a=new AbortController;this.webMcpResolveControllers.add(a);let{signal:i}=a;this.setStreaming(!0);let d=(A=n.toolCall)==null?void 0:A.args,l=this.client.executeWebMcpToolCall(r,d,i);try{let w;if(l?w=await l:w={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},i.aborted)return;let B=(R=(k=n.agentMetadata)==null?void 0:k.webMcpToolCallId)!=null?R:r;await this.resumeWithToolOutput(t,B,w,{onHttpOk:()=>{this.webMcpResolvedKeys.add(o)},signal:i})}catch(w){w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"))||(L=(H=this.callbacks).onError)==null||L.call(H,w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(o),this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(n,t,r,s){var a,i;let o=await this.client.resumeFlow(n,{[t]:r},{signal:s==null?void 0:s.signal});if(!o.ok){let d=await o.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${o.status}`)}(i=s==null?void 0:s.onHttpOk)==null||i.call(s),o.body?await this.connectStream(o.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let n of this.webMcpResolveControllers)n.abort();this.webMcpResolveControllers.clear();for(let n of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(n,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(n.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(n,t=null){this.artifacts.clear();for(let r of n)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>r.speak(s),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>{var u,p,f,m,v,x;if(o!==r)return s;let a={...s,...t};((u=s.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1});let i=(p=t.toolCall)==null?void 0:p.name,d=(f=t.agentMetadata)==null?void 0:f.executionId,l=(m=t.toolCall)==null?void 0:m.id;if(i&&ba(i)&&d&&l&&((v=t.agentMetadata)==null?void 0:v.awaitingLocalTool)===!0){let S=`${d}:${l}`;(this.webMcpInflightKeys.has(S)||this.webMcpResolvedKeys.has(S))&&(a.agentMetadata={...(x=a.agentMetadata)!=null?x:{},awaitingLocalTool:!1})}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var d,l;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},br=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};import{Activity as Ym,ArrowDown as Qm,ArrowUp as Zm,ArrowUpRight as eg,Bot as tg,ChevronDown as ng,ChevronUp as rg,ChevronRight as og,ChevronLeft as sg,Check as ag,Clipboard as ig,ClipboardCopy as lg,Copy as cg,File as dg,FileCode as pg,FileSpreadsheet as ug,FileText as mg,ImagePlus as gg,Loader as fg,LoaderCircle as hg,Mic as yg,Paperclip as bg,RefreshCw as xg,Search as vg,Send as wg,ShieldAlert as Cg,ShieldCheck as Ag,ShieldX as Sg,Square as Eg,ThumbsDown as Tg,ThumbsUp as Mg,Upload as kg,Volume2 as Lg,X as Pg,User as Ig,Mail as Wg,Phone as Rg,Calendar as Hg,Clock as Bg,Building as Dg,MapPin as Ng,Lock as Og,Key as Fg,CreditCard as $g,AtSign as _g,Hash as jg,Globe as Ug,Link as qg,CircleCheck as zg,CircleX as Vg,TriangleAlert as Kg,Info as Jg,Ban as Gg,Shield as Xg,ArrowLeft as Yg,ArrowRight as Qg,ExternalLink as Zg,Ellipsis as ef,EllipsisVertical as tf,Menu as nf,House as rf,Plus as of,Minus as sf,Pencil as af,Trash as lf,Trash2 as cf,Save as df,Download as pf,Share as uf,Funnel as mf,Settings as gf,RotateCw as ff,Maximize as hf,Minimize as yf,ShoppingCart as bf,ShoppingBag as xf,Package as vf,Truck as wf,Tag as Cf,Gift as Af,Receipt as Sf,Wallet as Ef,Store as Tf,DollarSign as Mf,Percent as kf,Play as Lf,Pause as Pf,VolumeX as If,Camera as Wf,Image as Rf,Film as Hf,Headphones as Bf,MessageCircle as Df,MessageSquare as Nf,Bell as Of,Heart as Ff,Star as $f,Eye as _f,EyeOff as jf,Bookmark as Uf,CalendarDays as qf,History as zf,Timer as Vf,Folder as Kf,FolderOpen as Jf,Files as Gf,Sparkles as Xf,Zap as Yf,Sun as Qf,Moon as Zf,Flag as eh,Monitor as th,Smartphone as nh}from"lucide";var rh={activity:Ym,"arrow-down":Qm,"arrow-up":Zm,"arrow-up-right":eg,bot:tg,"chevron-down":ng,"chevron-up":rg,"chevron-right":og,"chevron-left":sg,check:ag,clipboard:ig,"clipboard-copy":lg,copy:cg,file:dg,"file-code":pg,"file-spreadsheet":ug,"file-text":mg,"image-plus":gg,loader:fg,"loader-circle":hg,mic:yg,paperclip:bg,"refresh-cw":xg,search:vg,send:wg,"shield-alert":Cg,"shield-check":Ag,"shield-x":Sg,square:Eg,"thumbs-down":Tg,"thumbs-up":Mg,upload:kg,"volume-2":Lg,x:Pg,user:Ig,mail:Wg,phone:Rg,calendar:Hg,clock:Bg,building:Dg,"map-pin":Ng,lock:Og,key:Fg,"credit-card":$g,"at-sign":_g,hash:jg,globe:Ug,link:qg,"circle-check":zg,"circle-x":Vg,"triangle-alert":Kg,info:Jg,ban:Gg,shield:Xg,"arrow-left":Yg,"arrow-right":Qg,"external-link":Zg,ellipsis:ef,"ellipsis-vertical":tf,menu:nf,house:rf,plus:of,minus:sf,pencil:af,trash:lf,"trash-2":cf,save:df,download:pf,share:uf,funnel:mf,settings:gf,"rotate-cw":ff,maximize:hf,minimize:yf,"shopping-cart":bf,"shopping-bag":xf,package:vf,truck:wf,tag:Cf,gift:Af,receipt:Sf,wallet:Ef,store:Tf,"dollar-sign":Mf,percent:kf,play:Lf,pause:Pf,"volume-x":If,camera:Wf,image:Rf,film:Hf,headphones:Bf,"message-circle":Df,"message-square":Nf,bell:Of,heart:Ff,star:$f,eye:_f,"eye-off":jf,bookmark:Uf,"calendar-days":qf,history:zf,timer:Vf,folder:Kf,"folder-open":Jf,files:Gf,sparkles:Xf,zap:Yf,sun:Qf,moon:Zf,flag:eh,monitor:th,smartphone:nh},fe=(e,n=24,t="currentColor",r=2)=>{let s=rh[e];return s?oh(s,n,t,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function oh(e,n,t,r){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(r)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(!Array.isArray(o)||o.length<2)return;let a=o[0],i=o[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,u])=>{l!=="stroke"&&d.setAttribute(l,String(u))}),s.appendChild(d)}),s}var Ia={allowedTypes:Rr,maxFileSize:10*1024*1024,maxFiles:4};function sh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ah(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-code":"file"}var qo=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Ia.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Ia.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:Ia.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Ia.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,d;if(n.length){for(let l of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,l,"count");continue}let u=Mp(l,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,l,p);continue}try{let p=await Tp(l),f=Ma(l)?URL.createObjectURL(l):null,m={id:sh(),file:l,previewUrl:f,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(n){var o,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=Ma(n.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=h("img");a.src=n.previewUrl,a.alt=n.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=ah(n.file.type),d=fe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=h("span");l.textContent=kp(n.file.type,n.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=fe("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var Pp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ls(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];Pp(o)&&Pp(s)?t[r]=Ls(o,s):t[r]=s}return t}var Gn="min(440px, calc(100vw - 24px))",Si="440px",Ft={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Gn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{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:void 0,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",borderColor:void 0,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:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},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 Ip(e,n){if(!(!e&&!n))return e?n?Ls(e,n):e:n}function Ei(e){var n,t,r,s,o,a,i,d,l,u,p,f,m,v,x,S,A,k,R,H,L;return e?{...Ft,...e,theme:Ip(Ft.theme,e.theme),darkTheme:Ip(Ft.darkTheme,e.darkTheme),launcher:{...Ft.launcher,...e.launcher,dock:{...(n=Ft.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=Ft.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Ft.copy,...e.copy},sendButton:{...Ft.sendButton,...e.sendButton},statusIndicator:{...Ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ft.voiceRecognition,...e.voiceRecognition},features:(()=>{var ce,Ee,je,te,xe,G,ae,He;let w=(ce=Ft.features)==null?void 0:ce.artifacts,B=(Ee=e.features)==null?void 0:Ee.artifacts,F=(je=Ft.features)==null?void 0:je.scrollToBottom,$=(te=e.features)==null?void 0:te.scrollToBottom,W=(xe=Ft.features)==null?void 0:xe.streamAnimation,O=(G=e.features)==null?void 0:G.streamAnimation,V=(ae=Ft.features)==null?void 0:ae.askUserQuestion,oe=(He=e.features)==null?void 0:He.askUserQuestion,Ie=w===void 0&&B===void 0?void 0:{...w,...B,layout:{...w==null?void 0:w.layout,...B==null?void 0:B.layout}},Pe=F===void 0&&$===void 0?void 0:{...F,...$},ze=W===void 0&&O===void 0?void 0:{...W,...O},pe=V===void 0&&oe===void 0?void 0:{...V,...oe,styles:{...V==null?void 0:V.styles,...oe==null?void 0:oe.styles}};return{...Ft.features,...e.features,...Pe!==void 0?{scrollToBottom:Pe}:{},...Ie!==void 0?{artifacts:Ie}:{},...ze!==void 0?{streamAnimation:ze}:{},...pe!==void 0?{askUserQuestion:pe}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Ft.suggestionChips,suggestionChipsConfig:{...Ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ft.layout,...e.layout,header:{...(a=Ft.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ft.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(p=(u=Ft.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=Ft.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(A=(S=e.layout)==null?void 0:S.messages)==null?void 0:A.timestamp}},slots:{...(k=Ft.layout)==null?void 0:k.slots,...(R=e.layout)==null?void 0:R.slots}},markdown:{...Ft.markdown,...e.markdown,options:{...(H=Ft.markdown)==null?void 0:H.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...Ft.messageActions,...e.messageActions}}:Ft}var Wp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Rp={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Hp={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Gn,maxWidth:Si,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function zo(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?zo(e,r):r}function Ti(e){let n={};function t(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=zo(e,a);d!==void 0&&(n[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function Bp(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function Dp(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=Dp(o,s):t[r]=s}return t}function ih(e,n){return n?Dp(e,n):e}function Ps(e,n={}){var s,o,a,i,d,l,u,p,f,m,v,x,S;let t={palette:Wp,semantic:Rp,components:Hp},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(S=e==null?void 0:e.semantic)==null?void 0:S.typography}},components:ih(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let A=Bp(r);if(!A.valid)throw new Error(`Theme validation failed: ${A.errors.map(k=>k.message).join(", ")}`)}if(n.plugins)for(let A of n.plugins)r=A.transform(r);return r}function Mi(e){var x,S,A,k,R,H,L,w,B,F,$,W,O,V,oe,Ie,Pe,ze,pe,ce,Ee,je,te,xe,G,ae,He,ue,Re,tt,K,se,Oe,J,z,we,$e,ne,Te,ve,Ht,ie,re,sn,Nt,zt,vr,dr,Ue,U,Ae,Be,De,_e,ct,nt,Ct,jt,P,he,ge,dt,Ke,It,an,At,bt,Mt,ut,Vt,wr,_n,Br,vt,pr,ur,Cr,Qn,gt,io,mr,lo,Sn,ko,Dr,Ar,yt,Pn,In,fn,kt,jn,Un,Wn,Nr,Sr,Or,Rn,Wt,hn,qn,Fr,Er,$r,gr,Hn,Zn,ft,Kt,Jt,Bn,_r,zn,er,Dn,_;let n=Ti(e),t={};for(let[de,Nn]of Object.entries(n)){let tr=de.replace(/\./g,"-");t[`--persona-${tr}`]=Nn.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(S=t["--persona-semantic-colors-secondary"])!=null?S:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(A=t["--persona-semantic-colors-accent"])!=null?A:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(k=t["--persona-semantic-colors-surface"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(R=t["--persona-semantic-colors-background"])!=null?R:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(H=t["--persona-semantic-colors-container"])!=null?H:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(L=t["--persona-semantic-colors-text"])!=null?L:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(w=t["--persona-semantic-colors-text-muted"])!=null?w:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(B=t["--persona-semantic-colors-text-inverse"])!=null?B:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(F=t["--persona-semantic-colors-border"])!=null?F:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=($=t["--persona-semantic-colors-divider"])!=null?$:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(W=t["--persona-components-voice-recording-indicator"])!=null?W:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(O=t["--persona-components-voice-recording-background"])!=null?O:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(V=t["--persona-components-voice-processing-icon"])!=null?V:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(oe=t["--persona-components-voice-speaking-icon"])!=null?oe:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ie=t["--persona-components-approval-requested-background"])!=null?Ie:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Pe=t["--persona-components-approval-requested-border"])!=null?Pe:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(ze=t["--persona-components-approval-requested-text"])!=null?ze:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(pe=t["--persona-components-approval-approve-background"])!=null?pe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(ce=t["--persona-components-approval-deny-background"])!=null?ce:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Ee=t["--persona-components-attachment-image-background"])!=null?Ee:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(je=t["--persona-components-attachment-image-border"])!=null?je:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(te=t["--persona-semantic-typography-fontFamily"])!=null?te:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(xe=t["--persona-semantic-typography-fontSize"])!=null?xe:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(G=t["--persona-semantic-typography-fontWeight"])!=null?G:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ae=t["--persona-semantic-typography-lineHeight"])!=null?ae:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(He=t["--persona-palette-radius-sm"])!=null?He:"0.125rem",t["--persona-radius-md"]=(ue=t["--persona-palette-radius-md"])!=null?ue:"0.375rem",t["--persona-radius-lg"]=(Re=t["--persona-palette-radius-lg"])!=null?Re:"0.5rem",t["--persona-radius-xl"]=(tt=t["--persona-palette-radius-xl"])!=null?tt:"0.75rem",t["--persona-radius-full"]=(K=t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-launcher-radius"]=(Oe=(se=t["--persona-components-launcher-borderRadius"])!=null?se:t["--persona-palette-radius-full"])!=null?Oe:"9999px",t["--persona-launcher-bg"]=(J=t["--persona-components-launcher-background"])!=null?J:t["--persona-primary"],t["--persona-launcher-fg"]=(z=t["--persona-components-launcher-foreground"])!=null?z:t["--persona-text-inverse"],t["--persona-launcher-border"]=(we=t["--persona-components-launcher-border"])!=null?we:t["--persona-border"],t["--persona-button-primary-bg"]=($e=t["--persona-components-button-primary-background"])!=null?$e:t["--persona-primary"],t["--persona-button-primary-fg"]=(ne=t["--persona-components-button-primary-foreground"])!=null?ne:t["--persona-text-inverse"],t["--persona-button-radius"]=(ve=(Te=t["--persona-components-button-primary-borderRadius"])!=null?Te:t["--persona-palette-radius-full"])!=null?ve:"9999px",t["--persona-panel-radius"]=(ie=(Ht=t["--persona-components-panel-borderRadius"])!=null?Ht:t["--persona-radius-xl"])!=null?ie:"0.75rem",t["--persona-panel-border"]=(re=t["--persona-components-panel-border"])!=null?re:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Nt=(sn=t["--persona-components-panel-shadow"])!=null?sn:t["--persona-palette-shadows-xl"])!=null?Nt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(vr=(zt=t["--persona-components-input-borderRadius"])!=null?zt:t["--persona-radius-lg"])!=null?vr:"0.5rem",t["--persona-message-user-radius"]=(Ue=(dr=t["--persona-components-message-user-borderRadius"])!=null?dr:t["--persona-radius-lg"])!=null?Ue:"0.5rem",t["--persona-message-assistant-radius"]=(Ae=(U=t["--persona-components-message-assistant-borderRadius"])!=null?U:t["--persona-radius-lg"])!=null?Ae:"0.5rem",t["--persona-header-bg"]=(Be=t["--persona-components-header-background"])!=null?Be:t["--persona-surface"],t["--persona-header-border"]=(De=t["--persona-components-header-border"])!=null?De:t["--persona-divider"],t["--persona-header-icon-bg"]=(_e=t["--persona-components-header-iconBackground"])!=null?_e:t["--persona-primary"],t["--persona-header-icon-fg"]=(ct=t["--persona-components-header-iconForeground"])!=null?ct:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(nt=t["--persona-components-header-titleForeground"])!=null?nt:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Ct=t["--persona-components-header-subtitleForeground"])!=null?Ct:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(jt=t["--persona-components-header-actionIconForeground"])!=null?jt:t["--persona-muted"];let r=(P=e.components)==null?void 0:P.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let s=(he=e.components)==null?void 0:he.introCard;t["--persona-intro-card-bg"]=(ge=t["--persona-components-introCard-background"])!=null?ge:t["--persona-surface"],t["--persona-intro-card-radius"]=(dt=t["--persona-components-introCard-borderRadius"])!=null?dt:"1rem",t["--persona-intro-card-padding"]=(Ke=t["--persona-components-introCard-padding"])!=null?Ke:"1.5rem",t["--persona-intro-card-shadow"]=(an=(It=s==null?void 0:s.shadow)!=null?It:t["--persona-components-introCard-shadow"])!=null?an:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(At=t["--persona-components-input-background"])!=null?At:t["--persona-surface"],t["--persona-input-placeholder"]=(bt=t["--persona-components-input-placeholder"])!=null?bt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Mt=t["--persona-components-message-user-background"])!=null?Mt:t["--persona-accent"],t["--persona-message-user-text"]=(ut=t["--persona-components-message-user-text"])!=null?ut:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Vt=t["--persona-components-message-user-shadow"])!=null?Vt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(wr=t["--persona-components-message-assistant-background"])!=null?wr:t["--persona-surface"],t["--persona-message-assistant-text"]=(_n=t["--persona-components-message-assistant-text"])!=null?_n:t["--persona-text"],t["--persona-message-assistant-border"]=(Br=t["--persona-components-message-assistant-border"])!=null?Br:t["--persona-border"],t["--persona-message-assistant-shadow"]=(vt=t["--persona-components-message-assistant-shadow"])!=null?vt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(ur=(pr=t["--persona-components-scrollToBottom-background"])!=null?pr:t["--persona-button-primary-bg"])!=null?ur:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Qn=(Cr=t["--persona-components-scrollToBottom-foreground"])!=null?Cr:t["--persona-button-primary-fg"])!=null?Qn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(gt=t["--persona-components-scrollToBottom-border"])!=null?gt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(io=t["--persona-components-scrollToBottom-size"])!=null?io:"40px",t["--persona-scroll-to-bottom-radius"]=(Sn=(lo=(mr=t["--persona-components-scrollToBottom-borderRadius"])!=null?mr:t["--persona-button-radius"])!=null?lo:t["--persona-radius-full"])!=null?Sn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Dr=(ko=t["--persona-components-scrollToBottom-shadow"])!=null?ko:t["--persona-palette-shadows-sm"])!=null?Dr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Ar=t["--persona-components-scrollToBottom-padding"])!=null?Ar:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(yt=t["--persona-components-scrollToBottom-gap"])!=null?yt:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(In=(Pn=t["--persona-components-scrollToBottom-fontSize"])!=null?Pn:t["--persona-palette-typography-fontSize-sm"])!=null?In:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(fn=t["--persona-components-scrollToBottom-iconSize"])!=null?fn:"14px",t["--persona-tool-bubble-shadow"]=(kt=t["--persona-components-toolBubble-shadow"])!=null?kt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(jn=t["--persona-components-reasoningBubble-shadow"])!=null?jn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Un=t["--persona-components-composer-shadow"])!=null?Un:"none",t["--persona-md-inline-code-bg"]=(Wn=t["--persona-components-markdown-inlineCode-background"])!=null?Wn:t["--persona-container"],t["--persona-md-inline-code-color"]=(Nr=t["--persona-components-markdown-inlineCode-foreground"])!=null?Nr:t["--persona-text"],t["--persona-md-link-color"]=(Or=(Sr=t["--persona-components-markdown-link-foreground"])!=null?Sr:t["--persona-accent"])!=null?Or:"#0f0f0f";let o=t["--persona-components-markdown-heading-h1-fontSize"];o&&(t["--persona-md-h1-size"]=o);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let l=t["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(t["--persona-md-prose-font-family"]=l),t["--persona-md-code-block-bg"]=(Rn=t["--persona-components-markdown-codeBlock-background"])!=null?Rn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Wt=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Wt:t["--persona-border"],t["--persona-md-code-block-text-color"]=(hn=t["--persona-components-markdown-codeBlock-textColor"])!=null?hn:"inherit",t["--persona-md-table-header-bg"]=(qn=t["--persona-components-markdown-table-headerBackground"])!=null?qn:t["--persona-container"],t["--persona-md-table-border-color"]=(Fr=t["--persona-components-markdown-table-borderColor"])!=null?Fr:t["--persona-border"],t["--persona-md-hr-color"]=(Er=t["--persona-components-markdown-hr-color"])!=null?Er:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=($r=t["--persona-components-markdown-blockquote-borderColor"])!=null?$r:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(gr=t["--persona-components-markdown-blockquote-background"])!=null?gr:"transparent",t["--persona-md-blockquote-text-color"]=(Hn=t["--persona-components-markdown-blockquote-textColor"])!=null?Hn:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Zn=t["--persona-components-collapsibleWidget-container"])!=null?Zn:t["--persona-surface"],t["--cw-surface"]=(ft=t["--persona-components-collapsibleWidget-surface"])!=null?ft:t["--persona-surface"],t["--cw-border"]=(Kt=t["--persona-components-collapsibleWidget-border"])!=null?Kt:t["--persona-border"],t["--persona-message-border"]=(Jt=t["--persona-components-message-border"])!=null?Jt:t["--persona-border"];let u=e.components,p=u==null?void 0:u.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let f=u==null?void 0:u.labelButton;f&&(f.background&&(t["--persona-label-btn-bg"]=f.background),f.border&&(t["--persona-label-btn-border"]=f.border),f.color&&(t["--persona-label-btn-color"]=f.color),f.padding&&(t["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(t["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(t["--persona-label-btn-gap"]=f.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let v=u==null?void 0:u.artifact;if(v!=null&&v.toolbar){let de=v.toolbar;de.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=de.iconHoverColor),de.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=de.iconHoverBackground),de.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=de.iconPadding),de.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=de.iconBorderRadius),de.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=de.iconBorder),de.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=de.toggleGroupGap),de.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=de.toggleBorderRadius),de.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=de.copyBackground),de.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=de.copyBorder),de.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=de.copyColor),de.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=de.copyBorderRadius),de.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=de.copyPadding),de.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=de.copyMenuBackground,t["--persona-dropdown-bg"]=(Bn=t["--persona-dropdown-bg"])!=null?Bn:de.copyMenuBackground),de.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=de.copyMenuBorder,t["--persona-dropdown-border"]=(_r=t["--persona-dropdown-border"])!=null?_r:de.copyMenuBorder),de.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=de.copyMenuShadow,t["--persona-dropdown-shadow"]=(zn=t["--persona-dropdown-shadow"])!=null?zn:de.copyMenuShadow),de.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=de.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(er=t["--persona-dropdown-radius"])!=null?er:de.copyMenuBorderRadius),de.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=de.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Dn=t["--persona-dropdown-item-hover-bg"])!=null?Dn:de.copyMenuItemHoverBackground),de.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=de.iconBackground),de.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=de.toolbarBorder)}if(v!=null&&v.tab){let de=v.tab;de.background&&(t["--persona-artifact-tab-bg"]=de.background),de.activeBackground&&(t["--persona-artifact-tab-active-bg"]=de.activeBackground),de.activeBorder&&(t["--persona-artifact-tab-active-border"]=de.activeBorder),de.borderRadius&&(t["--persona-artifact-tab-radius"]=de.borderRadius),de.textColor&&(t["--persona-artifact-tab-color"]=de.textColor),de.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=de.hoverBackground),de.listBackground&&(t["--persona-artifact-tab-list-bg"]=de.listBackground),de.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=de.listBorderColor),de.listPadding&&(t["--persona-artifact-tab-list-padding"]=de.listPadding)}if(v!=null&&v.pane){let de=v.pane;if(de.toolbarBackground){let Nn=(_=zo(e,de.toolbarBackground))!=null?_:de.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Nn}}return t}var lh={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var ch={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Np=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Wa=()=>{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"},dh=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Wa()},Op=e=>dh(e),ph=e=>Ps(e),uh=e=>{var t;let n=Ps(void 0,{validate:!1});return Ps({...e,palette:{...n.palette,colors:{...ch.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Is=e=>{let n=Op(e),t=Np(e==null?void 0:e.theme),r=Np(e==null?void 0:e.darkTheme);return n==="dark"?uh(Ls(t!=null?t:{},r!=null?r:{})):ph(t)},mh=e=>Mi(e),So=(e,n)=>{var o;let t=Is(n),r=mh(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},ki=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Wa())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Wa());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};import{Idiomorph as gh}from"idiomorph";var Ra=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;gh.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let d=(a=s.textContent)!=null?a:"",l=(i=o.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Ha={index:-1,draft:""};function Fp(e){let{direction:n,history:t,currentValue:r,atStart:s,state:o}=e,a=o.index!==-1;if(t.length===0)return{handled:!1,state:o};if(n==="up"){if(!a&&!s)return{handled:!1,state:o};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(o.index>0){let i=o.index-1;return{handled:!0,value:t[i],state:{index:i,draft:o.draft}}}return{handled:!0,state:o}}if(!a)return{handled:!1,state:o};if(o.index<t.length-1){let i=o.index+1;return{handled:!0,value:t[i],state:{index:i,draft:o.draft}}}return{handled:!0,value:o.draft,state:{...Ha}}}function $p(e,n){var t,r,s,o,a,i,d,l,u,p,f,m,v,x,S,A,k,R,H,L,w,B,F,$,W,O,V,oe,Ie,Pe,ze,pe,ce,Ee,je,te,xe,G;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(l=e.llmContent)==null?void 0:l.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(S=(x=e.toolCall)==null?void 0:x.name)!=null?S:"",(R=(k=(A=e.toolCall)==null?void 0:A.chunks)==null?void 0:k.length)!=null?R:0,(B=(w=(L=(H=e.toolCall)==null?void 0:H.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:w.slice(-32))!=null?B:"",typeof((F=e.toolCall)==null?void 0:F.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(V=(O=(W=e.reasoning)==null?void 0:W.chunks)==null?void 0:O.length)!=null?V:0,(ze=(Pe=(Ie=(oe=e.reasoning)==null?void 0:oe.chunks)==null?void 0:Ie[e.reasoning.chunks.length-1])==null?void 0:Pe.length)!=null?ze:0,(je=(Ee=(ce=(pe=e.reasoning)==null?void 0:pe.chunks)==null?void 0:ce[e.reasoning.chunks.length-1])==null?void 0:Ee.slice(-32))!=null?je:"",(xe=(te=e.contentParts)==null?void 0:te.length)!=null?xe:0,(G=e.stopReason)!=null?G:"",n].join("\0")}function _p(){return new Map}function jp(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Up(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function qp(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function Ba(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function Ws(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Rs(e,n){return Ws(e)-e.scrollTop<=n}function Da(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,u=t-r;return a||Math.abs(u)<o?{action:"none",delta:u,nextLastScrollTop:t}:!n&&s&&(!l||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:n&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:n&&d&&!s?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Na(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return n&&t<0?"pause":!n&&s&&t>0&&r?"resume":"none"}var mn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},gn=1e5,Yr=gn+1;var Hs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},fh=["pre","code","a","script","style"],Oa=e=>{var n,t,r,s,o;return{type:(n=e==null?void 0:e.type)!=null?n:Hs.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:Hs.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:Hs.speed,duration:(s=e==null?void 0:e.duration)!=null?s:Hs.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:Hs.buffer}},Vp=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Bs=new Map;for(let e of Vp)Bs.set(e.name,e);var hh=e=>{Bs.set(e.name,e)},yh=e=>{Vp.some(n=>n.name===e)||Bs.delete(e)},bh=()=>Array.from(Bs.keys()),Ds=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=Bs.get(e))!=null?r:null},Fa=(e,n,t,r,s)=>{if(!s)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(n==="line"){let o=e.lastIndexOf(`
15
+ `);return o<0?"":e.slice(0,o)}return e},xh=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${t}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=n,s},vh=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${t}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=n,s},Li=/\s/,wh=(e,n)=>{let t=e.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(n.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Ch=(e,n,t)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(Li.test(o[i])){let l=i;for(;l<o.length&&Li.test(o[l]);)l+=1;a.appendChild(r.createTextNode(o.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let u=i;for(;u<o.length&&!Li.test(o[u]);)l.appendChild(xh(r,o[u],n,t.value)),t.value+=1,u+=1;a.appendChild(l),i=u}s.replaceChild(a,e)},Ah=(e,n,t)=>{var d;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(d=e.nodeValue)!=null?d:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(vh(r,l,n,t.value)),t.value+=1));s.replaceChild(a,e)},Ns=(e,n,t,r)=>{var p,f;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((p=r==null?void 0:r.skipTags)!=null?p:fh).map(m=>m.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)wh(d,o)||i.push(d),d=a.nextNode();let l={value:(f=r==null?void 0:r.startIndex)!=null?f:0},u=n==="char"?Ch:Ah;for(let m of i)u(m,t,l);return s.innerHTML},$a=(e=document)=>{let n=e.createElement("span");return n.className="persona-stream-caret",n.setAttribute("aria-hidden","true"),n.setAttribute("data-preserve-animation","stream-caret"),n},Os=(e=document)=>{let n=e.createElement("div");n.className="persona-stream-skeleton",n.setAttribute("data-preserve-animation","stream-skeleton"),n.setAttribute("aria-hidden","true");let t=e.createElement("div");return t.className="persona-stream-skeleton-line",n.appendChild(t),n},zp=new WeakMap,Sh=(e,n)=>{var o;if(!e.styles)return;let t=zp.get(n);if(t||(t=new Set,zp.set(n,t)),t.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(n.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(e.name)}t.add(e.name);let s=(n instanceof ShadowRoot?n.ownerDocument:(o=n.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,n.appendChild(s)},Pi=new WeakMap,Eh=(e,n)=>{if(!e.onAttach)return;let t=Pi.get(n);if(t||(t=new Map,Pi.set(n,t)),t.has(e.name))return;let r=e.onAttach(n);t.set(e.name,r)},Kp=e=>{let n=Pi.get(e);if(n){for(let t of n.values())typeof t=="function"&&t();n.clear()}},Ii=(e,n)=>{Sh(e,n),Eh(e,n)};function Wi(e,n=gn){let t=e.style.position,r=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(n),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=r,e.style.isolation=s}}var Fs=0,Qr=null;function Ri(e=document){var t;if(Fs++,Fs===1){let r=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Qr={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let n=!1;return()=>{var r;if(!n&&(n=!0,Fs=Math.max(0,Fs-1),Fs===0&&Qr)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=Qr.originalOverflow,s.style.position=Qr.originalPosition,s.style.top=Qr.originalTop,s.style.width=Qr.originalWidth,o.scrollTo(0,Qr.scrollY),Qr=null}}}var _a={side:"right",width:"420px",animate:!0,reveal:"resize"},on=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},Zr=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="composer-bar"},lr=e=>{var t,r,s,o,a;let n=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(r=n==null?void 0:n.side)!=null?r:_a.side,width:(s=n==null?void 0:n.width)!=null?s:_a.width,animate:(o=n==null?void 0:n.animate)!=null?o:_a.animate,reveal:(a=n==null?void 0:n.reveal)!=null?a:_a.reveal}};var cr={"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 $s=(e,n)=>{let t=h("button");t.type="button",t.innerHTML=`
9
16
  <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>
10
17
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
11
18
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -13,14 +20,14 @@ import{Marked as Yu}from"marked";var Zu=e=>{if(e)return e},ca=e=>{var o,s;let n=
13
20
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
14
21
  </span>
15
22
  <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>
16
- `,t.addEventListener("click",n);let r=s=>{var B,D,L,S,F,$,j,W,O,V,oe,Pe,ke,Ge;let a=(B=s.launcher)!=null?B:{},i=on(s),d=t.querySelector("[data-role='launcher-title']");if(d){let de=(D=a.title)!=null?D:"Chat Assistant";d.textContent=de,d.setAttribute("title",de)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let de=(L=a.subtitle)!=null?L:"Get answers fast";l.textContent=de,l.setAttribute("title",de)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let de=(S=a.agentIconSize)!=null?S:"40px";if(p.style.height=de,p.style.width=de,p.innerHTML="",a.agentIconName){let pe=parseFloat(de)||24,Me=ge(a.agentIconName,pe*.6,"var(--persona-text-inverse, #ffffff)",2);Me?(p.appendChild(Me),p.style.display=""):(p.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=($=a.agentIconText)!=null?$:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let de=(j=a.agentIconSize)!=null?j:"40px";f.style.height=de,f.style.width=de,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=t.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let de=(W=a.callToActionIconSize)!=null?W:"32px";g.style.height=de,g.style.width=de,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let pe=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,pe=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Me=parseFloat(de)||24,_e=Math.max(Me-pe,8),ee=ge(a.callToActionIconName,_e,"currentColor",2);ee?g.appendChild(ee):g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else g.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let C=a.position&&cr[a.position]?cr[a.position]:cr["bottom-right"],x="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",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?T:`${x} ${C}`,i||(t.style.zIndex=String((oe=a.zIndex)!=null?oe:fn));let A="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))";t.style.border=(Pe=a.border)!=null?Pe:A,t.style.boxShadow=(ke=a.shadow)!=null?ke:k,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Ge=a.collapsedMaxWidth)!=null?Ge:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:o}};var eh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Wa=(e,n={})=>{var x,T,A,k,B,D;let{showClose:t=!0,wrapperClassName:r=eh,buttonSize:o,iconSize:s="28px"}=n,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(T=o!=null?o:a.closeButtonSize)!=null?T:"32px",d=h("div",r),l=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(A=a.closeButtonTooltipText)!=null?A:"Close chat",p=(k=a.closeButtonShowTooltip)!=null?k:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let f=(B=a.closeButtonIconName)!=null?B:"x",g=(D=a.closeButtonIconText)!=null?D:"\xD7";l.style.color=a.closeButtonColor||An.actionIconColor;let C=ge(f,s,"currentColor",1);if(C?(C.style.display="block",l.appendChild(C)):l.textContent=g,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let L=a.closeButtonBorderWidth||"0px",S=a.closeButtonBorderColor||"transparent";l.style.border=`${L} solid ${S}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let L=null,S=()=>{if(L)return;let $=l.ownerDocument,j=$.body;if(!j)return;L=br($,"div","persona-clear-chat-tooltip"),L.textContent=u;let W=br($,"div");W.className="persona-clear-chat-tooltip-arrow",L.appendChild(W);let O=l.getBoundingClientRect();L.style.position="fixed",L.style.zIndex=String(Qr),L.style.left=`${O.left+O.width/2}px`,L.style.top=`${O.top-8}px`,L.style.transform="translate(-50%, -100%)",j.appendChild(L)},F=()=>{L&&L.parentNode&&(L.parentNode.removeChild(L),L=null)};d.addEventListener("mouseenter",S),d.addEventListener("mouseleave",F),l.addEventListener("focus",S),l.addEventListener("blur",F),d._cleanupTooltip=()=>{F(),d.removeEventListener("mouseenter",S),d.removeEventListener("mouseleave",F),l.removeEventListener("focus",S),l.removeEventListener("blur",F)}}return{button:l,wrapper:d}},th="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ra=(e,n={})=>{var L,S,F,$,j,W,O,V,oe,Pe,ke,Ge,de;let{wrapperClassName:t=th,buttonSize:r,iconSize:o="20px"}=n,a=(S=((L=e==null?void 0:e.launcher)!=null?L:{}).clearChat)!=null?S:{},i=(F=r!=null?r:a.size)!=null?F:"32px",d=($=a.iconName)!=null?$:"refresh-cw",l=(j=a.iconColor)!=null?j:"",u=(W=a.backgroundColor)!=null?W:"",p=(O=a.borderWidth)!=null?O:"",f=(V=a.borderColor)!=null?V:"",g=(oe=a.borderRadius)!=null?oe:"",C=(Pe=a.paddingX)!=null?Pe:"",x=(ke=a.paddingY)!=null?ke:"",T=(Ge=a.tooltipText)!=null?Ge:"Clear chat",A=(de=a.showTooltip)!=null?de:!0,k=h("div",t),B=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");B.style.height=i,B.style.width=i,B.type="button",B.setAttribute("aria-label",T),B.style.color=l||An.actionIconColor;let D=ge(d,o,"currentColor",1);if(D&&(D.style.display="block",B.appendChild(D)),u&&(B.style.backgroundColor=u,B.classList.remove("hover:persona-bg-gray-100")),p||f){let pe=p||"0px",Me=f||"transparent";B.style.border=`${pe} solid ${Me}`,B.classList.remove("persona-border-none")}if(g&&(B.style.borderRadius=g,B.classList.remove("persona-rounded-full")),C&&(B.style.paddingLeft=C,B.style.paddingRight=C),x&&(B.style.paddingTop=x,B.style.paddingBottom=x),k.appendChild(B),A&&T){let pe=null,Me=()=>{if(pe)return;let ee=B.ownerDocument,Ae=ee.body;if(!Ae)return;pe=br(ee,"div","persona-clear-chat-tooltip"),pe.textContent=T;let Q=br(ee,"div");Q.className="persona-clear-chat-tooltip-arrow",pe.appendChild(Q);let ae=B.getBoundingClientRect();pe.style.position="fixed",pe.style.zIndex=String(Qr),pe.style.left=`${ae.left+ae.width/2}px`,pe.style.top=`${ae.top-8}px`,pe.style.transform="translate(-50%, -100%)",Ae.appendChild(pe)},_e=()=>{pe&&pe.parentNode&&(pe.parentNode.removeChild(pe),pe=null)};k.addEventListener("mouseenter",Me),k.addEventListener("mouseleave",_e),B.addEventListener("focus",Me),B.addEventListener("blur",_e),k._cleanupTooltip=()=>{_e(),k.removeEventListener("mouseenter",Me),k.removeEventListener("mouseleave",_e),B.removeEventListener("focus",Me),B.removeEventListener("blur",_e)}}return{button:B,wrapper:k}};var An={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Zr=e=>{var L,S,F,$,j,W,O,V,oe,Pe,ke,Ge,de,pe,Me,_e;let{config:n,showClose:t=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let o=(L=n==null?void 0:n.launcher)!=null?L:{},s=(S=o.headerIconSize)!=null?S:"48px",a=(F=o.closeButtonPlacement)!=null?F:"inline",i=($=o.headerIconHidden)!=null?$:!1,d=o.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=s,l.style.width=s,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let ee=parseFloat(s)||24,Ae=ge(d,ee*.6,"currentColor",1);Ae?l.replaceChildren(Ae):l.textContent=(W=(j=n==null?void 0:n.launcher)==null?void 0:j.agentIconText)!=null?W:"\u{1F4AC}"}else if((O=n==null?void 0:n.launcher)!=null&&O.iconUrl){let ee=h("img");ee.src=n.launcher.iconUrl,ee.alt="",ee.className="persona-rounded-xl persona-object-cover",ee.style.height=s,ee.style.width=s,l.replaceChildren(ee)}else l.textContent=(oe=(V=n==null?void 0:n.launcher)==null?void 0:V.agentIconText)!=null?oe:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=h("span","persona-text-base persona-font-semibold");p.style.color=An.titleColor,p.textContent=(ke=(Pe=n==null?void 0:n.launcher)==null?void 0:Pe.title)!=null?ke:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=An.subtitleColor,f.textContent=(de=(Ge=n==null?void 0:n.launcher)==null?void 0:Ge.subtitle)!=null?de:"Here to help you get answers fast",u.append(p,f),i?r.append(u):r.append(l,u);let g=(pe=o.clearChat)!=null?pe:{},C=(Me=g.enabled)!=null?Me:!0,x=(_e=g.placement)!=null?_e:"inline",T=null,A=null;if(C){let Ae=Ra(n,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=Ae.button,A=Ae.wrapper,x==="top-right"&&(A.style.right="48px"),x==="inline"&&r.appendChild(A)}let k=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:B,wrapper:D}=Wa(n,{showClose:t,wrapperClassName:k});return a!=="top-right"&&r.appendChild(D),{header:r,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:B,closeButtonWrapper:D,clearChatButton:T,clearChatButtonWrapper:A}},Vo=(e,n,t)=>{var a,i,d,l;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(n.header),o==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function Eo(e){let{items:n,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Qr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of n){if(g.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",g.id),g.destructive&&C.setAttribute("data-destructive",""),g.icon){let T=ge(g.icon,16,"currentColor",1.5);T&&C.appendChild(T)}let x=document.createElement("span");x.textContent=g.label,C.appendChild(x),C.addEventListener("click",T=>{T.stopPropagation(),u(),t(g.id)}),a.appendChild(C)}let i=null;function d(){if(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=C=>{!a.contains(C.target)&&!r.contains(C.target)&&u()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function jt(e){let{icon:n,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=ge(n,r!=null?r:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function Ha(e){let{icon:n,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let u=h("button",l);if(u.type="button",u.setAttribute("aria-label",t),n){let f=ge(n,s!=null?s:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))u.setAttribute(f,g);return u}function Ba(e){let{items:n,selectedId:t,onSelect:r,className:o}=e,s=h("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of n){let p;u.icon?p=jt({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),r(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),r(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),s.appendChild(p)}function l(u){a=u,d()}return{element:s,setSelected:l}}function Ai(e){var g,C;let{label:n,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",n);let u=h("span","persona-combo-btn-label");u.textContent=n,l.appendChild(u);let p=ge(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",l.style.padding=(C=d.padding)!=null?C:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,T;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(T=d.border)!=null?T:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Eo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let T=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",T?"false":"true"),f.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{u.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let x=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var Lp=e=>{var r;let n=Zr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let o=n.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}))}return n};function nh(e,n,t){var r,o,s;if(n!=null&&n.length)for(let a of n){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=ge(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=h("div","persona-relative");d.appendChild(i);let l=Eo({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Pp=e=>{var k,B,D,L,S,F,$,j,W;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(k=n==null?void 0:n.launcher)!=null?k:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,u;if(d)l=Ai({label:(B=a.title)!=null?B:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=An.titleColor,u=(D=l.querySelector(".persona-combo-btn-label"))!=null?D:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=An.titleColor,u.textContent=(L=a.title)!=null?L:"Chat Assistant",l.appendChild(u),nh(l,o==null?void 0:o.trailingActions,(S=o==null?void 0:o.onAction)!=null?S:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=o.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||V()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),V())})}let O=o==null?void 0:o.titleRowHover;O&&(l.style.borderRadius=(F=O.borderRadius)!=null?F:"10px",l.style.padding=($=O.padding)!=null?$:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var V,oe;l.style.backgroundColor=(V=O.background)!=null?V:"",l.style.borderColor=(oe=O.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=(j=a.closeButtonSize)!=null?j:"32px",f=h("div",""),g=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=p,g.style.width=p,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=t?"":"none",g.style.color=a.closeButtonColor||An.actionIconColor;let C=(W=a.closeButtonIconName)!=null?W:"x",x=ge(C,"28px","currentColor",1);x?g.appendChild(x):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let T=h("div");T.style.display="none";let A=h("span");return A.style.display="none",{header:i,iconHolder:T,headerTitle:u,headerSubtitle:A,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Si={default:Lp,minimal:Pp},Ip=e=>{var n;return(n=Si[e])!=null?n:Si.default},Ns=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let l=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),g=h("button");g.style.display="none";let C=h("div");return C.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:g,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",s=Ip(r)({config:e,showClose:(d=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Da=e=>{var a,i;let n=h("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",n.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",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;n.style.maxHeight=`${t*r}px`,n.style.overflowY="auto";let o=()=>{let d=parseFloat(n.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},s=()=>{n.addEventListener("input",()=>{n.style.height="auto";let d=Math.min(n.scrollHeight,o());n.style.height=`${d}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:s}},Na=e=>{var L,S,F,$,j,W,O,V,oe,Pe,ke,Ge;let n=(L=e==null?void 0:e.sendButton)!=null?L:{},t=(S=n.useIcon)!=null?S:!1,r=(F=n.iconText)!=null?F:"\u2191",o=n.iconName,s=($=n.stopIconName)!=null?$:"square",a=(j=n.tooltipText)!=null?j:"Send message",i=(W=n.stopTooltipText)!=null?W:"Stop generating",d=(V=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?V:"Send",l=(Pe=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?Pe:"Stop",u=(ke=n.showTooltip)!=null?ke:!1,p=(Ge=n.size)!=null?Ge:"40px",f=n.backgroundColor,g=n.textColor,C=h("div","persona-send-button-wrapper"),x=h("button",t?"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");x.type="submit",x.setAttribute("data-persona-composer-submit","");let T=null,A=null;if(t){x.style.width=p,x.style.height=p,x.style.minWidth=p,x.style.minHeight=p,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",g?x.style.color=g:x.style.color="var(--persona-button-primary-fg, #ffffff)";let de=parseFloat(p)||24,pe=(g==null?void 0:g.trim())||"currentColor";o?(T=ge(o,de,pe,2),T?x.appendChild(T):x.textContent=r):x.textContent=r,A=ge(s,de,pe,2),f?x.style.backgroundColor=f:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,g?x.style.color=g:x.classList.add("persona-text-white");n.borderWidth&&(x.style.borderWidth=n.borderWidth,x.style.borderStyle="solid"),n.borderColor&&(x.style.borderColor=n.borderColor),n.paddingX?(x.style.paddingLeft=n.paddingX,x.style.paddingRight=n.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),n.paddingY?(x.style.paddingTop=n.paddingY,x.style.paddingBottom=n.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let k=null;u&&a&&(k=h("div","persona-send-button-tooltip"),k.textContent=a,C.appendChild(k)),x.setAttribute("aria-label",a),C.appendChild(x);let B="send";return{button:x,wrapper:C,setMode:de=>{if(de===B)return;B=de;let pe=de==="stop"?i:a;if(x.setAttribute("aria-label",pe),k&&(k.textContent=pe),t){if(T&&A){let Me=de==="stop"?A:T,_e=de==="stop"?T:A;_e.parentNode===x?x.replaceChild(Me,_e):x.appendChild(Me)}}else x.textContent=de==="stop"?l:d}}},Fa=e=>{var k,B,D,L,S,F,$,j,W,O,V,oe;let n=(k=e==null?void 0:e.voiceRecognition)!=null?k:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((B=n.provider)==null?void 0:B.type)==="runtype";if(!(r||o))return null;let a=(L=(D=e==null?void 0:e.sendButton)==null?void 0:D.size)!=null?L:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(S=n.iconName)!=null?S:"mic",u=(F=n.iconSize)!=null?F:a,p=parseFloat(u)||24,f=(j=n.backgroundColor)!=null?j:($=e==null?void 0:e.sendButton)==null?void 0:$.backgroundColor,g=(O=n.iconColor)!=null?O:(W=e==null?void 0:e.sendButton)==null?void 0:W.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",g?d.style.color=g:d.style.color="var(--persona-text, #111827)";let x=ge(l,p,g||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),n.borderWidth&&(d.style.borderWidth=n.borderWidth,d.style.borderStyle="solid"),n.borderColor&&(d.style.borderColor=n.borderColor),n.paddingX&&(d.style.paddingLeft=n.paddingX,d.style.paddingRight=n.paddingX),n.paddingY&&(d.style.paddingTop=n.paddingY,d.style.paddingBottom=n.paddingY),i.appendChild(d);let T=(V=n.tooltipText)!=null?V:"Start voice recognition";if(((oe=n.showTooltip)!=null?oe:!1)&&T){let Pe=h("div","persona-send-button-tooltip");Pe.textContent=T,i.appendChild(Pe)}return{button:d,wrapper:i}},Oa=e=>{var C,x,T,A,k,B,D,L;let n=(C=e==null?void 0:e.attachments)!=null?C:{};if(n.enabled!==!0)return null;let t=(T=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?T:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let o=h("input");o.type="file",o.accept=((A=n.allowedTypes)!=null?A:Rr).join(","),o.multiple=((k=n.maxFiles)!=null?k:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(B=n.buttonTooltipText)!=null?B:"Attach file");let i=(D=n.buttonIconName)!=null?D:"paperclip",d=t,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=ge(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",S=>{S.preventDefault(),o.click()}),s.appendChild(a);let f=(L=n.buttonTooltipText)!=null?L:"Attach file",g=h("div","persona-send-button-tooltip");return g.textContent=f,s.appendChild(g),{button:a,wrapper:s,input:o,previewsContainer:r}},$a=e=>{var a,i,d;let n=(a=e==null?void 0:e.statusIndicator)!=null?a:{},t=n.align==="left"?"persona-text-left":n.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=n.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=n.idleText)!=null?d:"Online";if(n.idleLink){let l=h("a");l.href=n.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},_a=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var Fs=e=>{var C,x,T,A,k,B;let{config:n}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let r=_a(),o=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let{textarea:s,attachAutoResize:a}=Da(n);a();let i=Na(n),d=Fa(n),l=Oa(n),u=$a(n);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let p=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),p.append(f,g),o.append(p),o.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),t.append(r,o,u),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:u,attachmentButton:(T=l==null?void 0:l.button)!=null?T:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(k=l==null?void 0:l.input)!=null?k:null,attachmentPreviewsContainer:(B=l==null?void 0:l.previewsContainer)!=null?B:null,actionsRow:p,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var Wp=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let n=h("span","persona-pill-peek__icon"),t=ge("message-square",16,"currentColor",1.5);t&&n.appendChild(t);let r=h("span","persona-pill-peek__text"),o=h("span","persona-pill-peek__caret"),s=ge("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(n,r,o),{root:e,textNode:r}},Rp=e=>{var C,x,T,A,k,B;let{config:n}=e,t=h("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let r=_a();r.style.display="none";let o=$a(n);o.style.display="none";let{textarea:s,attachAutoResize:a}=Da(n);s.style.maxHeight="100px",a();let i=Na(n),d=Fa(n),l=Oa(n);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=h("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.addEventListener("click",D=>{D.target!==i.button&&D.target!==i.wrapper&&D.target!==(d==null?void 0:d.button)&&D.target!==(d==null?void 0:d.wrapper)&&D.target!==(l==null?void 0:l.button)&&D.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&u.append(l.input),u.append(p,s,f),l&&t.append(l.previewsContainer),t.append(u,r,o);let g=u;return{footer:t,suggestions:r,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(C=d==null?void 0:d.button)!=null?C:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(T=l==null?void 0:l.button)!=null?T:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(k=l==null?void 0:l.input)!=null?k:null,attachmentPreviewsContainer:(B=l==null?void 0:l.previewsContainer)!=null?B:null,actionsRow:g,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Hp=e=>{var u,p,f,g,C,x,T,A,k,B,D,L,S,F,$,j,W;let n=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=on(e);if(Yr(e)){let O=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},V=h("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(C=O.expandedSize)!=null?C:"anchored",V.style.zIndex=String((T=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?T:fn);let oe=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",V.appendChild(oe);let Pe=h("div","persona-widget-pill-root");return Pe.setAttribute("data-persona-composer-bar",""),Pe.dataset.state="collapsed",Pe.dataset.expandedSize=(A=O.expandedSize)!=null?A:"anchored",Pe.style.zIndex=String((B=(k=e==null?void 0:e.launcher)==null?void 0:k.zIndex)!=null?B:fn),{wrapper:V,panel:oe,pillRoot:Pe}}if(t){let O=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(V),{wrapper:O,panel:V}}if(!n){let O=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(L=(D=e==null?void 0:e.launcher)==null?void 0:D.width)!=null?L:"100%";return O.style.width=oe,V.style.width="100%",O.appendChild(V),{wrapper:O,panel:V}}let o=(S=e==null?void 0:e.launcher)!=null?S:{},s=o.position&&cr[o.position]?cr[o.position]:cr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(($=(F=e==null?void 0:e.launcher)==null?void 0:F.zIndex)!=null?$:fn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(W=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?W:e==null?void 0:e.launcherWidth,l=d!=null?d:Gn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},rh=(e,n)=>{var D,L,S,F,$,j,W,O,V;let t=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=Wa(e,{showClose:n,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(S=(L=(D=e==null?void 0:e.launcher)==null?void 0:D.clearChat)==null?void 0:L.enabled)!=null?S:!0,a=null,i=null;if(s){let oe=Ra(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=($=(F=e==null?void 0:e.copy)==null?void 0:F.welcomeTitle)!=null?$:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(W=(j=e==null?void 0:e.copy)==null?void 0:j.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",u.append(p,f);let g=h("div","persona-flex persona-flex-col persona-gap-3"),C=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;C&&(g.style.maxWidth=C,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((V=e==null?void 0:e.copy)==null?void 0:V.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,g);let T=h("div","persona-composer-overlay persona-pointer-events-none");T.setAttribute("data-persona-composer-overlay",""),T.style.position="absolute",T.style.left="0",T.style.right="0",T.style.bottom="0",T.style.zIndex="20";let A=Rp({config:e}),{root:k,textNode:B}=Wp();return t.append(d,o,l,T),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:g,composerOverlay:T,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,introTitle:p,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:k,peekTextNode:B}},Bp=(e,n=!0)=>{var T,A,k,B,D,L,S,F,$;if(Yr(e))return rh(e,n);let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let r=(T=e==null?void 0:e.layout)==null?void 0:T.header,o=((A=e==null?void 0:e.layout)==null?void 0:A.showHeader)!==!1,s=r?Ns(e,r,{showClose:n}):Zr({config:e,showClose:n}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=on(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(B=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?B:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(L=(D=e==null?void 0:e.copy)==null?void 0:D.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",i.append(d,l);let u=h("div","persona-flex persona-flex-col persona-gap-3"),p=(S=e==null?void 0:e.layout)==null?void 0:S.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((F=e==null?void 0:e.copy)==null?void 0:F.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let g=Fs({config:e}),C=(($=e==null?void 0:e.layout)==null?void 0:$.showFooter)!==!1;o?Vo(t,s,e):(s.header.style.display="none",Vo(t,s,e)),t.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",C||(g.footer.style.display="none"),t.append(g.footer),t.append(x),{container:t,body:a,messagesWrapper:u,composerOverlay:x,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:d,introSubtitle:l,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:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var oh=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},sh=(e,n)=>{if(!e)return null;let t=oh(e);if(t===null)return null;let r=n==null?void 0:n[e],o=r!==void 0?r:t;return o||null},ah=(e,n)=>{let t=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=n,t},ih=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},Ei=e=>{let n=e.toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:text/html")||n.startsWith("data:text/javascript")||n.startsWith("data:text/xml")||n.startsWith("data:application/xhtml")||n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:")||!e.includes(":"))},Ti=320,Np=320,lh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),ch=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="audio"&&typeof n.audio=="string"&&n.audio.trim().length>0),dh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="video"&&typeof n.video=="string"&&n.video.trim().length>0),ph=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="file"&&typeof n.data=="string"&&n.data.trim().length>0),uh=(e,n,t)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let l=h("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Ti}px`,l.style.maxHeight=`${Np}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;o+=1,l.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{u=!0}),ih(i.image)?(l.src=i.image,r.appendChild(l)):(u=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},mh=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","audio");let t=0;return e.forEach(r=>{if(!Ei(r.audio))return;let o=h("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ti}px`,n.appendChild(o),t+=1}),t===0?(n.remove(),null):n}catch{return null}},gh=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","video");let t=0;return e.forEach(r=>{if(!Ei(r.video))return;let o=h("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ti}px`,o.style.maxHeight=`${Np}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",n.appendChild(o),t+=1}),t===0?(n.remove(),null):n}catch{return null}},fh=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","files");let t=0;return e.forEach(r=>{if(!Ei(r.data))return;let o=h("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",n.appendChild(o),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Jo=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(o),e},Fp=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Jo};if(n){let o=n(r);if(o!==null)return o}return Jo()},hh=(e,n)=>{let t=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=h("img");o.src=r,o.alt=n==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},Dp=(e,n)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},yh=(e,n="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},Op=(e,n,t)=>{var g,C,x,T,A,k;let r=(g=n.showCopy)!=null?g:!0,o=(C=n.showUpvote)!=null?C:!0,s=(x=n.showDownvote)!=null?x:!0;if(!r&&!o&&!s){let B=h("div");return B.style.display="none",B.id=`actions-${e.id}`,B.setAttribute("data-actions-for",e.id),B}let a=(T=n.visibility)!=null?T:"hover",i=(A=n.align)!=null?A:"right",d=(k=n.layout)!=null?k:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(B,D,L)=>{let S=jt({icon:B,label:D,size:14,className:"persona-message-action-btn"});return S.setAttribute("data-action",L),S};return r&&p.appendChild(f("copy","Copy message","copy")),o&&p.appendChild(f("thumbs-up","Upvote","upvote")),s&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},Os=(e,n,t,r,o,s)=>{var ee,Ae,Q,ae,Re,ce,We,Ze,J,se,Fe,K,z,xe,Oe,ne,Se;let a=t!=null?t:{},i=(ee=a.layout)!=null?ee:"bubble",d=a.avatar,l=a.timestamp,u=(Ae=d==null?void 0:d.show)!=null?Ae:!1,p=(Q=l==null?void 0:l.show)!=null?Q:!1,f=(ae=d==null?void 0:d.position)!=null?ae:"left",g=(Re=l==null?void 0:l.position)!=null?Re:"below",C=yh(e.role,i),x=h("div",C.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=lh(e),A=(We=(ce=e.content)==null?void 0:ce.trim())!=null?We:"",B=T.length>0&&A===ha,D=ka((J=(Ze=s==null?void 0:s.widgetConfig)==null?void 0:Ze.features)==null?void 0:J.streamAnimation),L=(K=(Fe=(se=s==null?void 0:s.widgetConfig)==null?void 0:se.features)==null?void 0:Fe.streamAnimation)==null?void 0:K.plugins,S=e.role==="assistant"&&D.type!=="none"?Ws(D.type,L):null,F=e.role==="assistant"&&((z=S==null?void 0:S.isAnimating)==null?void 0:z.call(S,e))===!0,$=e.role==="assistant"&&S!==null&&(!!e.streaming||F);$&&(S!=null&&S.bubbleClass)&&x.classList.add(S.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),$&&S&&(S.containerClass&&j.classList.add(S.containerClass),j.style.setProperty("--persona-stream-step",`${D.speed}ms`),j.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let W=$?La((xe=e.content)!=null?xe:"",D.buffer,S,e,!!e.streaming):(Oe=e.content)!=null?Oe:"",O=n({text:W,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=O;$&&(S==null?void 0:S.wrap)==="char"?V=Rs(O,"char",e.id,{skipTags:S.skipTags}):$&&(S==null?void 0:S.wrap)==="word"&&(V=Rs(O,"word",e.id,{skipTags:S.skipTags}));let oe=null;if(B?(oe=document.createElement("div"),oe.innerHTML=V,oe.style.display="none",j.appendChild(oe)):j.innerHTML=V,$&&(S!=null&&S.useCaret)&&!B&&A){let be=Pa(),Ht=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),Le=Ht[Ht.length-1];if(Le!=null&&Le.parentNode)Le.parentNode.insertBefore(be,Le.nextSibling);else{let te=j.lastElementChild;te?te.appendChild(be):j.appendChild(be)}}if(p&&g==="inline"&&e.createdAt){let be=Dp(e,l);be.classList.add("persona-ml-2","persona-inline"),j.appendChild(be)}if(T.length>0){let be=uh(T,!B&&!!A,()=>{B&&oe&&(oe.style.display="")});be?x.appendChild(be):B&&oe&&(oe.style.display="")}let Pe=ch(e);if(Pe.length>0){let be=mh(Pe);be&&x.appendChild(be)}let ke=dh(e);if(ke.length>0){let be=gh(ke);be&&x.appendChild(be)}let Ge=ph(e);if(Ge.length>0){let be=fh(Ge);be&&x.appendChild(be)}if(x.appendChild(j),p&&g==="below"&&e.createdAt){let be=Dp(e,l);be.classList.add("persona-mt-1"),x.appendChild(be)}let de=e.role==="assistant"?sh(e.stopReason,(Se=(ne=s==null?void 0:s.widgetConfig)==null?void 0:ne.copy)==null?void 0:Se.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let be=!!(W&&W.trim()),Ht=D.placeholder==="skeleton",Le=Ht&&D.buffer==="line"&&be;if(be)Le&&x.appendChild(Hs());else if(Ht)x.appendChild(Hs());else{let te=Fp("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);te&&x.appendChild(te)}}if(de&&e.stopReason&&!e.streaming&&(A||(j.style.display="none"),x.appendChild(ah(e.stopReason,de))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let be=Op(e,r,o);x.appendChild(be)}if(!u||e.role==="system")return x;let Me=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),_e=hh(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Me.append(x,_e):Me.append(_e,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Me},bh=(e,n,t,r,o,s)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Os(e,n,t,r,o,s)};var Ko=new Set,xh=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),vh=(e,n)=>{var r,o;let t=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,n).join(`
17
- `):""},$p=(e,n)=>{let t=Ko.has(e),r=n.querySelector('button[data-expand-header="true"]'),o=n.querySelector(".persona-border-t"),s=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",s&&(s.style.display=t?"none":s.textContent||s.childNodes.length?"":"none")},Mi=(e,n)=>{var ke,Ge,de,pe,Me,_e,ee,Ae,Q,ae,Re;let t=e.reasoning,r=h("div",["persona-message-bubble","persona-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(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!t)return r;let o=(Ge=(ke=n==null?void 0:n.features)==null?void 0:ke.reasoningDisplay)!=null?Ge:{},s=o.expandable!==!1,a=s&&Ko.has(e.id),i=t.status!=="complete",d=vh(e,(de=o.previewMaxLines)!=null?de:3),l=h("button",s?"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":"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-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(pe=n==null?void 0:n.reasoning)!=null?pe:{},C=String((Me=t.startedAt)!=null?Me:Date.now()),x=()=>{let ce=h("span","");return ce.setAttribute("data-tool-elapsed",C),ce.textContent=ua(t),ce},T=(_e=g.renderCollapsedSummary)==null?void 0:_e.call(g,{message:e,reasoning:t,defaultSummary:f,previewText:d,isActive:i,config:n!=null?n:{},elapsed:ua(t),createElapsedElement:x});typeof T=="string"&&T.trim()?(p.textContent=T,u.appendChild(p)):T instanceof HTMLElement?u.appendChild(T):(p.textContent=f,u.appendChild(p));let A=h("span","persona-text-xs persona-text-persona-primary");A.textContent=sp(t),u.appendChild(A);let k=(ee=o.loadingAnimation)!=null?ee:"none",B=g.activeTextTemplate,D=g.completeTextTemplate,L=i?B:D,S=T instanceof HTMLElement,F=(ce,We,Ze)=>{let J=Ze;for(let se of We){let Fe=h("span","persona-tool-char");Fe.style.setProperty("--char-index",String(J)),Fe.textContent=se===" "?"\xA0":se,ce.appendChild(Fe),J++}return J},$=(ce,We)=>{p.textContent="";let Ze=ma(ce,""),J=0;for(let se of Ze){let Fe=se.styles.length>0?(()=>{let K=h("span",se.styles.map(z=>`persona-tool-text-${z}`).join(" "));return p.appendChild(K),K})():p;if(se.isDuration&&i)Fe.appendChild(x());else{let K=se.isDuration?ua(t):se.text;We?J=F(Fe,K,J):Fe.appendChild(document.createTextNode(K))}}};if(!S&&L)if(A.style.display="none",p.style.display="",i&&k!=="none"){let ce=(Ae=g.loadingAnimationDuration)!=null?Ae:2e3;p.setAttribute("data-preserve-animation","true"),k==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),$(L,!1)):(p.classList.add(`persona-tool-loading-${k}`),p.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),$(L,!0))}else $(L,!1);else if(!S&&i&&k!=="none"){p.style.display="";let ce=(Q=g.loadingAnimationDuration)!=null?Q:2e3;if(p.setAttribute("data-preserve-animation","true"),k==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ce}ms`);else{p.classList.add(`persona-tool-loading-${k}`),p.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let We=p.textContent||f;p.textContent="",F(p,We,0)}t.status==="complete"&&(p.style.display="none")}else S||(t.status==="complete"?p.style.display="none":p.style.display="");let j=null;if(s){j=h("div","persona-flex persona-items-center");let We=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);We?j.appendChild(We):j.textContent=a?"Hide":"Show";let Ze=h("div","persona-flex persona-items-center persona-ml-auto");Ze.append(j),l.append(u,Ze)}else l.append(u);let W=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","reasoning"),W.style.display="none",W.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let ce=(Re=(ae=n==null?void 0:n.reasoning)==null?void 0:ae.renderCollapsedPreview)==null?void 0:Re.call(ae,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:n!=null?n:{}});xh(W,ce)||(W.textContent=d),W.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(l,W),r;let O=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let V=t.chunks.join(""),oe=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=V||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),j){j.innerHTML="";let We=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);We?j.appendChild(We):j.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",W.style.display=a?"none":W.textContent||W.childNodes.length?"":"none"})(),r.append(l,W,O),r};var Go=new Set,Ch=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),wh=(e,n)=>{var s;let t=e.toolCall;if(!t)return"";let r=((s=t.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-n).join(`
18
- `);let o=$o(t.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,n).join(`
19
- `):""},Ah=(e,n)=>{var u,p,f,g,C;let t=e.toolCall,r=(u=n==null?void 0:n.features)==null?void 0:u.toolCallDisplay,o=(p=r==null?void 0:r.collapsedMode)!=null?p:"tool-call",s=wh(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=t?ap(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let i=t.status!=="complete",d=(g=n==null?void 0:n.toolCall)!=null?g:{},l=a;return o==="tool-name"?l=((C=t.name)==null?void 0:C.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=ai(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=ai(t,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},_p=(e,n,t)=>{var u;let r=Go.has(e),o=(u=t==null?void 0:t.toolCall)!=null?u:{},s=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=o.toggleTextColor||o.headerTextColor||"currentColor",f=ge(r?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},ki=(e,n)=>{var V,oe,Pe,ke,Ge,de,pe,Me,_e;let t=e.toolCall,r=(V=n==null?void 0:n.toolCall)!=null?V:{},o=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),!t)return o;let s=(Pe=(oe=n==null?void 0:n.features)==null?void 0:oe.toolCallDisplay)!=null?Pe:{},a=s.expandable!==!1,i=a&&Go.has(e.id),{summary:d,previewText:l,isActive:u}=Ah(e,n),p=h("button",a?"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":"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-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(p.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(p.style.paddingLeft=r.headerPaddingX,p.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(p.style.paddingTop=r.headerPaddingY,p.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let C=String((ke=t.startedAt)!=null?ke:Date.now()),x=()=>{let ee=h("span","");return ee.setAttribute("data-tool-elapsed",C),ee.textContent=Cs(t),ee},T=(de=r.renderCollapsedSummary)==null?void 0:de.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(Ge=s.collapsedMode)!=null?Ge:"tool-call",isActive:u,config:n!=null?n:{},elapsed:Cs(t),createElapsedElement:x});typeof T=="string"&&T.trim()?(g.textContent=T,f.appendChild(g)):T instanceof HTMLElement?f.appendChild(T):(g.textContent=d,f.appendChild(g));let A=(pe=s.loadingAnimation)!=null?pe:"none",k=r.activeTextTemplate,B=r.completeTextTemplate,D=u?k:B,L=T instanceof HTMLElement,S=(ee,Ae,Q)=>{let ae=Q;for(let Re of Ae){let ce=h("span","persona-tool-char");ce.style.setProperty("--char-index",String(ae)),ce.textContent=Re===" "?"\xA0":Re,ee.appendChild(ce),ae++}return ae},F=(ee,Ae)=>{var ce;g.textContent="";let Q=((ce=t.name)==null?void 0:ce.trim())||"tool",ae=ma(ee,Q),Re=0;for(let We of ae){let Ze=We.styles.length>0?(()=>{let J=h("span",We.styles.map(se=>`persona-tool-text-${se}`).join(" "));return g.appendChild(J),J})():g;if(We.isDuration&&u)Ze.appendChild(x());else{let J=We.isDuration?Cs(t):We.text;Ae?Re=S(Ze,J,Re):Ze.appendChild(document.createTextNode(J))}}};if(!L)if(u&&A!=="none"){let ee=(Me=r.loadingAnimationDuration)!=null?Me:2e3;if(g.setAttribute("data-preserve-animation","true"),A==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),D&&F(D,!1);else if(g.classList.add(`persona-tool-loading-${A}`),g.style.setProperty("--persona-tool-anim-duration",`${ee}ms`),A==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),D)F(D,!0);else{let Ae=g.textContent||d;g.textContent="",S(g,Ae,0)}}else D&&F(D,!1);let $=null;if(a){$=h("div","persona-flex persona-items-center");let ee=r.toggleTextColor||r.headerTextColor||"currentColor",Ae=ge(i?"chevron-up":"chevron-down",16,ee,2);Ae?$.appendChild(Ae):$.textContent=i?"Hide":"Show";let Q=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append($),p.append(f,Q)}else p.append(f);let j=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","tool"),j.style.display="none",j.style.whiteSpace="pre-wrap",!i&&u&&s.activePreview&&l){let ee=(_e=r.renderCollapsedPreview)==null?void 0:_e.call(r,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:n!=null?n:{}});Ch(j,ee)||(j.textContent=l),j.style.display=""}if(!i&&u&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(p,j),o;let W=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(W.style.display=i?"":"none",r.contentBackgroundColor&&(W.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(W.style.color=r.contentTextColor),r.contentPaddingX&&(W.style.paddingLeft=r.contentPaddingX,W.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(W.style.paddingTop=r.contentPaddingY,W.style.paddingBottom=r.contentPaddingY),t.name){let ee=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ee.style.color=r.contentTextColor:r.headerTextColor&&(ee.style.color=r.headerTextColor),ee.textContent=t.name,W.appendChild(ee)}if(t.args!==void 0){let ee=h("div","persona-space-y-1"),Ae=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Ae.style.color=r.labelTextColor),Ae.textContent="Arguments";let Q=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(Q.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(Q.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(Q.style.color=r.codeBlockTextColor),Q.textContent=$o(t.args),ee.append(Ae,Q),W.appendChild(ee)}if(t.chunks&&t.chunks.length){let ee=h("div","persona-space-y-1"),Ae=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Ae.style.color=r.labelTextColor),Ae.textContent="Activity";let Q=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(Q.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(Q.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(Q.style.color=r.codeBlockTextColor),Q.textContent=t.chunks.join(""),ee.append(Ae,Q),W.appendChild(ee)}if(t.status==="complete"&&t.result!==void 0){let ee=h("div","persona-space-y-1"),Ae=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(Ae.style.color=r.labelTextColor),Ae.textContent="Result";let Q=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(Q.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(Q.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(Q.style.color=r.codeBlockTextColor),Q.textContent=$o(t.result),ee.append(Ae,Q),W.appendChild(ee)}if(t.status==="complete"&&typeof t.duration=="number"){let ee=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ee.style.color=r.contentTextColor),ee.textContent=`Duration: ${t.duration}ms`,W.appendChild(ee)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),$){$.innerHTML="";let ee=r.toggleTextColor||r.headerTextColor||"currentColor",Ae=ge(i?"chevron-up":"chevron-down",16,ee,2);Ae?$.appendChild(Ae):$.textContent=i?"Hide":"Show"}W.style.display=i?"":"none",j.style.display=i?"none":j.textContent||j.childNodes.length?"":"none"})(),o.append(p,j,W),o};import{parse as Sh,ARR as Eh,OBJ as Th,STR as Mh}from"partial-json";var Up="ask_user_question",Li=8,Qo="data-persona-ask-sheet-for",kh="Other",Lh="Other\u2026",qp="Type your own answer here",zp="Send",Ph="Next",Ih="Back",Wh="Submit all",Rh="Skip",Hh=3,Pi="data-ask-current-index",Ii="data-ask-question-count",Vp="data-ask-answers",Wi="data-ask-grouped",Jp="data-ask-layout",Bh=e=>e.layout==="pills"?"pills":"rows",Dh=e=>e.getAttribute(Jp)==="pills"?"pills":"rows",jp=!1,Kp=e=>e.replace(/["\\]/g,"\\$&"),eo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Up,ja=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},to=e=>{let n=e.toolCall;if(!n)return{payload:null,complete:!1};let t=n.status==="complete";if(n.args&&typeof n.args=="object")return{payload:n.args,complete:t};let r=n.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let o=r.join(""),s=Sh(o,Mh|Th|Eh);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},$s=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>Li&&!jp&&(jp=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${Li}.`)),n.slice(0,Li)},Nh=e=>{var n;return(n=$s(e)[0])!=null?n:null},Fh=(e,n)=>{var t;return(t=$s(e)[n])!=null?t:null},Gp=(e,n)=>{let t=n.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},Qp=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let o=h("span","persona-ask-row-check");r.appendChild(o)}else{let o=h("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},Oh=(e,n,t,r)=>{let s=h("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(n)),s.setAttribute("data-option-label",e.label),t==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=Qp(t,r,n);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},$h=e=>{let t=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},_h=(e,n,t,r)=>{var u,p,f;let s=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!t){for(let g=0;g<Hh;g++)s.appendChild($h(r));return s}if(d.forEach((g,C)=>{s.appendChild(Oh(g,C,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?kh:Lh;if(r==="rows"){let C=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");C.setAttribute("data-ask-user-action","focus-free-text"),C.setAttribute("data-option-index",String(d.length)),C.setAttribute("data-ask-other-row","true");let x=h("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=n.freeTextPlaceholder)!=null?u:qp,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(p=n.freeTextLabel)!=null?p:g),x.appendChild(T),C.appendChild(x);let A=Qp(r,a,d.length);A&&C.appendChild(A),s.appendChild(C)}else{let C=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");C.type="button",C.setAttribute("data-ask-user-action","open-free-text"),C.textContent=(f=n.freeTextLabel)!=null?f:g,s.appendChild(C)}}return s},Xp=(e,n)=>{var s,a;let r=h("div",n==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:qp,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),n!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:zp,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},jh=e=>{var r;let n=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");n.setAttribute("data-ask-multi-actions","true");let t=h("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=e.submitLabel)!=null?r:zp,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},Uh=(e,n,t)=>{var l,u,p,f;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=h("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=t.backLabel)!=null?l:Ih,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=t.skipLabel)!=null?u:Rh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===n-1;return i.textContent=d?(p=t.submitAllLabel)!=null?p:Wh:(f=t.nextLabel)!=null?f:Ph,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},To=e=>{let n=e.getAttribute(Vp);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},Yp=(e,n)=>{e.setAttribute(Vp,JSON.stringify(n))},Qn=e=>{var t;let n=Number((t=e.getAttribute(Pi))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},qh=(e,n)=>{e.setAttribute(Pi,String(Math.max(0,Math.floor(n))))},Xo=e=>{var t;let n=Number((t=e.getAttribute(Ii))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},no=e=>e.getAttribute(Wi)==="true",zh=(e,n)=>{var o;let t=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Vh=(e,n)=>{var r;let t=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(n-1,Math.floor(t)))},Ua=(e,n)=>{let{payload:t}=to(n),r=$s(t),o=To(e),s={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Zp=e=>{let n=To(e),t=Qn(e),r=n[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=o.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},eu=e=>{if(!no(e))return;let n=To(e),t=Qn(e),r=n[t],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Ri=(e,n,t)=>{let r=ja(t),o=Dh(e),{payload:s,complete:a}=to(n),i=no(e),d=Qn(e),l=Xo(e),u=i?Fh(s,d):Nh(s),p=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let C=e.querySelector('[data-ask-question="true"]');if(C){let k=typeof(u==null?void 0:u.question)=="string"?u.question:"";C.textContent=k,C.classList.toggle("persona-ask-question-skeleton",!k&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let k=_h(u,r,a,o);x.replaceWith(k)}if(o!=="rows"){let k=e.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(Xp(r,o))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!T?e.appendChild(jh(r)):(!p||i)&&T&&T.remove(),e.setAttribute("data-multi-select",p?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(i){let k=Uh(d,l,r);A?A.replaceWith(k):e.appendChild(k)}else A&&A.remove();Zp(e),eu(e)},Jh=(e,n,t)=>{let r=ja(n),o=Bh(r),s=e.toolCall.id,a=$s(t),i=Math.max(1,a.length),d=i>1,l=zh(e,a),u=d?Vh(e,i):0,p=h("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Qo,s),p.setAttribute("data-tool-call-id",s),p.setAttribute("data-message-id",e.id),p.setAttribute(Ii,String(i)),p.setAttribute(Pi,String(u)),p.setAttribute(Wi,d?"true":"false"),p.setAttribute(Jp,o),Yp(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Gp(p,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=h("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let C=h("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",f.appendChild(C),p.appendChild(f);let T=h("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),p.appendChild(T),o!=="rows"&&p.appendChild(Xp(r,o)),Ri(p,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},Kh=(e,n,t)=>{let{payload:r}=to(n),o=Math.max(1,$s(r).length);o>Xo(e)&&(e.setAttribute(Ii,String(o)),o>1&&!no(e)&&e.setAttribute(Wi,"true")),Ri(e,n,t)},Gh=(e,n)=>{let t=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let r=ja(n);Gp(t,r);let o=h("span","persona-ask-stub-label"),{complete:s}=to(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(o),t},_s=(e,n,t)=>{if(!t||!eo(e)||ja(n).enabled===!1)return;let o=e.toolCall.id;t.querySelectorAll(`[${Qo}]`).forEach(l=>{l.getAttribute(Qo)!==o&&l.remove()});let a=t.querySelector(`[${Qo}="${Kp(o)}"]`);if(a){Kh(a,e,n);return}let{payload:i}=to(e),d=Jh(e,n,i);t.appendChild(d)},Mo=(e,n)=>{if(!e)return;let t=n?`[${Qo}="${Kp(n)}"]`:`[${Qo}]`;e.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Hi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(n=>n.getAttribute("data-option-label")).filter(n=>typeof n=="string"&&n.length>0),ro=(e,n)=>{let t=To(e),r=Qn(e);typeof n=="string"&&n.length===0||Array.isArray(n)&&n.length===0?delete t[r]:t[r]=n,Yp(e,t),Zp(e),eu(e)},qa=(e,n,t,r)=>{let o=Xo(e),s=Math.max(0,Math.min(o-1,r));qh(e,s),Ri(e,n,t)};var Bi=(e,n)=>{var x,T,A,k,B,D,L,S,F,$,j,W;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,o=(t==null?void 0:t.status)==="pending",s=h("div",["persona-approval-bubble","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=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(T=r==null?void 0:r.borderColor)!=null?T:"var(--persona-approval-border, #fef08a)",!t)return s;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(A=r==null?void 0:r.titleColor)!=null?A:"currentColor",u=ge(d,20,l,2);u&&i.appendChild(u);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",f.appendChild(g),!o){let O=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",t.status),t.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):t.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):t.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),f.appendChild(O)}p.appendChild(f);let C=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(C.style.color=r.descriptionColor),C.textContent=t.description,p.appendChild(C),t.parameters){let O=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(O.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(O.style.color=r.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=$o(t.parameters),p.appendChild(O)}if(o){let O=h("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let V=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");V.type="button",V.style.backgroundColor=(B=r==null?void 0:r.approveButtonColor)!=null?B:"var(--persona-approval-approve-bg, #22c55e)",V.style.color=(D=r==null?void 0:r.approveButtonTextColor)!=null?D:"#ffffff",V.setAttribute("data-approval-action","approve");let oe=ge("shield-check",14,(L=r==null?void 0:r.approveButtonTextColor)!=null?L:"#ffffff",2);oe&&(oe.style.marginRight="4px",V.appendChild(oe));let Pe=document.createTextNode((S=r==null?void 0:r.approveLabel)!=null?S:"Approve");V.appendChild(Pe);let ke=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");ke.type="button",ke.style.backgroundColor=(F=r==null?void 0:r.denyButtonColor)!=null?F:"transparent",ke.style.color=($=r==null?void 0:r.denyButtonTextColor)!=null?$:"var(--persona-feedback-error, #dc2626)",ke.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ke.setAttribute("data-approval-action","deny");let Ge=ge("shield-x",14,(j=r==null?void 0:r.denyButtonTextColor)!=null?j:"var(--persona-feedback-error, #dc2626)",2);Ge&&(Ge.style.marginRight="4px",ke.appendChild(Ge));let de=document.createTextNode((W=r==null?void 0:r.denyLabel)!=null?W:"Deny");ke.appendChild(de),O.append(V,ke),p.appendChild(O)}return a.append(i,p),s.appendChild(a),s};var tu=e=>{let n=[];return{buttons:n,render:(r,o,s,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:o?o.getMessages():[]).some(g=>g.role==="user"))return;let u=document.createDocumentFragment(),p=o?o.isStreaming():!1,f=g=>{switch(g){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(g=>{let C=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=g,C.disabled=p,i!=null&&i.fontFamily&&(C.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(g))}),u.appendChild(C),n.push(C)}),e.appendChild(u)}}};var js=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Us=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)r.put(o)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{n(s.result)},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{n()},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)r.put(o)}catch{}}};function Yo(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Qh={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, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},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)"}},Xh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Yh=["flowName","stepName","reasoningText","text","name","tool","toolName"],Zh=100;function ey(e,n){let t={...Qh,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return Xh}function ty(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function ny(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0"),s=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${o}.${s}`}function ry(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let o=r.split("."),s=t;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function oy(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function sy(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function ay(e,n,t){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=n.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let i=s.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Di(e,n,t,r,o,s,a,i){var f;let d=o.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Yo(l,(f=r.classNames)==null?void 0:f.eventRow);let u=a.find(g=>g.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let g=u.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(g)return l.appendChild(g),l}return l.appendChild(p()),l;function p(){var V,oe;let g=h("div",""),C=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");C.setAttribute("data-event-id",e.id);let x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),T=ge(d?"chevron-down":"chevron-right","14px","currentColor",2);T&&x.appendChild(T);let A=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(V=r.timestampFormat)!=null?V:"relative";A.textContent=k==="relative"?ty(e.timestamp,t):ny(e.timestamp);let B=null;r.showSequenceNumbers!==!1&&(B=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),B.textContent=String(n+1));let D=ey(e.type,r.badgeColors),L=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");L.style.backgroundColor=D.bg,L.style.color=D.text,L.style.borderColor=D.text+"50",L.textContent=e.type;let S=(oe=r.descriptionFields)!=null?oe:Yh,F=ry(e.payload,S),$=null;F&&($=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),$.textContent=F);let j=h("div","persona-flex-1 persona-min-w-0"),W=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=ge("clipboard","12px","currentColor",1.5);return O&&W.appendChild(O),W.addEventListener("click",async Pe=>{Pe.stopPropagation(),await oy(sy(e)),W.innerHTML="";let ke=ge("check","12px","currentColor",1.5);ke&&W.appendChild(ke),setTimeout(()=>{W.innerHTML="";let Ge=ge("clipboard","12px","currentColor",1.5);Ge&&W.appendChild(Ge)},1500)}),C.appendChild(x),C.appendChild(A),B&&C.appendChild(B),C.appendChild(L),$&&C.appendChild($),C.appendChild(j),C.appendChild(W),g.appendChild(C),d&&g.appendChild(ay(e,a,i)),g}}function nu(e){var g,C,x,T,A;let{buffer:n,getFullHistory:t,onClose:r,config:o,plugins:s=[]}=e,a=(g=o==null?void 0:o.features)==null?void 0:g.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,d=(C=a==null?void 0:a.iconName)!=null?C:"arrow-down",l=(x=a==null?void 0:a.label)!=null?x:"",u=(A=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?A:{},p=s.find(k=>k.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&o){let k=p.renderEventStreamView({config:o,events:n.getAll(),defaultRenderer:()=>f().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=u.classNames,B=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Yo(B,k==null?void 0:k.panel);let D=[],L="",S="",F=null,$=[],j={},W=0,O=Ea(),V=0,oe=0,Pe=!1,ke=null,Ge=!1,de=0,pe=new Set,Me=new Map,_e="",ee="",Ae=null,Q,ae,Re,ce,We;function Ze(){let P=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),fe=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Yo(fe,k==null?void 0:k.headerBar);let me=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");me.textContent="Events",Q=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),Q.textContent="0";let ct=h("div","persona-flex-1");ae=h("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let qe=h("option","");qe.value="",qe.textContent="All events",ae.appendChild(qe),Re=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),Re.type="button",Re.title="Copy All";let an=ge("clipboard-copy","12px","currentColor",1.5);an&&Re.appendChild(an);let wt=h("span","persona-text-xs");wt.textContent="Copy All",Re.appendChild(wt),fe.appendChild(me),fe.appendChild(Q),fe.appendChild(ct),fe.appendChild(ae),fe.appendChild(Re);let bt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Yo(bt,k==null?void 0:k.searchBar);let Mt=ge("search","14px","var(--persona-muted, #9ca3af)",1.5),pt=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Mt&&pt.appendChild(Mt),ce=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Yo(ce,k==null?void 0:k.searchInput),ce.type="text",ce.placeholder="Search event payloads...",We=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),We.type="button",We.style.display="none";let Jt=ge("x","12px","currentColor",2);return Jt&&We.appendChild(Jt),bt.appendChild(pt),bt.appendChild(ce),bt.appendChild(We),P.appendChild(fe),P.appendChild(bt),P}let J,se=s.find(P=>P.renderEventStreamToolbar);if(se!=null&&se.renderEventStreamToolbar&&o){let P=se.renderEventStreamToolbar({config:o,defaultRenderer:()=>Ze(),eventCount:n.getSize(),filteredCount:0,onFilterChange:fe=>{L=fe,te(),Vt()},onSearchChange:fe=>{S=fe,te(),Vt()}});J=P!=null?P:Ze()}else J=Ze();let Fe=h("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Fe.style.display="none";let K=h("div","persona-flex-1 persona-min-h-0 persona-relative"),z=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");z.style.height="100%";let xe=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Yo(xe,k==null?void 0:k.scrollIndicator),xe.style.display="none",xe.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false");let Oe=ge(d,"14px","currentColor",2);Oe&&xe.appendChild(Oe);let ne=h("span","");ne.textContent=l,xe.appendChild(ne);let Se=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Se.style.display="none",K.appendChild(z),K.appendChild(Se),K.appendChild(xe),B.setAttribute("tabindex","0"),B.appendChild(J),B.appendChild(Fe),B.appendChild(K);function be(){let P=n.getAll(),fe={};for(let wt of P)fe[wt.type]=(fe[wt.type]||0)+1;let me=Object.keys(fe).sort(),ct=me.length!==$.length||!me.every((wt,bt)=>wt===$[bt]),qe=!ct&&me.some(wt=>fe[wt]!==j[wt]),It=P.length!==Object.values(j).reduce((wt,bt)=>wt+bt,0);if(!ct&&!qe&&!It||($=me,j=fe,!ae))return;let an=ae.value;if(ae.options[0].textContent="All events",ct){for(;ae.options.length>1;)ae.remove(1);for(let wt of me){let bt=h("option","");bt.value=wt,bt.textContent=`${wt} (${fe[wt]||0})`,ae.appendChild(bt)}an&&me.includes(an)?ae.value=an:an&&(ae.value="",L="")}else for(let wt=1;wt<ae.options.length;wt++){let bt=ae.options[wt];bt.textContent=`${bt.value} (${fe[bt.value]||0})`}}function Ht(){let P=n.getAll();if(L&&(P=P.filter(fe=>fe.type===L)),S){let fe=S.toLowerCase();P=P.filter(me=>me.type.toLowerCase().includes(fe)||me.payload.toLowerCase().includes(fe))}return P}function Le(){return L!==""||S!==""}function te(){W=0,V=0,O.resume(),xe.style.display="none"}function sn(P){pe.has(P)?pe.delete(P):pe.add(P),Ae=P;let fe=z.scrollTop,me=O.isFollowing();Ge=!0,O.pause(),Vt(),z.scrollTop=fe,me&&O.resume(),Ge=!1}function Nt(){return Ls(z,50)}function Vt(){oe=Date.now(),Pe=!1,be();let P=n.getEvictedCount();P>0?(Fe.textContent=`${P.toLocaleString()} older events truncated`,Fe.style.display=""):Fe.style.display="none",D=Ht();let fe=D.length,me=n.getSize()>0;Q&&(Q.textContent=String(n.getSize())),fe===0&&me&&Le()?(Se.textContent=S?`No events matching '${S}'`:"No events matching filter",Se.style.display="",z.style.display="none"):(Se.style.display="none",z.style.display=""),Re&&(Re.title=Le()?`Copy Filtered (${fe})`:"Copy All"),i&&!O.isFollowing()&&fe>W&&(V+=fe-W,ne.textContent=l?`${l}${V>0?` (${V})`:""}`:"",xe.style.display=""),W=fe;let ct=n.getAll(),qe=ct.length>0?ct[0].timestamp:0,It=new Set(D.map(bt=>bt.id));for(let bt of pe)It.has(bt)||pe.delete(bt);let an=L!==_e||S!==ee,wt=Me.size===0&&D.length>0;if(an||wt||D.length===0){z.innerHTML="",Me.clear();let bt=document.createDocumentFragment();for(let Mt=0;Mt<D.length;Mt++){let pt=Di(D[Mt],Mt,qe,u,pe,sn,s,o);Me.set(D[Mt].id,pt),bt.appendChild(pt)}z.appendChild(bt),_e=L,ee=S,Ae=null}else{if(Ae!==null){let Mt=Me.get(Ae);if(Mt&&Mt.parentNode===z){let pt=D.findIndex(Jt=>Jt.id===Ae);if(pt>=0){let Jt=Di(D[pt],pt,qe,u,pe,sn,s,o);z.insertBefore(Jt,Mt),Mt.remove(),Me.set(Ae,Jt)}}Ae=null}let bt=new Set(D.map(Mt=>Mt.id));for(let[Mt,pt]of Me)bt.has(Mt)||(pt.remove(),Me.delete(Mt));for(let Mt=0;Mt<D.length;Mt++){let pt=D[Mt];if(!Me.has(pt.id)){let Jt=Di(pt,Mt,qe,u,pe,sn,s,o);Me.set(pt.id,Jt),z.appendChild(Jt)}}}O.isFollowing()&&(z.scrollTop=z.scrollHeight)}function vr(){if(Date.now()-oe>=Zh){ke!==null&&(cancelAnimationFrame(ke),ke=null),Vt();return}Pe||(Pe=!0,ke=requestAnimationFrame(()=>{ke=null,Vt()}))}let dr=(P,fe)=>{if(!Re)return;Re.innerHTML="";let me=ge(P,"12px","currentColor",1.5);me&&Re.appendChild(me);let ct=h("span","persona-text-xs");ct.textContent="Copy All",Re.appendChild(ct),setTimeout(()=>{Re.innerHTML="";let qe=ge("clipboard-copy","12px","currentColor",1.5);qe&&Re.appendChild(qe);let It=h("span","persona-text-xs");It.textContent="Copy All",Re.appendChild(It),Re.disabled=!1},fe)},je=async()=>{if(Re){Re.disabled=!0;try{let P;Le()?P=D:t?(P=await t(),P.length===0&&(P=n.getAll())):P=n.getAll();let fe=P.map(me=>{try{return JSON.parse(me.payload)}catch{return me.payload}});await navigator.clipboard.writeText(JSON.stringify(fe,null,2)),dr("check",1500)}catch{dr("x",1500)}}},U=()=>{ae&&(L=ae.value,te(),Vt())},Ce=()=>{!ce||!We||(We.style.display=ce.value?"":"none",F&&clearTimeout(F),F=setTimeout(()=>{S=ce.value,te(),Vt()},150))},He=()=>{!ce||!We||(ce.value="",S="",We.style.display="none",F&&clearTimeout(F),te(),Vt())},Be=()=>{if(Ge)return;let P=z.scrollTop,{action:fe,nextLastScrollTop:me}=Ta({following:O.isFollowing(),currentScrollTop:P,lastScrollTop:de,nearBottom:Nt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});de=me,fe==="resume"?(O.resume(),V=0,xe.style.display="none"):fe==="pause"&&(O.pause(),i&&(ne.textContent=l,xe.style.display=""))},$e=P=>{let fe=Ma({following:O.isFollowing(),deltaY:P.deltaY,nearBottom:Nt(),resumeWhenNearBottom:!0});fe==="pause"?(O.pause(),i&&(ne.textContent=l,xe.style.display="")):fe==="resume"&&(O.resume(),V=0,xe.style.display="none")},lt=()=>{i&&(z.scrollTop=z.scrollHeight,O.resume(),V=0,xe.style.display="none")},et=P=>{let fe=P.target;if(!fe||fe.closest("button"))return;let me=fe.closest("[data-event-id]");if(!me)return;let ct=me.getAttribute("data-event-id");ct&&sn(ct)},Ct=P=>{if((P.metaKey||P.ctrlKey)&&P.key==="f"){P.preventDefault(),ce==null||ce.focus(),ce==null||ce.select();return}P.key==="Escape"&&(ce&&document.activeElement===ce?(He(),ce.blur(),B.focus()):r&&r())};Re&&Re.addEventListener("click",je),ae&&ae.addEventListener("change",U),ce&&ce.addEventListener("input",Ce),We&&We.addEventListener("click",He),z.addEventListener("scroll",Be),z.addEventListener("wheel",$e,{passive:!0}),z.addEventListener("click",et),xe.addEventListener("click",lt),B.addEventListener("keydown",Ct);function Ut(){F&&clearTimeout(F),ke!==null&&(cancelAnimationFrame(ke),ke=null),Pe=!1,Me.clear(),Re&&Re.removeEventListener("click",je),ae&&ae.removeEventListener("change",U),ce&&ce.removeEventListener("input",Ce),We&&We.removeEventListener("click",He),z.removeEventListener("scroll",Be),z.removeEventListener("wheel",$e),z.removeEventListener("click",et),xe.removeEventListener("click",lt),B.removeEventListener("keydown",Ct)}return{element:B,update:vr,destroy:Ut}}}function ru(e,n){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.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",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.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 l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(g)}else p.textContent=a;if(l.append(u,p),i.append(d,l),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var ou=(e,n)=>{var r,o,s;let t=(s=(o=(r=n==null?void 0:n.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:n.config,defaultRenderer:()=>ru(e,n)});if(u)return u}return ru(e,n)};var Ni=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},oo=new Ni;oo.register("PersonaArtifactCard",ou);function iy(e){var o;let n=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),n.appendChild(t),n.appendChild(r),n}function su(e,n){var Re,ce,We,Ze;let t=(ce=(Re=e.features)==null?void 0:Re.artifacts)==null?void 0:ce.layout,o=((We=t==null?void 0:t.toolbarPreset)!=null?We:"default")==="document",s=(Ze=t==null?void 0:t.panePadding)==null?void 0:Ze.trim(),a=e.markdown?Fo(e.markdown):null,i=xs(e.sanitize),d=J=>{let se=a?a(J):Oo(J);return i?i(se):se},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var J;u(),(J=n.onDismiss)==null||J.call(n)});let p=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),o&&p.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let g=h("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let C=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");C.type="button",C.textContent="Close",C.setAttribute("aria-label","Close artifacts panel"),C.addEventListener("click",()=>{var J;u(),(J=n.onDismiss)==null||J.call(n)});let x="rendered",T=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),A=o?jt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):jt({icon:"eye",label:"Rendered view"}),k=o?jt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):jt({icon:"code-2",label:"Source"}),B=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,S=t==null?void 0:t.documentToolbarCopyMenuItems,F=!!(L&&S&&S.length>0),$=null,j,W=null,O=null;if(o&&(D||L)&&!F){if(j=D?Ha({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let J=ge("chevron-down",14,"currentColor",2);J&&j.appendChild(J)}}else o&&F?($=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),j=D?Ha({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W=jt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),$.append(j,W)):o?j=jt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):j=jt({icon:"copy",label:"Copy"});let V=o?jt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):jt({icon:"refresh-cw",label:"Refresh"}),oe=o?jt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):jt({icon:"x",label:"Close"}),Pe=()=>{var z,xe,Oe;let J=(z=_e.find(ne=>ne.id===ee))!=null?z:_e[_e.length-1],se=(xe=J==null?void 0:J.id)!=null?xe:null,Fe=(J==null?void 0:J.artifactType)==="markdown"&&(Oe=J.markdown)!=null?Oe:"",K=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:Fe,jsonPayload:K,id:se}},ke=async()=>{var z;let{markdown:J,jsonPayload:se}=Pe(),Fe=(z=_e.find(xe=>xe.id===ee))!=null?z:_e[_e.length-1],K=(Fe==null?void 0:Fe.artifactType)==="markdown"?J:Fe?se:"";try{await navigator.clipboard.writeText(K)}catch{}};if(j.addEventListener("click",async()=>{let J=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(J&&F){let{markdown:se,jsonPayload:Fe,id:K}=Pe();try{await J({actionId:"primary",artifactId:K,markdown:se,jsonPayload:Fe})}catch{}return}await ke()}),W&&(S!=null&&S.length)){let J=()=>{var Fe;return(Fe=p.closest("[data-persona-root]"))!=null?Fe:document.body},se=()=>{O=Eo({items:S.map(Fe=>({id:Fe.id,label:Fe.label})),onSelect:async Fe=>{let{markdown:K,jsonPayload:z,id:xe}=Pe(),Oe=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Oe?await Oe({actionId:Fe,artifactId:xe,markdown:K,jsonPayload:z}):Fe==="markdown"||Fe==="md"?await navigator.clipboard.writeText(K):Fe==="json"||Fe==="source"?await navigator.clipboard.writeText(z):await navigator.clipboard.writeText(K||z)}catch{}},anchor:$!=null?$:W,position:"bottom-right",portal:J()})};p.isConnected?se():requestAnimationFrame(se),W.addEventListener("click",Fe=>{Fe.stopPropagation(),O==null||O.toggle()})}V.addEventListener("click",async()=>{var J;try{await((J=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:J.call(t))}catch{}Q()}),oe.addEventListener("click",()=>{var J;u(),(J=n.onDismiss)==null||J.call(n)});let Ge=()=>{o&&(A.setAttribute("aria-pressed",x==="rendered"?"true":"false"),k.setAttribute("aria-pressed",x==="source"?"true":"false"))};A.addEventListener("click",()=>{x="rendered",Ge(),Q()}),k.addEventListener("click",()=>{x="source",Ge(),Q()});let de=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(f.replaceChildren(),T.append(A,k),$?B.append($,V,oe):B.append(j,V,oe),f.append(T,de,B),Ge()):(f.appendChild(g),f.appendChild(C)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let pe=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Me=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(pe.style.paddingLeft=s,pe.style.paddingRight=s,Me.style.padding=s),p.appendChild(f),p.appendChild(pe),p.appendChild(Me);let _e=[],ee=null,Ae=!1,Q=()=>{var K,z,xe,Oe;let J=o&&_e.length<=1;pe.classList.toggle("persona-hidden",J),pe.replaceChildren();for(let ne of _e){let Se=h("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Se.type="button",Se.textContent=ne.title||ne.id.slice(0,8),ne.id===ee&&Se.classList.add("persona-bg-persona-container","persona-border-persona-border"),Se.addEventListener("click",()=>n.onSelect(ne.id)),pe.appendChild(Se)}Me.replaceChildren();let se=ee&&_e.find(ne=>ne.id===ee)||_e[_e.length-1];if(!se)return;if(o){let ne=se.artifactType==="markdown"?"MD":(K=se.component)!=null?K:"Component",be=(se.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";de.textContent=`${be} \xB7 ${ne}`}else g.textContent="Artifacts";if(se.artifactType==="markdown"){if(o&&x==="source"){let Se=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Se.textContent=(z=se.markdown)!=null?z:"",Me.appendChild(Se);return}let ne=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ne.innerHTML=d((xe=se.markdown)!=null?xe:""),Me.appendChild(ne);return}let Fe=se.component?oo.get(se.component):void 0;if(Fe){let Se={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let be=Fe((Oe=se.props)!=null?Oe:{},Se);if(be){Me.appendChild(be);return}}catch{}}Me.appendChild(iy(se))},ae=()=>{var se;let J=_e.length>0;if(p.classList.toggle("persona-hidden",!J),l){let Fe=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,z=((se=Fe==null?void 0:Fe.classList.contains("persona-artifact-narrow-host"))!=null?se:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&z&&Ae?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(J){var se,Fe,K;_e=J.artifacts,ee=(K=(Fe=J.selectedId)!=null?Fe:(se=J.artifacts[J.artifacts.length-1])==null?void 0:se.id)!=null?K:null,_e.length>0&&(Ae=!0),Q(),ae()},setMobileOpen(J){Ae=J,!J&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ae()}}}function Xn(e){var n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function au(e,n){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Xn(n))return;let t=(a=(s=n.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function ly(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 za(e,n){var d,l,u,p,f,g,C,x,T,A;if(!Xn(n)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),ly(e),au(e,n);return}let t=(l=(d=n.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(C=t==null?void 0:t.panePadding)==null?void 0:C.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(T=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:T.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(A=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:A.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),au(e,n)}var iu=["panel","seamless"];function Va(e,n){var i,d,l,u,p,f;for(let g of iu)e.classList.remove(`persona-artifact-appearance-${g}`);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"),!Xn(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",o=iu.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function lu(e,n){var t,r,o;return!n||!Xn(e)?!1:((o=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function cy(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function dy(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function py(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function uy(e,n,t,r){let o=e-r-2*n-t;return Math.max(0,o)}function cu(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function du(e,n,t,r,o,s){let a=cy(o,200),i=uy(n,t,r,200);i=Math.max(a,i);let d=dy(s);return d!==null&&(i=Math.min(i,d)),py(e,a,i)}var pu={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"}},Fi=(e,n,t,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var C,x,T;if(s.dataset.enhanced==="true")return;let a=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let i=(x=pu[a])!=null?x:pu.init;s.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let A=h("p","persona-text-sm persona-text-persona-muted");A.textContent=i.description,d.appendChild(A)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(A=>{var S,F;let k=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${n.id}-${a}-${A.name}`;let B=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");B.textContent=A.label,k.appendChild(B);let D=(S=A.type)!=null?S:"text",L;D==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=D),L.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",L.id=`${n.id}-${a}-${A.name}`,L.name=A.name,L.placeholder=(F=A.placeholder)!=null?F:"",A.required&&(L.required=!0),k.appendChild(L),u.appendChild(k)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=(T=i.submitLabel)!=null?T:"Submit",p.appendChild(f),p.appendChild(g),u.appendChild(p),s.replaceChildren(d,u),u.addEventListener("submit",async A=>{var L,S;A.preventDefault();let k=(L=t.formEndpoint)!=null?L:"/form",B=new FormData(u),D={};B.forEach((F,$)=>{D[$]=F}),D.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let F=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!F.ok)throw new Error(`Form submission failed (${F.status})`);let $=await F.json();f.textContent=(S=$.message)!=null?S:"Thanks! We'll be in touch soon.",$.success&&$.nextPrompt&&await r.sendMessage(String($.nextPrompt))}catch(F){f.textContent=F instanceof Error?F.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Oi=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(s=>s.id));return[...t.filter(s=>!r.has(s.id)),...n].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},Ja=new Oi;var uu=()=>{let e=new Map,n=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>t(o,s)),t=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:n,off:t,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var my=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},gy=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let o=t;o<n.length;o+=1){let s=n[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return n.slice(t,o+1)}return null},Ka=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=my(e),t=gy(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},$i=e=>typeof e=="string"?e:e==null?"":String(e),Zo={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:$i(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let t=e.payload,r=$i(t.element);if(r&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:$i(t.text)}}},mu=e=>Array.isArray(e)?e.map(n=>String(n)):[],Ga=e=>{let n=new Set(mu(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(mu(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;n.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var fy=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},hy=e=>e.map(n=>({...n,streaming:!1})),yy=e=>e.map(n=>({...n,status:"complete"})),_i=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?fy(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let o={...t,messages:t.messages?hy(t.messages):void 0,artifacts:t.artifacts?yy(t.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as by,STR as xy,OBJ as vy}from"partial-json";function Cy(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function wy(e,n){if(!Cy(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function ji(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let o=by(t,xy|vy),s=wy(o,t);s&&(e=s)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function Ay(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ui(e,n){let{config:t,message:r,onPropsUpdate:o}=n,s=oo.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Sy(){let e=ji();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function gu(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let n=e.content.trim();if(n.startsWith("{")||n.startsWith("["))return e.content}return null}function qi(e){let n=gu(e);if(!n)return!1;try{let t=JSON.parse(n);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function zi(e){let n=gu(e);if(!n)return null;try{let t=JSON.parse(n);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:n}}}catch{}return null}var Ey=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Vi(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Ey}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=r,g.appendChild(C);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,g.appendChild(x),f.appendChild(g);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let S=1;S<=5;S++){let F=document.createElement("button");F.type="button",F.className="persona-feedback-rating-btn persona-feedback-star-btn",F.setAttribute("role","radio"),F.setAttribute("aria-checked","false"),F.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${l[S-1]}`),F.title=l[S-1],F.dataset.rating=String(S),F.innerHTML=`
23
+ `,t.addEventListener("click",n);let r=o=>{var R,H,L,w,B,F,$,W,O,V,oe,Ie,Pe,ze;let a=(R=o.launcher)!=null?R:{},i=on(o),d=t.querySelector("[data-role='launcher-title']");if(d){let pe=(H=a.title)!=null?H:"Chat Assistant";d.textContent=pe,d.setAttribute("title",pe)}let l=t.querySelector("[data-role='launcher-subtitle']");if(l){let pe=(L=a.subtitle)!=null?L:"Get answers fast";l.textContent=pe,l.setAttribute("title",pe)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let pe=(w=a.agentIconSize)!=null?w:"40px";if(p.style.height=pe,p.style.width=pe,p.innerHTML="",a.agentIconName){let ce=parseFloat(pe)||24,Ee=fe(a.agentIconName,ce*.6,"var(--persona-text-inverse, #ffffff)",2);Ee?(p.appendChild(Ee),p.style.display=""):(p.textContent=(B=a.agentIconText)!=null?B:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let pe=($=a.agentIconSize)!=null?$:"40px";f.style.height=pe,f.style.width=pe,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let pe=(W=a.callToActionIconSize)!=null?W:"32px";m.style.height=pe,m.style.width=pe,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let ce=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ce=(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 Ee=parseFloat(pe)||24,je=Math.max(Ee-ce,8),te=fe(a.callToActionIconName,je,"currentColor",2);te?m.appendChild(te):m.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else m.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let v=a.position&&cr[a.position]?cr[a.position]:cr["bottom-right"],x="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",S="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?S:`${x} ${v}`,i||(t.style.zIndex=String((oe=a.zIndex)!=null?oe:gn));let A="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))";t.style.border=(Ie=a.border)!=null?Ie:A,t.style.boxShadow=(Pe=a.shadow)!=null?Pe:k,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(ze=a.collapsedMaxWidth)!=null?ze:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var Th="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ja=(e,n={})=>{var x,S,A,k,R,H;let{showClose:t=!0,wrapperClassName:r=Th,buttonSize:s,iconSize:o="28px"}=n,a=(x=e==null?void 0:e.launcher)!=null?x:{},i=(S=s!=null?s:a.closeButtonSize)!=null?S:"32px",d=h("div",r),l=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");l.style.height=i,l.style.width=i,l.type="button";let u=(A=a.closeButtonTooltipText)!=null?A:"Close chat",p=(k=a.closeButtonShowTooltip)!=null?k:!0;l.setAttribute("aria-label",u),l.style.display=t?"":"none";let f=(R=a.closeButtonIconName)!=null?R:"x",m=(H=a.closeButtonIconText)!=null?H:"\xD7";l.style.color=a.closeButtonColor||An.actionIconColor;let v=fe(f,o,"currentColor",1);if(v?(v.style.display="block",l.appendChild(v)):l.textContent=m,a.closeButtonBackgroundColor?(l.style.backgroundColor=a.closeButtonBackgroundColor,l.classList.remove("hover:persona-bg-gray-100")):(l.style.backgroundColor="",l.classList.add("hover:persona-bg-gray-100")),a.closeButtonBorderWidth||a.closeButtonBorderColor){let L=a.closeButtonBorderWidth||"0px",w=a.closeButtonBorderColor||"transparent";l.style.border=`${L} solid ${w}`,l.classList.remove("persona-border-none")}else l.style.border="",l.classList.add("persona-border-none");if(a.closeButtonBorderRadius?(l.style.borderRadius=a.closeButtonBorderRadius,l.classList.remove("persona-rounded-full")):(l.style.borderRadius="",l.classList.add("persona-rounded-full")),a.closeButtonPaddingX?(l.style.paddingLeft=a.closeButtonPaddingX,l.style.paddingRight=a.closeButtonPaddingX):(l.style.paddingLeft="",l.style.paddingRight=""),a.closeButtonPaddingY?(l.style.paddingTop=a.closeButtonPaddingY,l.style.paddingBottom=a.closeButtonPaddingY):(l.style.paddingTop="",l.style.paddingBottom=""),d.appendChild(l),p&&u){let L=null,w=()=>{if(L)return;let F=l.ownerDocument,$=F.body;if(!$)return;L=br(F,"div","persona-clear-chat-tooltip"),L.textContent=u;let W=br(F,"div");W.className="persona-clear-chat-tooltip-arrow",L.appendChild(W);let O=l.getBoundingClientRect();L.style.position="fixed",L.style.zIndex=String(Yr),L.style.left=`${O.left+O.width/2}px`,L.style.top=`${O.top-8}px`,L.style.transform="translate(-50%, -100%)",$.appendChild(L)},B=()=>{L&&L.parentNode&&(L.parentNode.removeChild(L),L=null)};d.addEventListener("mouseenter",w),d.addEventListener("mouseleave",B),l.addEventListener("focus",w),l.addEventListener("blur",B),d._cleanupTooltip=()=>{B(),d.removeEventListener("mouseenter",w),d.removeEventListener("mouseleave",B),l.removeEventListener("focus",w),l.removeEventListener("blur",B)}}return{button:l,wrapper:d}},Mh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ua=(e,n={})=>{var L,w,B,F,$,W,O,V,oe,Ie,Pe,ze,pe;let{wrapperClassName:t=Mh,buttonSize:r,iconSize:s="20px"}=n,a=(w=((L=e==null?void 0:e.launcher)!=null?L:{}).clearChat)!=null?w:{},i=(B=r!=null?r:a.size)!=null?B:"32px",d=(F=a.iconName)!=null?F:"refresh-cw",l=($=a.iconColor)!=null?$:"",u=(W=a.backgroundColor)!=null?W:"",p=(O=a.borderWidth)!=null?O:"",f=(V=a.borderColor)!=null?V:"",m=(oe=a.borderRadius)!=null?oe:"",v=(Ie=a.paddingX)!=null?Ie:"",x=(Pe=a.paddingY)!=null?Pe:"",S=(ze=a.tooltipText)!=null?ze:"Clear chat",A=(pe=a.showTooltip)!=null?pe:!0,k=h("div",t),R=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");R.style.height=i,R.style.width=i,R.type="button",R.setAttribute("aria-label",S),R.style.color=l||An.actionIconColor;let H=fe(d,s,"currentColor",1);if(H&&(H.style.display="block",R.appendChild(H)),u&&(R.style.backgroundColor=u,R.classList.remove("hover:persona-bg-gray-100")),p||f){let ce=p||"0px",Ee=f||"transparent";R.style.border=`${ce} solid ${Ee}`,R.classList.remove("persona-border-none")}if(m&&(R.style.borderRadius=m,R.classList.remove("persona-rounded-full")),v&&(R.style.paddingLeft=v,R.style.paddingRight=v),x&&(R.style.paddingTop=x,R.style.paddingBottom=x),k.appendChild(R),A&&S){let ce=null,Ee=()=>{if(ce)return;let te=R.ownerDocument,xe=te.body;if(!xe)return;ce=br(te,"div","persona-clear-chat-tooltip"),ce.textContent=S;let G=br(te,"div");G.className="persona-clear-chat-tooltip-arrow",ce.appendChild(G);let ae=R.getBoundingClientRect();ce.style.position="fixed",ce.style.zIndex=String(Yr),ce.style.left=`${ae.left+ae.width/2}px`,ce.style.top=`${ae.top-8}px`,ce.style.transform="translate(-50%, -100%)",xe.appendChild(ce)},je=()=>{ce&&ce.parentNode&&(ce.parentNode.removeChild(ce),ce=null)};k.addEventListener("mouseenter",Ee),k.addEventListener("mouseleave",je),R.addEventListener("focus",Ee),R.addEventListener("blur",je),k._cleanupTooltip=()=>{je(),k.removeEventListener("mouseenter",Ee),k.removeEventListener("mouseleave",je),R.removeEventListener("focus",Ee),R.removeEventListener("blur",je)}}return{button:R,wrapper:k}};var An={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},eo=e=>{var L,w,B,F,$,W,O,V,oe,Ie,Pe,ze,pe,ce,Ee,je;let{config:n,showClose:t=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(L=n==null?void 0:n.launcher)!=null?L:{},o=(w=s.headerIconSize)!=null?w:"48px",a=(B=s.closeButtonPlacement)!=null?B:"inline",i=(F=s.headerIconHidden)!=null?F:!1,d=s.headerIconName,l=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(l.style.height=o,l.style.width=o,l.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",l.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!i)if(d){let te=parseFloat(o)||24,xe=fe(d,te*.6,"currentColor",1);xe?l.replaceChildren(xe):l.textContent=(W=($=n==null?void 0:n.launcher)==null?void 0:$.agentIconText)!=null?W:"\u{1F4AC}"}else if((O=n==null?void 0:n.launcher)!=null&&O.iconUrl){let te=h("img");te.src=n.launcher.iconUrl,te.alt="",te.className="persona-rounded-xl persona-object-cover",te.style.height=o,te.style.width=o,l.replaceChildren(te)}else l.textContent=(oe=(V=n==null?void 0:n.launcher)==null?void 0:V.agentIconText)!=null?oe:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),p=h("span","persona-text-base persona-font-semibold");p.style.color=An.titleColor,p.textContent=(Pe=(Ie=n==null?void 0:n.launcher)==null?void 0:Ie.title)!=null?Pe:"Chat Assistant";let f=h("span","persona-text-xs");f.style.color=An.subtitleColor,f.textContent=(pe=(ze=n==null?void 0:n.launcher)==null?void 0:ze.subtitle)!=null?pe:"Here to help you get answers fast",u.append(p,f),i?r.append(u):r.append(l,u);let m=(ce=s.clearChat)!=null?ce:{},v=(Ee=m.enabled)!=null?Ee:!0,x=(je=m.placement)!=null?je:"inline",S=null,A=null;if(v){let xe=Ua(n,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=xe.button,A=xe.wrapper,x==="top-right"&&(A.style.right="48px"),x==="inline"&&r.appendChild(A)}let k=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:R,wrapper:H}=ja(n,{showClose:t,wrapperClassName:k});return a!=="top-right"&&r.appendChild(H),{header:r,iconHolder:l,headerTitle:p,headerSubtitle:f,closeButton:R,closeButtonWrapper:H,clearChatButton:S,clearChatButtonWrapper:A}},Vo=(e,n,t)=>{var a,i,d,l;let r=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function Eo(e){let{items:n,onSelect:t,anchor:r,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Yr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of n){if(m.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let S=fe(m.icon,16,"currentColor",1.5);S&&v.appendChild(S)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",S=>{S.stopPropagation(),u(),t(m.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!r.contains(v.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?l():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:l,hide:u,toggle:p,destroy:f}}function _t(e){let{icon:n,label:t,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let l=fe(n,r!=null?r:16,"currentColor",s!=null?s:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function qa(e){let{icon:n,label:t,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+s,a&&(l+=" "+a);let u=h("button",l);if(u.type="button",u.setAttribute("aria-label",t),n){let f=fe(n,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))u.setAttribute(f,m);return u}function za(e){let{items:n,selectedId:t,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of n){let p;u.icon?p=_t({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),r(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),r(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),o.appendChild(p)}function l(u){a=u,d()}return{element:o,setSelected:l}}function Hi(e){var m,v;let{label:n,icon:t="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,l=h("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",n);let u=h("span","persona-combo-btn-label");u.textContent=n,l.appendChild(u);let p=fe(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",l.appendChild(p)),d&&(l.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,S;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(S=d.border)!=null?S:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let f=Eo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),s(x)},anchor:l,position:o,portal:a});return a||l.appendChild(f.element),l.addEventListener("click",x=>{x.stopPropagation();let S=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",S?"false":"true"),f.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{u.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),f.show()},close:()=>{l.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let x=!f.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),l.remove()}}}var Jp=e=>{var r;let n=eo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return n};function kh(e,n,t){var r,s,o;if(n!=null&&n.length)for(let a of n){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let d=fe(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let l=Eo({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",u=>{u.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Gp=e=>{var k,R,H,L,w,B,F,$,W;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(k=n==null?void 0:n.launcher)!=null?k:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,l,u;if(d)l=Hi({label:(R=a.title)!=null?R:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=An.titleColor,u=(H=l.querySelector(".persona-combo-btn-label"))!=null?H:l;else{if(l=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=An.titleColor,u.textContent=(L=a.title)!=null?L:"Chat Assistant",l.appendChild(u),kh(l,s==null?void 0:s.trailingActions,(w=s==null?void 0:s.onAction)!=null?w:o),s!=null&&s.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let V=s.onTitleClick;l.addEventListener("click",oe=>{oe.target.closest("button")||V()}),l.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),V())})}let O=s==null?void 0:s.titleRowHover;O&&(l.style.borderRadius=(B=O.borderRadius)!=null?B:"10px",l.style.padding=(F=O.padding)!=null?F:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var V,oe;l.style.backgroundColor=(V=O.background)!=null?V:"",l.style.borderColor=(oe=O.border)!=null?oe:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let p=($=a.closeButtonSize)!=null?$:"32px",f=h("div",""),m=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=p,m.style.width=p,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||An.actionIconColor;let v=(W=a.closeButtonIconName)!=null?W:"x",x=fe(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),f.appendChild(m),i.appendChild(f);let S=h("div");S.style.display="none";let A=h("span");return A.style.display="none",{header:i,iconHolder:S,headerTitle:u,headerSubtitle:A,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Bi={default:Jp,minimal:Gp},Xp=e=>{var n;return(n=Bi[e])!=null?n:Bi.default},_s=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let l=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:l,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=Xp(r)({config:e,showClose:(d=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var Va=e=>{var a,i;let n=h("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",n.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",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;n.style.maxHeight=`${t*r}px`,n.style.overflowY="auto";let s=()=>{let d=parseFloat(n.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},o=()=>{n.addEventListener("input",()=>{n.style.height="auto";let d=Math.min(n.scrollHeight,s());n.style.height=`${d}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:o}},Ka=e=>{var L,w,B,F,$,W,O,V,oe,Ie,Pe,ze;let n=(L=e==null?void 0:e.sendButton)!=null?L:{},t=(w=n.useIcon)!=null?w:!1,r=(B=n.iconText)!=null?B:"\u2191",s=n.iconName,o=(F=n.stopIconName)!=null?F:"square",a=($=n.tooltipText)!=null?$:"Send message",i=(W=n.stopTooltipText)!=null?W:"Stop generating",d=(V=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?V:"Send",l=(Ie=(oe=e==null?void 0:e.copy)==null?void 0:oe.stopButtonLabel)!=null?Ie:"Stop",u=(Pe=n.showTooltip)!=null?Pe:!1,p=(ze=n.size)!=null?ze:"40px",f=n.backgroundColor,m=n.textColor,v=h("div","persona-send-button-wrapper"),x=h("button",t?"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");x.type="submit",x.setAttribute("data-persona-composer-submit","");let S=null,A=null;if(t){x.style.width=p,x.style.height=p,x.style.minWidth=p,x.style.minHeight=p,x.style.fontSize="18px",x.style.lineHeight="1",x.innerHTML="",m?x.style.color=m:x.style.color="var(--persona-button-primary-fg, #ffffff)";let pe=parseFloat(p)||24,ce=(m==null?void 0:m.trim())||"currentColor";s?(S=fe(s,pe,ce,2),S?x.appendChild(S):x.textContent=r):x.textContent=r,A=fe(o,pe,ce,2),f?x.style.backgroundColor=f:x.classList.add("persona-bg-persona-primary")}else x.textContent=d,m?x.style.color=m:x.classList.add("persona-text-white");n.borderWidth&&(x.style.borderWidth=n.borderWidth,x.style.borderStyle="solid"),n.borderColor&&(x.style.borderColor=n.borderColor),n.paddingX?(x.style.paddingLeft=n.paddingX,x.style.paddingRight=n.paddingX):(x.style.paddingLeft="",x.style.paddingRight=""),n.paddingY?(x.style.paddingTop=n.paddingY,x.style.paddingBottom=n.paddingY):(x.style.paddingTop="",x.style.paddingBottom="");let k=null;u&&a&&(k=h("div","persona-send-button-tooltip"),k.textContent=a,v.appendChild(k)),x.setAttribute("aria-label",a),v.appendChild(x);let R="send";return{button:x,wrapper:v,setMode:pe=>{if(pe===R)return;R=pe;let ce=pe==="stop"?i:a;if(x.setAttribute("aria-label",ce),k&&(k.textContent=ce),t){if(S&&A){let Ee=pe==="stop"?A:S;x.replaceChildren(Ee)}}else x.textContent=pe==="stop"?l:d}}},Ja=e=>{var k,R,H,L,w,B,F,$,W,O,V,oe;let n=(k=e==null?void 0:e.voiceRecognition)!=null?k:{};if(!(n.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),s=((R=n.provider)==null?void 0:R.type)==="runtype";if(!(r||s))return null;let a=(L=(H=e==null?void 0:e.sendButton)==null?void 0:H.size)!=null?L:"40px",i=h("div","persona-send-button-wrapper"),d=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");d.type="button",d.setAttribute("data-persona-composer-mic",""),d.setAttribute("aria-label","Start voice recognition");let l=(w=n.iconName)!=null?w:"mic",u=(B=n.iconSize)!=null?B:a,p=parseFloat(u)||24,f=($=n.backgroundColor)!=null?$:(F=e==null?void 0:e.sendButton)==null?void 0:F.backgroundColor,m=(O=n.iconColor)!=null?O:(W=e==null?void 0:e.sendButton)==null?void 0:W.textColor;d.style.width=u,d.style.height=u,d.style.minWidth=u,d.style.minHeight=u,d.style.fontSize="18px",d.style.lineHeight="1",m?d.style.color=m:d.style.color="var(--persona-text, #111827)";let x=fe(l,p,m||"currentColor",1.5);x?d.appendChild(x):d.textContent="\u{1F3A4}",f&&(d.style.backgroundColor=f),n.borderWidth&&(d.style.borderWidth=n.borderWidth,d.style.borderStyle="solid"),n.borderColor&&(d.style.borderColor=n.borderColor),n.paddingX&&(d.style.paddingLeft=n.paddingX,d.style.paddingRight=n.paddingX),n.paddingY&&(d.style.paddingTop=n.paddingY,d.style.paddingBottom=n.paddingY),i.appendChild(d);let S=(V=n.tooltipText)!=null?V:"Start voice recognition";if(((oe=n.showTooltip)!=null?oe:!1)&&S){let Ie=h("div","persona-send-button-tooltip");Ie.textContent=S,i.appendChild(Ie)}return{button:d,wrapper:i}},Ga=e=>{var v,x,S,A,k,R,H,L;let n=(v=e==null?void 0:e.attachments)!=null?v:{};if(n.enabled!==!0)return null;let t=(S=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?S:"40px",r=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.style.display="none";let s=h("input");s.type="file",s.accept=((A=n.allowedTypes)!=null?A:Rr).join(","),s.multiple=((k=n.maxFiles)!=null?k:4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let o=h("div","persona-send-button-wrapper"),a=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button");a.type="button",a.setAttribute("aria-label",(R=n.buttonTooltipText)!=null?R:"Attach file");let i=(H=n.buttonIconName)!=null?H:"paperclip",d=t,l=parseFloat(d)||40,u=Math.round(l*.6);a.style.width=d,a.style.height=d,a.style.minWidth=d,a.style.minHeight=d,a.style.fontSize="18px",a.style.lineHeight="1",a.style.backgroundColor="transparent",a.style.color="var(--persona-primary, #111827)",a.style.border="none",a.style.borderRadius="6px",a.style.transition="background-color 0.15s ease",a.addEventListener("mouseenter",()=>{a.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),a.addEventListener("mouseleave",()=>{a.style.backgroundColor="transparent"});let p=fe(i,u,"currentColor",1.5);p?a.appendChild(p):a.textContent="\u{1F4CE}",a.addEventListener("click",w=>{w.preventDefault(),s.click()}),o.appendChild(a);let f=(L=n.buttonTooltipText)!=null?L:"Attach file",m=h("div","persona-send-button-tooltip");return m.textContent=f,o.appendChild(m),{button:a,wrapper:o,input:s,previewsContainer:r}},Xa=e=>{var a,i,d;let n=(a=e==null?void 0:e.statusIndicator)!=null?a:{},t=n.align==="left"?"persona-text-left":n.align==="center"?"persona-text-center":"persona-text-right",r=h("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let s=(i=n.visible)!=null?i:!0;r.style.display=s?"":"none";let o=(d=n.idleText)!=null?d:"Online";if(n.idleLink){let l=h("a");l.href=n.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=o,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=o;return r},Ya=()=>h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2");var js=e=>{var v,x,S,A,k,R;let{config:n}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let r=Ya(),s=h("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let{textarea:o,attachAutoResize:a}=Va(n);a();let i=Ka(n),d=Ja(n),l=Ga(n),u=Xa(n);l&&(l.previewsContainer.style.gap="8px",s.append(l.previewsContainer,l.input)),s.append(o);let p=h("div","persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full"),f=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&f.append(l.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),p.append(f,m),s.append(p),s.addEventListener("click",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&o.focus()}),t.append(r,s,u),{footer:t,suggestions:r,composerForm:s,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:u,attachmentButton:(S=l==null?void 0:l.button)!=null?S:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(k=l==null?void 0:l.input)!=null?k:null,attachmentPreviewsContainer:(R=l==null?void 0:l.previewsContainer)!=null?R:null,actionsRow:p,leftActions:f,rightActions:m,setSendButtonMode:i.setMode}};var Yp=()=>{let e=h("button","persona-pill-peek");e.type="button",e.setAttribute("data-persona-pill-peek",""),e.setAttribute("aria-label","Show conversation"),e.setAttribute("tabindex","-1");let n=h("span","persona-pill-peek__icon"),t=fe("message-square",16,"currentColor",1.5);t&&n.appendChild(t);let r=h("span","persona-pill-peek__text"),s=h("span","persona-pill-peek__caret"),o=fe("chevron-up",16,"currentColor",1.5);return o&&s.appendChild(o),e.append(n,r,s),{root:e,textNode:r}},Qp=e=>{var v,x,S,A,k,R;let{config:n}=e,t=h("div","persona-widget-footer persona-widget-footer--pill");t.setAttribute("data-persona-theme-zone","composer");let r=Ya();r.style.display="none";let s=Xa(n);s.style.display="none";let{textarea:o,attachAutoResize:a}=Va(n);o.style.maxHeight="100px",a();let i=Ka(n),d=Ja(n),l=Ga(n);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let u=h("form","persona-widget-composer persona-pill-composer");u.setAttribute("data-persona-composer-form",""),u.style.outline="none";let p=h("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&p.append(l.wrapper);let f=h("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),u.addEventListener("click",H=>{H.target!==i.button&&H.target!==i.wrapper&&H.target!==(d==null?void 0:d.button)&&H.target!==(d==null?void 0:d.wrapper)&&H.target!==(l==null?void 0:l.button)&&H.target!==(l==null?void 0:l.wrapper)&&o.focus()}),l&&u.append(l.input),u.append(p,o,f),l&&t.append(l.previewsContainer),t.append(u,r,s);let m=u;return{footer:t,suggestions:r,composerForm:u,textarea:o,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:s,attachmentButton:(S=l==null?void 0:l.button)!=null?S:null,attachmentButtonWrapper:(A=l==null?void 0:l.wrapper)!=null?A:null,attachmentInput:(k=l==null?void 0:l.input)!=null?k:null,attachmentPreviewsContainer:(R=l==null?void 0:l.previewsContainer)!=null?R:null,actionsRow:m,leftActions:p,rightActions:f,setSendButtonMode:i.setMode}};var Zp=e=>{var u,p,f,m,v,x,S,A,k,R,H,L,w,B,F,$,W;let n=(p=(u=e==null?void 0:e.launcher)==null?void 0:u.enabled)!=null?p:!0,t=on(e);if(Zr(e)){let O=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?m:{},V=h("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(v=O.expandedSize)!=null?v:"anchored",V.style.zIndex=String((S=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?S:gn);let oe=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");oe.style.width="100%",V.appendChild(oe);let Ie=h("div","persona-widget-pill-root");return Ie.setAttribute("data-persona-composer-bar",""),Ie.dataset.state="collapsed",Ie.dataset.expandedSize=(A=O.expandedSize)!=null?A:"anchored",Ie.style.zIndex=String((R=(k=e==null?void 0:e.launcher)==null?void 0:k.zIndex)!=null?R:gn),{wrapper:V,panel:oe,pillRoot:Ie}}if(t){let O=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(V),{wrapper:O,panel:V}}if(!n){let O=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),oe=(L=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?L:"100%";return O.style.width=oe,V.style.width="100%",O.appendChild(V),{wrapper:O,panel:V}}let s=(w=e==null?void 0:e.launcher)!=null?w:{},o=s.position&&cr[s.position]?cr[s.position]:cr["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${o} persona-transition`);a.style.zIndex=String((F=(B=e==null?void 0:e.launcher)==null?void 0:B.zIndex)!=null?F:gn);let i=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(W=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?W:e==null?void 0:e.launcherWidth,l=d!=null?d:Gn;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Lh=(e,n)=>{var H,L,w,B,F,$,W,O,V;let t=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:s}=ja(e,{showClose:n,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let o=(w=(L=(H=e==null?void 0:e.launcher)==null?void 0:H.clearChat)==null?void 0:L.enabled)!=null?w:!0,a=null,i=null;if(o){let oe=Ua(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=oe.button,i=oe.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=h("span","persona-widget-header");d.setAttribute("data-persona-theme-zone","header"),d.style.display="none";let l=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");l.style.paddingTop="48px",l.id="persona-scroll-container",l.setAttribute("data-persona-theme-zone","messages");let u=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");u.style.boxShadow="var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",u.setAttribute("data-persona-intro-card","");let p=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");p.textContent=(F=(B=e==null?void 0:e.copy)==null?void 0:B.welcomeTitle)!=null?F:"Hello \u{1F44B}";let f=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");f.textContent=(W=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",u.append(p,f);let m=h("div","persona-flex persona-flex-col persona-gap-3"),v=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((V=e==null?void 0:e.copy)==null?void 0:V.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let S=h("div","persona-composer-overlay persona-pointer-events-none");S.setAttribute("data-persona-composer-overlay",""),S.style.position="absolute",S.style.left="0",S.style.right="0",S.style.bottom="0",S.style.zIndex="20";let A=Qp({config:e}),{root:k,textNode:R}=Yp();return t.append(d,s,l,S),i&&t.appendChild(i),{container:t,body:l,messagesWrapper:m,composerOverlay:S,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,introTitle:p,introSubtitle:f,closeButton:r,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:d,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:k,peekTextNode:R}},eu=(e,n=!0)=>{var S,A,k,R,H,L,w,B,F;if(Zr(e))return Lh(e,n);let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let r=(S=e==null?void 0:e.layout)==null?void 0:S.header,s=((A=e==null?void 0:e.layout)==null?void 0:A.showHeader)!==!1,o=r?_s(e,r,{showClose:n}):eo({config:e,showClose:n}),a=h("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6");i.style.boxShadow=on(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))";let d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(R=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?R:"Hello \u{1F44B}";let l=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");l.textContent=(L=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",i.append(d,l);let u=h("div","persona-flex persona-flex-col persona-gap-3"),p=(w=e==null?void 0:e.layout)==null?void 0:w.contentMaxWidth;p&&(u.style.maxWidth=p,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),i.setAttribute("data-persona-intro-card",""),((B=e==null?void 0:e.copy)==null?void 0:B.showWelcomeCard)!==!1||(i.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(i,u);let m=js({config:e}),v=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;s?Vo(t,o,e):(o.header.style.display="none",Vo(t,o,e)),t.append(a);let x=h("div","persona-composer-overlay persona-pointer-events-none");return x.setAttribute("data-persona-composer-overlay",""),x.style.position="absolute",x.style.left="0",x.style.right="0",x.style.bottom="0",x.style.zIndex="20",v||(m.footer.style.display="none"),t.append(m.footer),t.append(x),{container:t,body:a,messagesWrapper:u,composerOverlay:x,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:l,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var Ph=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Ih=(e,n)=>{if(!e)return null;let t=Ph(e);if(t===null)return null;let r=n==null?void 0:n[e],s=r!==void 0?r:t;return s||null},Wh=(e,n)=>{let t=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=n,t},Rh=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},Di=e=>{let n=e.toLowerCase();return n.startsWith("javascript:")||n.startsWith("data:text/html")||n.startsWith("data:text/javascript")||n.startsWith("data:text/xml")||n.startsWith("data:application/xhtml")||n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:")||!e.includes(":"))},Ni=320,nu=320,Hh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Bh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="audio"&&typeof n.audio=="string"&&n.audio.trim().length>0),Dh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="video"&&typeof n.video=="string"&&n.video.trim().length>0),Nh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="file"&&typeof n.data=="string"&&n.data.trim().length>0),Oh=(e,n,t)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let l=h("img");l.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Ni}px`,l.style.maxHeight=`${nu}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,l.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),l.remove(),s===0&&a())}),l.addEventListener("load",()=>{u=!0}),Rh(i.image)?(l.src=i.image,r.appendChild(l)):(u=!0,s=Math.max(0,s-1),l.remove())}),s===0?(a(),null):r}catch{return t==null||t(),null}},Fh=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","audio");let t=0;return e.forEach(r=>{if(!Di(r.audio))return;let s=h("audio");s.controls=!0,s.preload="metadata",s.src=r.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Ni}px`,n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},$h=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","video");let t=0;return e.forEach(r=>{if(!Di(r.video))return;let s=h("video");s.controls=!0,s.preload="metadata",s.src=r.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${Ni}px`,s.style.maxHeight=`${nu}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},_h=e=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","files");let t=0;return e.forEach(r=>{if(!Di(r.data))return;let s=h("a");s.href=r.data,s.download=r.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",n.appendChild(s),t+=1}),t===0?(n.remove(),null):n}catch{return null}},Ko=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},ru=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Ko};if(n){let s=n(r);if(s!==null)return s}return Ko()},jh=(e,n)=>{let t=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},tu=(e,n)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Uh=(e,n="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},ou=(e,n,t)=>{var m,v,x,S,A,k;let r=(m=n.showCopy)!=null?m:!0,s=(v=n.showUpvote)!=null?v:!0,o=(x=n.showDownvote)!=null?x:!0;if(!r&&!s&&!o){let R=h("div");return R.style.display="none",R.id=`actions-${e.id}`,R.setAttribute("data-actions-for",e.id),R}let a=(S=n.visibility)!=null?S:"hover",i=(A=n.align)!=null?A:"right",d=(k=n.layout)!=null?k:"pill-inside",l={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${l} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(R,H,L)=>{let w=_t({icon:R,label:H,size:14,className:"persona-message-action-btn"});return w.setAttribute("data-action",L),w};return r&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},Us=(e,n,t,r,s,o)=>{var te,xe,G,ae,He,ue,Re,tt,K,se,Oe,J,z,we,$e,ne,Te;let a=t!=null?t:{},i=(te=a.layout)!=null?te:"bubble",d=a.avatar,l=a.timestamp,u=(xe=d==null?void 0:d.show)!=null?xe:!1,p=(G=l==null?void 0:l.show)!=null?G:!1,f=(ae=d==null?void 0:d.position)!=null?ae:"left",m=(He=l==null?void 0:l.position)!=null?He:"below",v=Uh(e.role,i),x=h("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=Hh(e),A=(Re=(ue=e.content)==null?void 0:ue.trim())!=null?Re:"",R=S.length>0&&A===Ea,H=Oa((K=(tt=o==null?void 0:o.widgetConfig)==null?void 0:tt.features)==null?void 0:K.streamAnimation),L=(J=(Oe=(se=o==null?void 0:o.widgetConfig)==null?void 0:se.features)==null?void 0:Oe.streamAnimation)==null?void 0:J.plugins,w=e.role==="assistant"&&H.type!=="none"?Ds(H.type,L):null,B=e.role==="assistant"&&((z=w==null?void 0:w.isAnimating)==null?void 0:z.call(w,e))===!0,F=e.role==="assistant"&&w!==null&&(!!e.streaming||B);F&&(w!=null&&w.bubbleClass)&&x.classList.add(w.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),F&&w&&(w.containerClass&&$.classList.add(w.containerClass),$.style.setProperty("--persona-stream-step",`${H.speed}ms`),$.style.setProperty("--persona-stream-duration",`${H.duration}ms`));let W=F?Fa((we=e.content)!=null?we:"",H.buffer,w,e,!!e.streaming):($e=e.content)!=null?$e:"",O=n({text:W,message:e,streaming:!!e.streaming,raw:e.rawContent}),V=O;F&&(w==null?void 0:w.wrap)==="char"?V=Ns(O,"char",e.id,{skipTags:w.skipTags}):F&&(w==null?void 0:w.wrap)==="word"&&(V=Ns(O,"word",e.id,{skipTags:w.skipTags}));let oe=null;if(R?(oe=document.createElement("div"),oe.innerHTML=V,oe.style.display="none",$.appendChild(oe)):$.innerHTML=V,F&&(w!=null&&w.useCaret)&&!R&&A){let ve=$a(),Ht=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),ie=Ht[Ht.length-1];if(ie!=null&&ie.parentNode)ie.parentNode.insertBefore(ve,ie.nextSibling);else{let re=$.lastElementChild;re?re.appendChild(ve):$.appendChild(ve)}}if(p&&m==="inline"&&e.createdAt){let ve=tu(e,l);ve.classList.add("persona-ml-2","persona-inline"),$.appendChild(ve)}if(S.length>0){let ve=Oh(S,!R&&!!A,()=>{R&&oe&&(oe.style.display="")});ve?x.appendChild(ve):R&&oe&&(oe.style.display="")}let Ie=Bh(e);if(Ie.length>0){let ve=Fh(Ie);ve&&x.appendChild(ve)}let Pe=Dh(e);if(Pe.length>0){let ve=$h(Pe);ve&&x.appendChild(ve)}let ze=Nh(e);if(ze.length>0){let ve=_h(ze);ve&&x.appendChild(ve)}if(x.appendChild($),p&&m==="below"&&e.createdAt){let ve=tu(e,l);ve.classList.add("persona-mt-1"),x.appendChild(ve)}let pe=e.role==="assistant"?Ih(e.stopReason,(Te=(ne=o==null?void 0:o.widgetConfig)==null?void 0:ne.copy)==null?void 0:Te.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ve=!!(W&&W.trim()),Ht=H.placeholder==="skeleton",ie=Ht&&H.buffer==="line"&&ve;if(ve)ie&&x.appendChild(Os());else if(Ht)x.appendChild(Os());else{let re=ru("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);re&&x.appendChild(re)}}if(pe&&e.stopReason&&!e.streaming&&(A||($.style.display="none"),x.appendChild(Wh(e.stopReason,pe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let ve=ou(e,r,s);x.appendChild(ve)}if(!u||e.role==="system")return x;let Ee=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),je=jh(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Ee.append(x,je):Ee.append(je,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Ee},qh=(e,n,t,r,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Us(e,n,t,r,s,o)};var Jo=new Set,zh=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),Vh=(e,n)=>{var r,s;let t=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,n).join(`
24
+ `):""},su=(e,n)=>{let t=Jo.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t"),o=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=fe(t?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},Oi=(e,n)=>{var Pe,ze,pe,ce,Ee,je,te,xe,G,ae,He;let t=e.reasoning,r=h("div",["persona-message-bubble","persona-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(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!t)return r;let s=(ze=(Pe=n==null?void 0:n.features)==null?void 0:Pe.reasoningDisplay)!=null?ze:{},o=s.expandable!==!1,a=o&&Jo.has(e.id),i=t.status!=="complete",d=Vh(e,(pe=s.previewMaxLines)!=null?pe:3),l=h("button",o?"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":"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-default persona-border-none");l.type="button",o&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let u=h("div","persona-flex persona-flex-col persona-text-left"),p=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",m=(ce=n==null?void 0:n.reasoning)!=null?ce:{},v=String((Ee=t.startedAt)!=null?Ee:Date.now()),x=()=>{let ue=h("span","");return ue.setAttribute("data-tool-elapsed",v),ue.textContent=wa(t),ue},S=(je=m.renderCollapsedSummary)==null?void 0:je.call(m,{message:e,reasoning:t,defaultSummary:f,previewText:d,isActive:i,config:n!=null?n:{},elapsed:wa(t),createElapsedElement:x});typeof S=="string"&&S.trim()?(p.textContent=S,u.appendChild(p)):S instanceof HTMLElement?u.appendChild(S):(p.textContent=f,u.appendChild(p));let A=h("span","persona-text-xs persona-text-persona-primary");A.textContent=Cp(t),u.appendChild(A);let k=(te=s.loadingAnimation)!=null?te:"none",R=m.activeTextTemplate,H=m.completeTextTemplate,L=i?R:H,w=S instanceof HTMLElement,B=(ue,Re,tt)=>{let K=tt;for(let se of Re){let Oe=h("span","persona-tool-char");Oe.style.setProperty("--char-index",String(K)),Oe.textContent=se===" "?"\xA0":se,ue.appendChild(Oe),K++}return K},F=(ue,Re)=>{p.textContent="";let tt=Ca(ue,""),K=0;for(let se of tt){let Oe=se.styles.length>0?(()=>{let J=h("span",se.styles.map(z=>`persona-tool-text-${z}`).join(" "));return p.appendChild(J),J})():p;if(se.isDuration&&i)Oe.appendChild(x());else{let J=se.isDuration?wa(t):se.text;Re?K=B(Oe,J,K):Oe.appendChild(document.createTextNode(J))}}};if(!w&&L)if(A.style.display="none",p.style.display="",i&&k!=="none"){let ue=(xe=m.loadingAnimationDuration)!=null?xe:2e3;p.setAttribute("data-preserve-animation","true"),k==="pulse"?(p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),F(L,!1)):(p.classList.add(`persona-tool-loading-${k}`),p.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),k==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),F(L,!0))}else F(L,!1);else if(!w&&i&&k!=="none"){p.style.display="";let ue=(G=m.loadingAnimationDuration)!=null?G:2e3;if(p.setAttribute("data-preserve-animation","true"),k==="pulse")p.classList.add("persona-tool-loading-pulse"),p.style.setProperty("--persona-tool-anim-duration",`${ue}ms`);else{p.classList.add(`persona-tool-loading-${k}`),p.style.setProperty("--persona-tool-anim-duration",`${ue}ms`),k==="shimmer-color"&&(m.loadingAnimationColor&&p.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&p.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let Re=p.textContent||f;p.textContent="",B(p,Re,0)}t.status==="complete"&&(p.style.display="none")}else w||(t.status==="complete"?p.style.display="none":p.style.display="");let $=null;if(o){$=h("div","persona-flex persona-items-center");let Re=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);Re?$.appendChild(Re):$.textContent=a?"Hide":"Show";let tt=h("div","persona-flex persona-items-center persona-ml-auto");tt.append($),l.append(u,tt)}else l.append(u);let W=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","reasoning"),W.style.display="none",W.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&d){let ue=(He=(ae=n==null?void 0:n.reasoning)==null?void 0:ae.renderCollapsedPreview)==null?void 0:He.call(ae,{message:e,reasoning:t,defaultPreview:d,isActive:i,config:n!=null?n:{}});zh(W,ue)||(W.textContent=d),W.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(l,W),r;let O=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let V=t.chunks.join(""),oe=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return oe.textContent=V||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(oe),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),$){$.innerHTML="";let Re=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);Re?$.appendChild(Re):$.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",W.style.display=a?"none":W.textContent||W.childNodes.length?"":"none"})(),r.append(l,W,O),r};var Go=new Set,Kh=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),Jh=(e,n)=>{var o;let t=e.toolCall;if(!t)return"";let r=((o=t.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-n).join(`
25
+ `);let s=$o(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,n).join(`
26
+ `):""},Gh=(e,n)=>{var u,p,f,m,v;let t=e.toolCall,r=(u=n==null?void 0:n.features)==null?void 0:u.toolCallDisplay,s=(p=r==null?void 0:r.collapsedMode)!=null?p:"tool-call",o=Jh(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=t?Ap(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",d=(m=n==null?void 0:n.toolCall)!=null?m:{},l=a;return s==="tool-name"?l=((v=t.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(l=o),i&&d.activeTextTemplate?l=yi(t,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=yi(t,d.completeTextTemplate,l)),{summary:l,previewText:o,isActive:i}},au=(e,n,t)=>{var u;let r=Go.has(e),s=(u=t==null?void 0:t.toolCall)!=null?u:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let d=o.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",f=fe(r?"chevron-up":"chevron-down",16,p,2);f?l.appendChild(f):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Fi=(e,n)=>{var V,oe,Ie,Pe,ze,pe,ce,Ee,je;let t=e.toolCall,r=(V=n==null?void 0:n.toolCall)!=null?V:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!t)return s;let o=(Ie=(oe=n==null?void 0:n.features)==null?void 0:oe.toolCallDisplay)!=null?Ie:{},a=o.expandable!==!1,i=a&&Go.has(e.id),{summary:d,previewText:l,isActive:u}=Gh(e,n),p=h("button",a?"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":"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-default persona-border-none");p.type="button",a&&(p.setAttribute("aria-expanded",i?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(p.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(p.style.paddingLeft=r.headerPaddingX,p.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(p.style.paddingTop=r.headerPaddingY,p.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),m=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let v=String((Pe=t.startedAt)!=null?Pe:Date.now()),x=()=>{let te=h("span","");return te.setAttribute("data-tool-elapsed",v),te.textContent=Es(t),te},S=(pe=r.renderCollapsedSummary)==null?void 0:pe.call(r,{message:e,toolCall:t,defaultSummary:d,previewText:l,collapsedMode:(ze=o.collapsedMode)!=null?ze:"tool-call",isActive:u,config:n!=null?n:{},elapsed:Es(t),createElapsedElement:x});typeof S=="string"&&S.trim()?(m.textContent=S,f.appendChild(m)):S instanceof HTMLElement?f.appendChild(S):(m.textContent=d,f.appendChild(m));let A=(ce=o.loadingAnimation)!=null?ce:"none",k=r.activeTextTemplate,R=r.completeTextTemplate,H=u?k:R,L=S instanceof HTMLElement,w=(te,xe,G)=>{let ae=G;for(let He of xe){let ue=h("span","persona-tool-char");ue.style.setProperty("--char-index",String(ae)),ue.textContent=He===" "?"\xA0":He,te.appendChild(ue),ae++}return ae},B=(te,xe)=>{var ue;m.textContent="";let G=((ue=t.name)==null?void 0:ue.trim())||"tool",ae=Ca(te,G),He=0;for(let Re of ae){let tt=Re.styles.length>0?(()=>{let K=h("span",Re.styles.map(se=>`persona-tool-text-${se}`).join(" "));return m.appendChild(K),K})():m;if(Re.isDuration&&u)tt.appendChild(x());else{let K=Re.isDuration?Es(t):Re.text;xe?He=w(tt,K,He):tt.appendChild(document.createTextNode(K))}}};if(!L)if(u&&A!=="none"){let te=(Ee=r.loadingAnimationDuration)!=null?Ee:2e3;if(m.setAttribute("data-preserve-animation","true"),A==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${te}ms`),H&&B(H,!1);else if(m.classList.add(`persona-tool-loading-${A}`),m.style.setProperty("--persona-tool-anim-duration",`${te}ms`),A==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),H)B(H,!0);else{let xe=m.textContent||d;m.textContent="",w(m,xe,0)}}else H&&B(H,!1);let F=null;if(a){F=h("div","persona-flex persona-items-center");let te=r.toggleTextColor||r.headerTextColor||"currentColor",xe=fe(i?"chevron-up":"chevron-down",16,te,2);xe?F.appendChild(xe):F.textContent=i?"Hide":"Show";let G=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");G.append(F),p.append(f,G)}else p.append(f);let $=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!i&&u&&o.activePreview&&l){let te=(je=r.renderCollapsedPreview)==null?void 0:je.call(r,{message:e,toolCall:t,defaultPreview:l,isActive:u,config:n!=null?n:{}});Kh($,te)||($.textContent=l),$.style.display=""}if(!i&&u&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(p,$),s;let W=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(W.style.display=i?"":"none",r.contentBackgroundColor&&(W.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(W.style.color=r.contentTextColor),r.contentPaddingX&&(W.style.paddingLeft=r.contentPaddingX,W.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(W.style.paddingTop=r.contentPaddingY,W.style.paddingBottom=r.contentPaddingY),t.name){let te=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?te.style.color=r.contentTextColor:r.headerTextColor&&(te.style.color=r.headerTextColor),te.textContent=t.name,W.appendChild(te)}if(t.args!==void 0){let te=h("div","persona-space-y-1"),xe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(xe.style.color=r.labelTextColor),xe.textContent="Arguments";let G=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(G.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(G.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(G.style.color=r.codeBlockTextColor),G.textContent=$o(t.args),te.append(xe,G),W.appendChild(te)}if(t.chunks&&t.chunks.length){let te=h("div","persona-space-y-1"),xe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(xe.style.color=r.labelTextColor),xe.textContent="Activity";let G=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(G.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(G.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(G.style.color=r.codeBlockTextColor),G.textContent=t.chunks.join(""),te.append(xe,G),W.appendChild(te)}if(t.status==="complete"&&t.result!==void 0){let te=h("div","persona-space-y-1"),xe=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(xe.style.color=r.labelTextColor),xe.textContent="Result";let G=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");G.style.fontSize="0.75rem",G.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(G.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(G.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(G.style.color=r.codeBlockTextColor),G.textContent=$o(t.result),te.append(xe,G),W.appendChild(te)}if(t.status==="complete"&&typeof t.duration=="number"){let te=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(te.style.color=r.contentTextColor),te.textContent=`Duration: ${t.duration}ms`,W.appendChild(te)}return(()=>{if(p.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let te=r.toggleTextColor||r.headerTextColor||"currentColor",xe=fe(i?"chevron-up":"chevron-down",16,te,2);xe?F.appendChild(xe):F.textContent=i?"Hide":"Show"}W.style.display=i?"":"none",$.style.display=i?"none":$.textContent||$.childNodes.length?"":"none"})(),s.append(p,$,W),s};import{parse as Xh,ARR as Yh,OBJ as Qh,STR as Zh}from"partial-json";var lu="ask_user_question",$i=8,Xo="data-persona-ask-sheet-for",ey="Other",ty="Other\u2026",cu="Type your own answer here",du="Send",ny="Next",ry="Back",oy="Submit all",sy="Skip",ay=3,_i="data-ask-current-index",ji="data-ask-question-count",pu="data-ask-answers",Ui="data-ask-grouped",uu="data-ask-layout",iy=e=>e.layout==="pills"?"pills":"rows",ly=e=>e.getAttribute(uu)==="pills"?"pills":"rows",iu=!1,mu=e=>e.replace(/["\\]/g,"\\$&"),to=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===lu,Qa=e=>{var n,t;return(t=(n=e==null?void 0:e.features)==null?void 0:n.askUserQuestion)!=null?t:{}},no=e=>{let n=e.toolCall;if(!n)return{payload:null,complete:!1};let t=n.status==="complete";if(n.args&&typeof n.args=="object")return{payload:n.args,complete:t};let r=n.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let s=r.join(""),o=Xh(s,Zh|Qh|Yh);if(o&&typeof o=="object")return{payload:o,complete:t}}catch{}return{payload:null,complete:t}},qs=e=>{let n=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return n.length>$i&&!iu&&(iu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${n.length} questions; truncating to ${$i}.`)),n.slice(0,$i)},cy=e=>{var n;return(n=qs(e)[0])!=null?n:null},dy=(e,n)=>{var t;return(t=qs(e)[n])!=null?t:null},gu=(e,n)=>{let t=n.styles;t&&(t.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},fu=(e,n,t)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),n){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(t+1),r.appendChild(s)}return r},py=(e,n,t,r)=>{let o=h("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(n)),o.setAttribute("data-option-label",e.label),t==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=fu(t,r,n);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},uy=e=>{let t=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},my=(e,n,t,r)=>{var u,p,f;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<ay;m++)o.appendChild(uy(r));return o}if(d.forEach((m,v)=>{o.appendChild(py(m,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=r==="rows"?ey:ty;if(r==="rows"){let v=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=h("span","persona-ask-row-content"),S=document.createElement("input");S.type="text",S.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",S.placeholder=(u=n.freeTextPlaceholder)!=null?u:cu,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(p=n.freeTextLabel)!=null?p:m),x.appendChild(S),v.appendChild(x);let A=fu(r,a,d.length);A&&v.appendChild(A),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(f=n.freeTextLabel)!=null?f:m,o.appendChild(v)}}return o},hu=(e,n)=>{var o,a;let r=h("div",n==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:cu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),n!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:du,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},gy=e=>{var r;let n=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");n.setAttribute("data-ask-multi-actions","true");let t=h("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=e.submitLabel)!=null?r:du,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,n.appendChild(t),n},fy=(e,n,t)=>{var l,u,p,f;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=t.backLabel)!=null?l:ry,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=t.skipLabel)!=null?u:sy,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===n-1;return i.textContent=d?(p=t.submitAllLabel)!=null?p:oy:(f=t.nextLabel)!=null?f:ny,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},To=e=>{let n=e.getAttribute(pu);if(!n)return{};try{let t=JSON.parse(n);return t&&typeof t=="object"?t:{}}catch{return{}}},yu=(e,n)=>{e.setAttribute(pu,JSON.stringify(n))},Xn=e=>{var t;let n=Number((t=e.getAttribute(_i))!=null?t:"0");return Number.isFinite(n)?Math.max(0,Math.floor(n)):0},hy=(e,n)=>{e.setAttribute(_i,String(Math.max(0,Math.floor(n))))},Yo=e=>{var t;let n=Number((t=e.getAttribute(ji))!=null?t:"1");return Number.isFinite(n)?Math.max(1,Math.floor(n)):1},ro=e=>e.getAttribute(Ui)==="true",yy=(e,n)=>{var s;let t=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return n.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},by=(e,n)=>{var r;let t=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(n-1,Math.floor(t)))},Za=(e,n)=>{let{payload:t}=no(n),r=qs(t),s=To(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},bu=e=>{let n=To(e),t=Xn(e),r=n[t],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var p;let l=(p=d.getAttribute("data-option-label"))!=null?p:"",u=s.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},xu=e=>{if(!ro(e))return;let n=To(e),t=Xn(e),r=n[t],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},qi=(e,n,t)=>{let r=Qa(t),s=ly(e),{payload:o,complete:a}=no(n),i=ro(e),d=Xn(e),l=Yo(e),u=i?dy(o,d):cy(o),p=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let k=typeof(u==null?void 0:u.question)=="string"?u.question:"";v.textContent=k,v.classList.toggle("persona-ask-question-skeleton",!k&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let k=my(u,r,a,s);x.replaceWith(k)}if(s!=="rows"){let k=e.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(hu(r,s))}let S=e.querySelector('[data-ask-multi-actions="true"]');!i&&p&&!S?e.appendChild(gy(r)):(!p||i)&&S&&S.remove(),e.setAttribute("data-multi-select",p?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(i){let k=fy(d,l,r);A?A.replaceWith(k):e.appendChild(k)}else A&&A.remove();bu(e),xu(e)},xy=(e,n,t)=>{let r=Qa(n),s=iy(r),o=e.toolCall.id,a=qs(t),i=Math.max(1,a.length),d=i>1,l=yy(e,a),u=d?by(e,i):0,p=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));p.setAttribute(Xo,o),p.setAttribute("data-tool-call-id",o),p.setAttribute("data-message-id",e.id),p.setAttribute(ji,String(i)),p.setAttribute(_i,String(u)),p.setAttribute(Ui,d?"true":"false"),p.setAttribute(uu,s),yu(p,l),p.setAttribute("role","group"),p.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&p.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),gu(p,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=h("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",f.appendChild(m);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),p.appendChild(f);let S=h("div",s==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),p.appendChild(S),s!=="rows"&&p.appendChild(hu(r,s)),qi(p,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>p.classList.remove("persona-ask-sheet-enter"))}),p},vy=(e,n,t)=>{let{payload:r}=no(n),s=Math.max(1,qs(r).length);s>Yo(e)&&(e.setAttribute(ji,String(s)),s>1&&!ro(e)&&e.setAttribute(Ui,"true")),qi(e,n,t)},wy=(e,n)=>{let t=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),t.setAttribute("data-bubble-type","ask-user-question");let r=Qa(n);gu(t,r);let s=h("span","persona-ask-stub-label"),{complete:o}=no(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(s),t},zs=(e,n,t)=>{if(!t||!to(e)||Qa(n).enabled===!1)return;let s=e.toolCall.id;t.querySelectorAll(`[${Xo}]`).forEach(l=>{l.getAttribute(Xo)!==s&&l.remove()});let a=t.querySelector(`[${Xo}="${mu(s)}"]`);if(a){vy(a,e,n);return}let{payload:i}=no(e),d=xy(e,n,i);t.appendChild(d)},Mo=(e,n)=>{if(!e)return;let t=n?`[${Xo}="${mu(n)}"]`:`[${Xo}]`;e.querySelectorAll(t).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},zi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(n=>n.getAttribute("data-option-label")).filter(n=>typeof n=="string"&&n.length>0),oo=(e,n)=>{let t=To(e),r=Xn(e);typeof n=="string"&&n.length===0||Array.isArray(n)&&n.length===0?delete t[r]:t[r]=n,yu(e,t),bu(e),xu(e)},ei=(e,n,t,r)=>{let s=Yo(e),o=Math.max(0,Math.min(s-1,r));hy(e,o),qi(e,n,t)};var Vi=(e,n)=>{var x,S,A,k,R,H,L,w,B,F,$,W;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(x=r==null?void 0:r.backgroundColor)!=null?x:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(S=r==null?void 0:r.borderColor)!=null?S:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",l=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(A=r==null?void 0:r.titleColor)!=null?A:"currentColor",u=fe(d,20,l,2);u&&i.appendChild(u);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",f.appendChild(m),!s){let O=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",t.status),t.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):t.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):t.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),f.appendChild(O)}p.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=t.description,p.appendChild(v),t.parameters){let O=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(O.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(O.style.color=r.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=$o(t.parameters),p.appendChild(O)}if(s){let O=h("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let V=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");V.type="button",V.style.backgroundColor=(R=r==null?void 0:r.approveButtonColor)!=null?R:"var(--persona-approval-approve-bg, #22c55e)",V.style.color=(H=r==null?void 0:r.approveButtonTextColor)!=null?H:"#ffffff",V.setAttribute("data-approval-action","approve");let oe=fe("shield-check",14,(L=r==null?void 0:r.approveButtonTextColor)!=null?L:"#ffffff",2);oe&&(oe.style.marginRight="4px",V.appendChild(oe));let Ie=document.createTextNode((w=r==null?void 0:r.approveLabel)!=null?w:"Approve");V.appendChild(Ie);let Pe=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");Pe.type="button",Pe.style.backgroundColor=(B=r==null?void 0:r.denyButtonColor)!=null?B:"transparent",Pe.style.color=(F=r==null?void 0:r.denyButtonTextColor)!=null?F:"var(--persona-feedback-error, #dc2626)",Pe.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Pe.setAttribute("data-approval-action","deny");let ze=fe("shield-x",14,($=r==null?void 0:r.denyButtonTextColor)!=null?$:"var(--persona-feedback-error, #dc2626)",2);ze&&(ze.style.marginRight="4px",Pe.appendChild(ze));let pe=document.createTextNode((W=r==null?void 0:r.denyLabel)!=null?W:"Deny");Pe.appendChild(pe),O.append(V,Pe),p.appendChild(O)}return a.append(i,p),o.appendChild(a),o};var vu=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let u=document.createDocumentFragment(),p=s?s.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};r.forEach(m=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=m,v.disabled=p,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),u.appendChild(v),n.push(v)}),e.appendChild(u)}}};var Vs=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ks=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};function Qo(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Cy={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, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},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)"}},Ay={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Sy=["flowName","stepName","reasoningText","text","name","tool","toolName"],Ey=100;function Ty(e,n){let t={...Cy,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return Ay}function My(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function ky(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function Ly(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function Py(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function Iy(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function Wy(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Ki(e,n,t,r,s,o,a,i){var f;let d=s.has(e.id),l=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Qo(l,(f=r.classNames)==null?void 0:f.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(p()),l;function p(){var V,oe;let m=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let x=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=fe(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&x.appendChild(S);let A=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(V=r.timestampFormat)!=null?V:"relative";A.textContent=k==="relative"?My(e.timestamp,t):ky(e.timestamp);let R=null;r.showSequenceNumbers!==!1&&(R=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(n+1));let H=Ty(e.type,r.badgeColors),L=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");L.style.backgroundColor=H.bg,L.style.color=H.text,L.style.borderColor=H.text+"50",L.textContent=e.type;let w=(oe=r.descriptionFields)!=null?oe:Sy,B=Ly(e.payload,w),F=null;B&&(F=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.textContent=B);let $=h("div","persona-flex-1 persona-min-w-0"),W=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=fe("clipboard","12px","currentColor",1.5);return O&&W.appendChild(O),W.addEventListener("click",async Ie=>{Ie.stopPropagation(),await Py(Iy(e)),W.innerHTML="";let Pe=fe("check","12px","currentColor",1.5);Pe&&W.appendChild(Pe),setTimeout(()=>{W.innerHTML="";let ze=fe("clipboard","12px","currentColor",1.5);ze&&W.appendChild(ze)},1500)}),v.appendChild(x),v.appendChild(A),R&&v.appendChild(R),v.appendChild(L),F&&v.appendChild(F),v.appendChild($),v.appendChild(W),m.appendChild(v),d&&m.appendChild(Wy(e,a,i)),m}}function wu(e){var m,v,x,S,A;let{buffer:n,getFullHistory:t,onClose:r,config:s,plugins:o=[]}=e,a=(m=s==null?void 0:s.features)==null?void 0:m.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,d=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",l=(x=a==null?void 0:a.label)!=null?x:"",u=(A=(S=s==null?void 0:s.features)==null?void 0:S.eventStream)!=null?A:{},p=o.find(k=>k.renderEventStreamView);if(p!=null&&p.renderEventStreamView&&s){let k=p.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>f().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=u.classNames,R=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Qo(R,k==null?void 0:k.panel);let H=[],L="",w="",B=null,F=[],$={},W=0,O=Ba(),V=0,oe=0,Ie=!1,Pe=null,ze=!1,pe=0,ce=new Set,Ee=new Map,je="",te="",xe=null,G,ae,He,ue,Re;function tt(){let P=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),he=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Qo(he,k==null?void 0:k.headerBar);let ge=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");ge.textContent="Events",G=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),G.textContent="0";let dt=h("div","persona-flex-1");ae=h("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ke=h("option","");Ke.value="",Ke.textContent="All events",ae.appendChild(Ke),He=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),He.type="button",He.title="Copy All";let an=fe("clipboard-copy","12px","currentColor",1.5);an&&He.appendChild(an);let At=h("span","persona-text-xs");At.textContent="Copy All",He.appendChild(At),he.appendChild(ge),he.appendChild(G),he.appendChild(dt),he.appendChild(ae),he.appendChild(He);let bt=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Qo(bt,k==null?void 0:k.searchBar);let Mt=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),ut=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Mt&&ut.appendChild(Mt),ue=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Qo(ue,k==null?void 0:k.searchInput),ue.type="text",ue.placeholder="Search event payloads...",Re=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Re.type="button",Re.style.display="none";let Vt=fe("x","12px","currentColor",2);return Vt&&Re.appendChild(Vt),bt.appendChild(ut),bt.appendChild(ue),bt.appendChild(Re),P.appendChild(he),P.appendChild(bt),P}let K,se=o.find(P=>P.renderEventStreamToolbar);if(se!=null&&se.renderEventStreamToolbar&&s){let P=se.renderEventStreamToolbar({config:s,defaultRenderer:()=>tt(),eventCount:n.getSize(),filteredCount:0,onFilterChange:he=>{L=he,re(),zt()},onSearchChange:he=>{w=he,re(),zt()}});K=P!=null?P:tt()}else K=tt();let Oe=h("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Oe.style.display="none";let J=h("div","persona-flex-1 persona-min-h-0 persona-relative"),z=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");z.style.height="100%";let we=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Qo(we,k==null?void 0:k.scrollIndicator),we.style.display="none",we.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false");let $e=fe(d,"14px","currentColor",2);$e&&we.appendChild($e);let ne=h("span","");ne.textContent=l,we.appendChild(ne);let Te=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Te.style.display="none",J.appendChild(z),J.appendChild(Te),J.appendChild(we),R.setAttribute("tabindex","0"),R.appendChild(K),R.appendChild(Oe),R.appendChild(J);function ve(){let P=n.getAll(),he={};for(let At of P)he[At.type]=(he[At.type]||0)+1;let ge=Object.keys(he).sort(),dt=ge.length!==F.length||!ge.every((At,bt)=>At===F[bt]),Ke=!dt&&ge.some(At=>he[At]!==$[At]),It=P.length!==Object.values($).reduce((At,bt)=>At+bt,0);if(!dt&&!Ke&&!It||(F=ge,$=he,!ae))return;let an=ae.value;if(ae.options[0].textContent="All events",dt){for(;ae.options.length>1;)ae.remove(1);for(let At of ge){let bt=h("option","");bt.value=At,bt.textContent=`${At} (${he[At]||0})`,ae.appendChild(bt)}an&&ge.includes(an)?ae.value=an:an&&(ae.value="",L="")}else for(let At=1;At<ae.options.length;At++){let bt=ae.options[At];bt.textContent=`${bt.value} (${he[bt.value]||0})`}}function Ht(){let P=n.getAll();if(L&&(P=P.filter(he=>he.type===L)),w){let he=w.toLowerCase();P=P.filter(ge=>ge.type.toLowerCase().includes(he)||ge.payload.toLowerCase().includes(he))}return P}function ie(){return L!==""||w!==""}function re(){W=0,V=0,O.resume(),we.style.display="none"}function sn(P){ce.has(P)?ce.delete(P):ce.add(P),xe=P;let he=z.scrollTop,ge=O.isFollowing();ze=!0,O.pause(),zt(),z.scrollTop=he,ge&&O.resume(),ze=!1}function Nt(){return Rs(z,50)}function zt(){oe=Date.now(),Ie=!1,ve();let P=n.getEvictedCount();P>0?(Oe.textContent=`${P.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",H=Ht();let he=H.length,ge=n.getSize()>0;G&&(G.textContent=String(n.getSize())),he===0&&ge&&ie()?(Te.textContent=w?`No events matching '${w}'`:"No events matching filter",Te.style.display="",z.style.display="none"):(Te.style.display="none",z.style.display=""),He&&(He.title=ie()?`Copy Filtered (${he})`:"Copy All"),i&&!O.isFollowing()&&he>W&&(V+=he-W,ne.textContent=l?`${l}${V>0?` (${V})`:""}`:"",we.style.display=""),W=he;let dt=n.getAll(),Ke=dt.length>0?dt[0].timestamp:0,It=new Set(H.map(bt=>bt.id));for(let bt of ce)It.has(bt)||ce.delete(bt);let an=L!==je||w!==te,At=Ee.size===0&&H.length>0;if(an||At||H.length===0){z.innerHTML="",Ee.clear();let bt=document.createDocumentFragment();for(let Mt=0;Mt<H.length;Mt++){let ut=Ki(H[Mt],Mt,Ke,u,ce,sn,o,s);Ee.set(H[Mt].id,ut),bt.appendChild(ut)}z.appendChild(bt),je=L,te=w,xe=null}else{if(xe!==null){let Mt=Ee.get(xe);if(Mt&&Mt.parentNode===z){let ut=H.findIndex(Vt=>Vt.id===xe);if(ut>=0){let Vt=Ki(H[ut],ut,Ke,u,ce,sn,o,s);z.insertBefore(Vt,Mt),Mt.remove(),Ee.set(xe,Vt)}}xe=null}let bt=new Set(H.map(Mt=>Mt.id));for(let[Mt,ut]of Ee)bt.has(Mt)||(ut.remove(),Ee.delete(Mt));for(let Mt=0;Mt<H.length;Mt++){let ut=H[Mt];if(!Ee.has(ut.id)){let Vt=Ki(ut,Mt,Ke,u,ce,sn,o,s);Ee.set(ut.id,Vt),z.appendChild(Vt)}}}O.isFollowing()&&(z.scrollTop=z.scrollHeight)}function vr(){if(Date.now()-oe>=Ey){Pe!==null&&(cancelAnimationFrame(Pe),Pe=null),zt();return}Ie||(Ie=!0,Pe=requestAnimationFrame(()=>{Pe=null,zt()}))}let dr=(P,he)=>{if(!He)return;He.innerHTML="";let ge=fe(P,"12px","currentColor",1.5);ge&&He.appendChild(ge);let dt=h("span","persona-text-xs");dt.textContent="Copy All",He.appendChild(dt),setTimeout(()=>{He.innerHTML="";let Ke=fe("clipboard-copy","12px","currentColor",1.5);Ke&&He.appendChild(Ke);let It=h("span","persona-text-xs");It.textContent="Copy All",He.appendChild(It),He.disabled=!1},he)},Ue=async()=>{if(He){He.disabled=!0;try{let P;ie()?P=H:t?(P=await t(),P.length===0&&(P=n.getAll())):P=n.getAll();let he=P.map(ge=>{try{return JSON.parse(ge.payload)}catch{return ge.payload}});await navigator.clipboard.writeText(JSON.stringify(he,null,2)),dr("check",1500)}catch{dr("x",1500)}}},U=()=>{ae&&(L=ae.value,re(),zt())},Ae=()=>{!ue||!Re||(Re.style.display=ue.value?"":"none",B&&clearTimeout(B),B=setTimeout(()=>{w=ue.value,re(),zt()},150))},Be=()=>{!ue||!Re||(ue.value="",w="",Re.style.display="none",B&&clearTimeout(B),re(),zt())},De=()=>{if(ze)return;let P=z.scrollTop,{action:he,nextLastScrollTop:ge}=Da({following:O.isFollowing(),currentScrollTop:P,lastScrollTop:pe,nearBottom:Nt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});pe=ge,he==="resume"?(O.resume(),V=0,we.style.display="none"):he==="pause"&&(O.pause(),i&&(ne.textContent=l,we.style.display=""))},_e=P=>{let he=Na({following:O.isFollowing(),deltaY:P.deltaY,nearBottom:Nt(),resumeWhenNearBottom:!0});he==="pause"?(O.pause(),i&&(ne.textContent=l,we.style.display="")):he==="resume"&&(O.resume(),V=0,we.style.display="none")},ct=()=>{i&&(z.scrollTop=z.scrollHeight,O.resume(),V=0,we.style.display="none")},nt=P=>{let he=P.target;if(!he||he.closest("button"))return;let ge=he.closest("[data-event-id]");if(!ge)return;let dt=ge.getAttribute("data-event-id");dt&&sn(dt)},Ct=P=>{if((P.metaKey||P.ctrlKey)&&P.key==="f"){P.preventDefault(),ue==null||ue.focus(),ue==null||ue.select();return}P.key==="Escape"&&(ue&&document.activeElement===ue?(Be(),ue.blur(),R.focus()):r&&r())};He&&He.addEventListener("click",Ue),ae&&ae.addEventListener("change",U),ue&&ue.addEventListener("input",Ae),Re&&Re.addEventListener("click",Be),z.addEventListener("scroll",De),z.addEventListener("wheel",_e,{passive:!0}),z.addEventListener("click",nt),we.addEventListener("click",ct),R.addEventListener("keydown",Ct);function jt(){B&&clearTimeout(B),Pe!==null&&(cancelAnimationFrame(Pe),Pe=null),Ie=!1,Ee.clear(),He&&He.removeEventListener("click",Ue),ae&&ae.removeEventListener("change",U),ue&&ue.removeEventListener("input",Ae),Re&&Re.removeEventListener("click",Be),z.removeEventListener("scroll",De),z.removeEventListener("wheel",_e),z.removeEventListener("click",nt),we.removeEventListener("click",ct),R.removeEventListener("keydown",Ct)}return{element:R,update:vr,destroy:jt}}}function Cu(e,n){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.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",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.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 l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(m)}else p.textContent=a;if(l.append(u,p),i.append(d,l),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var Au=(e,n)=>{var r,s,o;let t=(o=(s=(r=n==null?void 0:n.config)==null?void 0:r.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:n.config,defaultRenderer:()=>Cu(e,n)});if(u)return u}return Cu(e,n)};var Ji=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},so=new Ji;so.register("PersonaArtifactCard",Au);function Ry(e){var s;let n=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),n.appendChild(t),n.appendChild(r),n}function Su(e,n){var He,ue,Re,tt;let t=(ue=(He=e.features)==null?void 0:He.artifacts)==null?void 0:ue.layout,s=((Re=t==null?void 0:t.toolbarPreset)!=null?Re:"default")==="document",o=(tt=t==null?void 0:t.panePadding)==null?void 0:tt.trim(),a=e.markdown?Oo(e.markdown):null,i=Cs(e.sanitize),d=K=>{let se=a?a(K):Fo(K);return i?i(se):se},l=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{l==null||l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var K;u(),(K=n.onDismiss)==null||K.call(n)});let p=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var K;u(),(K=n.onDismiss)==null||K.call(n)});let x="rendered",S=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),A=s?_t({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):_t({icon:"eye",label:"Rendered view"}),k=s?_t({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):_t({icon:"code-2",label:"Source"}),R=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),H=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,w=t==null?void 0:t.documentToolbarCopyMenuItems,B=!!(L&&w&&w.length>0),F=null,$,W=null,O=null;if(s&&(H||L)&&!B){if($=H?qa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let K=fe("chevron-down",14,"currentColor",2);K&&$.appendChild(K)}}else s&&B?(F=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=H?qa({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W=_t({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),F.append($,W)):s?$=_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=_t({icon:"copy",label:"Copy"});let V=s?_t({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):_t({icon:"refresh-cw",label:"Refresh"}),oe=s?_t({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):_t({icon:"x",label:"Close"}),Ie=()=>{var z,we,$e;let K=(z=je.find(ne=>ne.id===te))!=null?z:je[je.length-1],se=(we=K==null?void 0:K.id)!=null?we:null,Oe=(K==null?void 0:K.artifactType)==="markdown"&&($e=K.markdown)!=null?$e:"",J=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:Oe,jsonPayload:J,id:se}},Pe=async()=>{var z;let{markdown:K,jsonPayload:se}=Ie(),Oe=(z=je.find(we=>we.id===te))!=null?z:je[je.length-1],J=(Oe==null?void 0:Oe.artifactType)==="markdown"?K:Oe?se:"";try{await navigator.clipboard.writeText(J)}catch{}};if($.addEventListener("click",async()=>{let K=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(K&&B){let{markdown:se,jsonPayload:Oe,id:J}=Ie();try{await K({actionId:"primary",artifactId:J,markdown:se,jsonPayload:Oe})}catch{}return}await Pe()}),W&&(w!=null&&w.length)){let K=()=>{var Oe;return(Oe=p.closest("[data-persona-root]"))!=null?Oe:document.body},se=()=>{O=Eo({items:w.map(Oe=>({id:Oe.id,label:Oe.label})),onSelect:async Oe=>{let{markdown:J,jsonPayload:z,id:we}=Ie(),$e=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{$e?await $e({actionId:Oe,artifactId:we,markdown:J,jsonPayload:z}):Oe==="markdown"||Oe==="md"?await navigator.clipboard.writeText(J):Oe==="json"||Oe==="source"?await navigator.clipboard.writeText(z):await navigator.clipboard.writeText(J||z)}catch{}},anchor:F!=null?F:W,position:"bottom-right",portal:K()})};p.isConnected?se():requestAnimationFrame(se),W.addEventListener("click",Oe=>{Oe.stopPropagation(),O==null||O.toggle()})}V.addEventListener("click",async()=>{var K;try{await((K=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:K.call(t))}catch{}G()}),oe.addEventListener("click",()=>{var K;u(),(K=n.onDismiss)==null||K.call(n)});let ze=()=>{s&&(A.setAttribute("aria-pressed",x==="rendered"?"true":"false"),k.setAttribute("aria-pressed",x==="source"?"true":"false"))};A.addEventListener("click",()=>{x="rendered",ze(),G()}),k.addEventListener("click",()=>{x="source",ze(),G()});let pe=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),S.append(A,k),F?R.append(F,V,oe):R.append($,V,oe),f.append(S,pe,R),ze()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ce=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Ee=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ce.style.paddingLeft=o,ce.style.paddingRight=o,Ee.style.padding=o),p.appendChild(f),p.appendChild(ce),p.appendChild(Ee);let je=[],te=null,xe=!1,G=()=>{var J,z,we,$e;let K=s&&je.length<=1;ce.classList.toggle("persona-hidden",K),ce.replaceChildren();for(let ne of je){let Te=h("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Te.type="button",Te.textContent=ne.title||ne.id.slice(0,8),ne.id===te&&Te.classList.add("persona-bg-persona-container","persona-border-persona-border"),Te.addEventListener("click",()=>n.onSelect(ne.id)),ce.appendChild(Te)}Ee.replaceChildren();let se=te&&je.find(ne=>ne.id===te)||je[je.length-1];if(!se)return;if(s){let ne=se.artifactType==="markdown"?"MD":(J=se.component)!=null?J:"Component",ve=(se.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";pe.textContent=`${ve} \xB7 ${ne}`}else m.textContent="Artifacts";if(se.artifactType==="markdown"){if(s&&x==="source"){let Te=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Te.textContent=(z=se.markdown)!=null?z:"",Ee.appendChild(Te);return}let ne=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ne.innerHTML=d((we=se.markdown)!=null?we:""),Ee.appendChild(ne);return}let Oe=se.component?so.get(se.component):void 0;if(Oe){let Te={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let ve=Oe(($e=se.props)!=null?$e:{},Te);if(ve){Ee.appendChild(ve);return}}catch{}}Ee.appendChild(Ry(se))},ae=()=>{var se;let K=je.length>0;if(p.classList.toggle("persona-hidden",!K),l){let Oe=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,z=((se=Oe==null?void 0:Oe.classList.contains("persona-artifact-narrow-host"))!=null?se:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&z&&xe?(l.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:l,update(K){var se,Oe,J;je=K.artifacts,te=(J=(Oe=K.selectedId)!=null?Oe:(se=K.artifacts[K.artifacts.length-1])==null?void 0:se.id)!=null?J:null,je.length>0&&(xe=!0),G(),ae()},setMobileOpen(K){xe=K,!K&&l?(l.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ae()}}}function Yn(e){var n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function Eu(e,n){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Yn(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Hy(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 ti(e,n){var d,l,u,p,f,m,v,x,S,A;if(!Yn(n)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Hy(e),Eu(e,n);return}let t=(l=(d=n.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(S=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:S.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(A=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:A.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Eu(e,n)}var Tu=["panel","seamless"];function ni(e,n){var i,d,l,u,p,f;for(let m of Tu)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"),!Yn(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=t==null?void 0:t.paneAppearance)!=null?l:"panel",s=Tu.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Mu(e,n){var t,r,s;return!n||!Yn(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function By(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function Dy(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function Ny(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function Oy(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function ku(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function Lu(e,n,t,r,s,o){let a=By(s,200),i=Oy(n,t,r,200);i=Math.max(a,i);let d=Dy(o);return d!==null&&(i=Math.min(i,d)),Ny(e,a,i)}var Pu={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"}},Gi=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,x,S;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(x=Pu[a])!=null?x:Pu.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),l=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let A=h("p","persona-text-sm persona-text-persona-muted");A.textContent=i.description,d.appendChild(A)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(A=>{var w,B;let k=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${n.id}-${a}-${A.name}`;let R=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=A.label,k.appendChild(R);let H=(w=A.type)!=null?w:"text",L;H==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=H),L.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",L.id=`${n.id}-${a}-${A.name}`,L.name=A.name,L.placeholder=(B=A.placeholder)!=null?B:"",A.required&&(L.required=!0),k.appendChild(L),u.appendChild(k)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(S=i.submitLabel)!=null?S:"Submit",p.appendChild(f),p.appendChild(m),u.appendChild(p),o.replaceChildren(d,u),u.addEventListener("submit",async A=>{var L,w;A.preventDefault();let k=(L=t.formEndpoint)!=null?L:"/form",R=new FormData(u),H={};R.forEach((B,F)=>{H[F]=B}),H.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let B=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!B.ok)throw new Error(`Form submission failed (${B.status})`);let F=await B.json();f.textContent=(w=F.message)!=null?w:"Thanks! We'll be in touch soon.",F.success&&F.nextPrompt&&await r.sendMessage(String(F.nextPrompt))}catch(B){f.textContent=B instanceof Error?B.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Xi=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},ri=new Xi;var Iu=()=>{let e=new Map,n=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:n,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Fy=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},$y=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},oi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Fy(e),t=$y(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},Yi=e=>typeof e=="string"?e:e==null?"":String(e),Zo={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Yi(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=Yi(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Yi(t.text)}}},Wu=e=>Array.isArray(e)?e.map(n=>String(n)):[],si=e=>{let n=new Set(Wu(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(Wu(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,u)=>l||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;n.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let u=()=>{e.emit("action:resubmit",d)},p=l(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var _y=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},jy=e=>e.map(n=>({...n,streaming:!1})),Uy=e=>e.map(n=>({...n,status:"complete"})),Qi=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?_y(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?jy(t.messages):void 0,artifacts:t.artifacts?Uy(t.artifacts):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as qy,STR as zy,OBJ as Vy}from"partial-json";function Ky(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Jy(e,n){if(!Ky(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function Zi(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=qy(t,zy|Vy),o=Jy(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function Gy(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function el(e,n){let{config:t,message:r,onPropsUpdate:s}=n,o=so.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Xy(){let e=Zi();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ru(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let n=e.content.trim();if(n.startsWith("{")||n.startsWith("["))return e.content}return null}function tl(e){let n=Ru(e);if(!n)return!1;try{let t=JSON.parse(n);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function nl(e){let n=Ru(e);if(!n)return null;try{let t=JSON.parse(n);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:n}}}catch{}return null}var Yy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function rl(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Yy}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=s,m.appendChild(x),f.appendChild(m);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let A=[];for(let w=1;w<=5;w++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-star-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${l[w-1]}`),B.title=l[w-1],B.dataset.rating=String(w),B.innerHTML=`
20
27
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
21
28
  <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>
22
29
  </svg>
23
- `,F.addEventListener("click",()=>{p=S,A.forEach(($,j)=>{let W=j<S;$.classList.toggle("selected",W),$.setAttribute("aria-checked",j===S-1?"true":"false")})}),A.push(F),T.appendChild(F)}f.appendChild(T);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),f.appendChild(S)}let B=document.createElement("div");B.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{t==null||t(),u.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(p===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let S=(k==null?void 0:k.value.trim())||void 0;await n(p,S),u.remove()}catch(S){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",S)}}),B.appendChild(D),B.appendChild(L),f.appendChild(B),u.appendChild(f),u}function Ji(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,C.appendChild(x);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=o,C.appendChild(T),g.appendChild(C);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let B=document.createElement("span");B.className="persona-feedback-label-low",B.textContent=l;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=u,k.appendChild(B),k.appendChild(D);let L=document.createElement("div");L.className="persona-feedback-numbers";let S=[];for(let O=0;O<=10;O++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${O} out of 10`),V.textContent=String(O),V.dataset.rating=String(O),O<=6?V.classList.add("persona-feedback-detractor"):O<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{f=O,S.forEach((oe,Pe)=>{oe.classList.toggle("selected",Pe===O),oe.setAttribute("aria-checked",Pe===O?"true":"false")})}),S.push(V),L.appendChild(V)}A.appendChild(k),A.appendChild(L),g.appendChild(A);let F=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",F=document.createElement("textarea"),F.className="persona-feedback-comment",F.placeholder=s,F.rows=3,F.setAttribute("aria-label","Additional comments"),O.appendChild(F),g.appendChild(O)}let $=document.createElement("div");$.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=i,j.addEventListener("click",()=>{t==null||t(),p.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let O=(F==null?void 0:F.value.trim())||void 0;await n(f,O),p.remove()}catch(O){W.disabled=!1,W.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),$.appendChild(j),$.appendChild(W),g.appendChild($),p.appendChild(g),p}var es="persona-chat-history",Ty=30*1e3,My={"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 ky(e){var r,o,s;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let d=(o=My[i.type])!=null?o:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&n.push(a);return n}function Qa(e){if(!e)return!1;let n=e.types;return n?typeof n.contains=="function"?n.contains("Files"):Array.from(n).includes("Files"):!1}function Ly(e){var n,t,r,o,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function Py(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var Ki=e=>!e||typeof e!="object"?{}:{...e},fu=e=>e.map(n=>({...n,streaming:!1})),hu=(e,n,t)=>{let r=e!=null&&e.markdown?Fo(e.markdown):null,o=xs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var l,u,p;let a=(l=s.text)!=null?l:"",i=(u=s.message.rawContent)!=null?u:null;if(n){let f=n.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...s,text:a,raw:(p=i!=null?i:s.text)!=null?p:""}):r?d=r(a):d=Oo(a),o?o(d):d}};function yu(e){var i,d,l,u;let n=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&n.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&n.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&n.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&n.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&n.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&n.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&n.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=ge(t,r,o,s);if(a&&n.appendChild(a),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,n.appendChild(p)}return n}var Gi=(e,n,t)=>{var ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,Cl,wl,Al,Sl,El,Tl,Ml,kl,Ll,Pl,Il,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,Ul,ql,zl,Vl,Jl,Kl,Gl,Ql,Xl,Yl,Zl,ec;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=gi(n),o=Ja.getForInstance(r.plugins);r.components&&oo.registerAll(r.components);let s=uu(),i=r.persistState===!1?null:(ll=r.storageAdapter)!=null?ll:_i(),d={},l=null,u=!1,p=c=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(c);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:b}=m;return b&&(u=!0),y}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return p(y)});else{let m=c!=null?c:{messages:[],metadata:{}},y=p(m);y.metadata&&(d=Ki(y.metadata)),(cl=y.messages)!=null&&cl.length&&(r={...r,initialMessages:y.messages}),(dl=y.artifacts)!=null&&dl.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(pl=y.selectedArtifactId)!=null?pl:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=p({messages:[],metadata:{}});(ul=c.messages)!=null&&ul.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,g=c=>{var y;d=(y=c({...d}))!=null?y:{},Po()},C=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ka],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Zo.message,Zo.messageAndClick],T=Ga({parsers:C,handlers:x,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let A=(gl=(ml=r.launcher)==null?void 0:ml.enabled)!=null?gl:!0,k=(hl=(fl=r.launcher)==null?void 0:fl.autoExpand)!=null?hl:!1,B=(yl=r.autoFocusInput)!=null?yl:!1,D=k,L=A,S=(xl=(bl=r.layout)==null?void 0:bl.header)==null?void 0:xl.layout,F=!1,$=()=>Yr(r),j=()=>A||$(),W=$()?!1:A?k:!0,O=!1,V=null,oe=()=>{O=!0,V&&clearTimeout(V),V=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},Pe=hu(r,T,oe),ke=(Cl=(vl=r.features)==null?void 0:vl.showReasoning)!=null?Cl:!0,Ge=(Al=(wl=r.features)==null?void 0:wl.showToolCalls)!=null?Al:!0,de=(El=(Sl=r.features)==null?void 0:Sl.showEventStreamToggle)!=null?El:!1,pe=(Ml=(Tl=r.features)==null?void 0:Tl.scrollToBottom)!=null?Ml:{},_e=`${(Ll=typeof r.persistState=="object"?(kl=r.persistState)==null?void 0:kl.keyPrefix:void 0)!=null?Ll:"persona-"}event-stream`,ee=de?new Us(_e):null,Ae=(Wl=(Il=(Pl=r.features)==null?void 0:Pl.eventStream)==null?void 0:Il.maxEvents)!=null?Wl:2e3,Q=de?new js(Ae,ee):null,ae=null,Re=!1,ce=null,We=0;ee==null||ee.open().then(()=>Q==null?void 0:Q.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let Ze={onCopy:c=>{var m,y;s.emit("message:copy",c),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(m=r.messageActions)==null?void 0:m.onCopy)==null||y.call(m,c)},onFeedback:c=>{var m,y;s.emit("message:feedback",c),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(m=r.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,c)}},J=(Rl=r.statusIndicator)!=null?Rl:{},se=c=>{var m,y,b,M;return c==="idle"?(m=J.idleText)!=null?m:gn.idle:c==="connecting"?(y=J.connectingText)!=null?y:gn.connecting:c==="connected"?(b=J.connectedText)!=null?b:gn.connected:c==="error"?(M=J.errorText)!=null?M:gn.error:gn[c]};function Fe(c,m,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let M=document.createElement("a");M.href=y.idleLink,M.target="_blank",M.rel="noopener noreferrer",M.textContent=m,M.style.color="inherit",M.style.textDecoration="none",c.appendChild(M)}else c.textContent=m}let{wrapper:K,panel:z,pillRoot:xe}=Hp(r),Oe=Bp(r,j()),{container:ne,body:Se,messagesWrapper:be,suggestions:Ht,textarea:Le,sendButton:te,sendButtonWrapper:sn,composerForm:Nt,statusText:Vt,introTitle:vr,introSubtitle:dr,closeButton:je,iconHolder:U,headerTitle:Ce,headerSubtitle:He,header:Be,footer:$e,actionsRow:lt,leftActions:et,rightActions:Ct}=Oe,Ut=Oe.setSendButtonMode,P=Oe.micButton,fe=Oe.micButtonWrapper,me=Oe.attachmentButton,ct=Oe.attachmentButtonWrapper,qe=Oe.attachmentInput,It=Oe.attachmentPreviewsContainer;ne.classList.add("persona-relative"),Se.classList.add("persona-relative");let an=12,wt=()=>{var c;return(c=pe.label)!=null?c:""},bt=()=>{var c;return(c=pe.iconName)!=null?c:"arrow-down"},Mt=()=>pe.enabled!==!1,pt=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");pt.type="button",pt.style.display="none",pt.setAttribute("data-persona-scroll-to-bottom","true");let Jt=h("span","persona-flex persona-items-center"),Cr=h("span","");pt.append(Jt,Cr),ne.appendChild(pt);let jn=()=>{let m=$e.style.display==="none"?0:$e.offsetHeight;pt.style.bottom=`${m+an}px`};jn();let Br=()=>{let c=!!wt();pt.setAttribute("aria-label",wt()||"Jump to latest"),pt.title=wt(),pt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Jt.innerHTML="";let m=ge(bt(),"14px","currentColor",2);m?(Jt.appendChild(m),Jt.style.display=""):Jt.style.display="none",Cr.textContent=wt(),Cr.style.display=c?"":"none"};Br();let vt=null,pr=null,ur=o.find(c=>c.renderHeader);if(ur!=null&&ur.renderHeader){let c=ur.renderHeader({config:r,defaultRenderer:()=>{let m=Zr({config:r,showClose:j()});return Vo(ne,m,r),m.header},onClose:()=>Rt(!1,"user")});if(c){let m=ne.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Be=c)}}let wr=()=>{var m,y,b,M;if(!Q)return;if(Re=!0,!ae&&Q&&(ae=nu({buffer:Q,getFullHistory:()=>Q.getAllFromStore(),onClose:()=>Yn(),config:r,plugins:o})),ae&&(Se.style.display="none",(m=$e.parentNode)==null||m.insertBefore(ae.element,$e),ae.update()),mt){mt.style.boxShadow=`inset 0 0 0 1.5px ${An.actionIconColor}`;let H=(M=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:M.toggleButtonActive;H&&H.split(/\s+/).forEach(N=>N&&mt.classList.add(N))}let c=()=>{if(!Re)return;let H=Date.now();H-We>=200&&(ae==null||ae.update(),We=H),ce=requestAnimationFrame(c)};We=0,ce=requestAnimationFrame(c),kr(),s.emit("eventStream:opened",{timestamp:Date.now()})},Yn=()=>{var c,m,y;if(Re){if(Re=!1,ae&&ae.element.remove(),Se.style.display="",mt){mt.style.boxShadow="";let b=(y=(m=(c=r.features)==null?void 0:c.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(M=>M&&mt.classList.remove(M))}ce!==null&&(cancelAnimationFrame(ce),ce=null),kr(),s.emit("eventStream:closed",{timestamp:Date.now()})}},mt=null;if(de){let c=(Bl=(Hl=r.features)==null?void 0:Hl.eventStream)==null?void 0:Bl.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");mt=h("button",m),mt.style.width="28px",mt.style.height="28px",mt.style.color=An.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let y=ge("activity","18px","currentColor",1.5);y&&mt.appendChild(y);let b=Oe.clearChatButtonWrapper,M=Oe.closeButtonWrapper,H=b||M;H&&H.parentNode===Be?Be.insertBefore(mt,H):Be.appendChild(mt),mt.addEventListener("click",()=>{Re?Yn():wr()})}let ao=c=>{var b,M,H;let m=r.attachments;if(!(m!=null&&m.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(y,N):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=h("input");N.type="file",N.accept=((b=m.allowedTypes)!=null?b:Rr).join(","),N.multiple=((M=m.maxFiles)!=null?M:4)>1,N.style.display="none",N.setAttribute("aria-label",(H=m.buttonTooltipText)!=null?H:"Attach files"),c.appendChild(N)}},mr=o.find(c=>c.renderComposer);if(mr!=null&&mr.renderComposer){let c=r.composer,m=mr.renderComposer({config:r,defaultRenderer:()=>Fs({config:r}).footer,onSubmit:y=>{var N;if(!_||_.isStreaming())return;let b=y.trim(),M=(N=vt==null?void 0:vt.hasAttachments())!=null?N:!1;if(!b&&!M)return;ps();let H;M&&(H=[],H.push(...vt.getContentParts()),b&&H.push(ya(b))),_.sendMessage(b,{contentParts:H}),M&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{qe==null||qe.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((Dl=r.voiceRecognition)==null?void 0:Dl.enabled)===!0?()=>{pr==null||pr()}:void 0});m&&($e.replaceWith(m),$e=m)}let io=c=>{let m=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),M=c.querySelector("[data-persona-composer-mic]"),H=c.querySelector("[data-persona-composer-status]");m&&(Nt=m),y&&(Le=y),b&&(te=b),M&&(P=M,fe=M.parentElement),H&&(Vt=H);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Ht=N);let q=c.querySelector(".persona-attachment-button");q&&(me=q,ct=q.parentElement),qe=c.querySelector('input[type="file"]'),It=c.querySelector(".persona-attachment-previews");let I=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");I&&(lt=I)};ao($e),io($e);let Sn=(_l=(Nl=r.layout)==null?void 0:Nl.contentMaxWidth)!=null?_l:$()?($l=(Ol=(Fl=r.launcher)==null?void 0:Fl.composerBar)==null?void 0:Ol.contentMaxWidth)!=null?$l:"720px":void 0;if(Sn&&(be.style.maxWidth=Sn,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%"),Sn&&Nt&&!$()&&(Nt.style.maxWidth=Sn,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Sn&&Ht&&!$()&&(Ht.style.maxWidth=Sn,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Sn&&It&&!$()&&(It.style.maxWidth=Sn,It.style.marginLeft="auto",It.style.marginRight="auto"),(jl=r.attachments)!=null&&jl.enabled&&qe&&It){vt=qo.fromConfig(r.attachments),vt.setPreviewsContainer(It),qe.addEventListener("change",y=>{let b=y.target;vt==null||vt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=yu(c);ne.appendChild(m)}(()=>{var b,M;let c=(M=(b=r.layout)==null?void 0:b.slots)!=null?M:{},m=H=>{switch(H){case"body-top":return ne.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return be;case"footer-top":return Ht;case"composer":return Nt;case"footer-bottom":return Vt;default:return null}},y=(H,N)=>{var q;switch(H){case"header-left":case"header-center":case"header-right":if(H==="header-left")Be.insertBefore(N,Be.firstChild);else if(H==="header-right")Be.appendChild(N);else{let I=Be.querySelector(".persona-flex-col");I?(q=I.parentNode)==null||q.insertBefore(N,I.nextSibling):Be.appendChild(N)}break;case"body-top":{let I=Se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");I?I.replaceWith(N):Se.insertBefore(N,Se.firstChild);break}case"body-bottom":Se.appendChild(N);break;case"footer-top":Ht.replaceWith(N);break;case"footer-bottom":Vt.replaceWith(N);break;default:break}};for(let[H,N]of Object.entries(c))if(N)try{let q=N({config:r,defaultContent:()=>m(H)});q&&y(H,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${H}":`,q)}})();let Dr=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let b=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!b)return;let M=b.getAttribute("data-message-id");if(!M)return;let H=y.getAttribute("data-bubble-type");H==="reasoning"?(Ko.has(M)?Ko.delete(M):Ko.add(M),$p(M,b)):H==="tool"&&(Go.has(M)?Go.delete(M):Go.add(M),_p(M,b,r)),Fn.delete(M)};be.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Dr(c))}),be.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Dr(c))});let Ar=new Map;be.addEventListener("click",c=>{var N;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let M=b.getAttribute("data-actions-for");if(!M)return;let H=y.getAttribute("data-action");if(H==="copy"){let I=_.getMessages().find(ye=>ye.id===M);if(I&&Ze.onCopy){let ye=I.content||"";navigator.clipboard.writeText(ye).then(()=>{y.classList.add("persona-message-action-success");let ie=ge("check",14,"currentColor",2);ie&&(y.innerHTML="",y.appendChild(ie)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Z=ge("copy",14,"currentColor",2);Z&&(y.innerHTML="",y.appendChild(Z))},2e3)}).catch(ie=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ie)}),Ze.onCopy(I)}}else if(H==="upvote"||H==="downvote"){let I=((N=Ar.get(M))!=null?N:null)===H,ye=H==="upvote"?"thumbs-up":"thumbs-down";if(I){Ar.delete(M),y.classList.remove("persona-message-action-active");let ie=ge(ye,14,"currentColor",2);ie&&(y.innerHTML="",y.appendChild(ie))}else{let ie=H==="upvote"?"downvote":"upvote",Z=b.querySelector(`[data-action="${ie}"]`);if(Z){Z.classList.remove("persona-message-action-active");let Ke=ge(ie==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ke&&(Z.innerHTML="",Z.appendChild(Ke))}Ar.set(M,H),y.classList.add("persona-message-action-active");let ue=ge(ye,14,"currentColor",2);ue&&(ue.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ue)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ne=_.getMessages().find(Ye=>Ye.id===M);Ne&&Ze.onFeedback&&Ze.onFeedback({type:H,messageId:Ne.id,message:Ne})}}}),be.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest(".persona-approval-bubble");if(!b)return;let M=b.getAttribute("data-message-id");if(!M)return;let H=y.getAttribute("data-approval-action");if(!H)return;let N=H==="approve"?"approved":"denied",I=_.getMessages().find(ie=>ie.id===M);if(!(I!=null&&I.approval))return;let ye=b.querySelector("[data-approval-buttons]");ye&&ye.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),_.resolveApproval(I.approval,N)});let yt=null,In=null,Wn={artifacts:[],selectedId:null},hn=!1,kt={current:null};be.addEventListener("click",c=>{var Z,ue,ve,Ne,Ye;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((ve=(ue=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:ue.onArtifactAction)==null?void 0:ve.call(ue,{type:"download",artifactId:b}))===!0)return;let H=_.getArtifactById(b),N=H==null?void 0:H.markdown,q=(H==null?void 0:H.title)||"artifact";if(!N){let Ke=y.closest("[data-open-artifact]"),ot=Ke==null?void 0:Ke.closest("[data-message-id]"),st=ot==null?void 0:ot.getAttribute("data-message-id");if(st){let Ee=_.getMessages().find(Ue=>Ue.id===st);if(Ee!=null&&Ee.rawContent)try{let Ue=JSON.parse(Ee.rawContent);N=(Ne=Ue==null?void 0:Ue.props)==null?void 0:Ne.markdown,q=((Ye=Ue==null?void 0:Ue.props)==null?void 0:Ye.title)||q}catch{}}}if(!N)return;let I=new Blob([N],{type:"text/markdown"}),ye=URL.createObjectURL(I),ie=document.createElement("a");ie.href=ye,ie.download=`${q}.md`,ie.click(),URL.revokeObjectURL(ye)}),be.addEventListener("click",c=>{var H,N,q;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((q=(N=(H=r.features)==null?void 0:H.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:q.call(N,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),hn=!1,_.selectArtifact(b),Bn())}),be.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let Un=Oe.composerOverlay,qn=(c,m,y)=>{var q,I,ye,ie;let b=m.trim();if(!b||!kt.current)return;let M=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",H=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:M,answer:b,answers:y.structured,values:(I=y.values)!=null?I:y.source==="multi"?b.split(", "):[b],isFreeText:H,source:y.source},bubbles:!0,composed:!0})),Mo(Un,M);let N=kt.current.getMessages().find(Z=>{var ue;return((ue=Z.toolCall)==null?void 0:ue.id)===M});(ye=N==null?void 0:N.agentMetadata)!=null&&ye.awaitingLocalTool?kt.current.resolveAskUserQuestion(N,(ie=y.structured)!=null?ie:b):kt.current.sendMessage(b)},Rn=c=>{var M;let m=kt.current;if(!m)return;let y=(M=c.getAttribute("data-tool-call-id"))!=null?M:"",b=m.getMessages().find(H=>{var N;return((N=H.toolCall)==null?void 0:N.id)===y});b&&m.persistAskUserQuestionProgress(b,{answers:Ua(c,b),currentIndex:Qn(c)})},Nr=c=>Object.entries(c).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Sr=c=>{var M,H,N;if(((H=(M=r.features)==null?void 0:M.askUserQuestion)==null?void 0:H.groupedAutoAdvance)===!1)return;let m=Qn(c),y=Xo(c);if(m>=y-1)return;let b=(N=kt.current)==null?void 0:N.getMessages().find(q=>{var I;return((I=q.toolCall)==null?void 0:I.id)===c.getAttribute("data-tool-call-id")});b&&(qa(c,b,r,m+1),Rn(c))};Un.addEventListener("click",c=>{var H,N,q,I,ye,ie,Z,ue,ve,Ne,Ye,Ke,ot,st;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let M=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),M==="dismiss"){let Te=(H=b.getAttribute("data-tool-call-id"))!=null?H:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Te},bubbles:!0,composed:!0})),Mo(Un,Te);let Ee=(N=kt.current)==null?void 0:N.getMessages().find(Ue=>{var E;return((E=Ue.toolCall)==null?void 0:E.id)===Te});(q=Ee==null?void 0:Ee.agentMetadata)!=null&&q.awaitingLocalTool&&((I=kt.current)==null||I.markAskUserQuestionResolved(Ee),(ye=kt.current)==null||ye.resolveAskUserQuestion(Ee,"(dismissed)"));return}if(M==="pick"){let Te=y.getAttribute("data-option-label");if(!Te)return;let Ee=b.getAttribute("data-multi-select")==="true",Ue=no(b);if(Ue&&Ee){let E=To(b)[Qn(b)],we=new Set(Array.isArray(E)?E:[]);we.has(Te)?we.delete(Te):we.add(Te),ro(b,Array.from(we)),Rn(b);return}if(Ue){ro(b,Te),Rn(b),Sr(b);return}if(Ee){let E=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",E?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!E);let we=b.querySelector('[data-ask-user-action="submit-multi"]');we&&(we.disabled=Hi(b).length===0);return}qn(b,Te,{source:"pick",values:[Te]});return}if(M==="submit-multi"){let Te=Hi(b);if(Te.length===0)return;qn(b,Te.join(", "),{source:"multi",values:Te});return}if(M==="open-free-text"){let Te=b.querySelector('[data-ask-free-text-row="true"]');if(Te){Te.classList.remove("persona-hidden");let Ee=Te.querySelector('[data-ask-free-text-input="true"]');Ee==null||Ee.focus()}return}if(M==="focus-free-text"){let Te=b.querySelector('[data-ask-free-text-input="true"]');Te==null||Te.focus();return}if(M==="submit-free-text"){let Te=b.querySelector('[data-ask-free-text-input="true"]'),Ee=(ie=Te==null?void 0:Te.value)!=null?ie:"";if(!Ee.trim())return;if(no(b)){ro(b,Ee.trim()),Rn(b),Sr(b);return}qn(b,Ee,{source:"free-text"});return}if(M==="next"||M==="back"){if(!kt.current)return;let Te=(Z=b.getAttribute("data-tool-call-id"))!=null?Z:"",Ee=kt.current.getMessages().find(ze=>{var he;return((he=ze.toolCall)==null?void 0:he.id)===Te});if(!Ee)return;let Ue=b.querySelector('[data-ask-free-text-input="true"]'),E=(ve=(ue=Ue==null?void 0:Ue.value)==null?void 0:ue.trim())!=null?ve:"";if(E){let ze=To(b)[Qn(b)];(typeof ze!="string"||ze!==E)&&ro(b,E)}let we=M==="next"?1:-1,Ie=Qn(b)+we;qa(b,Ee,r,Ie),Rn(b);return}if(M==="submit-all"){if(!kt.current)return;let Te=(Ne=b.getAttribute("data-tool-call-id"))!=null?Ne:"",Ee=kt.current.getMessages().find(ze=>{var he;return((he=ze.toolCall)==null?void 0:he.id)===Te});if(!Ee)return;let Ue=b.querySelector('[data-ask-free-text-input="true"]'),E=(Ke=(Ye=Ue==null?void 0:Ue.value)==null?void 0:Ye.trim())!=null?Ke:"";E&&ro(b,E);let we=Ua(b,Ee);kt.current.persistAskUserQuestionProgress(Ee,{answers:we,currentIndex:Qn(b)});let Ie=Nr(we);qn(b,Ie||"(submitted)",{source:"submit-all",structured:we});return}if(M==="skip"){if(!kt.current)return;let Te=(ot=b.getAttribute("data-tool-call-id"))!=null?ot:"",Ee=kt.current.getMessages().find(he=>{var Tt;return((Tt=he.toolCall)==null?void 0:Tt.id)===Te});if(!Ee)return;let Ue=no(b),E=Qn(b),we=Xo(b),Ie=E>=we-1;if(!Ue){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Te},bubbles:!0,composed:!0})),Mo(Un,Te),(st=Ee.agentMetadata)!=null&&st.awaitingLocalTool&&(kt.current.markAskUserQuestionResolved(Ee),kt.current.resolveAskUserQuestion(Ee,"(dismissed)"));return}ro(b,"");let ze=b.querySelector('[data-ask-free-text-input="true"]');if(ze&&(ze.value=""),Ie){let he=Ua(b,Ee),Tt=Nr(he);qn(b,Tt||"(skipped)",{source:"submit-all",structured:he});return}qa(b,Ee,r,E+1),Rn(b);return}}),Un.addEventListener("keydown",c=>{var H;if(c.key!=="Enter")return;let y=c.target;if(!((H=y.matches)!=null&&H.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let M=y.value;if(M.trim()){if(no(b)){ro(b,M.trim()),Rn(b),Sr(b);return}qn(b,M,{source:"free-text"})}});let Fr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let m=c.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let y=Un.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),H=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];H&&(c.preventDefault(),H.click())};document.addEventListener("keydown",Fr);let Hn=null,Wt=null,yn=null,zn=null,Or=()=>{};function Er(){zn==null||zn(),zn=null}let $r=()=>{var N;if(!Hn||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let b=Hn.firstElementChild;if(!b||b===Wt)return;let M=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${M}px`,Wt.style.zIndex="5";let H=b.offsetWidth-M/2;Wt.style.left=`${Math.max(0,H)}px`},gr=()=>{},Bn=()=>{var y,b,M,H,N;if(!yt||!Xn(r))return;za(e,r),Va(e,r),gr();let c=(H=(M=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:M.narrowHostMaxWidth)!=null?H:520,m=z.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),yt.update(Wn),hn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(N=yt.backdrop)==null||N.classList.add("persona-hidden")):Wn.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),Or()};if(Xn(r)){z.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ne),yt=su(r,{onSelect:y=>{var b;return(b=kt.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{hn=!0,Bn()}}),yt.element.classList.add("persona-hidden"),Hn=m,m.appendChild(c),m.appendChild(yt.element),yt.backdrop&&z.appendChild(yt.backdrop),z.appendChild(m),Or=()=>{var b,M,H,N;if(!Hn||!yt)return;if(!(((H=(M=(b=r.features)==null?void 0:b.artifacts)==null?void 0:M.layout)==null?void 0:H.resizable)===!0)){yn==null||yn(),yn=null,Er(),Wt&&(Wt.remove(),Wt=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!Wt){let q=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let I=e.ownerDocument,ye=(N=I.defaultView)!=null?N:window,ie=Z=>{var ot,st;if(!yt||Z.button!==0||e.classList.contains("persona-artifact-narrow-host")||ye.innerWidth<=640)return;Z.preventDefault(),Er();let ue=Z.clientX,ve=yt.element.getBoundingClientRect().width,Ne=(st=(ot=r.features)==null?void 0:ot.artifacts)==null?void 0:st.layout,Ye=Te=>{let Ee=Hn.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),E=Ue?0:cu(Hn,ye),we=Ue?0:q.getBoundingClientRect().width||6,Ie=ve-(Te.clientX-ue),ze=du(Ie,Ee,E,we,Ne==null?void 0:Ne.resizableMinWidth,Ne==null?void 0:Ne.resizableMaxWidth);yt.element.style.width=`${ze}px`,yt.element.style.maxWidth="none",$r()},Ke=()=>{I.removeEventListener("pointermove",Ye),I.removeEventListener("pointerup",Ke),I.removeEventListener("pointercancel",Ke),zn=null;try{q.releasePointerCapture(Z.pointerId)}catch{}};zn=Ke,I.addEventListener("pointermove",Ye),I.addEventListener("pointerup",Ke),I.addEventListener("pointercancel",Ke);try{q.setPointerCapture(Z.pointerId)}catch{}};q.addEventListener("pointerdown",ie),Wt=q,Hn.insertBefore(q,yt.element),yn=()=>{q.removeEventListener("pointerdown",ie)}}if(Wt){let q=Wn.artifacts.length>0&&!hn;Wt.classList.toggle("persona-hidden",!q),$r()}},gr=()=>{var ye,ie,Z,ue,ve,Ne,Ye,Ke,ot,st,Te,Ee,Ue,E;if(!A||!yt||((ie=(ye=r.launcher)==null?void 0:ye.sidebarMode)!=null?ie:!1)||on(r)&&lr(r).reveal==="emerge")return;let b=(Z=e.ownerDocument.defaultView)!=null?Z:window,M=(ve=(ue=r.launcher)==null?void 0:ue.mobileFullscreen)!=null?ve:!0,H=(Ye=(Ne=r.launcher)==null?void 0:Ne.mobileBreakpoint)!=null?Ye:640;if(M&&b.innerWidth<=H||!lu(r,A))return;let N=(st=(ot=(Ke=r.launcher)==null?void 0:Ke.width)!=null?ot:r.launcherWidth)!=null?st:Gn,q=(E=(Ue=(Ee=(Te=r.features)==null?void 0:Te.artifacts)==null?void 0:Ee.layout)==null?void 0:Ue.expandedPanelWidth)!=null?E:"min(720px, calc(100vw - 24px))";Wn.artifacts.length>0&&!hn?(z.style.width=q,z.style.maxWidth=q):(z.style.width=N,z.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(In=new ResizeObserver(()=>{Bn()}),In.observe(z))}else z.appendChild(ne),$()&&xe&&(Oe.peekBanner&&xe.appendChild(Oe.peekBanner),xe.appendChild($e));e.appendChild(K),xe&&e.appendChild(xe);let Zn=()=>{var ze,he,Tt,rt,Qt,cn,Pt,xn,dn,Qe,at,vn,un,fo,ho,yo,Do,No,qt,bo,Gr,ht,Mn,Ir,Cn,kn,Bt,_t;if($()){z.style.width="100%",z.style.maxWidth="100%";let Dt=(he=(ze=r.launcher)==null?void 0:ze.composerBar)!=null?he:{},zt=K.dataset.state==="expanded",Ln=(Tt=Dt.expandedSize)!=null?Tt:"anchored";if(!(zt&&Ln!=="fullscreen")){ne.style.background="",ne.style.border="",ne.style.borderRadius="",ne.style.overflow="",ne.style.boxShadow="";return}let en=(Qt=(rt=r.theme)==null?void 0:rt.components)==null?void 0:Qt.panel,yr=Ms(r),Wr=(xo,la)=>{var hs;return xo==null||xo===""?la:(hs=zo(yr,xo))!=null?hs:xo},sa="1px solid var(--persona-border)",aa="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ia="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ne.style.background="var(--persona-surface, #ffffff)",ne.style.border=Wr(en==null?void 0:en.border,sa),ne.style.borderRadius=Wr(en==null?void 0:en.borderRadius,ia),ne.style.boxShadow=Wr(en==null?void 0:en.shadow,aa),ne.style.overflow="hidden";return}let c=on(r),m=(Pt=(cn=r.launcher)==null?void 0:cn.sidebarMode)!=null?Pt:!1,y=c||m||((dn=(xn=r.launcher)==null?void 0:xn.fullHeight)!=null?dn:!1),b=((Qe=r.launcher)==null?void 0:Qe.enabled)===!1,M=(vn=(at=r.theme)==null?void 0:at.components)==null?void 0:vn.panel,H=Ms(r),N=(Dt,zt)=>{var Ln;return Dt==null||Dt===""?zt:(Ln=zo(H,Dt))!=null?Ln:Dt},q=(un=e.ownerDocument.defaultView)!=null?un:window,I=(ho=(fo=r.launcher)==null?void 0:fo.mobileFullscreen)!=null?ho:!0,ye=(Do=(yo=r.launcher)==null?void 0:yo.mobileBreakpoint)!=null?Do:640,ie=q.innerWidth<=ye,Z=I&&ie&&A,ue=(qt=(No=r.launcher)==null?void 0:No.position)!=null?qt:"bottom-left",ve=ue==="bottom-left"||ue==="top-left",Ne=(Gr=(bo=r.launcher)==null?void 0:bo.zIndex)!=null?Gr:fn,Ye=m||Z?"none":"1px solid var(--persona-border)",Ke=Z?"none":m?ve?"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))";c&&!Z&&(Ke="none",Ye="none");let ot=m||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=N(M==null?void 0:M.border,Ye),Te=N(M==null?void 0:M.shadow,Ke),Ee=N(M==null?void 0:M.borderRadius,ot),Ue=Se.scrollTop;e.style.cssText="",K.style.cssText="",z.style.cssText="",ne.style.cssText="",Se.style.cssText="",$e.style.cssText="";let E=()=>{var zt;if(Ue<=0)return;((zt=Se.ownerDocument.defaultView)!=null?zt:window).requestAnimationFrame(()=>{if(Se.scrollTop===Ue)return;let Ln=Se.scrollHeight-Se.clientHeight;Ln<=0||(Se.scrollTop=Math.min(Ue,Ln))})};if(Z){K.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"),K.style.cssText=`
30
+ `,B.addEventListener("click",()=>{p=w,A.forEach((F,$)=>{let W=$<w;F.classList.toggle("selected",W),F.setAttribute("aria-checked",$===w-1?"true":"false")})}),A.push(B),S.appendChild(B)}f.appendChild(S);let k=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=o,k.rows=3,k.setAttribute("aria-label","Additional comments"),w.appendChild(k),f.appendChild(w)}let R=document.createElement("div");R.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=i,H.addEventListener("click",()=>{t==null||t(),u.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(p===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let w=(k==null?void 0:k.value.trim())||void 0;await n(p,w),u.remove()}catch(w){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),R.appendChild(H),R.appendChild(L),f.appendChild(R),u.appendChild(f),u}function ol(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=s,v.appendChild(S),m.appendChild(v);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-nps",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=l;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=u,k.appendChild(R),k.appendChild(H);let L=document.createElement("div");L.className="persona-feedback-numbers";let w=[];for(let O=0;O<=10;O++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${O} out of 10`),V.textContent=String(O),V.dataset.rating=String(O),O<=6?V.classList.add("persona-feedback-detractor"):O<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{f=O,w.forEach((oe,Ie)=>{oe.classList.toggle("selected",Ie===O),oe.setAttribute("aria-checked",Ie===O?"true":"false")})}),w.push(V),L.appendChild(V)}A.appendChild(k),A.appendChild(L),m.appendChild(A);let B=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=o,B.rows=3,B.setAttribute("aria-label","Additional comments"),O.appendChild(B),m.appendChild(O)}let F=document.createElement("div");F.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=i,$.addEventListener("click",()=>{t==null||t(),p.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let O=(B==null?void 0:B.value.trim())||void 0;await n(f,O),p.remove()}catch(O){W.disabled=!1,W.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),F.appendChild($),F.appendChild(W),m.appendChild(F),p.appendChild(m),p}var es="persona-chat-history",Qy=30*1e3,Zy={"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 eb(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let d=(s=Zy[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function ai(e){if(!e)return!1;let n=e.types;return n?typeof n.contains=="function"?n.contains("Files"):Array.from(n).includes("Files"):!1}function tb(e){var n,t,r,s,o,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function nb(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var sl=e=>!e||typeof e!="object"?{}:{...e},Hu=e=>e.map(n=>({...n,streaming:!1})),Bu=(e,n,t)=>{let r=e!=null&&e.markdown?Oo(e.markdown):null,s=Cs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var l,u,p;let a=(l=o.text)!=null?l:"",i=(u=o.message.rawContent)!=null?u:null;if(n){let f=n.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):r?d=r(a):d=Fo(a),s?s(d):d}};function Du(e){var i,d,l,u;let n=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&n.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&n.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&n.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&n.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&n.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&n.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&n.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",s=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",o=(u=e==null?void 0:e.iconStrokeWidth)!=null?u:.5,a=fe(t,r,s,o);if(a&&n.appendChild(a),e!=null&&e.label){let p=h("span","persona-drop-overlay-label");p.textContent=e.label,n.appendChild(p)}return n}var al=(e,n,t)=>{var Al,Sl,El,Tl,Ml,kl,Ll,Pl,Il,Wl,Rl,Hl,Bl,Dl,Nl,Ol,Fl,$l,_l,jl,Ul,ql,zl,Vl,Kl,Jl,Gl,Xl,Yl,Ql,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=Ei(n),s=ri.getForInstance(r.plugins);r.components&&so.registerAll(r.components);let o=Iu(),i=r.persistState===!1?null:(Al=r.storageAdapter)!=null?Al:Qi(),d={},l=null,u=!1,p=c=>{if(r.onStateLoaded)try{let g=r.onStateLoaded(c);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:b}=g;return b&&(u=!0),y}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return c};if(i!=null&&i.load)try{let c=i.load();if(c&&typeof c.then=="function")l=c.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return p(y)});else{let g=c!=null?c:{messages:[],metadata:{}},y=p(g);y.metadata&&(d=sl(y.metadata)),(Sl=y.messages)!=null&&Sl.length&&(r={...r,initialMessages:y.messages}),(El=y.artifacts)!=null&&El.length&&(r={...r,initialArtifacts:y.artifacts,initialSelectedArtifactId:(Tl=y.selectedArtifactId)!=null?Tl:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=p({messages:[],metadata:{}});(Ml=c.messages)!=null&&Ml.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let f=()=>d,m=c=>{var y;d=(y=c({...d}))!=null?y:{},Po()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[oi],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Zo.message,Zo.messageAndClick],S=si({parsers:v,handlers:x,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let A=(Ll=(kl=r.launcher)==null?void 0:kl.enabled)!=null?Ll:!0,k=(Il=(Pl=r.launcher)==null?void 0:Pl.autoExpand)!=null?Il:!1,R=(Wl=r.autoFocusInput)!=null?Wl:!1,H=k,L=A,w=(Hl=(Rl=r.layout)==null?void 0:Rl.header)==null?void 0:Hl.layout,B=!1,F=()=>Zr(r),$=()=>A||F(),W=F()?!1:A?k:!0,O=!1,V=null,oe=()=>{O=!0,V&&clearTimeout(V),V=setTimeout(()=>{O&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),O=!1)},1e4)},Ie=Bu(r,S,oe),Pe=(Dl=(Bl=r.features)==null?void 0:Bl.showReasoning)!=null?Dl:!0,ze=(Ol=(Nl=r.features)==null?void 0:Nl.showToolCalls)!=null?Ol:!0,pe=($l=(Fl=r.features)==null?void 0:Fl.showEventStreamToggle)!=null?$l:!1,ce=(jl=(_l=r.features)==null?void 0:_l.scrollToBottom)!=null?jl:{},je=`${(ql=typeof r.persistState=="object"?(Ul=r.persistState)==null?void 0:Ul.keyPrefix:void 0)!=null?ql:"persona-"}event-stream`,te=pe?new Ks(je):null,xe=(Kl=(Vl=(zl=r.features)==null?void 0:zl.eventStream)==null?void 0:Vl.maxEvents)!=null?Kl:2e3,G=pe?new Vs(xe,te):null,ae=null,He=!1,ue=null,Re=0;te==null||te.open().then(()=>G==null?void 0:G.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let tt={onCopy:c=>{var g,y;o.emit("message:copy",c),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(y=(g=r.messageActions)==null?void 0:g.onCopy)==null||y.call(g,c)},onFeedback:c=>{var g,y;o.emit("message:feedback",c),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(y=(g=r.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,c)}},K=(Jl=r.statusIndicator)!=null?Jl:{},se=c=>{var g,y,b,T;return c==="idle"?(g=K.idleText)!=null?g:mn.idle:c==="connecting"?(y=K.connectingText)!=null?y:mn.connecting:c==="connected"?(b=K.connectedText)!=null?b:mn.connected:c==="error"?(T=K.errorText)!=null?T:mn.error:mn[c]};function Oe(c,g,y,b){if(b==="idle"&&y.idleLink){c.textContent="";let T=document.createElement("a");T.href=y.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=g,T.style.color="inherit",T.style.textDecoration="none",c.appendChild(T)}else c.textContent=g}let{wrapper:J,panel:z,pillRoot:we}=Zp(r),$e=eu(r,$()),{container:ne,body:Te,messagesWrapper:ve,suggestions:Ht,textarea:ie,sendButton:re,sendButtonWrapper:sn,composerForm:Nt,statusText:zt,introTitle:vr,introSubtitle:dr,closeButton:Ue,iconHolder:U,headerTitle:Ae,headerSubtitle:Be,header:De,footer:_e,actionsRow:ct,leftActions:nt,rightActions:Ct}=$e,jt=$e.setSendButtonMode,P=$e.micButton,he=$e.micButtonWrapper,ge=$e.attachmentButton,dt=$e.attachmentButtonWrapper,Ke=$e.attachmentInput,It=$e.attachmentPreviewsContainer;ne.classList.add("persona-relative"),Te.classList.add("persona-relative");let an=12,At=()=>{var c;return(c=ce.label)!=null?c:""},bt=()=>{var c;return(c=ce.iconName)!=null?c:"arrow-down"},Mt=()=>ce.enabled!==!1,ut=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");ut.type="button",ut.style.display="none",ut.setAttribute("data-persona-scroll-to-bottom","true");let Vt=h("span","persona-flex persona-items-center"),wr=h("span","");ut.append(Vt,wr),ne.appendChild(ut);let _n=()=>{let g=_e.style.display==="none"?0:_e.offsetHeight;ut.style.bottom=`${g+an}px`};_n();let Br=()=>{let c=!!At();ut.setAttribute("aria-label",At()||"Jump to latest"),ut.title=At(),ut.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Vt.innerHTML="";let g=fe(bt(),"14px","currentColor",2);g?(Vt.appendChild(g),Vt.style.display=""):Vt.style.display="none",wr.textContent=At(),wr.style.display=c?"":"none"};Br();let vt=null,pr=null,ur=s.find(c=>c.renderHeader);if(ur!=null&&ur.renderHeader){let c=ur.renderHeader({config:r,defaultRenderer:()=>{let g=eo({config:r,showClose:$()});return Vo(ne,g,r),g.header},onClose:()=>Rt(!1,"user")});if(c){let g=ne.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(c),De=c)}}let Cr=()=>{var g,y,b,T;if(!G)return;if(He=!0,!ae&&G&&(ae=wu({buffer:G,getFullHistory:()=>G.getAllFromStore(),onClose:()=>Qn(),config:r,plugins:s})),ae&&(Te.style.display="none",(g=_e.parentNode)==null||g.insertBefore(ae.element,_e),ae.update()),gt){gt.style.boxShadow=`inset 0 0 0 1.5px ${An.actionIconColor}`;let D=(T=(b=(y=r.features)==null?void 0:y.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;D&&D.split(/\s+/).forEach(N=>N&&gt.classList.add(N))}let c=()=>{if(!He)return;let D=Date.now();D-Re>=200&&(ae==null||ae.update(),Re=D),ue=requestAnimationFrame(c)};Re=0,ue=requestAnimationFrame(c),kr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Qn=()=>{var c,g,y;if(He){if(He=!1,ae&&ae.element.remove(),Te.style.display="",gt){gt.style.boxShadow="";let b=(y=(g=(c=r.features)==null?void 0:c.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;b&&b.split(/\s+/).forEach(T=>T&&gt.classList.remove(T))}ue!==null&&(cancelAnimationFrame(ue),ue=null),kr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},gt=null;if(pe){let c=(Xl=(Gl=r.features)==null?void 0:Gl.eventStream)==null?void 0:Xl.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");gt=h("button",g),gt.style.width="28px",gt.style.height="28px",gt.style.color=An.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let y=fe("activity","18px","currentColor",1.5);y&&gt.appendChild(y);let b=$e.clearChatButtonWrapper,T=$e.closeButtonWrapper,D=b||T;D&&D.parentNode===De?De.insertBefore(gt,D):De.appendChild(gt),gt.addEventListener("click",()=>{He?Qn():Cr()})}let io=c=>{var b,T,D;let g=r.attachments;if(!(g!=null&&g.enabled))return;let y=c.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let N=c.querySelector("[data-persona-composer-form]");N!=null&&N.parentNode?N.parentNode.insertBefore(y,N):c.insertBefore(y,c.firstChild)}if(!c.querySelector('input[type="file"]')){let N=h("input");N.type="file",N.accept=((b=g.allowedTypes)!=null?b:Rr).join(","),N.multiple=((T=g.maxFiles)!=null?T:4)>1,N.style.display="none",N.setAttribute("aria-label",(D=g.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(N)}},mr=s.find(c=>c.renderComposer);if(mr!=null&&mr.renderComposer){let c=r.composer,g=mr.renderComposer({config:r,defaultRenderer:()=>js({config:r}).footer,onSubmit:y=>{var N;if(!_||_.isStreaming())return;let b=y.trim(),T=(N=vt==null?void 0:vt.hasAttachments())!=null?N:!1;if(!b&&!T)return;ps();let D;T&&(D=[],D.push(...vt.getContentParts()),b&&D.push(Ta(b))),_.sendMessage(b,{contentParts:D}),T&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ke==null||Ke.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:((Yl=r.voiceRecognition)==null?void 0:Yl.enabled)===!0?()=>{pr==null||pr()}:void 0});g&&(_e.replaceWith(g),_e=g)}let lo=c=>{let g=c.querySelector("[data-persona-composer-form]"),y=c.querySelector("[data-persona-composer-input]"),b=c.querySelector("[data-persona-composer-submit]"),T=c.querySelector("[data-persona-composer-mic]"),D=c.querySelector("[data-persona-composer-status]");g&&(Nt=g),y&&(ie=y),b&&(re=b),T&&(P=T,he=T.parentElement),D&&(zt=D);let N=c.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(Ht=N);let q=c.querySelector(".persona-attachment-button");q&&(ge=q,dt=q.parentElement),Ke=c.querySelector('input[type="file"]'),It=c.querySelector(".persona-attachment-previews");let I=c.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");I&&(ct=I)};io(_e),lo(_e);let Sn=(nc=(Ql=r.layout)==null?void 0:Ql.contentMaxWidth)!=null?nc:F()?(tc=(ec=(Zl=r.launcher)==null?void 0:Zl.composerBar)==null?void 0:ec.contentMaxWidth)!=null?tc:"720px":void 0;if(Sn&&(ve.style.maxWidth=Sn,ve.style.marginLeft="auto",ve.style.marginRight="auto",ve.style.width="100%"),Sn&&Nt&&!F()&&(Nt.style.maxWidth=Sn,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Sn&&Ht&&!F()&&(Ht.style.maxWidth=Sn,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Sn&&It&&!F()&&(It.style.maxWidth=Sn,It.style.marginLeft="auto",It.style.marginRight="auto"),(rc=r.attachments)!=null&&rc.enabled&&Ke&&It){vt=qo.fromConfig(r.attachments),vt.setPreviewsContainer(It),Ke.addEventListener("change",y=>{let b=y.target;vt==null||vt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,g=Du(c);ne.appendChild(g)}(()=>{var b,T;let c=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},g=D=>{switch(D){case"body-top":return ne.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ve;case"footer-top":return Ht;case"composer":return Nt;case"footer-bottom":return zt;default:return null}},y=(D,N)=>{var q;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")De.insertBefore(N,De.firstChild);else if(D==="header-right")De.appendChild(N);else{let I=De.querySelector(".persona-flex-col");I?(q=I.parentNode)==null||q.insertBefore(N,I.nextSibling):De.appendChild(N)}break;case"body-top":{let I=Te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");I?I.replaceWith(N):Te.insertBefore(N,Te.firstChild);break}case"body-bottom":Te.appendChild(N);break;case"footer-top":Ht.replaceWith(N);break;case"footer-bottom":zt.replaceWith(N);break;default:break}};for(let[D,N]of Object.entries(c))if(N)try{let q=N({config:r,defaultContent:()=>g(D)});q&&y(D,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,q)}})();let Dr=c=>{let y=c.target.closest('button[data-expand-header="true"]');if(!y)return;let b=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let D=y.getAttribute("data-bubble-type");D==="reasoning"?(Jo.has(T)?Jo.delete(T):Jo.add(T),su(T,b)):D==="tool"&&(Go.has(T)?Go.delete(T):Go.add(T),au(T,b,r)),Nn.delete(T)};ve.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Dr(c))}),ve.addEventListener("keydown",c=>{let g=c.target;(c.key==="Enter"||c.key===" ")&&g.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Dr(c))});let Ar=new Map;ve.addEventListener("click",c=>{var N;let y=c.target.closest(".persona-message-action-btn[data-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest("[data-actions-for]");if(!b)return;let T=b.getAttribute("data-actions-for");if(!T)return;let D=y.getAttribute("data-action");if(D==="copy"){let I=_.getMessages().find(be=>be.id===T);if(I&&tt.onCopy){let be=I.content||"";navigator.clipboard.writeText(be).then(()=>{y.classList.add("persona-message-action-success");let le=fe("check",14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ee=fe("copy",14,"currentColor",2);ee&&(y.innerHTML="",y.appendChild(ee))},2e3)}).catch(le=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",le)}),tt.onCopy(I)}}else if(D==="upvote"||D==="downvote"){let I=((N=Ar.get(T))!=null?N:null)===D,be=D==="upvote"?"thumbs-up":"thumbs-down";if(I){Ar.delete(T),y.classList.remove("persona-message-action-active");let le=fe(be,14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le))}else{let le=D==="upvote"?"downvote":"upvote",ee=b.querySelector(`[data-action="${le}"]`);if(ee){ee.classList.remove("persona-message-action-active");let Xe=fe(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Xe&&(ee.innerHTML="",ee.appendChild(Xe))}Ar.set(T,D),y.classList.add("persona-message-action-active");let me=fe(be,14,"currentColor",2);me&&(me.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(me)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ne=_.getMessages().find(et=>et.id===T);Ne&&tt.onFeedback&&tt.onFeedback({type:D,messageId:Ne.id,message:Ne})}}}),ve.addEventListener("click",c=>{let y=c.target.closest("button[data-approval-action]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.closest(".persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let D=y.getAttribute("data-approval-action");if(!D)return;let N=D==="approve"?"approved":"denied",I=_.getMessages().find(le=>le.id===T);if(!(I!=null&&I.approval))return;let be=b.querySelector("[data-approval-buttons]");be&&be.querySelectorAll("button").forEach(ee=>{ee.disabled=!0,ee.style.opacity="0.5",ee.style.cursor="not-allowed"}),I.approval.toolType==="webmcp"?_.resolveWebMcpApproval(T,N):_.resolveApproval(I.approval,N)});let yt=null,Pn=null,In={artifacts:[],selectedId:null},fn=!1,kt={current:null};ve.addEventListener("click",c=>{var ee,me,Ce,Ne,et;let y=c.target.closest("[data-download-artifact]");if(!y)return;c.preventDefault(),c.stopPropagation();let b=y.getAttribute("data-download-artifact");if(!b||((Ce=(me=(ee=r.features)==null?void 0:ee.artifacts)==null?void 0:me.onArtifactAction)==null?void 0:Ce.call(me,{type:"download",artifactId:b}))===!0)return;let D=_.getArtifactById(b),N=D==null?void 0:D.markdown,q=(D==null?void 0:D.title)||"artifact";if(!N){let Xe=y.closest("[data-open-artifact]"),st=Xe==null?void 0:Xe.closest("[data-message-id]"),at=st==null?void 0:st.getAttribute("data-message-id");if(at){let ke=_.getMessages().find(qe=>qe.id===at);if(ke!=null&&ke.rawContent)try{let qe=JSON.parse(ke.rawContent);N=(Ne=qe==null?void 0:qe.props)==null?void 0:Ne.markdown,q=((et=qe==null?void 0:qe.props)==null?void 0:et.title)||q}catch{}}}if(!N)return;let I=new Blob([N],{type:"text/markdown"}),be=URL.createObjectURL(I),le=document.createElement("a");le.href=be,le.download=`${q}.md`,le.click(),URL.revokeObjectURL(be)}),ve.addEventListener("click",c=>{var D,N,q;let y=c.target.closest("[data-open-artifact]");if(!y)return;let b=y.getAttribute("data-open-artifact");!b||((q=(N=(D=r.features)==null?void 0:D.artifacts)==null?void 0:N.onArtifactAction)==null?void 0:q.call(N,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),fn=!1,_.selectArtifact(b),Hn())}),ve.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let g=c.target;g.hasAttribute("data-open-artifact")&&(c.preventDefault(),g.click())});let jn=$e.composerOverlay,Un=(c,g,y)=>{var q,I,be,le;let b=g.trim();if(!b||!kt.current)return;let T=(q=c.getAttribute("data-tool-call-id"))!=null?q:"",D=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:y.structured,values:(I=y.values)!=null?I:y.source==="multi"?b.split(", "):[b],isFreeText:D,source:y.source},bubbles:!0,composed:!0})),Mo(jn,T);let N=kt.current.getMessages().find(ee=>{var me;return((me=ee.toolCall)==null?void 0:me.id)===T});(be=N==null?void 0:N.agentMetadata)!=null&&be.awaitingLocalTool?kt.current.resolveAskUserQuestion(N,(le=y.structured)!=null?le:b):kt.current.sendMessage(b)},Wn=c=>{var T;let g=kt.current;if(!g)return;let y=(T=c.getAttribute("data-tool-call-id"))!=null?T:"",b=g.getMessages().find(D=>{var N;return((N=D.toolCall)==null?void 0:N.id)===y});b&&g.persistAskUserQuestionProgress(b,{answers:Za(c,b),currentIndex:Xn(c)})},Nr=c=>Object.entries(c).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Sr=c=>{var T,D,N;if(((D=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let g=Xn(c),y=Yo(c);if(g>=y-1)return;let b=(N=kt.current)==null?void 0:N.getMessages().find(q=>{var I;return((I=q.toolCall)==null?void 0:I.id)===c.getAttribute("data-tool-call-id")});b&&(ei(c,b,r,g+1),Wn(c))};jn.addEventListener("click",c=>{var D,N,q,I,be,le,ee,me,Ce,Ne,et,Xe,st,at;let y=c.target.closest("[data-ask-user-action]");if(!y)return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;let T=y.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),T==="dismiss"){let Le=(D=b.getAttribute("data-tool-call-id"))!=null?D:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),Mo(jn,Le);let ke=(N=kt.current)==null?void 0:N.getMessages().find(qe=>{var E;return((E=qe.toolCall)==null?void 0:E.id)===Le});(q=ke==null?void 0:ke.agentMetadata)!=null&&q.awaitingLocalTool&&((I=kt.current)==null||I.markAskUserQuestionResolved(ke),(be=kt.current)==null||be.resolveAskUserQuestion(ke,"(dismissed)"));return}if(T==="pick"){let Le=y.getAttribute("data-option-label");if(!Le)return;let ke=b.getAttribute("data-multi-select")==="true",qe=ro(b);if(qe&&ke){let E=To(b)[Xn(b)],Se=new Set(Array.isArray(E)?E:[]);Se.has(Le)?Se.delete(Le):Se.add(Le),oo(b,Array.from(Se)),Wn(b);return}if(qe){oo(b,Le),Wn(b),Sr(b);return}if(ke){let E=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",E?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!E);let Se=b.querySelector('[data-ask-user-action="submit-multi"]');Se&&(Se.disabled=zi(b).length===0);return}Un(b,Le,{source:"pick",values:[Le]});return}if(T==="submit-multi"){let Le=zi(b);if(Le.length===0)return;Un(b,Le.join(", "),{source:"multi",values:Le});return}if(T==="open-free-text"){let Le=b.querySelector('[data-ask-free-text-row="true"]');if(Le){Le.classList.remove("persona-hidden");let ke=Le.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus()}return}if(T==="focus-free-text"){let Le=b.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus();return}if(T==="submit-free-text"){let Le=b.querySelector('[data-ask-free-text-input="true"]'),ke=(le=Le==null?void 0:Le.value)!=null?le:"";if(!ke.trim())return;if(ro(b)){oo(b,ke.trim()),Wn(b),Sr(b);return}Un(b,ke,{source:"free-text"});return}if(T==="next"||T==="back"){if(!kt.current)return;let Le=(ee=b.getAttribute("data-tool-call-id"))!=null?ee:"",ke=kt.current.getMessages().find(Je=>{var ye;return((ye=Je.toolCall)==null?void 0:ye.id)===Le});if(!ke)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),E=(Ce=(me=qe==null?void 0:qe.value)==null?void 0:me.trim())!=null?Ce:"";if(E){let Je=To(b)[Xn(b)];(typeof Je!="string"||Je!==E)&&oo(b,E)}let Se=T==="next"?1:-1,We=Xn(b)+Se;ei(b,ke,r,We),Wn(b);return}if(T==="submit-all"){if(!kt.current)return;let Le=(Ne=b.getAttribute("data-tool-call-id"))!=null?Ne:"",ke=kt.current.getMessages().find(Je=>{var ye;return((ye=Je.toolCall)==null?void 0:ye.id)===Le});if(!ke)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),E=(Xe=(et=qe==null?void 0:qe.value)==null?void 0:et.trim())!=null?Xe:"";E&&oo(b,E);let Se=Za(b,ke);kt.current.persistAskUserQuestionProgress(ke,{answers:Se,currentIndex:Xn(b)});let We=Nr(Se);Un(b,We||"(submitted)",{source:"submit-all",structured:Se});return}if(T==="skip"){if(!kt.current)return;let Le=(st=b.getAttribute("data-tool-call-id"))!=null?st:"",ke=kt.current.getMessages().find(ye=>{var Tt;return((Tt=ye.toolCall)==null?void 0:Tt.id)===Le});if(!ke)return;let qe=ro(b),E=Xn(b),Se=Yo(b),We=E>=Se-1;if(!qe){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Le},bubbles:!0,composed:!0})),Mo(jn,Le),(at=ke.agentMetadata)!=null&&at.awaitingLocalTool&&(kt.current.markAskUserQuestionResolved(ke),kt.current.resolveAskUserQuestion(ke,"(dismissed)"));return}oo(b,"");let Je=b.querySelector('[data-ask-free-text-input="true"]');if(Je&&(Je.value=""),We){let ye=Za(b,ke),Tt=Nr(ye);Un(b,Tt||"(skipped)",{source:"submit-all",structured:ye});return}ei(b,ke,r,E+1),Wn(b);return}}),jn.addEventListener("keydown",c=>{var D;if(c.key!=="Enter")return;let y=c.target;if(!((D=y.matches)!=null&&D.call(y,'[data-ask-free-text-input="true"]')))return;let b=y.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let T=y.value;if(T.trim()){if(ro(b)){oo(b,T.trim()),Wn(b),Sr(b);return}Un(b,T,{source:"free-text"})}});let Or=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let g=c.target;if((g==null?void 0:g.tagName)==="INPUT"||(g==null?void 0:g.tagName)==="TEXTAREA"||g!=null&&g.isContentEditable)return;let y=jn.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),D=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];D&&(c.preventDefault(),D.click())};document.addEventListener("keydown",Or);let Rn=null,Wt=null,hn=null,qn=null,Fr=()=>{};function Er(){qn==null||qn(),qn=null}let $r=()=>{var N;if(!Rn||!Wt)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),y=((N=e.ownerDocument.defaultView)!=null?N:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||y){Wt.style.removeProperty("position"),Wt.style.removeProperty("left"),Wt.style.removeProperty("top"),Wt.style.removeProperty("bottom"),Wt.style.removeProperty("width"),Wt.style.removeProperty("z-index");return}let b=Rn.firstElementChild;if(!b||b===Wt)return;let T=10;Wt.style.position="absolute",Wt.style.top="0",Wt.style.bottom="0",Wt.style.width=`${T}px`,Wt.style.zIndex="5";let D=b.offsetWidth-T/2;Wt.style.left=`${Math.max(0,D)}px`},gr=()=>{},Hn=()=>{var y,b,T,D,N;if(!yt||!Yn(r))return;ti(e,r),ni(e,r),gr();let c=(D=(T=(b=(y=r.features)==null?void 0:y.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?D:520,g=z.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=c),yt.update(In),fn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(N=yt.backdrop)==null||N.classList.add("persona-hidden")):In.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),Fr()};if(Yn(r)){z.style.position="relative";let c=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(ne),yt=Su(r,{onSelect:y=>{var b;return(b=kt.current)==null?void 0:b.selectArtifact(y)},onDismiss:()=>{fn=!0,Hn()}}),yt.element.classList.add("persona-hidden"),Rn=g,g.appendChild(c),g.appendChild(yt.element),yt.backdrop&&z.appendChild(yt.backdrop),z.appendChild(g),Fr=()=>{var b,T,D,N;if(!Rn||!yt)return;if(!(((D=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:D.resizable)===!0)){hn==null||hn(),hn=null,Er(),Wt&&(Wt.remove(),Wt=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!Wt){let q=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let I=e.ownerDocument,be=(N=I.defaultView)!=null?N:window,le=ee=>{var st,at;if(!yt||ee.button!==0||e.classList.contains("persona-artifact-narrow-host")||be.innerWidth<=640)return;ee.preventDefault(),Er();let me=ee.clientX,Ce=yt.element.getBoundingClientRect().width,Ne=(at=(st=r.features)==null?void 0:st.artifacts)==null?void 0:at.layout,et=Le=>{let ke=Rn.getBoundingClientRect().width,qe=e.classList.contains("persona-artifact-appearance-seamless"),E=qe?0:ku(Rn,be),Se=qe?0:q.getBoundingClientRect().width||6,We=Ce-(Le.clientX-me),Je=Lu(We,ke,E,Se,Ne==null?void 0:Ne.resizableMinWidth,Ne==null?void 0:Ne.resizableMaxWidth);yt.element.style.width=`${Je}px`,yt.element.style.maxWidth="none",$r()},Xe=()=>{I.removeEventListener("pointermove",et),I.removeEventListener("pointerup",Xe),I.removeEventListener("pointercancel",Xe),qn=null;try{q.releasePointerCapture(ee.pointerId)}catch{}};qn=Xe,I.addEventListener("pointermove",et),I.addEventListener("pointerup",Xe),I.addEventListener("pointercancel",Xe);try{q.setPointerCapture(ee.pointerId)}catch{}};q.addEventListener("pointerdown",le),Wt=q,Rn.insertBefore(q,yt.element),hn=()=>{q.removeEventListener("pointerdown",le)}}if(Wt){let q=In.artifacts.length>0&&!fn;Wt.classList.toggle("persona-hidden",!q),$r()}},gr=()=>{var be,le,ee,me,Ce,Ne,et,Xe,st,at,Le,ke,qe,E;if(!A||!yt||((le=(be=r.launcher)==null?void 0:be.sidebarMode)!=null?le:!1)||on(r)&&lr(r).reveal==="emerge")return;let b=(ee=e.ownerDocument.defaultView)!=null?ee:window,T=(Ce=(me=r.launcher)==null?void 0:me.mobileFullscreen)!=null?Ce:!0,D=(et=(Ne=r.launcher)==null?void 0:Ne.mobileBreakpoint)!=null?et:640;if(T&&b.innerWidth<=D||!Mu(r,A))return;let N=(at=(st=(Xe=r.launcher)==null?void 0:Xe.width)!=null?st:r.launcherWidth)!=null?at:Gn,q=(E=(qe=(ke=(Le=r.features)==null?void 0:Le.artifacts)==null?void 0:ke.layout)==null?void 0:qe.expandedPanelWidth)!=null?E:"min(720px, calc(100vw - 24px))";In.artifacts.length>0&&!fn?(z.style.width=q,z.style.maxWidth=q):(z.style.width=N,z.style.maxWidth=N)},typeof ResizeObserver!="undefined"&&(Pn=new ResizeObserver(()=>{Hn()}),Pn.observe(z))}else z.appendChild(ne),F()&&we&&($e.peekBanner&&we.appendChild($e.peekBanner),we.appendChild(_e));e.appendChild(J),we&&e.appendChild(we);let Zn=()=>{var Je,ye,Tt,ot,Xt,ln,Pt,xn,cn,Qe,it,vn,pn,fo,ho,yo,Do,No,Ut,bo,Xr,ht,Tn,Ir,wn,Mn,Bt,$t;if(F()){z.style.width="100%",z.style.maxWidth="100%";let Dt=(ye=(Je=r.launcher)==null?void 0:Je.composerBar)!=null?ye:{},qt=J.dataset.state==="expanded",kn=(Tt=Dt.expandedSize)!=null?Tt:"anchored";if(!(qt&&kn!=="fullscreen")){ne.style.background="",ne.style.border="",ne.style.borderRadius="",ne.style.overflow="",ne.style.boxShadow="";return}let Zt=(Xt=(ot=r.theme)==null?void 0:ot.components)==null?void 0:Xt.panel,yr=Is(r),Wr=(xo,ga)=>{var xs;return xo==null||xo===""?ga:(xs=zo(yr,xo))!=null?xs:xo},pa="1px solid var(--persona-border)",ua="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ma="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ne.style.background="var(--persona-surface, #ffffff)",ne.style.border=Wr(Zt==null?void 0:Zt.border,pa),ne.style.borderRadius=Wr(Zt==null?void 0:Zt.borderRadius,ma),ne.style.boxShadow=Wr(Zt==null?void 0:Zt.shadow,ua),ne.style.overflow="hidden";return}let c=on(r),g=(Pt=(ln=r.launcher)==null?void 0:ln.sidebarMode)!=null?Pt:!1,y=c||g||((cn=(xn=r.launcher)==null?void 0:xn.fullHeight)!=null?cn:!1),b=((Qe=r.launcher)==null?void 0:Qe.enabled)===!1,T=(vn=(it=r.theme)==null?void 0:it.components)==null?void 0:vn.panel,D=Is(r),N=(Dt,qt)=>{var kn;return Dt==null||Dt===""?qt:(kn=zo(D,Dt))!=null?kn:Dt},q=(pn=e.ownerDocument.defaultView)!=null?pn:window,I=(ho=(fo=r.launcher)==null?void 0:fo.mobileFullscreen)!=null?ho:!0,be=(Do=(yo=r.launcher)==null?void 0:yo.mobileBreakpoint)!=null?Do:640,le=q.innerWidth<=be,ee=I&&le&&A,me=(Ut=(No=r.launcher)==null?void 0:No.position)!=null?Ut:"bottom-left",Ce=me==="bottom-left"||me==="top-left",Ne=(Xr=(bo=r.launcher)==null?void 0:bo.zIndex)!=null?Xr:gn,et=g||ee?"none":"1px solid var(--persona-border)",Xe=ee?"none":g?Ce?"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))";c&&!ee&&(Xe="none",et="none");let st=g||ee?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",at=N(T==null?void 0:T.border,et),Le=N(T==null?void 0:T.shadow,Xe),ke=N(T==null?void 0:T.borderRadius,st),qe=Te.scrollTop;e.style.cssText="",J.style.cssText="",z.style.cssText="",ne.style.cssText="",Te.style.cssText="",_e.style.cssText="";let E=()=>{var qt;if(qe<=0)return;((qt=Te.ownerDocument.defaultView)!=null?qt:window).requestAnimationFrame(()=>{if(Te.scrollTop===qe)return;let kn=Te.scrollHeight-Te.clientHeight;kn<=0||(Te.scrollTop=Math.min(qe,kn))})};if(ee){J.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),J.style.cssText=`
24
31
  position: fixed !important;
25
32
  inset: 0 !important;
26
33
  width: 100% !important;
@@ -56,7 +63,7 @@ import{Marked as Yu}from"marked";var Zu=e=>{if(e)return e},ca=e=>{var o,s;let n=
56
63
  overflow: hidden !important;
57
64
  border-radius: 0 !important;
58
65
  border: none !important;
59
- `,Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.overflowY="auto",$e.style.flexShrink="0",F=!0,E();return}let we=(Mn=(ht=r==null?void 0:r.launcher)==null?void 0:ht.width)!=null?Mn:r==null?void 0:r.launcherWidth,Ie=we!=null?we:Gn;if(!m&&!c)b&&y?(z.style.width="100%",z.style.maxWidth="100%"):(z.style.width=Ie,z.style.maxWidth=Ie);else if(c)if(lr(r).reveal==="emerge"){let zt=lr(r).width;z.style.width=zt,z.style.maxWidth=zt}else z.style.width="100%",z.style.maxWidth="100%";if(gr(),z.style.boxShadow=Te,z.style.borderRadius=Ee,ne.style.border=st,ne.style.borderRadius=Ee,c&&!Z&&(M==null?void 0:M.border)===void 0&&(ne.style.border="none",lr(r).side==="right"?ne.style.borderLeft="1px solid var(--persona-border)":ne.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),K.style.display="flex",K.style.flexDirection="column",K.style.flex="1 1 0%",K.style.minHeight="0",K.style.maxHeight="100%",K.style.height="100%",b&&(K.style.overflow="hidden"),z.style.display="flex",z.style.flexDirection="column",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.maxHeight="100%",z.style.height="100%",z.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",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.overflowY="auto",$e.style.flexShrink="0"),K.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"),!m&&!b&&!c&&((Ir=cr[ue])!=null?Ir:cr["bottom-right"]).split(" ").forEach(zt=>K.classList.add(zt)),m){let Dt=(kn=(Cn=r.launcher)==null?void 0:Cn.sidebarWidth)!=null?kn:"420px";K.style.cssText=`
66
+ `,Te.style.flex="1 1 0%",Te.style.minHeight="0",Te.style.overflowY="auto",_e.style.flexShrink="0",B=!0,E();return}let Se=(Tn=(ht=r==null?void 0:r.launcher)==null?void 0:ht.width)!=null?Tn:r==null?void 0:r.launcherWidth,We=Se!=null?Se:Gn;if(!g&&!c)b&&y?(z.style.width="100%",z.style.maxWidth="100%"):(z.style.width=We,z.style.maxWidth=We);else if(c)if(lr(r).reveal==="emerge"){let qt=lr(r).width;z.style.width=qt,z.style.maxWidth=qt}else z.style.width="100%",z.style.maxWidth="100%";if(gr(),z.style.boxShadow=Le,z.style.borderRadius=ke,ne.style.border=at,ne.style.borderRadius=ke,c&&!ee&&(T==null?void 0:T.border)===void 0&&(ne.style.border="none",lr(r).side==="right"?ne.style.borderLeft="1px solid var(--persona-border)":ne.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),J.style.display="flex",J.style.flexDirection="column",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.maxHeight="100%",J.style.height="100%",b&&(J.style.overflow="hidden"),z.style.display="flex",z.style.flexDirection="column",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.maxHeight="100%",z.style.height="100%",z.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",Te.style.flex="1 1 0%",Te.style.minHeight="0",Te.style.overflowY="auto",_e.style.flexShrink="0"),J.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!b&&!c&&((Ir=cr[me])!=null?Ir:cr["bottom-right"]).split(" ").forEach(qt=>J.classList.add(qt)),g){let Dt=(Mn=(wn=r.launcher)==null?void 0:wn.sidebarWidth)!=null?Mn:"420px";J.style.cssText=`
60
67
  position: fixed !important;
61
68
  top: 0 !important;
62
69
  bottom: 0 !important;
@@ -68,7 +75,7 @@ import{Marked as Yu}from"marked";var Zu=e=>{if(e)return e},ca=e=>{var o,s;let n=
68
75
  display: flex !important;
69
76
  flex-direction: column !important;
70
77
  z-index: ${Ne} !important;
71
- ${ve?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
78
+ ${Ce?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
72
79
  `,z.style.cssText=`
73
80
  position: relative !important;
74
81
  display: flex !important;
@@ -80,8 +87,8 @@ import{Marked as Yu}from"marked";var Zu=e=>{if(e)return e},ca=e=>{var o,s;let n=
80
87
  min-height: 0 !important;
81
88
  margin: 0 !important;
82
89
  padding: 0 !important;
83
- box-shadow: ${Te} !important;
84
- border-radius: ${Ee} !important;
90
+ box-shadow: ${Le} !important;
91
+ border-radius: ${ke} !important;
85
92
  `,z.style.setProperty("width","100%","important"),z.style.setProperty("max-width","100%","important"),ne.style.cssText=`
86
93
  display: flex !important;
87
94
  flex-direction: column !important;
@@ -91,29 +98,29 @@ import{Marked as Yu}from"marked";var Zu=e=>{if(e)return e},ca=e=>{var o,s;let n=
91
98
  min-height: 0 !important;
92
99
  max-height: 100% !important;
93
100
  overflow: hidden !important;
94
- border-radius: ${Ee} !important;
95
- border: ${st} !important;
96
- `,$e.style.cssText=`
101
+ border-radius: ${ke} !important;
102
+ border: ${at} !important;
103
+ `,_e.style.cssText=`
97
104
  flex-shrink: 0 !important;
98
105
  border-top: none !important;
99
106
  padding: 8px 16px 12px 16px !important;
100
- `}if(!b&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",zt=m?"":"padding-top: 1.25em !important;",Ln=m?"":`z-index: ${(_t=(Bt=r.launcher)==null?void 0:Bt.zIndex)!=null?_t:fn} !important;`;K.style.cssText+=Dt+zt+Ln}E()};Zn(),So(e,r),za(e,r),Va(e,r);let gt=[];gt.push(()=>{document.removeEventListener("keydown",Fr)});let Kt=null,Gt=null;gt.push(()=>{Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null}),In&&gt.push(()=>{In==null||In.disconnect(),In=null}),gt.push(()=>{yn==null||yn(),yn=null,Er(),Wt&&(Wt.remove(),Wt=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),de&&gt.push(()=>{ce!==null&&(cancelAnimationFrame(ce),ce=null),ae==null||ae.destroy(),ae=null,Q==null||Q.destroy(),Q=null,ee=null});let Dn=null,_r=()=>{Dn&&(Dn(),Dn=null),r.colorScheme==="auto"&&(Dn=yi(()=>{So(e,r)}))};_r(),gt.push(()=>{Dn&&(Dn(),Dn=null)});let Vn=(Ul=r.features)==null?void 0:Ul.streamAnimation;if(Vn!=null&&Vn.type&&Vn.type!=="none"){let c=Ws(Vn.type,Vn.plugins);c&&(vi(c,e),gt.push(()=>kp(e)))}let er=tu(Ht),Nn=null,_,le=!1,Fn=wp(),tr=new Map,fr=new Map,ns=0,nr=Ea(),rr=0,or=null,Tr=!1,lo=!1,qs=4,rs=24,zs=80,Lo=new Map,ut={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},os=(zl=(ql=r.voiceRecognition)==null?void 0:ql.autoResume)!=null?zl:!1,Jn=c=>{s.emit("voice:state",{active:ut.active,source:c,timestamp:Date.now()})},En=()=>{g(c=>({...c,voiceState:{active:ut.active,timestamp:Date.now(),manuallyDeactivated:ut.manuallyDeactivated}}))},Vs=()=>{var b,M;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=Ki(d.voiceState),m=!!c.active,y=Number((M=c.timestamp)!=null?M:0);ut.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-y<Ty&&setTimeout(()=>{var H,N;ut.active||(ut.manuallyDeactivated=!1,((N=(H=r.voiceRecognition)==null?void 0:H.provider)==null?void 0:N.type)==="runtype"?_.toggleVoice().then(()=>{ut.active=_.isVoiceActive(),Jn("restore"),_.isVoiceActive()&&Kr()}):uo("restore"))},1e3)},Js=()=>_?fu(_.getMessages()).filter(c=>!c.__skipPersist):[];function Po(c){if(!(i!=null&&i.save))return;let y={messages:c?fu(c):_?Js():[],metadata:d,artifacts:Wn.artifacts,selectedArtifactId:Wn.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Mr=null,Ks=()=>K.querySelector("#persona-scroll-container")||Se,co=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),Tr=!1},ss=()=>{or!==null&&(cancelAnimationFrame(or),or=null),lo=!1,co()},kr=()=>{if(!Mt()||Re){pt.parentNode&&pt.remove(),pt.style.display="none";return}pt.parentNode!==ne&&ne.appendChild(pt),jn();let c=ks(Se)>0;pt.style.display=nr.isFollowing()||!c?"none":""},as=()=>{nr.pause()&&(ss(),kr())},jr=()=>{nr.resume(),kr()},Ur=(c=!1)=>{nr.isFollowing()&&(!c&&!le||(or!==null&&(cancelAnimationFrame(or),or=null),lo=!0,or=requestAnimationFrame(()=>{or=null,lo=!1,nr.isFollowing()&&Gs(Ks(),c?220:140)})))},Gs=(c,m=500)=>{let y=c.scrollTop,b=ks(c),M=b-y;if(Math.abs(M)<1){rr=c.scrollTop;return}if(Math.abs(M)>=zs){co(),Tr=!0,c.scrollTop=b,rr=c.scrollTop,Tr=!1;return}co();let H=performance.now();Tr=!0;let N=I=>1-Math.pow(1-I,3),q=I=>{if(!nr.isFollowing()){co();return}let ye=ks(c);ye!==b&&(b=ye,M=b-y);let ie=I-H,Z=Math.min(ie/m,1),ue=N(Z),ve=y+M*ue;c.scrollTop=ve,rr=c.scrollTop,Z<1?Mr=requestAnimationFrame(q):(c.scrollTop=b,rr=c.scrollTop,Mr=null,Tr=!1)};Mr=requestAnimationFrame(q)},Qs=c=>{let m=new Map;c.forEach(y=>{let b=Lo.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&s.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&s.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&s.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):s.emit("approval:requested",{approval:y.approval,message:y}))}),Lo.clear(),m.forEach((y,b)=>{Lo.set(b,y)})},po=(c,m,y)=>{var Ke,ot,st,Te,Ee,Ue;let b=document.createElement("div"),H=(()=>{var we;let E=o.find(Ie=>Ie.renderLoadingIndicator);if(E!=null&&E.renderLoadingIndicator)return E.renderLoadingIndicator;if((we=r.loadingIndicator)!=null&&we.render)return r.loadingIndicator.render})(),N=(E,we)=>we==null?!1:typeof we=="string"?(E.textContent=we,!0):(E.appendChild(we),!0),q=new Set,I=new Set,ye=o.some(E=>E.renderAskUserQuestion),ie=[],Z=[],ue=r.enableComponentStreaming!==!1;if(m.forEach(E=>{var xn,dn,Qe,at,vn,un,fo,ho,yo,Do,No,qt,bo,Gr;q.add(E.id);let we=ye&&eo(E),Ie=!we&&E.role==="assistant"&&!E.variant&&ue&&qi(E);if(!Ie&&fr.has(E.id)){let ht=c.querySelector(`#wrapper-${E.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),fr.delete(E.id)}let ze=eo(E)?`:${(xn=E.agentMetadata)!=null&&xn.askUserQuestionAnswered?"a":"u"}:${(dn=E.agentMetadata)!=null&&dn.askUserQuestionAnswers?Object.keys(E.agentMetadata.askUserQuestionAnswers).length:0}`:"",he=Cp(E,ns)+ze,Tt=we||Ie?null:Ap(Fn,E.id,he);if(Tt){b.appendChild(Tt.cloneNode(!0)),eo(E)&&((Qe=E.toolCall)!=null&&Qe.id)&&((at=E.agentMetadata)==null?void 0:at.awaitingLocalTool)===!0&&!((vn=E.agentMetadata)!=null&&vn.askUserQuestionAnswered)&&(I.add(E.toolCall.id),_s(E,r,Oe.composerOverlay));return}let rt=null,Qt=o.find(ht=>!!(E.variant==="reasoning"&&ht.renderReasoning||E.variant==="tool"&&ht.renderToolCall||E.variant==="approval"&&ht.renderApproval||!E.variant&&ht.renderMessage)),cn=(un=r.layout)==null?void 0:un.messages;if(eo(E)&&((fo=E.agentMetadata)==null?void 0:fo.askUserQuestionAnswered)===!0){tr.delete(E.id);let ht=c.querySelector(`#wrapper-${E.id}`);ht==null||ht.removeAttribute("data-preserve-runtime");return}if(eo(E)&&((yo=(ho=r.features)==null?void 0:ho.askUserQuestion)==null?void 0:yo.enabled)!==!1){let ht=o.find(Mn=>typeof Mn.renderAskUserQuestion=="function");if(ht&&kt.current){let Mn=tr.get(E.id),Ir=Mn!==he,Cn=null;if(Ir){let{payload:_t,complete:Dt}=to(E),zt=E.id,Ln=()=>{var $n;return($n=kt.current)==null?void 0:$n.getMessages().find(en=>en.id===zt)};Cn=ht.renderAskUserQuestion({message:E,payload:_t,complete:Dt,resolve:$n=>{var yr;let en=Ln();en&&((yr=kt.current)==null||yr.resolveAskUserQuestion(en,$n))},dismiss:()=>{var en,yr,Wr;let $n=Ln();(en=$n==null?void 0:$n.agentMetadata)!=null&&en.awaitingLocalTool&&((yr=kt.current)==null||yr.markAskUserQuestionResolved($n),(Wr=kt.current)==null||Wr.resolveAskUserQuestion($n,"(dismissed)"))},config:r})}let kn=Mn!=null;if(Ir&&Cn===null&&!kn){((Do=E.agentMetadata)==null?void 0:Do.awaitingLocalTool)===!0&&!((No=E.agentMetadata)!=null&&No.askUserQuestionAnswered)&&(I.add(E.toolCall.id),_s(E,r,Oe.composerOverlay));return}let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${E.id}`,Bt.setAttribute("data-wrapper-id",E.id),Bt.setAttribute("data-ask-plugin-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),b.appendChild(Bt),ie.push({messageId:E.id,fingerprint:he,bubble:Cn});return}else{((qt=E.agentMetadata)==null?void 0:qt.awaitingLocalTool)===!0&&!((bo=E.agentMetadata)!=null&&bo.askUserQuestionAnswered)&&(I.add(E.toolCall.id),_s(E,r,Oe.composerOverlay));return}}else if(Qt)if(E.variant==="reasoning"&&E.reasoning&&Qt.renderReasoning){if(!ke)return;rt=Qt.renderReasoning({message:E,defaultRenderer:()=>Mi(E,r),config:r})}else if(E.variant==="tool"&&E.toolCall&&Qt.renderToolCall){if(!Ge)return;rt=Qt.renderToolCall({message:E,defaultRenderer:()=>ki(E,r),config:r})}else if(E.variant==="approval"&&E.approval&&Qt.renderApproval){if(r.approval===!1)return;rt=Qt.renderApproval({message:E,defaultRenderer:()=>Bi(E,r),config:r})}else Qt.renderMessage&&(rt=Qt.renderMessage({message:E,defaultRenderer:()=>{let ht=Os(E,y,cn,r.messageActions,Ze,{loadingIndicatorRenderer:H,widgetConfig:r});return E.role!=="user"&&Fi(ht,E,r,_),ht},config:r}));if(!rt&&Ie){let ht=zi(E);if(ht){let Mn=fr.get(E.id),Ir=Mn!==he,Cn=r.wrapComponentDirectiveInBubble!==!1,kn=null;if(Ir){let Bt=Ui(ht,{config:r,message:E,transform:y});if(Bt)if(Cn){let _t=document.createElement("div");if(_t.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),_t.id=`bubble-${E.id}`,_t.setAttribute("data-message-id",E.id),E.content&&E.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=y({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),_t.appendChild(Dt)}_t.appendChild(Bt),kn=_t}else{let _t=document.createElement("div");if(_t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",_t.id=`bubble-${E.id}`,_t.setAttribute("data-message-id",E.id),_t.setAttribute("data-persona-component-directive","true"),E.content&&E.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=y({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),_t.appendChild(Dt)}_t.appendChild(Bt),kn=_t}}if(kn||Mn!=null){let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${E.id}`,Bt.setAttribute("data-wrapper-id",E.id),Bt.setAttribute("data-component-directive-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),Cn||Bt.classList.add("persona-w-full"),b.appendChild(Bt),Z.push({messageId:E.id,fingerprint:he,bubble:kn});return}}}if(!rt)if(E.variant==="reasoning"&&E.reasoning){if(!ke)return;rt=Mi(E,r)}else if(E.variant==="tool"&&E.toolCall){if(!Ge)return;rt=ki(E,r)}else if(E.variant==="approval"&&E.approval){if(r.approval===!1)return;rt=Bi(E,r)}else{let ht=(Gr=r.layout)==null?void 0:Gr.messages;ht!=null&&ht.renderUserMessage&&E.role==="user"?rt=ht.renderUserMessage({message:E,config:r,streaming:!!E.streaming}):ht!=null&&ht.renderAssistantMessage&&E.role==="assistant"?rt=ht.renderAssistantMessage({message:E,config:r,streaming:!!E.streaming}):rt=Os(E,y,ht,r.messageActions,Ze,{loadingIndicatorRenderer:H,widgetConfig:r}),E.role!=="user"&&rt&&Fi(rt,E,r,_)}let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-${E.id}`,Pt.setAttribute("data-wrapper-id",E.id),E.role==="user"&&Pt.classList.add("persona-justify-end"),(rt==null?void 0:rt.getAttribute("data-persona-component-directive"))==="true"&&Pt.classList.add("persona-w-full"),Pt.appendChild(rt),Sp(Fn,E.id,he,Pt),b.appendChild(Pt)}),Oe.composerOverlay&&Oe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(we=>{let Ie=we.getAttribute("data-persona-ask-sheet-for");Ie&&!I.has(Ie)&&Mo(Oe.composerOverlay,Ie)}),(ot=(Ke=r.features)==null?void 0:Ke.toolCallDisplay)!=null&&ot.grouped){let E=[],we=[];m.forEach(Ie=>{if(Ie.variant==="tool"&&Ie.toolCall&&Ge){we.push(Ie);return}we.length>1&&E.push(we),we=[]}),we.length>1&&E.push(we),E.forEach((Ie,ze)=>{var dn,Qe;let he=Ie.map(at=>Array.from(b.children).find(vn=>vn instanceof HTMLElement&&vn.getAttribute("data-wrapper-id")===at.id)).filter(at=>!!at);if(he.length<2)return;let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id=`wrapper-tool-group-${ze}-${Ie[0].id}`,Tt.setAttribute("data-wrapper-id",`tool-group-${ze}-${Ie[0].id}`);let rt=document.createElement("div");rt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",rt.setAttribute("data-persona-tool-group","true");let Qt=document.createElement("div");Qt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let cn=`Called ${Ie.length} tools`,Pt=(Qe=(dn=r.toolCall)==null?void 0:dn.renderGroupedSummary)==null?void 0:Qe.call(dn,{messages:Ie,toolCalls:Ie.map(at=>at.toolCall).filter(at=>!!at),defaultSummary:cn,config:r});N(Qt,Pt)||(Qt.textContent=cn);let xn=document.createElement("div");xn.className="persona-tool-group-stack persona-flex persona-flex-col",rt.append(Qt,xn),Tt.appendChild(rt),he[0].before(Tt),he.forEach((at,vn)=>{let un=document.createElement("div");un.className="persona-tool-group-item persona-relative",un.setAttribute("data-persona-tool-group-item","true"),vn<he.length-1&&un.setAttribute("data-persona-tool-group-connector","true"),un.appendChild(at),xn.appendChild(un)})})}Ep(Fn,q);let ve=m.some(E=>E.role==="assistant"&&E.streaming),Ne=m[m.length-1],Ye=(Ne==null?void 0:Ne.role)==="assistant"&&!Ne.streaming&&Ne.variant!=="approval";if(le&&m.some(E=>E.role==="user")&&!ve&&!Ye){let E={config:r,streaming:!0,location:"standalone",defaultRenderer:Jo},we=o.find(ze=>ze.renderLoadingIndicator),Ie=null;if(we!=null&&we.renderLoadingIndicator&&(Ie=we.renderLoadingIndicator(E)),Ie===null&&((st=r.loadingIndicator)!=null&&st.render)&&(Ie=r.loadingIndicator.render(E)),Ie===null&&(Ie=Jo()),Ie){let ze=document.createElement("div"),he=((Te=r.loadingIndicator)==null?void 0:Te.showBubble)!==!1;ze.className=he?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ze.setAttribute("data-typing-indicator","true"),ze.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ze.appendChild(Ie);let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id="wrapper-typing-indicator",Tt.setAttribute("data-wrapper-id","typing-indicator"),Tt.appendChild(ze),b.appendChild(Tt)}}if(!le&&m.length>0){let E=m[m.length-1],we={config:r,lastMessage:E,messageCount:m.length},Ie=o.find(he=>he.renderIdleIndicator),ze=null;if(Ie!=null&&Ie.renderIdleIndicator&&(ze=Ie.renderIdleIndicator(we)),ze===null&&((Ee=r.loadingIndicator)!=null&&Ee.renderIdle)&&(ze=r.loadingIndicator.renderIdle(we)),ze){let he=document.createElement("div"),Tt=((Ue=r.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;he.className=Tt?["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(" "),he.setAttribute("data-idle-indicator","true"),he.appendChild(ze);let rt=document.createElement("div");rt.className="persona-flex",rt.id="wrapper-idle-indicator",rt.setAttribute("data-wrapper-id","idle-indicator"),rt.appendChild(he),b.appendChild(rt)}}if(Sa(c,b),ie.length>0)for(let{messageId:E,fingerprint:we,bubble:Ie}of ie){let ze=c.querySelector(`#wrapper-${E}`);ze&&Ie!==null&&(ze.replaceChildren(Ie),ze.setAttribute("data-bubble-fp",we),tr.set(E,we))}if(tr.size>0)for(let E of tr.keys())q.has(E)||tr.delete(E);if(Z.length>0)for(let{messageId:E,fingerprint:we,bubble:Ie}of Z){let ze=c.querySelector(`#wrapper-${E}`);ze&&Ie!==null&&(ze.replaceChildren(Ie),ze.setAttribute("data-bubble-fp",we),fr.set(E,we))}if(fr.size>0)for(let E of fr.keys())q.has(E)||fr.delete(E)},qr=null,Xs=()=>{var y;if(qr)return;let c=b=>{let M=b.composedPath();M.includes(K)||xe&&M.includes(xe)||Rt(!1,"user")};qr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},is=()=>{var m;if(!qr)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",qr,!0),qr=null};gt.push(()=>is());let zr=null,Ys=()=>{var y;if(zr)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Rt(!1,"user"))};zr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},ls=()=>{var m;if(!zr)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",zr,!0),zr=null};gt.push(()=>ls());let Vr=!1,cs=new Set,Zs=()=>{var m,y,b,M;let c=(b=(y=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((M=r.features)==null?void 0:M.streamAnimation)},Lr=()=>{var ot,st,Te,Ee;if(!$())return;let c=Oe.peekBanner,m=Oe.peekTextNode;if(!c||!m)return;if(W){c.classList.remove("persona-pill-peek--visible");return}let y=(ot=_==null?void 0:_.getMessages())!=null?ot:[],b;for(let Ue=y.length-1;Ue>=0;Ue--){let E=y[Ue];if(E.role==="assistant"&&E.content){b=E;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let M=b.content,H=!!b.streaming,N=Zs(),q=ka(N),I=q.type!=="none"?Ws(q.type,N==null?void 0:N.plugins):null,ye=((st=I==null?void 0:I.isAnimating)==null?void 0:st.call(I,b))===!0,ie=I!==null&&(H||ye);ie&&I&&!cs.has(I.name)&&(vi(I,e),cs.add(I.name));let Z=ie&&(I!=null&&I.containerClass)?I.containerClass:null,ue=(Te=m.dataset.personaPeekStreamClass)!=null?Te:null;ue&&ue!==Z&&(m.classList.remove(ue),delete m.dataset.personaPeekStreamClass),Z&&ue!==Z&&(m.classList.add(Z),m.dataset.personaPeekStreamClass=Z),ie?(m.style.setProperty("--persona-stream-step",`${q.speed}ms`),m.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let ve=ie?La(M,q.buffer,I,b,H):M;if(ie&&q.placeholder==="skeleton"&&H&&(!ve||!ve.trim())){let Ue=document.createElement("div"),E=Hs();E.classList.add("persona-pill-peek__skeleton"),Ue.appendChild(E),Sa(m,Ue)}else{let Ue=Math.max(0,ve.length-100),E=ve.length>100?ve.slice(-100):ve,we=Oo(E);if(!ie||!I){let Ie=ve.length>100?`\u2026${E}`:E;m.textContent!==Ie&&(m.textContent=Ie)}else{let Ie=we;(I.wrap==="char"||I.wrap==="word")&&(Ie=Rs(we,I.wrap,`peek-${b.id}`,{skipTags:I.skipTags,startIndex:Ue}));let ze=document.createElement("div");if(ze.innerHTML=Ie,I.useCaret&&E.length>0){let he=Pa(),Tt=ze.querySelectorAll(".persona-stream-char, .persona-stream-word"),rt=Tt[Tt.length-1];rt!=null&&rt.parentNode?rt.parentNode.insertBefore(he,rt.nextSibling):ze.appendChild(he)}Sa(m,ze),(Ee=I.onAfterRender)==null||Ee.call(I,{container:m,bubble:c,messageId:b.id,message:b,speed:q.speed,duration:q.duration})}}let Ke=le||Vr;c.classList.toggle("persona-pill-peek--visible",Ke)};if($()){let c=Oe.peekBanner;if(c){let b=M=>{M.preventDefault(),M.stopPropagation(),Rt(!0,"user")};c.addEventListener("pointerdown",b),gt.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{Vr||(Vr=!0,Lr())},y=()=>{Vr&&(Vr=!1,Lr())};z.addEventListener("pointerenter",m),z.addEventListener("pointerleave",y),gt.push(()=>{z.removeEventListener("pointerenter",m),z.removeEventListener("pointerleave",y)}),xe&&(xe.addEventListener("pointerenter",m),xe.addEventListener("pointerleave",y),gt.push(()=>{xe.removeEventListener("pointerenter",m),xe.removeEventListener("pointerleave",y)}))}let ea=c=>{var ue,ve,Ne,Ye,Ke,ot,st,Te;let m=(ve=(ue=r.launcher)==null?void 0:ue.composerBar)!=null?ve:{},y=(Ne=m.expandedSize)!=null?Ne:"anchored",b=(Ye=m.bottomOffset)!=null?Ye:"16px",M=m.collapsedMaxWidth,H=(Ke=m.expandedMaxWidth)!=null?Ke:"880px",N=(ot=m.expandedTopOffset)!=null?ot:"5vh",q=(st=m.modalMaxWidth)!=null?st:"880px",I=(Te=m.modalMaxHeight)!=null?Te:"min(90vh, 800px)",ye="calc(100vw - 32px)",ie="var(--persona-pill-area-height, 80px)",Z=K.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",xe){let Ee=xe.style;Ee.bottom=b,Ee.width=M!=null?M:""}if(c&&y!=="fullscreen"){if(y==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=q,Z.maxWidth=ye,Z.maxHeight=I,Z.height=I;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${b} + ${ie})`,Z.top=N,Z.width=H,Z.maxWidth=ye}},Jr=()=>{var I,ye,ie,Z,ue,ve,Ne,Ye;if(!j())return;if($()){let ot=(ie=((ye=(I=r.launcher)==null?void 0:I.composerBar)!=null?ye:{}).expandedSize)!=null?ie:"anchored",st=W?"expanded":"collapsed";K.dataset.state=st,K.dataset.expandedSize=ot,xe&&(xe.dataset.state=st,xe.dataset.expandedSize=ot),K.style.removeProperty("display"),K.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ea(W),ne.style.display=W?"flex":"none",Zn(),W?(Xs(),Ys()):(is(),ls()),Lr();return}let c=on(r),m=(Z=e.ownerDocument.defaultView)!=null?Z:window,y=(ve=(ue=r.launcher)==null?void 0:ue.mobileBreakpoint)!=null?ve:640,b=(Ye=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Ye:!0,M=m.innerWidth<=y,H=b&&M&&A,N=lr(r).reveal;W?(K.style.removeProperty("display"),K.style.display=c?"flex":"",K.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-95","persona-opacity-0"),z.classList.add("persona-scale-100","persona-opacity-100"),R?R.element.style.display="none":w&&(w.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!H?(K.style.removeProperty("display"),K.style.display="flex",K.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(K.style.setProperty("display","none","important"),K.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(K.style.display="",K.classList.add("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-100","persona-opacity-100"),z.classList.add("persona-scale-95","persona-opacity-0")),R?R.element.style.display=c?"none":"":w&&(w.style.display=c?"none":""))},Rt=(c,m="user")=>{var H,N;if(!j()||W===c)return;let y=W;W=c,Jr();let b=(()=>{var Ne,Ye,Ke,ot,st,Te,Ee,Ue,E,we;let q=(Ye=(Ne=r.launcher)==null?void 0:Ne.sidebarMode)!=null?Ye:!1,I=(Ke=e.ownerDocument.defaultView)!=null?Ke:window,ye=(st=(ot=r.launcher)==null?void 0:ot.mobileFullscreen)!=null?st:!0,ie=(Ee=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?Ee:640,Z=I.innerWidth<=ie,ue=on(r)&&ye&&Z,ve=$()&&((we=(E=(Ue=r.launcher)==null?void 0:Ue.composerBar)==null?void 0:E.expandedSize)!=null?we:"fullscreen")==="fullscreen";return q||ye&&Z&&A||ue||ve})();if(W&&b){if(!Kt){let q=e.getRootNode(),I=q instanceof ShadowRoot?q.host:e.closest(".persona-host");I&&(Kt=Ci(I,(N=(H=r.launcher)==null?void 0:H.zIndex)!=null?N:fn))}Gt||(Gt=wi(e.ownerDocument))}else W||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null);W&&(G(),Ur(!0));let M={open:W,source:m,timestamp:Date.now()};W&&!y?s.emit("widget:opened",M):!W&&y&&s.emit("widget:closed",M),s.emit("widget:state",{open:W,launcherEnabled:A,voiceActive:ut.active,streaming:_.isStreaming()})},Io=c=>{Ut(c?"stop":"send"),P&&(P.disabled=c),er.buttons.forEach(m=>{m.disabled=c}),$e.dataset.personaComposerStreaming=c?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},Wo=()=>{ut.active||Le&&Le.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Wo(),200)});let ds=()=>{var y,b,M,H,N,q,I,ye,ie,Z,ue;vr.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",dr.textContent=(H=(M=r.copy)==null?void 0:M.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",Le.placeholder=(q=(N=r.copy)==null?void 0:N.inputPlaceholder)!=null?q:"How can I help...";let c=Se.querySelector("[data-persona-intro-card]");if(c){let ve=((I=r.copy)==null?void 0:I.showWelcomeCard)!==!1;c.style.display=ve?"":"none",ve?(Se.classList.remove("persona-gap-3"),Se.classList.add("persona-gap-6")):(Se.classList.remove("persona-gap-6"),Se.classList.add("persona-gap-3"))}!((ie=(ye=r.sendButton)==null?void 0:ye.useIcon)!=null&&ie)&&!(_!=null&&_.isStreaming())&&(te.textContent=(ue=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?ue:"Send"),Le.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Le.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{g(m=>({...m,sessionId:c}))}});let hr=null,ta=()=>{hr==null&&(hr=setInterval(()=>{let c=be.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(hr),hr=null;return}let m=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=pa(m-b))})},100))};if(_=new Ss(r,{onMessagesChanged(c){po(be,c,Pe),ta(),_&&(c.some(M=>M.role==="user")?er.render([],_,Le,c):er.render(r.suggestionChips,_,Le,c,r.suggestionChipsConfig)),Ur(!le),Qs(c);let m=[...c].reverse().find(b=>b.role==="user"),y=ut.lastUserMessageId;m&&m.id!==y&&(ut.lastUserMessageId=m.id,s.emit("user:message",m)),ut.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Po(c),Lr()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};Fe(Vt,(M=>{var H,N,q,I;return M==="idle"?(H=m.idleText)!=null?H:gn.idle:M==="connecting"?(N=m.connectingText)!=null?N:gn.connecting:M==="connected"?(q=m.connectedText)!=null?q:gn.connected:M==="error"?(I=m.errorText)!=null?I:gn.error:gn[M]})(c),m,c)},onStreamingChanged(c){le=c,Io(c),_&&po(be,_.getMessages(),Pe),c||Ur(!0),Lr()},onVoiceStatusChanged(c){var m,y;if(((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":ar(),ra();break;case"speaking":ar(),oa();break;default:c==="idle"&&_.isBargeInActive()?(ar(),Kr(),P==null||P.setAttribute("aria-label","End voice session")):(ut.active=!1,ar(),Jn("system"),En());break}},onArtifactsState(c){Wn=c,Bn(),Po()}}),kt.current=_,((Jl=(Vl=r.voiceRecognition)==null?void 0:Vl.provider)==null?void 0:Jl.type)==="runtype")try{_.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&_.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(Q||r.onSSEEvent)&&_.setSSEEventCallback((c,m)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,m),Q==null||Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),l&&l.then(c=>{var m,y,b;c&&(c.metadata&&(d=Ki(c.metadata),T.syncFromMetadata()),(m=c.messages)!=null&&m.length&&_.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&_.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ps=()=>{var m,y,b;!$()||W||!((b=(y=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Rt(!0,"auto")},us=c=>{var M;if(c.preventDefault(),_.isStreaming()){_.cancel();return}let m=Le.value.trim(),y=(M=vt==null?void 0:vt.hasAttachments())!=null?M:!1;if(!m&&!y)return;ps();let b;y&&(b=[],b.push(...vt.getContentParts()),m&&b.push(ya(m))),Le.value="",Le.style.height="auto",_.sendMessage(m,{contentParts:b}),y&&vt.clearAttachments()},ms=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),te.click())},gs=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!vt)return;let m=ky(c.clipboardData);m.length!==0&&(c.preventDefault(),await vt.handleFiles(m))},bn=null,On=!1,Pr=null,tt=null,fs=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,uo=(c="user")=>{var H,N,q,I,ye,ie,Z;if(On||_.isStreaming())return;let m=fs();if(!m)return;bn=new m;let b=(N=((H=r.voiceRecognition)!=null?H:{}).pauseDuration)!=null?N:2e3;bn.continuous=!0,bn.interimResults=!0,bn.lang="en-US";let M=Le.value;bn.onresult=ue=>{let ve="",Ne="";for(let Ke=0;Ke<ue.results.length;Ke++){let ot=ue.results[Ke],st=ot[0].transcript;ot.isFinal?ve+=st+" ":Ne=st}let Ye=M+ve+Ne;Le.value=Ye,Pr&&clearTimeout(Pr),(ve||Ne)&&(Pr=window.setTimeout(()=>{let Ke=Le.value.trim();Ke&&bn&&On&&(sr(),Le.value="",Le.style.height="auto",_.sendMessage(Ke,{viaVoice:!0}))},b))},bn.onerror=ue=>{ue.error!=="no-speech"&&sr()},bn.onend=()=>{if(On){let ue=Le.value.trim();ue&&ue!==M.trim()&&(Le.value="",Le.style.height="auto",_.sendMessage(ue,{viaVoice:!0})),sr()}};try{if(bn.start(),On=!0,ut.active=!0,c!=="system"&&(ut.manuallyDeactivated=!1),Jn(c),En(),P){let ue=(q=r.voiceRecognition)!=null?q:{};tt={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor,iconName:(I=ue.iconName)!=null?I:"mic",iconSize:parseFloat((Z=(ie=ue.iconSize)!=null?ie:(ye=r.sendButton)==null?void 0:ye.size)!=null?Z:"40")||24};let ve=ue.recordingBackgroundColor,Ne=ue.recordingIconColor,Ye=ue.recordingBorderColor;if(P.classList.add("persona-voice-recording"),P.style.backgroundColor=ve!=null?ve:"var(--persona-voice-recording-bg, #ef4444)",P.style.color=Ne!=null?Ne:"var(--persona-voice-recording-indicator, #ffffff)",Ne){let Ke=P.querySelector("svg");Ke&&Ke.setAttribute("stroke",Ne)}Ye&&(P.style.borderColor=Ye),P.setAttribute("aria-label","Stop voice recognition")}}catch{sr("system")}},sr=(c="user")=>{if(On){if(On=!1,Pr&&(clearTimeout(Pr),Pr=null),bn){try{bn.stop()}catch{}bn=null}if(ut.active=!1,Jn(c),En(),P){if(P.classList.remove("persona-voice-recording"),tt){P.style.backgroundColor=tt.backgroundColor,P.style.color=tt.color,P.style.borderColor=tt.borderColor;let m=P.querySelector("svg");m&&m.setAttribute("stroke",tt.color||"currentColor"),tt=null}P.setAttribute("aria-label","Start voice recognition")}}},na=(c,m)=>{var ot,st,Te,Ee,Ue,E,we,Ie;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((ot=c==null?void 0:c.provider)==null?void 0:ot.type)==="runtype";if(!(y||b))return null;let H=h("div","persona-send-button-wrapper"),N=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let q=(st=c==null?void 0:c.iconName)!=null?st:"mic",I=(Te=m==null?void 0:m.size)!=null?Te:"40px",ye=(Ee=c==null?void 0:c.iconSize)!=null?Ee:I,ie=parseFloat(ye)||24,Z=(Ue=c==null?void 0:c.backgroundColor)!=null?Ue:m==null?void 0:m.backgroundColor,ue=(E=c==null?void 0:c.iconColor)!=null?E:m==null?void 0:m.textColor;N.style.width=ye,N.style.height=ye,N.style.minWidth=ye,N.style.minHeight=ye,N.style.fontSize="18px",N.style.lineHeight="1",ue?N.style.color=ue:N.style.color="var(--persona-text, #111827)";let Ne=ge(q,ie,ue||"currentColor",1.5);Ne?N.appendChild(Ne):N.textContent="\u{1F3A4}",Z?N.style.backgroundColor=Z:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),H.appendChild(N);let Ye=(we=c==null?void 0:c.tooltipText)!=null?we:"Start voice recognition";if(((Ie=c==null?void 0:c.showTooltip)!=null?Ie:!1)&&Ye){let ze=h("div","persona-send-button-tooltip");ze.textContent=Ye,H.appendChild(ze)}return{micButton:N,micButtonWrapper:H}},Ro=()=>{var m,y,b,M,H;if(!P||tt)return;let c=(m=r.voiceRecognition)!=null?m:{};tt={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((H=(M=c.iconSize)!=null?M:(b=r.sendButton)==null?void 0:b.size)!=null?H:"40")||24}},Ho=(c,m)=>{var H,N,q,I,ye;if(!P)return;let y=P.querySelector("svg");y&&y.remove();let b=(ye=tt==null?void 0:tt.iconSize)!=null?ye:parseFloat((I=(q=(H=r.voiceRecognition)==null?void 0:H.iconSize)!=null?q:(N=r.sendButton)==null?void 0:N.size)!=null?I:"40")||24,M=ge(c,b,m,1.5);M&&P.appendChild(M)},mo=()=>{P&&P.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Kr=()=>{var M;if(!P)return;Ro();let c=(M=r.voiceRecognition)!=null?M:{},m=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(mo(),P.classList.add("persona-voice-recording"),P.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",P.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let H=P.querySelector("svg");H&&H.setAttribute("stroke",y)}b&&(P.style.borderColor=b),P.setAttribute("aria-label","Stop voice recognition")},ra=()=>{var q,I,ye,ie,Z,ue,ve,Ne;if(!P)return;Ro();let c=(q=r.voiceRecognition)!=null?q:{},m=_.getVoiceInterruptionMode(),y=(I=c.processingIconName)!=null?I:"loader",b=(ie=(ye=c.processingIconColor)!=null?ye:tt==null?void 0:tt.color)!=null?ie:"",M=(ue=(Z=c.processingBackgroundColor)!=null?Z:tt==null?void 0:tt.backgroundColor)!=null?ue:"",H=(Ne=(ve=c.processingBorderColor)!=null?ve:tt==null?void 0:tt.borderColor)!=null?Ne:"";mo(),P.classList.add("persona-voice-processing"),P.style.backgroundColor=M,P.style.borderColor=H;let N=b||"currentColor";P.style.color=N,Ho(y,N),P.setAttribute("aria-label","Processing voice input"),m==="none"&&(P.style.cursor="default")},oa=()=>{var ye,ie,Z,ue,ve,Ne,Ye,Ke,ot,st,Te,Ee;if(!P)return;Ro();let c=(ye=r.voiceRecognition)!=null?ye:{},m=_.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(ie=c.speakingIconName)!=null?ie:y,M=(Ne=c.speakingIconColor)!=null?Ne:m==="barge-in"?(ue=(Z=c.recordingIconColor)!=null?Z:tt==null?void 0:tt.color)!=null?ue:"":(ve=tt==null?void 0:tt.color)!=null?ve:"",H=(ot=c.speakingBackgroundColor)!=null?ot:m==="barge-in"?(Ye=c.recordingBackgroundColor)!=null?Ye:"var(--persona-voice-recording-bg, #ef4444)":(Ke=tt==null?void 0:tt.backgroundColor)!=null?Ke:"",N=(Ee=c.speakingBorderColor)!=null?Ee:m==="barge-in"?(st=c.recordingBorderColor)!=null?st:"":(Te=tt==null?void 0:tt.borderColor)!=null?Te:"";mo(),P.classList.add("persona-voice-speaking"),P.style.backgroundColor=H,P.style.borderColor=N;let q=M||"currentColor";P.style.color=q,Ho(b,q);let I=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";P.setAttribute("aria-label",I),m==="none"&&(P.style.cursor="default"),m==="barge-in"&&P.classList.add("persona-voice-recording")},ar=()=>{var c,m,y;P&&(mo(),tt&&(P.style.backgroundColor=(c=tt.backgroundColor)!=null?c:"",P.style.color=(m=tt.color)!=null?m:"",P.style.borderColor=(y=tt.borderColor)!=null?y:"",Ho(tt.iconName,tt.color||"currentColor"),tt=null),P.style.cursor="",P.setAttribute("aria-label","Start voice recognition"))},go=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let y=_.getVoiceStatus(),b=_.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{ut.active=!1,ut.manuallyDeactivated=!0,En(),Jn("user"),ar()});return}_.toggleVoice().then(()=>{ut.active=_.isVoiceActive(),ut.manuallyDeactivated=!_.isVoiceActive(),En(),Jn("user"),_.isVoiceActive()?Kr():ar()});return}if(On){let y=Le.value.trim();ut.manuallyDeactivated=!0,En(),sr("user"),y&&(Le.value="",Le.style.height="auto",_.sendMessage(y))}else ut.manuallyDeactivated=!1,En(),uo("user")};pr=go,P&&(P.addEventListener("click",go),gt.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),ar()):sr("system"),P&&P.removeEventListener("click",go)}));let Bo=s.on("assistant:complete",()=>{os&&(ut.active||ut.manuallyDeactivated||os==="assistant"&&!ut.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!ut.active&&!ut.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?_.toggleVoice().then(()=>{ut.active=_.isVoiceActive(),Jn("auto"),_.isVoiceActive()&&Kr()}):uo("auto"))},600))});gt.push(Bo);let Ve=s.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});gt.push(Ve);let v=()=>{Rt(!W,"user")},R=null,w=null;if(A&&!$()){let c=o.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:r,defaultRenderer:()=>Ds(r,v).element,onToggle:v});m&&(w=m)}w||(R=Ds(r,v))}R?e.appendChild(R.element):w&&e.appendChild(w),Jr(),er.render(r.suggestionChips,_,Le,void 0,r.suggestionChipsConfig),ds(),Io(_.isStreaming()),Ur(!0),Vs(),B&&(!A||$()?setTimeout(()=>Wo(),0):W&&setTimeout(()=>Wo(),200));let G=()=>{var I,ye,ie,Z,ue,ve,Ne,Ye,Ke,ot,st,Te,Ee,Ue,E,we,Ie,ze,he,Tt,rt,Qt;if($()){jn(),Jr();return}let c=on(r),m=(ye=(I=r.launcher)==null?void 0:I.sidebarMode)!=null?ye:!1,y=c||m||((Z=(ie=r.launcher)==null?void 0:ie.fullHeight)!=null?Z:!1),b=(ue=e.ownerDocument.defaultView)!=null?ue:window,M=(Ne=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Ne:!0,H=(Ke=(Ye=r.launcher)==null?void 0:Ye.mobileBreakpoint)!=null?Ke:640,N=b.innerWidth<=H,q=M&&N&&A;try{if(q){Zn(),So(e,r);return}if(F&&(F=!1,Zn(),So(e,r)),!A&&!c){z.style.height="",z.style.width="";return}if(!m&&!c){let cn=(st=(ot=r==null?void 0:r.launcher)==null?void 0:ot.width)!=null?st:r==null?void 0:r.launcherWidth,Pt=cn!=null?cn:Gn;z.style.width=Pt,z.style.maxWidth=Pt}if(gr(),!y){let cn=b.innerHeight,Pt=64,xn=(Ee=(Te=r.launcher)==null?void 0:Te.heightOffset)!=null?Ee:0,dn=Math.max(200,cn-Pt),Qe=Math.min(640,dn),at=Math.max(200,Qe-xn);z.style.height=`${at}px`}}finally{if(jn(),Jr(),W&&A){let Pt=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((we=(E=r.launcher)==null?void 0:E.mobileBreakpoint)!=null?we:640),xn=(ze=(Ie=r.launcher)==null?void 0:Ie.sidebarMode)!=null?ze:!1,dn=(Tt=(he=r.launcher)==null?void 0:he.mobileFullscreen)!=null?Tt:!0,Qe=on(r)&&dn&&Pt,at=xn||dn&&Pt&&A||Qe;if(at&&!Gt){let vn=e.getRootNode(),un=vn instanceof ShadowRoot?vn.host:e.closest(".persona-host");un&&!Kt&&(Kt=Ci(un,(Qt=(rt=r.launcher)==null?void 0:rt.zIndex)!=null?Qt:fn)),Gt=wi(e.ownerDocument)}else at||(Kt==null||Kt(),Kt=null,Gt==null||Gt(),Gt=null)}}};G();let re=(Kl=e.ownerDocument.defaultView)!=null?Kl:window;if(re.addEventListener("resize",G),gt.push(()=>re.removeEventListener("resize",G)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{jn()});c.observe($e),gt.push(()=>c.disconnect())}rr=Se.scrollTop;let X=Se.scrollHeight,Je=()=>{let c=Se.scrollTop,m=Se.scrollHeight,y=m<X;X=m;let{action:b,nextLastScrollTop:M}=Ta({following:nr.isFollowing(),currentScrollTop:c,lastScrollTop:rr,nearBottom:Ls(Se,rs),userScrollThreshold:qs,isAutoScrolling:Tr||lo||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(rr=M,b==="resume"){jr();return}b==="pause"&&as()};Se.addEventListener("scroll",Je,{passive:!0}),gt.push(()=>Se.removeEventListener("scroll",Je));let De=c=>{let m=Ma({following:nr.isFollowing(),deltaY:c.deltaY,nearBottom:Ls(Se,rs),resumeWhenNearBottom:!0});m==="pause"?as():m==="resume"&&jr()};Se.addEventListener("wheel",De,{passive:!0}),gt.push(()=>Se.removeEventListener("wheel",De)),pt.addEventListener("click",()=>{Se.scrollTop=Se.scrollHeight,rr=Se.scrollTop,jr(),Ur(!0)}),gt.push(()=>pt.remove()),gt.push(()=>{ss()});let nt=()=>{je&&(Nn&&(je.removeEventListener("click",Nn),Nn=null),j()?(je.style.display="",Nn=()=>{Rt(!1,"user")},je.addEventListener("click",Nn)):je.style.display="none")};nt(),(()=>{let{clearChatButton:c}=Oe;c&&c.addEventListener("click",()=>{_.clearMessages(),Fn.clear(),jr(),Mo(Oe.composerOverlay);try{localStorage.removeItem(es),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},T.syncFromMetadata(),Q==null||Q.clear(),ae==null||ae.update()})})(),Nt&&Nt.addEventListener("submit",us),Le==null||Le.addEventListener("keydown",ms),Le==null||Le.addEventListener("paste",gs);let St="persona-attachment-drop-active",Lt=0,Yt=()=>{Lt=0,ne.classList.remove(St)},ft=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&vt!==null},Et=c=>{!Qa(c.dataTransfer)||!ft()||(Lt++,Lt===1&&ne.classList.add(St))},tn=c=>{!Qa(c.dataTransfer)||!ft()||(Lt--,Lt<=0&&Yt())},pn=c=>{!Qa(c.dataTransfer)||!ft()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},ln=c=>{var y;if(!Qa(c.dataTransfer)||!ft())return;c.preventDefault(),c.stopPropagation(),Yt();let m=Array.from((y=c.dataTransfer.files)!=null?y:[]);m.length!==0&&vt.handleFiles(m)},Ft=!0;ne.addEventListener("dragenter",Et,Ft),ne.addEventListener("dragleave",tn,Ft),e.addEventListener("dragover",pn,Ft),e.addEventListener("drop",ln,Ft);let Tn=e.ownerDocument,al=c=>{ft()&&c.preventDefault()},il=c=>{ft()&&c.preventDefault()};Tn.addEventListener("dragover",al),Tn.addEventListener("drop",il),gt.push(()=>{Nt&&Nt.removeEventListener("submit",us),Le==null||Le.removeEventListener("keydown",ms),Le==null||Le.removeEventListener("paste",gs)}),gt.push(()=>{ne.removeEventListener("dragenter",Et,Ft),ne.removeEventListener("dragleave",tn,Ft),e.removeEventListener("dragover",pn,Ft),e.removeEventListener("drop",ln,Ft),Tn.removeEventListener("dragover",al),Tn.removeEventListener("drop",il),Yt()}),gt.push(()=>{_.cancel()}),R?gt.push(()=>{R==null||R.destroy()}):w&&gt.push(()=>{w==null||w.remove()});let Zt={update(c){var en,yr,Wr,sa,aa,ia,xo,la,hs,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,Cc,wc,Ac,Sc,Ec,Tc,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,jc,Uc,qc,zc,Vc,Jc,Kc,Gc,Qc,Xc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,Cd,wd,Ad,Sd,Ed,Td,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,$d,_d,jd,Ud,qd,zd,Vd,Jd,Kd,Gd,Qd;let m=r.toolCall,y=r.messageActions,b=(en=r.layout)==null?void 0:en.messages,M=r.colorScheme,H=r.loadingIndicator,N=r.iterationDisplay,q=(yr=r.features)==null?void 0:yr.showReasoning,I=(Wr=r.features)==null?void 0:Wr.showToolCalls,ye=(sa=r.features)==null?void 0:sa.toolCallDisplay,ie=(aa=r.features)==null?void 0:aa.reasoningDisplay;r={...r,...c},Zn(),So(e,r),za(e,r),Va(e,r),Bn(),r.colorScheme!==M&&_r();let Z=Ja.getForInstance(r.plugins);o.length=0,o.push(...Z),A=(xo=(ia=r.launcher)==null?void 0:ia.enabled)!=null?xo:!0,k=(hs=(la=r.launcher)==null?void 0:la.autoExpand)!=null?hs:!1,ke=(nc=(tc=r.features)==null?void 0:tc.showReasoning)!=null?nc:!0,Ge=(oc=(rc=r.features)==null?void 0:rc.showToolCalls)!=null?oc:!0,pe=(ac=(sc=r.features)==null?void 0:sc.scrollToBottom)!=null?ac:{},Br(),kr();let ue=de;if(de=(lc=(ic=r.features)==null?void 0:ic.showEventStreamToggle)!=null?lc:!1,de&&!ue){if(Q||(ee=new Us(_e),Q=new js(Ae,ee),ee.open().then(()=>Q==null?void 0:Q.restore()).catch(()=>{}),_.setSSEEventCallback((Y,xt)=>{var Ot;(Ot=r.onSSEEvent)==null||Ot.call(r,Y,xt),Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(xt)})})),!mt&&Be){let Y=(dc=(cc=r.features)==null?void 0:cc.eventStream)==null?void 0:dc.classNames,xt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Y!=null&&Y.toggleButton?" "+Y.toggleButton:"");mt=h("button",xt),mt.style.width="28px",mt.style.height="28px",mt.style.color=An.actionIconColor,mt.type="button",mt.setAttribute("aria-label","Event Stream"),mt.title="Event Stream";let Ot=ge("activity","18px","currentColor",1.5);Ot&&mt.appendChild(Ot);let it=Oe.clearChatButtonWrapper,At=Oe.closeButtonWrapper,nn=it||At;nn&&nn.parentNode===Be?Be.insertBefore(mt,nn):Be.appendChild(mt),mt.addEventListener("click",()=>{Re?Yn():wr()})}}else!de&&ue&&(Yn(),mt&&(mt.remove(),mt=null),Q==null||Q.clear(),ee==null||ee.destroy(),Q=null,ee=null);if(((pc=r.launcher)==null?void 0:pc.enabled)===!1&&R&&(R.destroy(),R=null),((uc=r.launcher)==null?void 0:uc.enabled)===!1&&w&&(w.remove(),w=null),((mc=r.launcher)==null?void 0:mc.enabled)!==!1&&!R&&!w){let Y=o.find(xt=>xt.renderLauncher);if(Y!=null&&Y.renderLauncher){let xt=Y.renderLauncher({config:r,defaultRenderer:()=>Ds(r,v).element,onToggle:v});xt&&(w=xt,e.appendChild(w))}w||(R=Ds(r,v),e.appendChild(R.element))}R&&R.update(r),Ce&&((gc=r.launcher)==null?void 0:gc.title)!==void 0&&(Ce.textContent=r.launcher.title),He&&((fc=r.launcher)==null?void 0:fc.subtitle)!==void 0&&(He.textContent=r.launcher.subtitle);let ve=(hc=r.layout)==null?void 0:hc.header;if((ve==null?void 0:ve.layout)!==S&&Be){let Y=ve?Ns(r,ve,{showClose:j(),onClose:()=>Rt(!1,"user")}):Zr({config:r,showClose:j(),onClose:()=>Rt(!1,"user")});Be.replaceWith(Y.header),Be=Y.header,U=Y.iconHolder,Ce=Y.headerTitle,He=Y.headerSubtitle,je=Y.closeButton,S=ve==null?void 0:ve.layout}else if(ve&&(U&&(U.style.display=ve.showIcon===!1?"none":""),Ce&&(Ce.style.display=ve.showTitle===!1?"none":""),He&&(He.style.display=ve.showSubtitle===!1?"none":""),je&&(je.style.display=ve.showCloseButton===!1?"none":""),Oe.clearChatButtonWrapper)){let Y=ve.showClearChat;if(Y!==void 0){Oe.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:xt}=Oe;xt&&!xt.classList.contains("persona-absolute")&&(Y?xt.classList.remove("persona-ml-auto"):xt.classList.add("persona-ml-auto"))}}let Ye=((yc=r.layout)==null?void 0:yc.showHeader)!==!1;Be&&(Be.style.display=Ye?"":"none");let Ke=((bc=r.layout)==null?void 0:bc.showFooter)!==!1;$e&&($e.style.display=Ke?"":"none"),jn(),kr(),A!==L?A?Rt(k,"auto"):(W=!0,Jr()):k!==D&&Rt(k,"auto"),D=k,L=A,G(),nt();let Te=JSON.stringify(c.toolCall)!==JSON.stringify(m),Ee=JSON.stringify(r.messageActions)!==JSON.stringify(y),Ue=JSON.stringify((xc=r.layout)==null?void 0:xc.messages)!==JSON.stringify(b),E=((vc=r.loadingIndicator)==null?void 0:vc.render)!==(H==null?void 0:H.render)||((Cc=r.loadingIndicator)==null?void 0:Cc.renderIdle)!==(H==null?void 0:H.renderIdle)||((wc=r.loadingIndicator)==null?void 0:wc.showBubble)!==(H==null?void 0:H.showBubble),we=r.iterationDisplay!==N,Ie=((Sc=(Ac=r.features)==null?void 0:Ac.showReasoning)!=null?Sc:!0)!==(q!=null?q:!0)||((Tc=(Ec=r.features)==null?void 0:Ec.showToolCalls)!=null?Tc:!0)!==(I!=null?I:!0)||JSON.stringify((Mc=r.features)==null?void 0:Mc.toolCallDisplay)!==JSON.stringify(ye)||JSON.stringify((kc=r.features)==null?void 0:kc.reasoningDisplay)!==JSON.stringify(ie);(Te||Ee||Ue||E||we||Ie)&&_&&(ns++,po(be,_.getMessages(),Pe));let he=(Lc=r.launcher)!=null?Lc:{},Tt=(Pc=he.headerIconHidden)!=null?Pc:!1,rt=(Wc=(Ic=r.layout)==null?void 0:Ic.header)==null?void 0:Wc.showIcon,Qt=Tt||rt===!1,cn=he.headerIconName,Pt=(Rc=he.headerIconSize)!=null?Rc:"48px";if(U){let Y=ne.querySelector(".persona-border-b-persona-divider"),xt=Y==null?void 0:Y.querySelector(".persona-flex-col");if(Qt)U.style.display="none",Y&&xt&&!Y.contains(xt)&&Y.insertBefore(xt,Y.firstChild);else{if(U.style.display="",U.style.height=Pt,U.style.width=Pt,Y&&xt&&(Y.contains(U)?U.nextSibling!==xt&&(U.remove(),Y.insertBefore(U,xt)):Y.insertBefore(U,xt)),cn){let it=parseFloat(Pt)||24,At=ge(cn,it*.6,"#ffffff",2);At?U.replaceChildren(At):U.textContent=(Hc=he.agentIconText)!=null?Hc:"\u{1F4AC}"}else if(he.iconUrl){let it=U.querySelector("img");if(it)it.src=he.iconUrl,it.style.height=Pt,it.style.width=Pt;else{let At=document.createElement("img");At.src=he.iconUrl,At.alt="",At.className="persona-rounded-xl persona-object-cover",At.style.height=Pt,At.style.width=Pt,U.replaceChildren(At)}}else{let it=U.querySelector("svg"),At=U.querySelector("img");(it||At)&&U.replaceChildren(),U.textContent=(Bc=he.agentIconText)!=null?Bc:"\u{1F4AC}"}let Ot=U.querySelector("img");Ot&&(Ot.style.height=Pt,Ot.style.width=Pt)}}let xn=(Nc=(Dc=r.layout)==null?void 0:Dc.header)==null?void 0:Nc.showTitle,dn=(Oc=(Fc=r.layout)==null?void 0:Fc.header)==null?void 0:Oc.showSubtitle;if(Ce&&(Ce.style.display=xn===!1?"none":""),He&&(He.style.display=dn===!1?"none":""),je){((_c=($c=r.layout)==null?void 0:$c.header)==null?void 0:_c.showCloseButton)===!1?je.style.display="none":je.style.display="";let xt=(jc=he.closeButtonSize)!=null?jc:"32px",Ot=(Uc=he.closeButtonPlacement)!=null?Uc:"inline";je.style.height=xt,je.style.width=xt;let{closeButtonWrapper:it}=Oe,At=Ot==="top-right",nn=it==null?void 0:it.classList.contains("persona-absolute");if(it&&At!==nn)if(it.remove(),At)it.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ne.style.position="relative",ne.appendChild(it);else{let dt=(zc=(qc=he.clearChat)==null?void 0:qc.placement)!=null?zc:"inline",rn=(Jc=(Vc=he.clearChat)==null?void 0:Vc.enabled)!=null?Jc:!0;it.className=rn&&dt==="inline"?"":"persona-ml-auto";let Pn=ne.querySelector(".persona-border-b-persona-divider");Pn&&Pn.appendChild(it)}if(je.style.color=he.closeButtonColor||An.actionIconColor,he.closeButtonBackgroundColor?(je.style.backgroundColor=he.closeButtonBackgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let dt=he.closeButtonBorderWidth||"0px",rn=he.closeButtonBorderColor||"transparent";je.style.border=`${dt} solid ${rn}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");he.closeButtonBorderRadius?(je.style.borderRadius=he.closeButtonBorderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(je.style.paddingLeft=he.closeButtonPaddingX,je.style.paddingRight=he.closeButtonPaddingX):(je.style.paddingLeft="",je.style.paddingRight=""),he.closeButtonPaddingY?(je.style.paddingTop=he.closeButtonPaddingY,je.style.paddingBottom=he.closeButtonPaddingY):(je.style.paddingTop="",je.style.paddingBottom="");let mn=(Kc=he.closeButtonIconName)!=null?Kc:"x",ir=(Gc=he.closeButtonIconText)!=null?Gc:"\xD7";je.innerHTML="";let wn=ge(mn,"28px","currentColor",1);wn?je.appendChild(wn):je.textContent=ir;let Xt=(Qc=he.closeButtonTooltipText)!=null?Qc:"Close chat",_n=(Xc=he.closeButtonShowTooltip)!=null?Xc:!0;if(je.setAttribute("aria-label",Xt),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),_n&&Xt)){let dt=null,rn=()=>{if(dt||!je)return;let vo=je.ownerDocument,ys=vo.body;if(!ys)return;dt=br(vo,"div","persona-clear-chat-tooltip"),dt.textContent=Xt;let bs=br(vo,"div");bs.className="persona-clear-chat-tooltip-arrow",dt.appendChild(bs);let Co=je.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Qr),dt.style.left=`${Co.left+Co.width/2}px`,dt.style.top=`${Co.top-8}px`,dt.style.transform="translate(-50%, -100%)",ys.appendChild(dt)},Pn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};it.addEventListener("mouseenter",rn),it.addEventListener("mouseleave",Pn),je.addEventListener("focus",rn),je.addEventListener("blur",Pn),it._cleanupTooltip=()=>{Pn(),it&&(it.removeEventListener("mouseenter",rn),it.removeEventListener("mouseleave",Pn)),je&&(je.removeEventListener("focus",rn),je.removeEventListener("blur",Pn))}}}let{clearChatButton:Qe,clearChatButtonWrapper:at}=Oe;if(Qe){let Y=(Yc=he.clearChat)!=null?Yc:{},xt=(Zc=Y.enabled)!=null?Zc:!0,Ot=(td=(ed=r.layout)==null?void 0:ed.header)==null?void 0:td.showClearChat,it=Ot!==void 0?Ot:xt,At=(nd=Y.placement)!=null?nd:"inline";if(at){at.style.display=it?"":"none";let{closeButtonWrapper:nn}=Oe;!$()&&nn&&!nn.classList.contains("persona-absolute")&&(it?nn.classList.remove("persona-ml-auto"):nn.classList.add("persona-ml-auto"));let mn=At==="top-right",ir=at.classList.contains("persona-absolute");if(!$()&&mn!==ir&&it){if(at.remove(),mn)at.className="persona-absolute persona-top-4 persona-z-50",at.style.right="48px",ne.style.position="relative",ne.appendChild(at);else{at.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",at.style.right="";let Xt=ne.querySelector(".persona-border-b-persona-divider"),_n=Oe.closeButtonWrapper;Xt&&_n&&_n.parentElement===Xt?Xt.insertBefore(at,_n):Xt&&Xt.appendChild(at)}let wn=Oe.closeButtonWrapper;wn&&!wn.classList.contains("persona-absolute")&&(mn?wn.classList.add("persona-ml-auto"):wn.classList.remove("persona-ml-auto"))}}if(it){if(!$()){let dt=(rd=Y.size)!=null?rd:"32px";Qe.style.height=dt,Qe.style.width=dt}let nn=(od=Y.iconName)!=null?od:"refresh-cw",mn=(sd=Y.iconColor)!=null?sd:"";Qe.style.color=mn||An.actionIconColor,Qe.innerHTML="";let ir=$()?"14px":"20px",wn=ge(nn,ir,"currentColor",2);if(wn&&Qe.appendChild(wn),Y.backgroundColor?(Qe.style.backgroundColor=Y.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let dt=Y.borderWidth||"0px",rn=Y.borderColor||"transparent";Qe.style.border=`${dt} solid ${rn}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");Y.borderRadius?(Qe.style.borderRadius=Y.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),Y.paddingX?(Qe.style.paddingLeft=Y.paddingX,Qe.style.paddingRight=Y.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),Y.paddingY?(Qe.style.paddingTop=Y.paddingY,Qe.style.paddingBottom=Y.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let Xt=(ad=Y.tooltipText)!=null?ad:"Clear chat",_n=(id=Y.showTooltip)!=null?id:!0;if(Qe.setAttribute("aria-label",Xt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),_n&&Xt)){let dt=null,rn=()=>{if(dt||!Qe)return;let vo=Qe.ownerDocument,ys=vo.body;if(!ys)return;dt=br(vo,"div","persona-clear-chat-tooltip"),dt.textContent=Xt;let bs=br(vo,"div");bs.className="persona-clear-chat-tooltip-arrow",dt.appendChild(bs);let Co=Qe.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Qr),dt.style.left=`${Co.left+Co.width/2}px`,dt.style.top=`${Co.top-8}px`,dt.style.transform="translate(-50%, -100%)",ys.appendChild(dt)},Pn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};at.addEventListener("mouseenter",rn),at.addEventListener("mouseleave",Pn),Qe.addEventListener("focus",rn),Qe.addEventListener("blur",Pn),at._cleanupTooltip=()=>{Pn(),at&&(at.removeEventListener("mouseenter",rn),at.removeEventListener("mouseleave",Pn)),Qe&&(Qe.removeEventListener("focus",rn),Qe.removeEventListener("blur",Pn))}}}}let vn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ka],un=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Zo.message,Zo.messageAndClick];T=Ga({parsers:vn,handlers:un,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Pe=hu(r,T,oe),_.updateConfig(r),po(be,_.getMessages(),Pe),er.render(r.suggestionChips,_,Le,void 0,r.suggestionChipsConfig),ds(),Io(_.isStreaming());let fo=((ld=r.voiceRecognition)==null?void 0:ld.enabled)===!0,ho=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),yo=((dd=(cd=r.voiceRecognition)==null?void 0:cd.provider)==null?void 0:dd.type)==="runtype";if(fo&&(ho||yo))if(!P||!fe){let Y=na(r.voiceRecognition,r.sendButton);Y&&(P=Y.micButton,fe=Y.micButtonWrapper,Ct.insertBefore(fe,sn),P.addEventListener("click",go),P.disabled=_.isStreaming())}else{let Y=(pd=r.voiceRecognition)!=null?pd:{},xt=(ud=r.sendButton)!=null?ud:{},Ot=(md=Y.iconName)!=null?md:"mic",it=(gd=xt.size)!=null?gd:"40px",At=(fd=Y.iconSize)!=null?fd:it,nn=parseFloat(At)||24;P.style.width=At,P.style.height=At,P.style.minWidth=At,P.style.minHeight=At;let mn=(yd=(hd=Y.iconColor)!=null?hd:xt.textColor)!=null?yd:"currentColor";P.innerHTML="";let ir=ge(Ot,nn,mn,2);ir?P.appendChild(ir):P.textContent="\u{1F3A4}";let wn=(bd=Y.backgroundColor)!=null?bd:xt.backgroundColor;wn?P.style.backgroundColor=wn:P.style.backgroundColor="",mn?P.style.color=mn:P.style.color="var(--persona-text, #111827)",Y.borderWidth?(P.style.borderWidth=Y.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),Y.borderColor?P.style.borderColor=Y.borderColor:P.style.borderColor="",Y.paddingX?(P.style.paddingLeft=Y.paddingX,P.style.paddingRight=Y.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),Y.paddingY?(P.style.paddingTop=Y.paddingY,P.style.paddingBottom=Y.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let Xt=fe==null?void 0:fe.querySelector(".persona-send-button-tooltip"),_n=(xd=Y.tooltipText)!=null?xd:"Start voice recognition";if(((vd=Y.showTooltip)!=null?vd:!1)&&_n)if(Xt)Xt.textContent=_n,Xt.style.display="";else{let rn=document.createElement("div");rn.className="persona-send-button-tooltip",rn.textContent=_n,fe==null||fe.insertBefore(rn,P)}else Xt&&(Xt.style.display="none");fe.style.display="",P.disabled=_.isStreaming()}else P&&fe&&(fe.style.display="none",((wd=(Cd=r.voiceRecognition)==null?void 0:Cd.provider)==null?void 0:wd.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():On&&sr());if(((Ad=r.attachments)==null?void 0:Ad.enabled)===!0)if(!ct||!me){let Y=(Sd=r.attachments)!=null?Sd:{},Ot=(Td=((Ed=r.sendButton)!=null?Ed:{}).size)!=null?Td:"40px";It||(It=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),It.style.display="none",Nt.insertBefore(It,Le)),qe||(qe=document.createElement("input"),qe.type="file",qe.accept=((Md=Y.allowedTypes)!=null?Md:Rr).join(","),qe.multiple=((kd=Y.maxFiles)!=null?kd:4)>1,qe.style.display="none",qe.setAttribute("aria-label","Attach files"),Nt.insertBefore(qe,Le)),ct=h("div","persona-send-button-wrapper"),me=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),me.type="button",me.setAttribute("aria-label",(Ld=Y.buttonTooltipText)!=null?Ld:"Attach file");let it=(Pd=Y.buttonIconName)!=null?Pd:"paperclip",At=Ot,nn=parseFloat(At)||40,mn=Math.round(nn*.6);me.style.width=At,me.style.height=At,me.style.minWidth=At,me.style.minHeight=At,me.style.fontSize="18px",me.style.lineHeight="1",me.style.backgroundColor="transparent",me.style.color="var(--persona-primary, #111827)",me.style.border="none",me.style.borderRadius="6px",me.style.transition="background-color 0.15s ease",me.addEventListener("mouseenter",()=>{me.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),me.addEventListener("mouseleave",()=>{me.style.backgroundColor="transparent"});let ir=ge(it,mn,"currentColor",1.5);ir?me.appendChild(ir):me.textContent="\u{1F4CE}",me.addEventListener("click",_n=>{_n.preventDefault(),qe==null||qe.click()}),ct.appendChild(me);let wn=(Id=Y.buttonTooltipText)!=null?Id:"Attach file",Xt=h("div","persona-send-button-tooltip");Xt.textContent=wn,ct.appendChild(Xt),et.append(ct),!vt&&qe&&It&&(vt=qo.fromConfig(Y),vt.setPreviewsContainer(It),qe.addEventListener("change",async()=>{vt&&(qe!=null&&qe.files)&&(await vt.handleFileSelect(qe.files),qe.value="")})),ne.querySelector(".persona-attachment-drop-overlay")||ne.appendChild(yu(Y.dropOverlay))}else{ct.style.display="";let Y=(Wd=r.attachments)!=null?Wd:{};qe&&(qe.accept=((Rd=Y.allowedTypes)!=null?Rd:Rr).join(","),qe.multiple=((Hd=Y.maxFiles)!=null?Hd:4)>1),vt&&vt.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else ct&&(ct.style.display="none"),vt&&vt.clearAttachments(),(Bd=ne.querySelector(".persona-attachment-drop-overlay"))==null||Bd.remove();let qt=(Dd=r.sendButton)!=null?Dd:{},bo=(Nd=qt.useIcon)!=null?Nd:!1,Gr=(Fd=qt.iconText)!=null?Fd:"\u2191",ht=qt.iconName,Mn=(Od=qt.tooltipText)!=null?Od:"Send message",Ir=($d=qt.showTooltip)!=null?$d:!1,Cn=(_d=qt.size)!=null?_d:"40px",kn=qt.backgroundColor,Bt=qt.textColor;if(bo){if(te.style.width=Cn,te.style.height=Cn,te.style.minWidth=Cn,te.style.minHeight=Cn,te.style.fontSize="18px",te.style.lineHeight="1",te.innerHTML="",Bt?te.style.color=Bt:te.style.color="var(--persona-button-primary-fg, #ffffff)",ht){let Y=parseFloat(Cn)||24,xt=(Bt==null?void 0:Bt.trim())||"currentColor",Ot=ge(ht,Y,xt,2);Ot?te.appendChild(Ot):te.textContent=Gr}else te.textContent=Gr;te.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",kn?(te.style.backgroundColor=kn,te.classList.remove("persona-bg-persona-primary")):(te.style.backgroundColor="",te.classList.add("persona-bg-persona-primary"))}else te.textContent=(Ud=(jd=r.copy)==null?void 0:jd.sendButtonLabel)!=null?Ud:"Send",te.style.width="",te.style.height="",te.style.minWidth="",te.style.minHeight="",te.style.fontSize="",te.style.lineHeight="",te.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",kn?(te.style.backgroundColor=kn,te.classList.remove("persona-bg-persona-accent")):te.classList.add("persona-bg-persona-accent"),Bt?te.style.color=Bt:te.classList.add("persona-text-white");qt.borderWidth?(te.style.borderWidth=qt.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),qt.borderColor?te.style.borderColor=qt.borderColor:te.style.borderColor="",qt.paddingX?(te.style.paddingLeft=qt.paddingX,te.style.paddingRight=qt.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),qt.paddingY?(te.style.paddingTop=qt.paddingY,te.style.paddingBottom=qt.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let _t=sn==null?void 0:sn.querySelector(".persona-send-button-tooltip");if(Ir&&Mn)if(_t)_t.textContent=Mn,_t.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=Mn,sn==null||sn.insertBefore(Y,te)}else _t&&(_t.style.display="none");let Dt=(Kd=(qd=r.layout)==null?void 0:qd.contentMaxWidth)!=null?Kd:$()?(Jd=(Vd=(zd=r.launcher)==null?void 0:zd.composerBar)==null?void 0:Vd.contentMaxWidth)!=null?Jd:"720px":void 0;Dt?(be.style.maxWidth=Dt,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%",Nt&&(Nt.style.maxWidth=Dt,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Ht&&(Ht.style.maxWidth=Dt,Ht.style.marginLeft="auto",Ht.style.marginRight="auto")):(be.style.maxWidth="",be.style.marginLeft="",be.style.marginRight="",be.style.width="",Nt&&(Nt.style.maxWidth="",Nt.style.marginLeft="",Nt.style.marginRight=""),Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""));let zt=(Gd=r.statusIndicator)!=null?Gd:{},Ln=(Qd=zt.visible)!=null?Qd:!0;if(Vt.style.display=Ln?"":"none",_){let Y=_.getStatus();Fe(Vt,(Ot=>{var it,At,nn,mn;return Ot==="idle"?(it=zt.idleText)!=null?it:gn.idle:Ot==="connecting"?(At=zt.connectingText)!=null?At:gn.connecting:Ot==="connected"?(nn=zt.connectedText)!=null?nn:gn.connected:Ot==="error"?(mn=zt.errorText)!=null?mn:gn.error:gn[Ot]})(Y),zt,Y)}Vt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let $n=zt.align==="left"?"persona-text-left":zt.align==="center"?"persona-text-center":"persona-text-right";Vt.classList.add($n)},open(){j()&&Rt(!0,"api")},close(){j()&&Rt(!1,"api")},toggle(){j()&&Rt(!W,"api")},clearChat(){hn=!1,_.clearMessages(),Fn.clear(),jr();try{localStorage.removeItem(es),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let m=i.clear();m instanceof Promise&&m.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}d={},T.syncFromMetadata(),Q==null||Q.clear(),ae==null||ae.update()},setMessage(c){return!Le||_.isStreaming()?!1:(!W&&j()&&Rt(!0,"system"),Le.value=c,Le.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(_.isStreaming())return!1;let m=(c==null?void 0:c.trim())||Le.value.trim();return m?(!W&&j()&&Rt(!0,"system"),Le.value="",Le.style.height="auto",_.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return _.isStreaming()?!1:((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(_.isVoiceActive()||(!W&&j()&&Rt(!0,"system"),ut.manuallyDeactivated=!1,En(),_.toggleVoice().then(()=>{ut.active=_.isVoiceActive(),Jn("user"),_.isVoiceActive()&&Kr()})),!0):On?!0:fs()?(!W&&j()&&Rt(!0,"system"),ut.manuallyDeactivated=!1,En(),uo("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{ut.active=!1,ut.manuallyDeactivated=!0,En(),Jn("user"),ar()}),!0):!1:On?(ut.manuallyDeactivated=!0,En(),sr("user"),!0):!1},injectMessage(c){return!W&&j()&&Rt(!0,"system"),_.injectMessage(c)},injectAssistantMessage(c){!W&&j()&&Rt(!0,"system");let m=_.injectAssistantMessage(c);return O&&(O=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),m},injectUserMessage(c){return!W&&j()&&Rt(!0,"system"),_.injectUserMessage(c)},injectSystemMessage(c){return!W&&j()&&Rt(!0,"system"),_.injectSystemMessage(c)},injectMessageBatch(c){return!W&&j()&&Rt(!0,"system"),_.injectMessageBatch(c)},injectComponentDirective(c){return!W&&j()&&Rt(!0,"system"),_.injectComponentDirective(c)},injectTestMessage(c){!W&&j()&&Rt(!0,"system"),_.injectTestEvent(c)},async connectStream(c,m){return _.connectStream(c,m)},__pushEventStreamEvent(c){Q&&Q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)})},showEventStream(){!de||!Q||wr()},hideEventStream(){Re&&Yn()},isEventStreamVisible(){return Re},showArtifacts(){Xn(r)&&(hn=!1,Bn(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){Xn(r)&&(hn=!0,Bn())},upsertArtifact(c){return Xn(r)?(hn=!1,_.upsertArtifact(c)):null},selectArtifact(c){Xn(r)&&_.selectArtifact(c)},clearArtifacts(){Xn(r)&&_.clearArtifacts()},getArtifacts(){var c;return(c=_==null?void 0:_.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=_==null?void 0:_.getSelectedArtifactId())!=null?c:null},focusInput(){return A&&!W&&!$()||!Le?!1:(Le.focus(),!0)},async resolveApproval(c,m){let b=_.getMessages().find(M=>{var H;return M.variant==="approval"&&((H=M.approval)==null?void 0:H.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);return _.resolveApproval(b.approval,m)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return s.on(c,m)},off(c,m){s.off(c,m)},isOpen(){return j()&&W},isVoiceActive(){return ut.active},getState(){return{open:j()&&W,launcherEnabled:A,voiceActive:ut.active,streaming:_.isStreaming()}},showCSATFeedback(c){!W&&j()&&Rt(!0,"system");let m=be.querySelector(".persona-feedback-container");m&&m.remove();let y=Vi({onSubmit:async(b,M)=>{var H;_.isClientTokenMode()&&await _.submitCSATFeedback(b,M),(H=c==null?void 0:c.onSubmit)==null||H.call(c,b,M)},onDismiss:c==null?void 0:c.onDismiss,...c});be.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!W&&j()&&Rt(!0,"system");let m=be.querySelector(".persona-feedback-container");m&&m.remove();let y=Ji({onSubmit:async(b,M)=>{var H;_.isClientTokenMode()&&await _.submitNPSFeedback(b,M),(H=c==null?void 0:c.onSubmit)==null||H.call(c,b,M)},onDismiss:c==null?void 0:c.onDismiss,...c});be.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return _.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return _.submitNPSFeedback(c,m)},destroy(){hr!=null&&(clearInterval(hr),hr=null),gt.forEach(c=>c()),K.remove(),xe==null||xe.remove(),R==null||R.destroy(),w==null||w.remove(),Nn&&je.removeEventListener("click",Nn)}};if((((Gl=t==null?void 0:t.debugTools)!=null?Gl:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:Zt,getMessages:Zt.getMessages,getStatus:Zt.getStatus,getMetadata:Zt.getPersistentMetadata,updateMetadata:Zt.updatePersistentMetadata,clearHistory:()=>Zt.clearChat(),setVoiceActive:y=>y?Zt.startVoiceRecognition():Zt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,gt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=q=>{let I=q.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Zt.focusInput()};if(window.addEventListener("persona:focusInput",m),gt.push(()=>{window.removeEventListener("persona:focusInput",m)}),de){let q=ye=>{let ie=ye.detail;(!(ie!=null&&ie.instanceId)||ie.instanceId===c)&&Zt.showEventStream()},I=ye=>{let ie=ye.detail;(!(ie!=null&&ie.instanceId)||ie.instanceId===c)&&Zt.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",I),gt.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",I)})}let y=q=>{let I=q.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Zt.showArtifacts()},b=q=>{let I=q.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Zt.hideArtifacts()},M=q=>{let I=q.detail;I!=null&&I.instanceId&&I.instanceId!==c||I!=null&&I.artifact&&Zt.upsertArtifact(I.artifact)},H=q=>{let I=q.detail;I!=null&&I.instanceId&&I.instanceId!==c||typeof(I==null?void 0:I.id)=="string"&&Zt.selectArtifact(I.id)},N=q=>{let I=q.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",H),window.addEventListener("persona:clearArtifacts",N),gt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",H),window.removeEventListener("persona:clearArtifacts",N)})}let Kn=Ly(r.persistState);if(Kn&&j()){let c=Py(Kn.storage),m=`${Kn.keyPrefix}widget-open`,y=`${Kn.keyPrefix}widget-voice`,b=`${Kn.keyPrefix}widget-voice-mode`;if(c){let M=((Ql=Kn.persist)==null?void 0:Ql.openState)&&c.getItem(m)==="true",H=((Xl=Kn.persist)==null?void 0:Xl.voiceState)&&c.getItem(y)==="true",N=((Yl=Kn.persist)==null?void 0:Yl.voiceState)&&c.getItem(b)==="true";if(M&&setTimeout(()=>{Zt.open(),setTimeout(()=>{var q;if(H||N)Zt.startVoiceRecognition();else if((q=Kn.persist)!=null&&q.focusInput){let I=e.querySelector("textarea");I&&I.focus()}},100)},0),(Zl=Kn.persist)!=null&&Zl.openState&&(s.on("widget:opened",()=>{c.setItem(m,"true")}),s.on("widget:closed",()=>{c.setItem(m,"false")})),(ec=Kn.persist)!=null&&ec.voiceState&&(s.on("voice:state",q=>{c.setItem(y,q.active?"true":"false")}),s.on("user:message",q=>{c.setItem(b,q.viaVoice?"true":"false")})),Kn.clearOnChatClear){let q=()=>{c.removeItem(m),c.removeItem(y),c.removeItem(b)},I=()=>q();window.addEventListener("persona:clear-chat",I),gt.push(()=>{window.removeEventListener("persona:clear-chat",I)})}}}return u&&j()&&setTimeout(()=>{Zt.open()},0),Lr(),Zt};var Iy=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,n*parseFloat(o[1])/100):420},bu=(e,n)=>{var r,o;let t=(o=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?o:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},Zi=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},xu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Zi(e)},Qi=e=>{e.style.transition=""},Xi=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},Yi=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Xa=(e,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},Wy=(e,n,t,r,o)=>{o?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},Ry=(e,n,t,r,o,s)=>{let a=s?n:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},vu=(e,n,t,r,o,s,a)=>{var C,x,T,A,k,B;let i=lr(s),d=i.reveal==="push";Wy(e,n,t,r,d),Ry(e,n,t,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(x=(C=s==null?void 0:s.launcher)==null?void 0:C.mobileFullscreen)!=null?x:!0,p=(A=(T=s==null?void 0:s.launcher)==null?void 0:T.mobileBreakpoint)!=null?A:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Xi(n),Qi(r),xu(r),Yi(t),Xa(o,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((B=(k=s==null?void 0:s.launcher)==null?void 0:k.zIndex)!=null?B:fn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),xu(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Xi(n),Qi(r),Yi(t),Xa(o,r);let D=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=a?"translateX(0)":L;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=D,r.style.transform=S,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Qi(r),Zi(r),Xa(o,r);let D=Iy(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),S=i.animate?"transform 180ms ease":"none",F=i.side==="right"?a?`translateX(-${D}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${D}px)`;n.style.display="flex",n.style.flexDirection="row",n.style.flex="0 0 auto",n.style.minHeight="0",n.style.minWidth="0",n.style.alignItems="stretch",n.style.height="100%",n.style.width=`${L+D}px`,n.style.transition=S,n.style.transform=F,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${L}px`,t.style.maxWidth=`${L}px`,t.style.minWidth=`${L}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Xi(n),Zi(r),Yi(t),Xa(o,r);let D=i.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=a?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",F=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${L}`,r.style.width=L,r.style.maxWidth=L,r.style.minWidth=L,r.style.minHeight="0",r.style.position="relative",r.style.overflow=D||F?"hidden":"visible",r.style.transition=S,D&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},Hy=(e,n)=>{let t=e.ownerDocument.createElement("div");return bu(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){bu(t,r)},destroy(){t.remove()}}},By=(e,n)=>{var k,B,D,L;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),p=(B=(k=n==null?void 0:n.launcher)==null?void 0:k.enabled)==null||B?(L=(D=n==null?void 0:n.launcher)==null?void 0:D.autoExpand)!=null?L:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},C=()=>{g(),lr(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{vu(a,i,d,l,u,n,p)}),f.observe(a))},x=()=>{vu(a,i,d,l,u,n,p),C()},T=a.ownerDocument.defaultView,A=()=>{x()};return T==null||T.addEventListener("resize",A),lr(n).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:u,shell:a,syncWidgetState(S){let F=S.launcherEnabled?S.open:!0;p!==F&&(p=F,x())},updateConfig(S){var F,$;n=S,(($=(F=n==null?void 0:n.launcher)==null?void 0:F.enabled)!=null?$:!0)===!1&&(p=!0),x()},destroy(){T==null||T.removeEventListener("resize",A),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Ya=(e,n)=>on(n)?By(e,n):Hy(e,n);var el={},Dy=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},Ny=()=>{try{if(typeof el!="undefined"&&el.url)return new URL("../widget.css",el.url).href}catch{}return null},Cu=(e,n)=>{let t=Ny(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=n.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),n.head.appendChild(s)}},wu=e=>{var T;let n=Dy(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,o=e.config,s=Ya(n,o),a,i=[],d=(A,k)=>{var S,F;let D=!((F=(S=k==null?void 0:k.launcher)==null?void 0:S.enabled)!=null?F:!0)||on(k),L=r.createElement("div");if(L.setAttribute("data-persona-root","true"),D&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),t){let $=A.attachShadow({mode:"open"});$.appendChild(L),Cu($,r)}else A.appendChild(L),Cu(A,r);return n.id&&L.setAttribute("data-persona-instance",n.id),L},l=()=>{s.syncWidgetState(a.getState())},u=()=>{i.forEach(A=>A()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},p=()=>{let A=d(s.host,o);a=Gi(A,o,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(A=>A()),i=[],a.destroy()};p(),(T=e.onReady)==null||T.call(e);let g=A=>{f(),s.destroy(),s=Ya(n,A),o=A,p()},C={update(A){var F,$,j,W,O,V;let k={...o,...A,launcher:{...(F=o==null?void 0:o.launcher)!=null?F:{},...($=A==null?void 0:A.launcher)!=null?$:{},dock:{...(W=(j=o==null?void 0:o.launcher)==null?void 0:j.dock)!=null?W:{},...(V=(O=A==null?void 0:A.launcher)==null?void 0:O.dock)!=null?V:{}}}},B=on(o),D=on(k),L=Yr(o),S=Yr(k);if(B!==D||L!==S){g(k);return}o=k,s.updateConfig(o),a.update(A),l()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(C,{get(A,k,B){if(k==="host")return s.host;if(k in A)return Reflect.get(A,k,B);let D=a[k];return typeof D=="function"?D.bind(a):D}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Mu=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Fy=new Set(["button","a","input","select","textarea","details","summary"]),Oy=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),tl=/\b(product|card|item|listing|result)\b/i,rl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,$y=3e3,_y=100;function ku(e){let n=typeof e.className=="string"?e.className:"";if(tl.test(n)||e.id&&tl.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&tl.test(r.value))return!0}return!1}function Lu(e){var n;return rl.test(((n=e.textContent)!=null?n:"").trim())}function Pu(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let o=(t=n[r].getAttribute("href"))!=null?t:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function jy(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Au(e){let n=e.match(rl);return n?n[0]:null}function Su(e){var r,o,s;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((o=n.textContent)!=null&&o.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=t==null?void 0:t.textContent)!=null&&s.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function Uy(e){let n=[],t=r=>{let o=r.trim();o&&!n.includes(o)&&n.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return t((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return t((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;t((o=r.value)!=null?o:"")}),n.slice(0,6)}var qy="commerce-card",zy="result-card";function Eu(e){return!ku(e)||!Lu(e)||!Pu(e)&&!jy(e)?0:5200}function Tu(e){var r;return!ku(e)||Lu(e)||!Pu(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 Iu=[{id:qy,scoreElement(e){return Eu(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||rl.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,u;if(Eu(e)===0)return null;let{title:t,href:r}=Su(e),o=(u=(l=Au(((d=e.textContent)!=null?d:"").trim()))!=null?l:Au(n.text))!=null?u:"",s=Uy(e);return[r&&t?`[${t}](${r})${o?` \u2014 ${o}`:""}`:t?`${t}${o?` \u2014 ${o}`:""}`:o||n.text.trim().slice(0,120),`selector: ${n.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
101
- `)}},{id:zy,scoreElement(e){return Tu(e)},formatSummary(e,n){if(Tu(e)===0)return null;let{title:t,href:r}=Su(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
102
- `)}}];function Vy(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Jy(e){var u,p,f,g,C,x,T,A,k,B,D,L,S;let n=(u=e.options)!=null?u:{},t=(f=(p=n.maxElements)!=null?p:e.maxElements)!=null?f:80,r=(C=(g=n.excludeSelector)!=null?g:e.excludeSelector)!=null?C:".persona-host",o=(T=(x=n.maxTextLength)!=null?x:e.maxTextLength)!=null?T:200,s=(k=(A=n.visibleOnly)!=null?A:e.visibleOnly)!=null?k:!0,a=(B=n.root)!=null?B:e.root,i=(D=n.mode)!=null?D:"structured",d=(L=n.maxCandidates)!=null?L:Math.max(500,t*10),l=(S=e.rules)!=null?S:Iu;return i==="simple"&&e.rules&&e.rules.length>0?(Vy(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function nl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Ky=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Gy(e){let n=e.tagName.toLowerCase(),t=e.getAttribute("role");return n==="a"&&e.hasAttribute("href")?"navigable":n==="input"||n==="select"||n==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":n==="button"||t==="button"||Fy.has(n)||t&&Oy.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Wu(e){if(e.hidden)return!1;try{let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Qy(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let o=e.getAttribute("aria-label");o&&(n["aria-label"]=o);let s=e.getAttribute("type");s&&(n.type=s);let a=e.getAttribute("value");a&&(n.value=a);let i=e.getAttribute("name");i&&(n.name=i);let d=e.getAttribute("role");d&&(n.role=d);for(let l=0;l<e.attributes.length;l++){let u=e.attributes[l];u.name.startsWith("data-")&&(n[u.name]=u.value)}return n}function Ru(e){let n=e.tagName.toLowerCase();if(e.id){let o=`#${nl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of Ky){let s=e.getAttribute(o);if(s){let a=`${n}[${o}="${nl(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(t.length>0){let o=`${n}.${t.map(a=>nl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(s>=0)return`${n}:nth-of-type(${s+1})`}return n}function Xy(e){return e==="static"?_y:$y}function Hu(e,n){var o;let t=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,n);return{selector:Ru(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:Gy(e),attributes:Qy(e)}}function Yy(e,n,t,r){let o=Xy(n.interactivity),s=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function Zy(e,n){var t;for(let r of e)if(n.el!==r.el&&(t=r.formattingRule)!=null&&t.shouldSuppressDescendant&&r.el.contains(n.el)&&r.formattingRule.shouldSuppressDescendant(r.el,n.el,n.enriched))return!0;return!1}function eb(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(Mu.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Wu(l)){i=a.nextNode();continue}let p=Hu(l,e.maxTextLength),f=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(T=>T==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:C,formattingRule:x}=Yy(l,p,e.rules,t);o.push({el:l,domIndex:s,enriched:p,score:C,formattingRule:x}),s+=1}i=a.nextNode()}o.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex});let d=[];for(let l of o){if(d.length>=e.maxElements)break;Zy(d,l)||d.push(l)}return d.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex}),d.map(l=>{var f;let u;if((f=l.formattingRule)!=null&&f.formatSummary){let g=l.formattingRule.formatSummary(l.el,l.enriched,t);g&&(u=g)}let p={...l.enriched};return u&&(p.formattedSummary=u),p})}function tb(e,n){let t=[],r=new Set,o=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&t.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(Mu.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Wu(d)){s=o.nextNode();continue}let u=Hu(d,e.maxTextLength),p=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(g=>g==="role");if(!p&&!f){s=o.nextNode();continue}r.has(u.selector)||(r.add(u.selector),t.push(u))}s=o.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function nb(e={}){var r;let n=Jy(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?tb(n,t):eb(n,t):[]}var Za=100;function rb(e,n={}){var s;if(e.length===0)return"No page elements found.";let t=(s=n.mode)!=null?s:"structured",r=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
107
+ `}if(!b&&!c){let Dt="max-height: -moz-available !important; max-height: stretch !important;",qt=g?"":"padding-top: 1.25em !important;",kn=g?"":`z-index: ${($t=(Bt=r.launcher)==null?void 0:Bt.zIndex)!=null?$t:gn} !important;`;J.style.cssText+=Dt+qt+kn}E()};Zn(),So(e,r),ti(e,r),ni(e,r);let ft=[];ft.push(()=>{document.removeEventListener("keydown",Or)});let Kt=null,Jt=null;ft.push(()=>{Kt==null||Kt(),Kt=null,Jt==null||Jt(),Jt=null}),Pn&&ft.push(()=>{Pn==null||Pn.disconnect(),Pn=null}),ft.push(()=>{hn==null||hn(),hn=null,Er(),Wt&&(Wt.remove(),Wt=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),pe&&ft.push(()=>{ue!==null&&(cancelAnimationFrame(ue),ue=null),ae==null||ae.destroy(),ae=null,G==null||G.destroy(),G=null,te=null});let Bn=null,_r=()=>{Bn&&(Bn(),Bn=null),r.colorScheme==="auto"&&(Bn=ki(()=>{So(e,r)}))};_r(),ft.push(()=>{Bn&&(Bn(),Bn=null)});let zn=(oc=r.features)==null?void 0:oc.streamAnimation;if(zn!=null&&zn.type&&zn.type!=="none"){let c=Ds(zn.type,zn.plugins);c&&(Ii(c,e),ft.push(()=>Kp(e)))}let er=vu(Ht),Dn=null,_,de=!1,Nn=_p(),tr=new Map,fr=new Map,ns=0,nr=Ba(),rr=0,or=null,Tr=!1,co=!1,Js=4,rs=24,Gs=80,Lo=new Map,mt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},os=(ac=(sc=r.voiceRecognition)==null?void 0:sc.autoResume)!=null?ac:!1,Vn=c=>{o.emit("voice:state",{active:mt.active,source:c,timestamp:Date.now()})},En=()=>{m(c=>({...c,voiceState:{active:mt.active,timestamp:Date.now(),manuallyDeactivated:mt.manuallyDeactivated}}))},Xs=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=sl(d.voiceState),g=!!c.active,y=Number((T=c.timestamp)!=null?T:0);mt.manuallyDeactivated=!!c.manuallyDeactivated,g&&Date.now()-y<Qy&&setTimeout(()=>{var D,N;mt.active||(mt.manuallyDeactivated=!1,((N=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:N.type)==="runtype"?_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),Vn("restore"),_.isVoiceActive()&&j()}):go("restore"))},1e3)},Ys=()=>_?Hu(_.getMessages()).filter(c=>!c.__skipPersist):[];function Po(c){if(!(i!=null&&i.save))return;let y={messages:c?Hu(c):_?Ys():[],metadata:d,artifacts:In.artifacts,selectedArtifactId:In.selectedId};try{let b=i.save(y);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Mr=null,Qs=()=>J.querySelector("#persona-scroll-container")||Te,po=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),Tr=!1},ss=()=>{or!==null&&(cancelAnimationFrame(or),or=null),co=!1,po()},kr=()=>{if(!Mt()||He){ut.parentNode&&ut.remove(),ut.style.display="none";return}ut.parentNode!==ne&&ne.appendChild(ut),_n();let c=Ws(Te)>0;ut.style.display=nr.isFollowing()||!c?"none":""},as=()=>{nr.pause()&&(ss(),kr())},jr=()=>{nr.resume(),kr()},Ur=(c=!1)=>{nr.isFollowing()&&(!c&&!de||(or!==null&&(cancelAnimationFrame(or),or=null),co=!0,or=requestAnimationFrame(()=>{or=null,co=!1,nr.isFollowing()&&Zs(Qs(),c?220:140)})))},Zs=(c,g=500)=>{let y=c.scrollTop,b=Ws(c),T=b-y;if(Math.abs(T)<1){rr=c.scrollTop;return}if(Math.abs(T)>=Gs){po(),Tr=!0,c.scrollTop=b,rr=c.scrollTop,Tr=!1;return}po();let D=performance.now();Tr=!0;let N=I=>1-Math.pow(1-I,3),q=I=>{if(!nr.isFollowing()){po();return}let be=Ws(c);be!==b&&(b=be,T=b-y);let le=I-D,ee=Math.min(le/g,1),me=N(ee),Ce=y+T*me;c.scrollTop=Ce,rr=c.scrollTop,ee<1?Mr=requestAnimationFrame(q):(c.scrollTop=b,rr=c.scrollTop,Mr=null,Tr=!1)};Mr=requestAnimationFrame(q)},ea=c=>{let g=new Map;c.forEach(y=>{let b=Lo.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!b&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(b!=null&&b.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(b?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Lo.clear(),g.forEach((y,b)=>{Lo.set(b,y)})},uo=(c,g,y)=>{var Xe,st,at,Le,ke,qe;let b=document.createElement("div"),D=(()=>{var Se;let E=s.find(We=>We.renderLoadingIndicator);if(E!=null&&E.renderLoadingIndicator)return E.renderLoadingIndicator;if((Se=r.loadingIndicator)!=null&&Se.render)return r.loadingIndicator.render})(),N=(E,Se)=>Se==null?!1:typeof Se=="string"?(E.textContent=Se,!0):(E.appendChild(Se),!0),q=new Set,I=new Set,be=s.some(E=>E.renderAskUserQuestion),le=[],ee=[],me=r.enableComponentStreaming!==!1;if(g.forEach(E=>{var xn,cn,Qe,it,vn,pn,fo,ho,yo,Do,No,Ut,bo,Xr;q.add(E.id);let Se=be&&to(E),We=!Se&&E.role==="assistant"&&!E.variant&&me&&tl(E);if(!We&&fr.has(E.id)){let ht=c.querySelector(`#wrapper-${E.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),fr.delete(E.id)}let Je=to(E)?`:${(xn=E.agentMetadata)!=null&&xn.askUserQuestionAnswered?"a":"u"}:${(cn=E.agentMetadata)!=null&&cn.askUserQuestionAnswers?Object.keys(E.agentMetadata.askUserQuestionAnswers).length:0}`:"",ye=$p(E,ns)+Je,Tt=Se||We?null:jp(Nn,E.id,ye);if(Tt){b.appendChild(Tt.cloneNode(!0)),to(E)&&((Qe=E.toolCall)!=null&&Qe.id)&&((it=E.agentMetadata)==null?void 0:it.awaitingLocalTool)===!0&&!((vn=E.agentMetadata)!=null&&vn.askUserQuestionAnswered)&&(I.add(E.toolCall.id),zs(E,r,$e.composerOverlay));return}let ot=null,Xt=s.find(ht=>!!(E.variant==="reasoning"&&ht.renderReasoning||E.variant==="tool"&&ht.renderToolCall||E.variant==="approval"&&ht.renderApproval||!E.variant&&ht.renderMessage)),ln=(pn=r.layout)==null?void 0:pn.messages;if(to(E)&&((fo=E.agentMetadata)==null?void 0:fo.askUserQuestionAnswered)===!0){tr.delete(E.id);let ht=c.querySelector(`#wrapper-${E.id}`);ht==null||ht.removeAttribute("data-preserve-runtime");return}if(to(E)&&((yo=(ho=r.features)==null?void 0:ho.askUserQuestion)==null?void 0:yo.enabled)!==!1){let ht=s.find(Tn=>typeof Tn.renderAskUserQuestion=="function");if(ht&&kt.current){let Tn=tr.get(E.id),Ir=Tn!==ye,wn=null;if(Ir){let{payload:$t,complete:Dt}=no(E),qt=E.id,kn=()=>{var Fn;return(Fn=kt.current)==null?void 0:Fn.getMessages().find(Zt=>Zt.id===qt)};wn=ht.renderAskUserQuestion({message:E,payload:$t,complete:Dt,resolve:Fn=>{var yr;let Zt=kn();Zt&&((yr=kt.current)==null||yr.resolveAskUserQuestion(Zt,Fn))},dismiss:()=>{var Zt,yr,Wr;let Fn=kn();(Zt=Fn==null?void 0:Fn.agentMetadata)!=null&&Zt.awaitingLocalTool&&((yr=kt.current)==null||yr.markAskUserQuestionResolved(Fn),(Wr=kt.current)==null||Wr.resolveAskUserQuestion(Fn,"(dismissed)"))},config:r})}let Mn=Tn!=null;if(Ir&&wn===null&&!Mn){((Do=E.agentMetadata)==null?void 0:Do.awaitingLocalTool)===!0&&!((No=E.agentMetadata)!=null&&No.askUserQuestionAnswered)&&(I.add(E.toolCall.id),zs(E,r,$e.composerOverlay));return}let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${E.id}`,Bt.setAttribute("data-wrapper-id",E.id),Bt.setAttribute("data-ask-plugin-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),b.appendChild(Bt),le.push({messageId:E.id,fingerprint:ye,bubble:wn});return}else{((Ut=E.agentMetadata)==null?void 0:Ut.awaitingLocalTool)===!0&&!((bo=E.agentMetadata)!=null&&bo.askUserQuestionAnswered)&&(I.add(E.toolCall.id),zs(E,r,$e.composerOverlay));return}}else if(Xt)if(E.variant==="reasoning"&&E.reasoning&&Xt.renderReasoning){if(!Pe)return;ot=Xt.renderReasoning({message:E,defaultRenderer:()=>Oi(E,r),config:r})}else if(E.variant==="tool"&&E.toolCall&&Xt.renderToolCall){if(!ze)return;ot=Xt.renderToolCall({message:E,defaultRenderer:()=>Fi(E,r),config:r})}else if(E.variant==="approval"&&E.approval&&Xt.renderApproval){if(r.approval===!1)return;ot=Xt.renderApproval({message:E,defaultRenderer:()=>Vi(E,r),config:r})}else Xt.renderMessage&&(ot=Xt.renderMessage({message:E,defaultRenderer:()=>{let ht=Us(E,y,ln,r.messageActions,tt,{loadingIndicatorRenderer:D,widgetConfig:r});return E.role!=="user"&&Gi(ht,E,r,_),ht},config:r}));if(!ot&&We){let ht=nl(E);if(ht){let Tn=fr.get(E.id),Ir=Tn!==ye,wn=r.wrapComponentDirectiveInBubble!==!1,Mn=null;if(Ir){let Bt=el(ht,{config:r,message:E,transform:y});if(Bt)if(wn){let $t=document.createElement("div");if($t.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),$t.id=`bubble-${E.id}`,$t.setAttribute("data-message-id",E.id),E.content&&E.content.trim()){let Dt=document.createElement("div");Dt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Dt.innerHTML=y({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),$t.appendChild(Dt)}$t.appendChild(Bt),Mn=$t}else{let $t=document.createElement("div");if($t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$t.id=`bubble-${E.id}`,$t.setAttribute("data-message-id",E.id),$t.setAttribute("data-persona-component-directive","true"),E.content&&E.content.trim()){let Dt=document.createElement("div");Dt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Dt.innerHTML=y({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),$t.appendChild(Dt)}$t.appendChild(Bt),Mn=$t}}if(Mn||Tn!=null){let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${E.id}`,Bt.setAttribute("data-wrapper-id",E.id),Bt.setAttribute("data-component-directive-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),wn||Bt.classList.add("persona-w-full"),b.appendChild(Bt),ee.push({messageId:E.id,fingerprint:ye,bubble:Mn});return}}}if(!ot)if(E.variant==="reasoning"&&E.reasoning){if(!Pe)return;ot=Oi(E,r)}else if(E.variant==="tool"&&E.toolCall){if(!ze)return;ot=Fi(E,r)}else if(E.variant==="approval"&&E.approval){if(r.approval===!1)return;ot=Vi(E,r)}else{let ht=(Xr=r.layout)==null?void 0:Xr.messages;ht!=null&&ht.renderUserMessage&&E.role==="user"?ot=ht.renderUserMessage({message:E,config:r,streaming:!!E.streaming}):ht!=null&&ht.renderAssistantMessage&&E.role==="assistant"?ot=ht.renderAssistantMessage({message:E,config:r,streaming:!!E.streaming}):ot=Us(E,y,ht,r.messageActions,tt,{loadingIndicatorRenderer:D,widgetConfig:r}),E.role!=="user"&&ot&&Gi(ot,E,r,_)}let Pt=document.createElement("div");Pt.className="persona-flex",Pt.id=`wrapper-${E.id}`,Pt.setAttribute("data-wrapper-id",E.id),E.role==="user"&&Pt.classList.add("persona-justify-end"),(ot==null?void 0:ot.getAttribute("data-persona-component-directive"))==="true"&&Pt.classList.add("persona-w-full"),Pt.appendChild(ot),Up(Nn,E.id,ye,Pt),b.appendChild(Pt)}),$e.composerOverlay&&$e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Se=>{let We=Se.getAttribute("data-persona-ask-sheet-for");We&&!I.has(We)&&Mo($e.composerOverlay,We)}),(st=(Xe=r.features)==null?void 0:Xe.toolCallDisplay)!=null&&st.grouped){let E=[],Se=[];g.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&ze){Se.push(We);return}Se.length>1&&E.push(Se),Se=[]}),Se.length>1&&E.push(Se),E.forEach((We,Je)=>{var cn,Qe;let ye=We.map(it=>Array.from(b.children).find(vn=>vn instanceof HTMLElement&&vn.getAttribute("data-wrapper-id")===it.id)).filter(it=>!!it);if(ye.length<2)return;let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id=`wrapper-tool-group-${Je}-${We[0].id}`,Tt.setAttribute("data-wrapper-id",`tool-group-${Je}-${We[0].id}`);let ot=document.createElement("div");ot.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",ot.setAttribute("data-persona-tool-group","true");let Xt=document.createElement("div");Xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let ln=`Called ${We.length} tools`,Pt=(Qe=(cn=r.toolCall)==null?void 0:cn.renderGroupedSummary)==null?void 0:Qe.call(cn,{messages:We,toolCalls:We.map(it=>it.toolCall).filter(it=>!!it),defaultSummary:ln,config:r});N(Xt,Pt)||(Xt.textContent=ln);let xn=document.createElement("div");xn.className="persona-tool-group-stack persona-flex persona-flex-col",ot.append(Xt,xn),Tt.appendChild(ot),ye[0].before(Tt),ye.forEach((it,vn)=>{let pn=document.createElement("div");pn.className="persona-tool-group-item persona-relative",pn.setAttribute("data-persona-tool-group-item","true"),vn<ye.length-1&&pn.setAttribute("data-persona-tool-group-connector","true"),pn.appendChild(it),xn.appendChild(pn)})})}qp(Nn,q);let Ce=g.some(E=>E.role==="assistant"&&E.streaming),Ne=g[g.length-1],et=(Ne==null?void 0:Ne.role)==="assistant"&&!Ne.streaming&&Ne.variant!=="approval";if(de&&g.some(E=>E.role==="user")&&!Ce&&!et){let E={config:r,streaming:!0,location:"standalone",defaultRenderer:Ko},Se=s.find(Je=>Je.renderLoadingIndicator),We=null;if(Se!=null&&Se.renderLoadingIndicator&&(We=Se.renderLoadingIndicator(E)),We===null&&((at=r.loadingIndicator)!=null&&at.render)&&(We=r.loadingIndicator.render(E)),We===null&&(We=Ko()),We){let Je=document.createElement("div"),ye=((Le=r.loadingIndicator)==null?void 0:Le.showBubble)!==!1;Je.className=ye?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Je.setAttribute("data-typing-indicator","true"),Je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Je.appendChild(We);let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id="wrapper-typing-indicator",Tt.setAttribute("data-wrapper-id","typing-indicator"),Tt.appendChild(Je),b.appendChild(Tt)}}if(!de&&g.length>0){let E=g[g.length-1],Se={config:r,lastMessage:E,messageCount:g.length},We=s.find(ye=>ye.renderIdleIndicator),Je=null;if(We!=null&&We.renderIdleIndicator&&(Je=We.renderIdleIndicator(Se)),Je===null&&((ke=r.loadingIndicator)!=null&&ke.renderIdle)&&(Je=r.loadingIndicator.renderIdle(Se)),Je){let ye=document.createElement("div"),Tt=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;ye.className=Tt?["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(" "),ye.setAttribute("data-idle-indicator","true"),ye.appendChild(Je);let ot=document.createElement("div");ot.className="persona-flex",ot.id="wrapper-idle-indicator",ot.setAttribute("data-wrapper-id","idle-indicator"),ot.appendChild(ye),b.appendChild(ot)}}if(Ra(c,b),le.length>0)for(let{messageId:E,fingerprint:Se,bubble:We}of le){let Je=c.querySelector(`#wrapper-${E}`);Je&&We!==null&&(Je.replaceChildren(We),Je.setAttribute("data-bubble-fp",Se),tr.set(E,Se))}if(tr.size>0)for(let E of tr.keys())q.has(E)||tr.delete(E);if(ee.length>0)for(let{messageId:E,fingerprint:Se,bubble:We}of ee){let Je=c.querySelector(`#wrapper-${E}`);Je&&We!==null&&(Je.replaceChildren(We),Je.setAttribute("data-bubble-fp",Se),fr.set(E,Se))}if(fr.size>0)for(let E of fr.keys())q.has(E)||fr.delete(E)},qr=null,ta=()=>{var y;if(qr)return;let c=b=>{let T=b.composedPath();T.includes(J)||we&&T.includes(we)||Rt(!1,"user")};qr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("pointerdown",c,!0)},is=()=>{var g;if(!qr)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("pointerdown",qr,!0),qr=null};ft.push(()=>is());let zr=null,na=()=>{var y;if(zr)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Rt(!1,"user"))};zr=c,((y=e.ownerDocument)!=null?y:document).addEventListener("keydown",c,!0)},ls=()=>{var g;if(!zr)return;((g=e.ownerDocument)!=null?g:document).removeEventListener("keydown",zr,!0),zr=null};ft.push(()=>ls());let Vr=!1,cs=new Set,ra=()=>{var g,y,b,T;let c=(b=(y=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:y.peek)==null?void 0:b.streamAnimation;return c||((T=r.features)==null?void 0:T.streamAnimation)},Lr=()=>{var st,at,Le,ke;if(!F())return;let c=$e.peekBanner,g=$e.peekTextNode;if(!c||!g)return;if(W){c.classList.remove("persona-pill-peek--visible");return}let y=(st=_==null?void 0:_.getMessages())!=null?st:[],b;for(let qe=y.length-1;qe>=0;qe--){let E=y[qe];if(E.role==="assistant"&&E.content){b=E;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let T=b.content,D=!!b.streaming,N=ra(),q=Oa(N),I=q.type!=="none"?Ds(q.type,N==null?void 0:N.plugins):null,be=((at=I==null?void 0:I.isAnimating)==null?void 0:at.call(I,b))===!0,le=I!==null&&(D||be);le&&I&&!cs.has(I.name)&&(Ii(I,e),cs.add(I.name));let ee=le&&(I!=null&&I.containerClass)?I.containerClass:null,me=(Le=g.dataset.personaPeekStreamClass)!=null?Le:null;me&&me!==ee&&(g.classList.remove(me),delete g.dataset.personaPeekStreamClass),ee&&me!==ee&&(g.classList.add(ee),g.dataset.personaPeekStreamClass=ee),le?(g.style.setProperty("--persona-stream-step",`${q.speed}ms`),g.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ce=le?Fa(T,q.buffer,I,b,D):T;if(le&&q.placeholder==="skeleton"&&D&&(!Ce||!Ce.trim())){let qe=document.createElement("div"),E=Os();E.classList.add("persona-pill-peek__skeleton"),qe.appendChild(E),Ra(g,qe)}else{let qe=Math.max(0,Ce.length-100),E=Ce.length>100?Ce.slice(-100):Ce,Se=Fo(E);if(!le||!I){let We=Ce.length>100?`\u2026${E}`:E;g.textContent!==We&&(g.textContent=We)}else{let We=Se;(I.wrap==="char"||I.wrap==="word")&&(We=Ns(Se,I.wrap,`peek-${b.id}`,{skipTags:I.skipTags,startIndex:qe}));let Je=document.createElement("div");if(Je.innerHTML=We,I.useCaret&&E.length>0){let ye=$a(),Tt=Je.querySelectorAll(".persona-stream-char, .persona-stream-word"),ot=Tt[Tt.length-1];ot!=null&&ot.parentNode?ot.parentNode.insertBefore(ye,ot.nextSibling):Je.appendChild(ye)}Ra(g,Je),(ke=I.onAfterRender)==null||ke.call(I,{container:g,bubble:c,messageId:b.id,message:b,speed:q.speed,duration:q.duration})}}let Xe=de||Vr;c.classList.toggle("persona-pill-peek--visible",Xe)};if(F()){let c=$e.peekBanner;if(c){let b=T=>{T.preventDefault(),T.stopPropagation(),Rt(!0,"user")};c.addEventListener("pointerdown",b),ft.push(()=>{c.removeEventListener("pointerdown",b)})}let g=()=>{Vr||(Vr=!0,Lr())},y=()=>{Vr&&(Vr=!1,Lr())};z.addEventListener("pointerenter",g),z.addEventListener("pointerleave",y),ft.push(()=>{z.removeEventListener("pointerenter",g),z.removeEventListener("pointerleave",y)}),we&&(we.addEventListener("pointerenter",g),we.addEventListener("pointerleave",y),ft.push(()=>{we.removeEventListener("pointerenter",g),we.removeEventListener("pointerleave",y)}))}let oa=c=>{var me,Ce,Ne,et,Xe,st,at,Le;let g=(Ce=(me=r.launcher)==null?void 0:me.composerBar)!=null?Ce:{},y=(Ne=g.expandedSize)!=null?Ne:"anchored",b=(et=g.bottomOffset)!=null?et:"16px",T=g.collapsedMaxWidth,D=(Xe=g.expandedMaxWidth)!=null?Xe:"880px",N=(st=g.expandedTopOffset)!=null?st:"5vh",q=(at=g.modalMaxWidth)!=null?at:"880px",I=(Le=g.modalMaxHeight)!=null?Le:"min(90vh, 800px)",be="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",ee=J.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",we){let ke=we.style;ke.bottom=b,ke.width=T!=null?T:""}if(c&&y!=="fullscreen"){if(y==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=q,ee.maxWidth=be,ee.maxHeight=I,ee.height=I;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${b} + ${le})`,ee.top=N,ee.width=D,ee.maxWidth=be}},Kr=()=>{var I,be,le,ee,me,Ce,Ne,et;if(!$())return;if(F()){let st=(le=((be=(I=r.launcher)==null?void 0:I.composerBar)!=null?be:{}).expandedSize)!=null?le:"anchored",at=W?"expanded":"collapsed";J.dataset.state=at,J.dataset.expandedSize=st,we&&(we.dataset.state=at,we.dataset.expandedSize=st),J.style.removeProperty("display"),J.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),oa(W),ne.style.display=W?"flex":"none",Zn(),W?(ta(),na()):(is(),ls()),Lr();return}let c=on(r),g=(ee=e.ownerDocument.defaultView)!=null?ee:window,y=(Ce=(me=r.launcher)==null?void 0:me.mobileBreakpoint)!=null?Ce:640,b=(et=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?et:!0,T=g.innerWidth<=y,D=b&&T&&A,N=lr(r).reveal;W?(J.style.removeProperty("display"),J.style.display=c?"flex":"",J.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-95","persona-opacity-0"),z.classList.add("persona-scale-100","persona-opacity-100"),Me?Me.element.style.display="none":Ge&&(Ge.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!D?(J.style.removeProperty("display"),J.style.display="flex",J.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(J.style.setProperty("display","none","important"),J.classList.remove("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(J.style.display="",J.classList.add("persona-pointer-events-none","persona-opacity-0"),z.classList.remove("persona-scale-100","persona-opacity-100"),z.classList.add("persona-scale-95","persona-opacity-0")),Me?Me.element.style.display=c?"none":"":Ge&&(Ge.style.display=c?"none":""))},Rt=(c,g="user")=>{var D,N;if(!$()||W===c)return;let y=W;W=c,Kr();let b=(()=>{var Ne,et,Xe,st,at,Le,ke,qe,E,Se;let q=(et=(Ne=r.launcher)==null?void 0:Ne.sidebarMode)!=null?et:!1,I=(Xe=e.ownerDocument.defaultView)!=null?Xe:window,be=(at=(st=r.launcher)==null?void 0:st.mobileFullscreen)!=null?at:!0,le=(ke=(Le=r.launcher)==null?void 0:Le.mobileBreakpoint)!=null?ke:640,ee=I.innerWidth<=le,me=on(r)&&be&&ee,Ce=F()&&((Se=(E=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:E.expandedSize)!=null?Se:"fullscreen")==="fullscreen";return q||be&&ee&&A||me||Ce})();if(W&&b){if(!Kt){let q=e.getRootNode(),I=q instanceof ShadowRoot?q.host:e.closest(".persona-host");I&&(Kt=Wi(I,(N=(D=r.launcher)==null?void 0:D.zIndex)!=null?N:gn))}Jt||(Jt=Ri(e.ownerDocument))}else W||(Kt==null||Kt(),Kt=null,Jt==null||Jt(),Jt=null);W&&(Lt(),Ur(!0));let T={open:W,source:g,timestamp:Date.now()};W&&!y?o.emit("widget:opened",T):!W&&y&&o.emit("widget:closed",T),o.emit("widget:state",{open:W,launcherEnabled:A,voiceActive:mt.active,streaming:_.isStreaming()})},Io=c=>{jt(c?"stop":"send"),P&&(P.disabled=c),er.buttons.forEach(g=>{g.disabled=c}),_e.dataset.personaComposerStreaming=c?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=c)})},Wo=()=>{mt.active||ie&&ie.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Wo(),200)});let ds=()=>{var y,b,T,D,N,q,I,be,le,ee,me;vr.textContent=(b=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?b:"Hello \u{1F44B}",dr.textContent=(D=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",ie.placeholder=(q=(N=r.copy)==null?void 0:N.inputPlaceholder)!=null?q:"How can I help...";let c=Te.querySelector("[data-persona-intro-card]");if(c){let Ce=((I=r.copy)==null?void 0:I.showWelcomeCard)!==!1;c.style.display=Ce?"":"none",Ce?(Te.classList.remove("persona-gap-3"),Te.classList.add("persona-gap-6")):(Te.classList.remove("persona-gap-6"),Te.classList.add("persona-gap-3"))}!((le=(be=r.sendButton)==null?void 0:be.useIcon)!=null&&le)&&!(_!=null&&_.isStreaming())&&(re.textContent=(me=(ee=r.copy)==null?void 0:ee.sendButtonLabel)!=null?me:"Send"),ie.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ie.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{m(g=>({...g,sessionId:c}))}});let hr=null,sa=()=>{hr==null&&(hr=setInterval(()=>{let c=ve.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(hr),hr=null;return}let g=Date.now();c.forEach(y=>{let b=Number(y.getAttribute("data-tool-elapsed"));b&&(y.textContent=va(g-b))})},100))};if(_=new ks(r,{onMessagesChanged(c){uo(ve,c,Ie),sa(),_&&(c.some(T=>T.role==="user")?er.render([],_,ie,c):er.render(r.suggestionChips,_,ie,c,r.suggestionChipsConfig)),Ur(!de),ea(c);let g=[...c].reverse().find(b=>b.role==="user"),y=mt.lastUserMessageId;g&&g.id!==y&&(mt.lastUserMessageId=g.id,o.emit("user:message",g)),mt.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Po(c),Lr()},onStatusChanged(c){var b;let g=(b=r.statusIndicator)!=null?b:{};Oe(zt,(T=>{var D,N,q,I;return T==="idle"?(D=g.idleText)!=null?D:mn.idle:T==="connecting"?(N=g.connectingText)!=null?N:mn.connecting:T==="connected"?(q=g.connectedText)!=null?q:mn.connected:T==="error"?(I=g.errorText)!=null?I:mn.error:mn[T]})(c),g,c)},onStreamingChanged(c){de=c,Io(c),_&&uo(ve,_.getMessages(),Ie),c||Ur(!0),Lr()},onVoiceStatusChanged(c){var g,y;if(((y=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(c){case"listening":break;case"processing":X(),M();break;case"speaking":X(),Z();break;default:c==="idle"&&_.isBargeInActive()?(X(),j(),P==null||P.setAttribute("aria-label","End voice session")):(mt.active=!1,X(),Vn("system"),En());break}},onArtifactsState(c){In=c,Hn(),Po()}}),kt.current=_,((lc=(ic=r.voiceRecognition)==null?void 0:ic.provider)==null?void 0:lc.type)==="runtype")try{_.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&_.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(G||r.onSSEEvent)&&_.setSSEEventCallback((c,g)=>{var y;(y=r.onSSEEvent)==null||y.call(r,c,g),G==null||G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(g)})}),l&&l.then(c=>{var g,y,b;c&&(c.metadata&&(d=sl(c.metadata),S.syncFromMetadata()),(g=c.messages)!=null&&g.length&&_.hydrateMessages(c.messages),(y=c.artifacts)!=null&&y.length&&_.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null))}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let ps=()=>{var g,y,b;!F()||W||!((b=(y=(g=r.launcher)==null?void 0:g.composerBar)==null?void 0:y.expandOnSubmit)==null||b)||Rt(!0,"auto")},us=c=>{var T;if(c.preventDefault(),_.isStreaming()){_.cancel();return}let g=ie.value.trim(),y=(T=vt==null?void 0:vt.hasAttachments())!=null?T:!1;if(!g&&!y)return;ps();let b;y&&(b=[],b.push(...vt.getContentParts()),g&&b.push(Ta(g))),ie.value="",ie.style.height="auto",mo(),_.sendMessage(g,{contentParts:b}),y&&vt.clearAttachments()},aa=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Ro={...Ha},Ho=!1,mo=()=>{Ro={...Ha}},ia=()=>_.getMessages().filter(c=>c.role==="user").map(c=>{var g;return(g=c.content)!=null?g:""}).filter(c=>c.length>0),la=c=>{if(!ie)return;Ho=!0,ie.value=c,ie.dispatchEvent(new Event("input",{bubbles:!0})),Ho=!1;let g=ie.value.length;ie.setSelectionRange(g,g)},ms=()=>{Ho||mo()},gs=c=>{if(ie){if(aa()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let g=ie.selectionStart===0&&ie.selectionEnd===0,y=Fp({direction:c.key==="ArrowUp"?"up":"down",history:ia(),currentValue:ie.value,atStart:g,state:Ro});if(Ro=y.state,y.handled){c.preventDefault(),y.value!==void 0&&la(y.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(_.isStreaming()){c.preventDefault();return}mo(),c.preventDefault(),re.click()}}},fs=c=>{c.key!=="Escape"||c.isComposing||_.isStreaming()&&c.composedPath().includes(ne)&&(_.cancel(),mo(),c.preventDefault(),c.stopImmediatePropagation())},hs=async c=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!vt)return;let g=eb(c.clipboardData);g.length!==0&&(c.preventDefault(),await vt.handleFiles(g))},yn=null,On=!1,Pr=null,rt=null,ys=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,go=(c="user")=>{var D,N,q,I,be,le,ee;if(On||_.isStreaming())return;let g=ys();if(!g)return;yn=new g;let b=(N=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?N:2e3;yn.continuous=!0,yn.interimResults=!0,yn.lang="en-US";let T=ie.value;yn.onresult=me=>{let Ce="",Ne="";for(let Xe=0;Xe<me.results.length;Xe++){let st=me.results[Xe],at=st[0].transcript;st.isFinal?Ce+=at+" ":Ne=at}let et=T+Ce+Ne;ie.value=et,Pr&&clearTimeout(Pr),(Ce||Ne)&&(Pr=window.setTimeout(()=>{let Xe=ie.value.trim();Xe&&yn&&On&&(sr(),ie.value="",ie.style.height="auto",_.sendMessage(Xe,{viaVoice:!0}))},b))},yn.onerror=me=>{me.error!=="no-speech"&&sr()},yn.onend=()=>{if(On){let me=ie.value.trim();me&&me!==T.trim()&&(ie.value="",ie.style.height="auto",_.sendMessage(me,{viaVoice:!0})),sr()}};try{if(yn.start(),On=!0,mt.active=!0,c!=="system"&&(mt.manuallyDeactivated=!1),Vn(c),En(),P){let me=(q=r.voiceRecognition)!=null?q:{};rt={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor,iconName:(I=me.iconName)!=null?I:"mic",iconSize:parseFloat((ee=(le=me.iconSize)!=null?le:(be=r.sendButton)==null?void 0:be.size)!=null?ee:"40")||24};let Ce=me.recordingBackgroundColor,Ne=me.recordingIconColor,et=me.recordingBorderColor;if(P.classList.add("persona-voice-recording"),P.style.backgroundColor=Ce!=null?Ce:"var(--persona-voice-recording-bg, #ef4444)",P.style.color=Ne!=null?Ne:"var(--persona-voice-recording-indicator, #ffffff)",Ne){let Xe=P.querySelector("svg");Xe&&Xe.setAttribute("stroke",Ne)}et&&(P.style.borderColor=et),P.setAttribute("aria-label","Stop voice recognition")}}catch{sr("system")}},sr=(c="user")=>{if(On){if(On=!1,Pr&&(clearTimeout(Pr),Pr=null),yn){try{yn.stop()}catch{}yn=null}if(mt.active=!1,Vn(c),En(),P){if(P.classList.remove("persona-voice-recording"),rt){P.style.backgroundColor=rt.backgroundColor,P.style.color=rt.color,P.style.borderColor=rt.borderColor;let g=P.querySelector("svg");g&&g.setAttribute("stroke",rt.color||"currentColor"),rt=null}P.setAttribute("aria-label","Start voice recognition")}}},ca=(c,g)=>{var st,at,Le,ke,qe,E,Se,We;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((st=c==null?void 0:c.provider)==null?void 0:st.type)==="runtype";if(!(y||b))return null;let D=h("div","persona-send-button-wrapper"),N=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let q=(at=c==null?void 0:c.iconName)!=null?at:"mic",I=(Le=g==null?void 0:g.size)!=null?Le:"40px",be=(ke=c==null?void 0:c.iconSize)!=null?ke:I,le=parseFloat(be)||24,ee=(qe=c==null?void 0:c.backgroundColor)!=null?qe:g==null?void 0:g.backgroundColor,me=(E=c==null?void 0:c.iconColor)!=null?E:g==null?void 0:g.textColor;N.style.width=be,N.style.height=be,N.style.minWidth=be,N.style.minHeight=be,N.style.fontSize="18px",N.style.lineHeight="1",me?N.style.color=me:N.style.color="var(--persona-text, #111827)";let Ne=fe(q,le,me||"currentColor",1.5);Ne?N.appendChild(Ne):N.textContent="\u{1F3A4}",ee?N.style.backgroundColor=ee:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),D.appendChild(N);let et=(Se=c==null?void 0:c.tooltipText)!=null?Se:"Start voice recognition";if(((We=c==null?void 0:c.showTooltip)!=null?We:!1)&&et){let Je=h("div","persona-send-button-tooltip");Je.textContent=et,D.appendChild(Je)}return{micButton:N,micButtonWrapper:D}},Jr=()=>{var g,y,b,T,D;if(!P||rt)return;let c=(g=r.voiceRecognition)!=null?g:{};rt={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor,iconName:(y=c.iconName)!=null?y:"mic",iconSize:parseFloat((D=(T=c.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?D:"40")||24}},Ve=(c,g)=>{var D,N,q,I,be;if(!P)return;let y=P.querySelector("svg");y&&y.remove();let b=(be=rt==null?void 0:rt.iconSize)!=null?be:parseFloat((I=(q=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?q:(N=r.sendButton)==null?void 0:N.size)!=null?I:"40")||24,T=fe(c,b,g,1.5);T&&P.appendChild(T)},C=()=>{P&&P.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},j=()=>{var T;if(!P)return;Jr();let c=(T=r.voiceRecognition)!=null?T:{},g=c.recordingBackgroundColor,y=c.recordingIconColor,b=c.recordingBorderColor;if(C(),P.classList.add("persona-voice-recording"),P.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",P.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let D=P.querySelector("svg");D&&D.setAttribute("stroke",y)}b&&(P.style.borderColor=b),P.setAttribute("aria-label","Stop voice recognition")},M=()=>{var q,I,be,le,ee,me,Ce,Ne;if(!P)return;Jr();let c=(q=r.voiceRecognition)!=null?q:{},g=_.getVoiceInterruptionMode(),y=(I=c.processingIconName)!=null?I:"loader",b=(le=(be=c.processingIconColor)!=null?be:rt==null?void 0:rt.color)!=null?le:"",T=(me=(ee=c.processingBackgroundColor)!=null?ee:rt==null?void 0:rt.backgroundColor)!=null?me:"",D=(Ne=(Ce=c.processingBorderColor)!=null?Ce:rt==null?void 0:rt.borderColor)!=null?Ne:"";C(),P.classList.add("persona-voice-processing"),P.style.backgroundColor=T,P.style.borderColor=D;let N=b||"currentColor";P.style.color=N,Ve(y,N),P.setAttribute("aria-label","Processing voice input"),g==="none"&&(P.style.cursor="default")},Z=()=>{var be,le,ee,me,Ce,Ne,et,Xe,st,at,Le,ke;if(!P)return;Jr();let c=(be=r.voiceRecognition)!=null?be:{},g=_.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",b=(le=c.speakingIconName)!=null?le:y,T=(Ne=c.speakingIconColor)!=null?Ne:g==="barge-in"?(me=(ee=c.recordingIconColor)!=null?ee:rt==null?void 0:rt.color)!=null?me:"":(Ce=rt==null?void 0:rt.color)!=null?Ce:"",D=(st=c.speakingBackgroundColor)!=null?st:g==="barge-in"?(et=c.recordingBackgroundColor)!=null?et:"var(--persona-voice-recording-bg, #ef4444)":(Xe=rt==null?void 0:rt.backgroundColor)!=null?Xe:"",N=(ke=c.speakingBorderColor)!=null?ke:g==="barge-in"?(at=c.recordingBorderColor)!=null?at:"":(Le=rt==null?void 0:rt.borderColor)!=null?Le:"";C(),P.classList.add("persona-voice-speaking"),P.style.backgroundColor=D,P.style.borderColor=N;let q=T||"currentColor";P.style.color=q,Ve(b,q);let I=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";P.setAttribute("aria-label",I),g==="none"&&(P.style.cursor="default"),g==="barge-in"&&P.classList.add("persona-voice-recording")},X=()=>{var c,g,y;P&&(C(),rt&&(P.style.backgroundColor=(c=rt.backgroundColor)!=null?c:"",P.style.color=(g=rt.color)!=null?g:"",P.style.borderColor=(y=rt.borderColor)!=null?y:"",Ve(rt.iconName,rt.color||"currentColor"),rt=null),P.style.cursor="",P.setAttribute("aria-label","Start voice recognition"))},Y=()=>{var c,g;if(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"){let y=_.getVoiceStatus(),b=_.getVoiceInterruptionMode();if(b==="none"&&(y==="processing"||y==="speaking"))return;if(b==="cancel"&&(y==="processing"||y==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,En(),Vn("user"),X()});return}_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),mt.manuallyDeactivated=!_.isVoiceActive(),En(),Vn("user"),_.isVoiceActive()?j():X()});return}if(On){let y=ie.value.trim();mt.manuallyDeactivated=!0,En(),sr("user"),y&&(ie.value="",ie.style.height="auto",_.sendMessage(y))}else mt.manuallyDeactivated=!1,En(),go("user")};pr=Y,P&&(P.addEventListener("click",Y),ft.push(()=>{var c,g;((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),X()):sr("system"),P&&P.removeEventListener("click",Y)}));let Ye=o.on("assistant:complete",()=>{os&&(mt.active||mt.manuallyDeactivated||os==="assistant"&&!mt.lastUserMessageWasVoice||setTimeout(()=>{var c,g;!mt.active&&!mt.manuallyDeactivated&&(((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),Vn("auto"),_.isVoiceActive()&&j()}):go("auto"))},600))});ft.push(Ye);let Fe=o.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});ft.push(Fe);let Ze=()=>{Rt(!W,"user")},Me=null,Ge=null;if(A&&!F()){let c=s.find(g=>g.renderLauncher);if(c!=null&&c.renderLauncher){let g=c.renderLauncher({config:r,defaultRenderer:()=>$s(r,Ze).element,onToggle:Ze});g&&(Ge=g)}Ge||(Me=$s(r,Ze))}Me?e.appendChild(Me.element):Ge&&e.appendChild(Ge),Kr(),er.render(r.suggestionChips,_,ie,void 0,r.suggestionChipsConfig),ds(),Io(_.isStreaming()),Ur(!0),Xs(),R&&(!A||F()?setTimeout(()=>Wo(),0):W&&setTimeout(()=>Wo(),200));let Lt=()=>{var I,be,le,ee,me,Ce,Ne,et,Xe,st,at,Le,ke,qe,E,Se,We,Je,ye,Tt,ot,Xt;if(F()){_n(),Kr();return}let c=on(r),g=(be=(I=r.launcher)==null?void 0:I.sidebarMode)!=null?be:!1,y=c||g||((ee=(le=r.launcher)==null?void 0:le.fullHeight)!=null?ee:!1),b=(me=e.ownerDocument.defaultView)!=null?me:window,T=(Ne=(Ce=r.launcher)==null?void 0:Ce.mobileFullscreen)!=null?Ne:!0,D=(Xe=(et=r.launcher)==null?void 0:et.mobileBreakpoint)!=null?Xe:640,N=b.innerWidth<=D,q=T&&N&&A;try{if(q){Zn(),So(e,r);return}if(B&&(B=!1,Zn(),So(e,r)),!A&&!c){z.style.height="",z.style.width="";return}if(!g&&!c){let ln=(at=(st=r==null?void 0:r.launcher)==null?void 0:st.width)!=null?at:r==null?void 0:r.launcherWidth,Pt=ln!=null?ln:Gn;z.style.width=Pt,z.style.maxWidth=Pt}if(gr(),!y){let ln=b.innerHeight,Pt=64,xn=(ke=(Le=r.launcher)==null?void 0:Le.heightOffset)!=null?ke:0,cn=Math.max(200,ln-Pt),Qe=Math.min(640,cn),it=Math.max(200,Qe-xn);z.style.height=`${it}px`}}finally{if(_n(),Kr(),W&&A){let Pt=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((Se=(E=r.launcher)==null?void 0:E.mobileBreakpoint)!=null?Se:640),xn=(Je=(We=r.launcher)==null?void 0:We.sidebarMode)!=null?Je:!1,cn=(Tt=(ye=r.launcher)==null?void 0:ye.mobileFullscreen)!=null?Tt:!0,Qe=on(r)&&cn&&Pt,it=xn||cn&&Pt&&A||Qe;if(it&&!Jt){let vn=e.getRootNode(),pn=vn instanceof ShadowRoot?vn.host:e.closest(".persona-host");pn&&!Kt&&(Kt=Wi(pn,(Xt=(ot=r.launcher)==null?void 0:ot.zIndex)!=null?Xt:gn)),Jt=Ri(e.ownerDocument)}else it||(Kt==null||Kt(),Kt=null,Jt==null||Jt(),Jt=null)}}};Lt();let en=(cc=e.ownerDocument.defaultView)!=null?cc:window;if(en.addEventListener("resize",Lt),ft.push(()=>en.removeEventListener("resize",Lt)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{_n()});c.observe(_e),ft.push(()=>c.disconnect())}rr=Te.scrollTop;let wt=Te.scrollHeight,Et=()=>{let c=Te.scrollTop,g=Te.scrollHeight,y=g<wt;wt=g;let{action:b,nextLastScrollTop:T}=Da({following:nr.isFollowing(),currentScrollTop:c,lastScrollTop:rr,nearBottom:Rs(Te,rs),userScrollThreshold:Js,isAutoScrolling:Tr||co||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(rr=T,b==="resume"){jr();return}b==="pause"&&as()};Te.addEventListener("scroll",Et,{passive:!0}),ft.push(()=>Te.removeEventListener("scroll",Et));let tn=c=>{let g=Na({following:nr.isFollowing(),deltaY:c.deltaY,nearBottom:Rs(Te,rs),resumeWhenNearBottom:!0});g==="pause"?as():g==="resume"&&jr()};Te.addEventListener("wheel",tn,{passive:!0}),ft.push(()=>Te.removeEventListener("wheel",tn)),ut.addEventListener("click",()=>{Te.scrollTop=Te.scrollHeight,rr=Te.scrollTop,jr(),Ur(!0)}),ft.push(()=>ut.remove()),ft.push(()=>{ss()});let dn=()=>{Ue&&(Dn&&(Ue.removeEventListener("click",Dn),Dn=null),$()?(Ue.style.display="",Dn=()=>{Rt(!1,"user")},Ue.addEventListener("click",Dn)):Ue.style.display="none")};dn(),(()=>{let{clearChatButton:c}=$e;c&&c.addEventListener("click",()=>{_.clearMessages(),Nn.clear(),jr(),Mo($e.composerOverlay);try{localStorage.removeItem(es),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let y=i.clear();y instanceof Promise&&y.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}d={},S.syncFromMetadata(),G==null||G.clear(),ae==null||ae.update()})})(),Nt&&Nt.addEventListener("submit",us),ie==null||ie.addEventListener("keydown",gs),ie==null||ie.addEventListener("input",ms),ie==null||ie.addEventListener("paste",hs);let Gt=(dc=e.ownerDocument)!=null?dc:document;Gt.addEventListener("keydown",fs,!0);let Kn="persona-attachment-drop-active",bs=0,hi=()=>{bs=0,ne.classList.remove(Kn)},Bo=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&vt!==null},yl=c=>{!ai(c.dataTransfer)||!Bo()||(bs++,bs===1&&ne.classList.add(Kn))},bl=c=>{!ai(c.dataTransfer)||!Bo()||(bs--,bs<=0&&hi())},xl=c=>{!ai(c.dataTransfer)||!Bo()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},vl=c=>{var y;if(!ai(c.dataTransfer)||!Bo())return;c.preventDefault(),c.stopPropagation(),hi();let g=Array.from((y=c.dataTransfer.files)!=null?y:[]);g.length!==0&&vt.handleFiles(g)},Gr=!0;ne.addEventListener("dragenter",yl,Gr),ne.addEventListener("dragleave",bl,Gr),e.addEventListener("dragover",xl,Gr),e.addEventListener("drop",vl,Gr);let da=e.ownerDocument,wl=c=>{Bo()&&c.preventDefault()},Cl=c=>{Bo()&&c.preventDefault()};da.addEventListener("dragover",wl),da.addEventListener("drop",Cl),ft.push(()=>{Nt&&Nt.removeEventListener("submit",us),ie==null||ie.removeEventListener("keydown",gs),ie==null||ie.removeEventListener("input",ms),ie==null||ie.removeEventListener("paste",hs),Gt.removeEventListener("keydown",fs,!0)}),ft.push(()=>{ne.removeEventListener("dragenter",yl,Gr),ne.removeEventListener("dragleave",bl,Gr),e.removeEventListener("dragover",xl,Gr),e.removeEventListener("drop",vl,Gr),da.removeEventListener("dragover",wl),da.removeEventListener("drop",Cl),hi()}),ft.push(()=>{_.cancel()}),Me?ft.push(()=>{Me==null||Me.destroy()}):Ge&&ft.push(()=>{Ge==null||Ge.remove()});let Qt={update(c){var Zt,yr,Wr,pa,ua,ma,xo,ga,xs,yc,bc,xc,vc,wc,Cc,Ac,Sc,Ec,Tc,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Oc,Fc,$c,_c,jc,Uc,qc,zc,Vc,Kc,Jc,Gc,Xc,Yc,Qc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Ed,Td,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Od,Fd,$d,_d,jd,Ud,qd,zd,Vd,Kd,Jd,Gd,Xd,Yd,Qd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up;let g=r.toolCall,y=r.messageActions,b=(Zt=r.layout)==null?void 0:Zt.messages,T=r.colorScheme,D=r.loadingIndicator,N=r.iterationDisplay,q=(yr=r.features)==null?void 0:yr.showReasoning,I=(Wr=r.features)==null?void 0:Wr.showToolCalls,be=(pa=r.features)==null?void 0:pa.toolCallDisplay,le=(ua=r.features)==null?void 0:ua.reasoningDisplay;r={...r,...c},Zn(),So(e,r),ti(e,r),ni(e,r),Hn(),r.colorScheme!==T&&_r();let ee=ri.getForInstance(r.plugins);s.length=0,s.push(...ee),A=(xo=(ma=r.launcher)==null?void 0:ma.enabled)!=null?xo:!0,k=(xs=(ga=r.launcher)==null?void 0:ga.autoExpand)!=null?xs:!1,Pe=(bc=(yc=r.features)==null?void 0:yc.showReasoning)!=null?bc:!0,ze=(vc=(xc=r.features)==null?void 0:xc.showToolCalls)!=null?vc:!0,ce=(Cc=(wc=r.features)==null?void 0:wc.scrollToBottom)!=null?Cc:{},Br(),kr();let me=pe;if(pe=(Sc=(Ac=r.features)==null?void 0:Ac.showEventStreamToggle)!=null?Sc:!1,pe&&!me){if(G||(te=new Ks(je),G=new Vs(xe,te),te.open().then(()=>G==null?void 0:G.restore()).catch(()=>{}),_.setSSEEventCallback((Q,xt)=>{var Ot;(Ot=r.onSSEEvent)==null||Ot.call(r,Q,xt),G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(xt)})})),!gt&&De){let Q=(Tc=(Ec=r.features)==null?void 0:Ec.eventStream)==null?void 0:Tc.classNames,xt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");gt=h("button",xt),gt.style.width="28px",gt.style.height="28px",gt.style.color=An.actionIconColor,gt.type="button",gt.setAttribute("aria-label","Event Stream"),gt.title="Event Stream";let Ot=fe("activity","18px","currentColor",1.5);Ot&&gt.appendChild(Ot);let lt=$e.clearChatButtonWrapper,St=$e.closeButtonWrapper,nn=lt||St;nn&&nn.parentNode===De?De.insertBefore(gt,nn):De.appendChild(gt),gt.addEventListener("click",()=>{He?Qn():Cr()})}}else!pe&&me&&(Qn(),gt&&(gt.remove(),gt=null),G==null||G.clear(),te==null||te.destroy(),G=null,te=null);if(((Mc=r.launcher)==null?void 0:Mc.enabled)===!1&&Me&&(Me.destroy(),Me=null),((kc=r.launcher)==null?void 0:kc.enabled)===!1&&Ge&&(Ge.remove(),Ge=null),((Lc=r.launcher)==null?void 0:Lc.enabled)!==!1&&!Me&&!Ge){let Q=s.find(xt=>xt.renderLauncher);if(Q!=null&&Q.renderLauncher){let xt=Q.renderLauncher({config:r,defaultRenderer:()=>$s(r,Ze).element,onToggle:Ze});xt&&(Ge=xt,e.appendChild(Ge))}Ge||(Me=$s(r,Ze),e.appendChild(Me.element))}Me&&Me.update(r),Ae&&((Pc=r.launcher)==null?void 0:Pc.title)!==void 0&&(Ae.textContent=r.launcher.title),Be&&((Ic=r.launcher)==null?void 0:Ic.subtitle)!==void 0&&(Be.textContent=r.launcher.subtitle);let Ce=(Wc=r.layout)==null?void 0:Wc.header;if((Ce==null?void 0:Ce.layout)!==w&&De){let Q=Ce?_s(r,Ce,{showClose:$(),onClose:()=>Rt(!1,"user")}):eo({config:r,showClose:$(),onClose:()=>Rt(!1,"user")});De.replaceWith(Q.header),De=Q.header,U=Q.iconHolder,Ae=Q.headerTitle,Be=Q.headerSubtitle,Ue=Q.closeButton,w=Ce==null?void 0:Ce.layout}else if(Ce&&(U&&(U.style.display=Ce.showIcon===!1?"none":""),Ae&&(Ae.style.display=Ce.showTitle===!1?"none":""),Be&&(Be.style.display=Ce.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=Ce.showCloseButton===!1?"none":""),$e.clearChatButtonWrapper)){let Q=Ce.showClearChat;if(Q!==void 0){$e.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:xt}=$e;xt&&!xt.classList.contains("persona-absolute")&&(Q?xt.classList.remove("persona-ml-auto"):xt.classList.add("persona-ml-auto"))}}let et=((Rc=r.layout)==null?void 0:Rc.showHeader)!==!1;De&&(De.style.display=et?"":"none");let Xe=((Hc=r.layout)==null?void 0:Hc.showFooter)!==!1;_e&&(_e.style.display=Xe?"":"none"),_n(),kr(),A!==L?A?Rt(k,"auto"):(W=!0,Kr()):k!==H&&Rt(k,"auto"),H=k,L=A,Lt(),dn();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(g),ke=JSON.stringify(r.messageActions)!==JSON.stringify(y),qe=JSON.stringify((Bc=r.layout)==null?void 0:Bc.messages)!==JSON.stringify(b),E=((Dc=r.loadingIndicator)==null?void 0:Dc.render)!==(D==null?void 0:D.render)||((Nc=r.loadingIndicator)==null?void 0:Nc.renderIdle)!==(D==null?void 0:D.renderIdle)||((Oc=r.loadingIndicator)==null?void 0:Oc.showBubble)!==(D==null?void 0:D.showBubble),Se=r.iterationDisplay!==N,We=(($c=(Fc=r.features)==null?void 0:Fc.showReasoning)!=null?$c:!0)!==(q!=null?q:!0)||((jc=(_c=r.features)==null?void 0:_c.showToolCalls)!=null?jc:!0)!==(I!=null?I:!0)||JSON.stringify((Uc=r.features)==null?void 0:Uc.toolCallDisplay)!==JSON.stringify(be)||JSON.stringify((qc=r.features)==null?void 0:qc.reasoningDisplay)!==JSON.stringify(le);(Le||ke||qe||E||Se||We)&&_&&(ns++,uo(ve,_.getMessages(),Ie));let ye=(zc=r.launcher)!=null?zc:{},Tt=(Vc=ye.headerIconHidden)!=null?Vc:!1,ot=(Jc=(Kc=r.layout)==null?void 0:Kc.header)==null?void 0:Jc.showIcon,Xt=Tt||ot===!1,ln=ye.headerIconName,Pt=(Gc=ye.headerIconSize)!=null?Gc:"48px";if(U){let Q=ne.querySelector(".persona-border-b-persona-divider"),xt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Xt)U.style.display="none",Q&&xt&&!Q.contains(xt)&&Q.insertBefore(xt,Q.firstChild);else{if(U.style.display="",U.style.height=Pt,U.style.width=Pt,Q&&xt&&(Q.contains(U)?U.nextSibling!==xt&&(U.remove(),Q.insertBefore(U,xt)):Q.insertBefore(U,xt)),ln){let lt=parseFloat(Pt)||24,St=fe(ln,lt*.6,"#ffffff",2);St?U.replaceChildren(St):U.textContent=(Xc=ye.agentIconText)!=null?Xc:"\u{1F4AC}"}else if(ye.iconUrl){let lt=U.querySelector("img");if(lt)lt.src=ye.iconUrl,lt.style.height=Pt,lt.style.width=Pt;else{let St=document.createElement("img");St.src=ye.iconUrl,St.alt="",St.className="persona-rounded-xl persona-object-cover",St.style.height=Pt,St.style.width=Pt,U.replaceChildren(St)}}else{let lt=U.querySelector("svg"),St=U.querySelector("img");(lt||St)&&U.replaceChildren(),U.textContent=(Yc=ye.agentIconText)!=null?Yc:"\u{1F4AC}"}let Ot=U.querySelector("img");Ot&&(Ot.style.height=Pt,Ot.style.width=Pt)}}let xn=(Zc=(Qc=r.layout)==null?void 0:Qc.header)==null?void 0:Zc.showTitle,cn=(td=(ed=r.layout)==null?void 0:ed.header)==null?void 0:td.showSubtitle;if(Ae&&(Ae.style.display=xn===!1?"none":""),Be&&(Be.style.display=cn===!1?"none":""),Ue){((rd=(nd=r.layout)==null?void 0:nd.header)==null?void 0:rd.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let xt=(od=ye.closeButtonSize)!=null?od:"32px",Ot=(sd=ye.closeButtonPlacement)!=null?sd:"inline";Ue.style.height=xt,Ue.style.width=xt;let{closeButtonWrapper:lt}=$e,St=Ot==="top-right",nn=lt==null?void 0:lt.classList.contains("persona-absolute");if(lt&&St!==nn)if(lt.remove(),St)lt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ne.style.position="relative",ne.appendChild(lt);else{let pt=(id=(ad=ye.clearChat)==null?void 0:ad.placement)!=null?id:"inline",rn=(cd=(ld=ye.clearChat)==null?void 0:ld.enabled)!=null?cd:!0;lt.className=rn&&pt==="inline"?"":"persona-ml-auto";let Ln=ne.querySelector(".persona-border-b-persona-divider");Ln&&Ln.appendChild(lt)}if(Ue.style.color=ye.closeButtonColor||An.actionIconColor,ye.closeButtonBackgroundColor?(Ue.style.backgroundColor=ye.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),ye.closeButtonBorderWidth||ye.closeButtonBorderColor){let pt=ye.closeButtonBorderWidth||"0px",rn=ye.closeButtonBorderColor||"transparent";Ue.style.border=`${pt} solid ${rn}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");ye.closeButtonBorderRadius?(Ue.style.borderRadius=ye.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),ye.closeButtonPaddingX?(Ue.style.paddingLeft=ye.closeButtonPaddingX,Ue.style.paddingRight=ye.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),ye.closeButtonPaddingY?(Ue.style.paddingTop=ye.closeButtonPaddingY,Ue.style.paddingBottom=ye.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let un=(dd=ye.closeButtonIconName)!=null?dd:"x",ar=(pd=ye.closeButtonIconText)!=null?pd:"\xD7";Ue.innerHTML="";let Cn=fe(un,"28px","currentColor",1);Cn?Ue.appendChild(Cn):Ue.textContent=ar;let Yt=(ud=ye.closeButtonTooltipText)!=null?ud:"Close chat",$n=(md=ye.closeButtonShowTooltip)!=null?md:!0;if(Ue.setAttribute("aria-label",Yt),lt&&(lt._cleanupTooltip&&(lt._cleanupTooltip(),delete lt._cleanupTooltip),$n&&Yt)){let pt=null,rn=()=>{if(pt||!Ue)return;let vo=Ue.ownerDocument,vs=vo.body;if(!vs)return;pt=br(vo,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let ws=br(vo,"div");ws.className="persona-clear-chat-tooltip-arrow",pt.appendChild(ws);let wo=Ue.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Yr),pt.style.left=`${wo.left+wo.width/2}px`,pt.style.top=`${wo.top-8}px`,pt.style.transform="translate(-50%, -100%)",vs.appendChild(pt)},Ln=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};lt.addEventListener("mouseenter",rn),lt.addEventListener("mouseleave",Ln),Ue.addEventListener("focus",rn),Ue.addEventListener("blur",Ln),lt._cleanupTooltip=()=>{Ln(),lt&&(lt.removeEventListener("mouseenter",rn),lt.removeEventListener("mouseleave",Ln)),Ue&&(Ue.removeEventListener("focus",rn),Ue.removeEventListener("blur",Ln))}}}let{clearChatButton:Qe,clearChatButtonWrapper:it}=$e;if(Qe){let Q=(gd=ye.clearChat)!=null?gd:{},xt=(fd=Q.enabled)!=null?fd:!0,Ot=(yd=(hd=r.layout)==null?void 0:hd.header)==null?void 0:yd.showClearChat,lt=Ot!==void 0?Ot:xt,St=(bd=Q.placement)!=null?bd:"inline";if(it){it.style.display=lt?"":"none";let{closeButtonWrapper:nn}=$e;!F()&&nn&&!nn.classList.contains("persona-absolute")&&(lt?nn.classList.remove("persona-ml-auto"):nn.classList.add("persona-ml-auto"));let un=St==="top-right",ar=it.classList.contains("persona-absolute");if(!F()&&un!==ar&&lt){if(it.remove(),un)it.className="persona-absolute persona-top-4 persona-z-50",it.style.right="48px",ne.style.position="relative",ne.appendChild(it);else{it.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",it.style.right="";let Yt=ne.querySelector(".persona-border-b-persona-divider"),$n=$e.closeButtonWrapper;Yt&&$n&&$n.parentElement===Yt?Yt.insertBefore(it,$n):Yt&&Yt.appendChild(it)}let Cn=$e.closeButtonWrapper;Cn&&!Cn.classList.contains("persona-absolute")&&(un?Cn.classList.add("persona-ml-auto"):Cn.classList.remove("persona-ml-auto"))}}if(lt){if(!F()){let pt=(xd=Q.size)!=null?xd:"32px";Qe.style.height=pt,Qe.style.width=pt}let nn=(vd=Q.iconName)!=null?vd:"refresh-cw",un=(wd=Q.iconColor)!=null?wd:"";Qe.style.color=un||An.actionIconColor,Qe.innerHTML="";let ar=F()?"14px":"20px",Cn=fe(nn,ar,"currentColor",2);if(Cn&&Qe.appendChild(Cn),Q.backgroundColor?(Qe.style.backgroundColor=Q.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let pt=Q.borderWidth||"0px",rn=Q.borderColor||"transparent";Qe.style.border=`${pt} solid ${rn}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");Q.borderRadius?(Qe.style.borderRadius=Q.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),Q.paddingX?(Qe.style.paddingLeft=Q.paddingX,Qe.style.paddingRight=Q.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),Q.paddingY?(Qe.style.paddingTop=Q.paddingY,Qe.style.paddingBottom=Q.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let Yt=(Cd=Q.tooltipText)!=null?Cd:"Clear chat",$n=(Ad=Q.showTooltip)!=null?Ad:!0;if(Qe.setAttribute("aria-label",Yt),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),$n&&Yt)){let pt=null,rn=()=>{if(pt||!Qe)return;let vo=Qe.ownerDocument,vs=vo.body;if(!vs)return;pt=br(vo,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let ws=br(vo,"div");ws.className="persona-clear-chat-tooltip-arrow",pt.appendChild(ws);let wo=Qe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Yr),pt.style.left=`${wo.left+wo.width/2}px`,pt.style.top=`${wo.top-8}px`,pt.style.transform="translate(-50%, -100%)",vs.appendChild(pt)},Ln=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};it.addEventListener("mouseenter",rn),it.addEventListener("mouseleave",Ln),Qe.addEventListener("focus",rn),Qe.addEventListener("blur",Ln),it._cleanupTooltip=()=>{Ln(),it&&(it.removeEventListener("mouseenter",rn),it.removeEventListener("mouseleave",Ln)),Qe&&(Qe.removeEventListener("focus",rn),Qe.removeEventListener("blur",Ln))}}}}let vn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[oi],pn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Zo.message,Zo.messageAndClick];S=si({parsers:vn,handlers:pn,getSessionMetadata:f,updateSessionMetadata:m,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Ie=Bu(r,S,oe),_.updateConfig(r),uo(ve,_.getMessages(),Ie),er.render(r.suggestionChips,_,ie,void 0,r.suggestionChipsConfig),ds(),Io(_.isStreaming());let fo=((Sd=r.voiceRecognition)==null?void 0:Sd.enabled)===!0,ho=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),yo=((Td=(Ed=r.voiceRecognition)==null?void 0:Ed.provider)==null?void 0:Td.type)==="runtype";if(fo&&(ho||yo))if(!P||!he){let Q=ca(r.voiceRecognition,r.sendButton);Q&&(P=Q.micButton,he=Q.micButtonWrapper,Ct.insertBefore(he,sn),P.addEventListener("click",Y),P.disabled=_.isStreaming())}else{let Q=(Md=r.voiceRecognition)!=null?Md:{},xt=(kd=r.sendButton)!=null?kd:{},Ot=(Ld=Q.iconName)!=null?Ld:"mic",lt=(Pd=xt.size)!=null?Pd:"40px",St=(Id=Q.iconSize)!=null?Id:lt,nn=parseFloat(St)||24;P.style.width=St,P.style.height=St,P.style.minWidth=St,P.style.minHeight=St;let un=(Rd=(Wd=Q.iconColor)!=null?Wd:xt.textColor)!=null?Rd:"currentColor";P.innerHTML="";let ar=fe(Ot,nn,un,2);ar?P.appendChild(ar):P.textContent="\u{1F3A4}";let Cn=(Hd=Q.backgroundColor)!=null?Hd:xt.backgroundColor;Cn?P.style.backgroundColor=Cn:P.style.backgroundColor="",un?P.style.color=un:P.style.color="var(--persona-text, #111827)",Q.borderWidth?(P.style.borderWidth=Q.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),Q.borderColor?P.style.borderColor=Q.borderColor:P.style.borderColor="",Q.paddingX?(P.style.paddingLeft=Q.paddingX,P.style.paddingRight=Q.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),Q.paddingY?(P.style.paddingTop=Q.paddingY,P.style.paddingBottom=Q.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let Yt=he==null?void 0:he.querySelector(".persona-send-button-tooltip"),$n=(Bd=Q.tooltipText)!=null?Bd:"Start voice recognition";if(((Dd=Q.showTooltip)!=null?Dd:!1)&&$n)if(Yt)Yt.textContent=$n,Yt.style.display="";else{let rn=document.createElement("div");rn.className="persona-send-button-tooltip",rn.textContent=$n,he==null||he.insertBefore(rn,P)}else Yt&&(Yt.style.display="none");he.style.display="",P.disabled=_.isStreaming()}else P&&he&&(he.style.display="none",((Od=(Nd=r.voiceRecognition)==null?void 0:Nd.provider)==null?void 0:Od.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():On&&sr());if(((Fd=r.attachments)==null?void 0:Fd.enabled)===!0)if(!dt||!ge){let Q=($d=r.attachments)!=null?$d:{},Ot=(jd=((_d=r.sendButton)!=null?_d:{}).size)!=null?jd:"40px";It||(It=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),It.style.display="none",Nt.insertBefore(It,ie)),Ke||(Ke=document.createElement("input"),Ke.type="file",Ke.accept=((Ud=Q.allowedTypes)!=null?Ud:Rr).join(","),Ke.multiple=((qd=Q.maxFiles)!=null?qd:4)>1,Ke.style.display="none",Ke.setAttribute("aria-label","Attach files"),Nt.insertBefore(Ke,ie)),dt=h("div","persona-send-button-wrapper"),ge=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ge.type="button",ge.setAttribute("aria-label",(zd=Q.buttonTooltipText)!=null?zd:"Attach file");let lt=(Vd=Q.buttonIconName)!=null?Vd:"paperclip",St=Ot,nn=parseFloat(St)||40,un=Math.round(nn*.6);ge.style.width=St,ge.style.height=St,ge.style.minWidth=St,ge.style.minHeight=St,ge.style.fontSize="18px",ge.style.lineHeight="1",ge.style.backgroundColor="transparent",ge.style.color="var(--persona-primary, #111827)",ge.style.border="none",ge.style.borderRadius="6px",ge.style.transition="background-color 0.15s ease",ge.addEventListener("mouseenter",()=>{ge.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ge.addEventListener("mouseleave",()=>{ge.style.backgroundColor="transparent"});let ar=fe(lt,un,"currentColor",1.5);ar?ge.appendChild(ar):ge.textContent="\u{1F4CE}",ge.addEventListener("click",$n=>{$n.preventDefault(),Ke==null||Ke.click()}),dt.appendChild(ge);let Cn=(Kd=Q.buttonTooltipText)!=null?Kd:"Attach file",Yt=h("div","persona-send-button-tooltip");Yt.textContent=Cn,dt.appendChild(Yt),nt.append(dt),!vt&&Ke&&It&&(vt=qo.fromConfig(Q),vt.setPreviewsContainer(It),Ke.addEventListener("change",async()=>{vt&&(Ke!=null&&Ke.files)&&(await vt.handleFileSelect(Ke.files),Ke.value="")})),ne.querySelector(".persona-attachment-drop-overlay")||ne.appendChild(Du(Q.dropOverlay))}else{dt.style.display="";let Q=(Jd=r.attachments)!=null?Jd:{};Ke&&(Ke.accept=((Gd=Q.allowedTypes)!=null?Gd:Rr).join(","),Ke.multiple=((Xd=Q.maxFiles)!=null?Xd:4)>1),vt&&vt.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else dt&&(dt.style.display="none"),vt&&vt.clearAttachments(),(Yd=ne.querySelector(".persona-attachment-drop-overlay"))==null||Yd.remove();let Ut=(Qd=r.sendButton)!=null?Qd:{},bo=(Zd=Ut.useIcon)!=null?Zd:!1,Xr=(ep=Ut.iconText)!=null?ep:"\u2191",ht=Ut.iconName,Tn=(tp=Ut.tooltipText)!=null?tp:"Send message",Ir=(np=Ut.showTooltip)!=null?np:!1,wn=(rp=Ut.size)!=null?rp:"40px",Mn=Ut.backgroundColor,Bt=Ut.textColor;if(bo){if(re.style.width=wn,re.style.height=wn,re.style.minWidth=wn,re.style.minHeight=wn,re.style.fontSize="18px",re.style.lineHeight="1",re.innerHTML="",Bt?re.style.color=Bt:re.style.color="var(--persona-button-primary-fg, #ffffff)",ht){let Q=parseFloat(wn)||24,xt=(Bt==null?void 0:Bt.trim())||"currentColor",Ot=fe(ht,Q,xt,2);Ot?re.appendChild(Ot):re.textContent=Xr}else re.textContent=Xr;re.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Mn?(re.style.backgroundColor=Mn,re.classList.remove("persona-bg-persona-primary")):(re.style.backgroundColor="",re.classList.add("persona-bg-persona-primary"))}else re.textContent=(sp=(op=r.copy)==null?void 0:op.sendButtonLabel)!=null?sp:"Send",re.style.width="",re.style.height="",re.style.minWidth="",re.style.minHeight="",re.style.fontSize="",re.style.lineHeight="",re.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",Mn?(re.style.backgroundColor=Mn,re.classList.remove("persona-bg-persona-accent")):re.classList.add("persona-bg-persona-accent"),Bt?re.style.color=Bt:re.classList.add("persona-text-white");Ut.borderWidth?(re.style.borderWidth=Ut.borderWidth,re.style.borderStyle="solid"):(re.style.borderWidth="",re.style.borderStyle=""),Ut.borderColor?re.style.borderColor=Ut.borderColor:re.style.borderColor="",Ut.paddingX?(re.style.paddingLeft=Ut.paddingX,re.style.paddingRight=Ut.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),Ut.paddingY?(re.style.paddingTop=Ut.paddingY,re.style.paddingBottom=Ut.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let $t=sn==null?void 0:sn.querySelector(".persona-send-button-tooltip");if(Ir&&Tn)if($t)$t.textContent=Tn,$t.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Tn,sn==null||sn.insertBefore(Q,re)}else $t&&($t.style.display="none");let Dt=(dp=(ap=r.layout)==null?void 0:ap.contentMaxWidth)!=null?dp:F()?(cp=(lp=(ip=r.launcher)==null?void 0:ip.composerBar)==null?void 0:lp.contentMaxWidth)!=null?cp:"720px":void 0;Dt?(ve.style.maxWidth=Dt,ve.style.marginLeft="auto",ve.style.marginRight="auto",ve.style.width="100%",Nt&&(Nt.style.maxWidth=Dt,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Ht&&(Ht.style.maxWidth=Dt,Ht.style.marginLeft="auto",Ht.style.marginRight="auto")):(ve.style.maxWidth="",ve.style.marginLeft="",ve.style.marginRight="",ve.style.width="",Nt&&(Nt.style.maxWidth="",Nt.style.marginLeft="",Nt.style.marginRight=""),Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""));let qt=(pp=r.statusIndicator)!=null?pp:{},kn=(up=qt.visible)!=null?up:!0;if(zt.style.display=kn?"":"none",_){let Q=_.getStatus();Oe(zt,(Ot=>{var lt,St,nn,un;return Ot==="idle"?(lt=qt.idleText)!=null?lt:mn.idle:Ot==="connecting"?(St=qt.connectingText)!=null?St:mn.connecting:Ot==="connected"?(nn=qt.connectedText)!=null?nn:mn.connected:Ot==="error"?(un=qt.errorText)!=null?un:mn.error:mn[Ot]})(Q),qt,Q)}zt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Fn=qt.align==="left"?"persona-text-left":qt.align==="center"?"persona-text-center":"persona-text-right";zt.classList.add(Fn)},open(){$()&&Rt(!0,"api")},close(){$()&&Rt(!1,"api")},toggle(){$()&&Rt(!W,"api")},clearChat(){fn=!1,_.clearMessages(),Nn.clear(),jr();try{localStorage.removeItem(es),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}d={},S.syncFromMetadata(),G==null||G.clear(),ae==null||ae.update()},setMessage(c){return!ie||_.isStreaming()?!1:(!W&&$()&&Rt(!0,"system"),ie.value=c,ie.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(_.isStreaming())return!1;let g=(c==null?void 0:c.trim())||ie.value.trim();return g?(!W&&$()&&Rt(!0,"system"),ie.value="",ie.style.height="auto",_.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return _.isStreaming()?!1:((y=(g=r.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(_.isVoiceActive()||(!W&&$()&&Rt(!0,"system"),mt.manuallyDeactivated=!1,En(),_.toggleVoice().then(()=>{mt.active=_.isVoiceActive(),Vn("user"),_.isVoiceActive()&&j()})),!0):On?!0:ys()?(!W&&$()&&Rt(!0,"system"),mt.manuallyDeactivated=!1,En(),go("user"),!0):!1},stopVoiceRecognition(){var c,g;return((g=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:g.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{mt.active=!1,mt.manuallyDeactivated=!0,En(),Vn("user"),X()}),!0):!1:On?(mt.manuallyDeactivated=!0,En(),sr("user"),!0):!1},injectMessage(c){return!W&&$()&&Rt(!0,"system"),_.injectMessage(c)},injectAssistantMessage(c){!W&&$()&&Rt(!0,"system");let g=_.injectAssistantMessage(c);return O&&(O=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),g},injectUserMessage(c){return!W&&$()&&Rt(!0,"system"),_.injectUserMessage(c)},injectSystemMessage(c){return!W&&$()&&Rt(!0,"system"),_.injectSystemMessage(c)},injectMessageBatch(c){return!W&&$()&&Rt(!0,"system"),_.injectMessageBatch(c)},injectComponentDirective(c){return!W&&$()&&Rt(!0,"system"),_.injectComponentDirective(c)},injectTestMessage(c){!W&&$()&&Rt(!0,"system"),_.injectTestEvent(c)},async connectStream(c,g){return _.connectStream(c,g)},__pushEventStreamEvent(c){G&&G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)})},showEventStream(){!pe||!G||Cr()},hideEventStream(){He&&Qn()},isEventStreamVisible(){return He},showArtifacts(){Yn(r)&&(fn=!1,Hn(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){Yn(r)&&(fn=!0,Hn())},upsertArtifact(c){return Yn(r)?(fn=!1,_.upsertArtifact(c)):null},selectArtifact(c){Yn(r)&&_.selectArtifact(c)},clearArtifacts(){Yn(r)&&_.clearArtifacts()},getArtifacts(){var c;return(c=_==null?void 0:_.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=_==null?void 0:_.getSelectedArtifactId())!=null?c:null},focusInput(){return A&&!W&&!F()||!ie?!1:(ie.focus(),!0)},async resolveApproval(c,g){let b=_.getMessages().find(T=>{var D;return T.variant==="approval"&&((D=T.approval)==null?void 0:D.id)===c});if(!(b!=null&&b.approval))throw new Error(`Approval not found: ${c}`);if(b.approval.toolType==="webmcp"){_.resolveWebMcpApproval(b.id,g);return}return _.resolveApproval(b.approval,g)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){m(c)},on(c,g){return o.on(c,g)},off(c,g){o.off(c,g)},isOpen(){return $()&&W},isVoiceActive(){return mt.active},getState(){return{open:$()&&W,launcherEnabled:A,voiceActive:mt.active,streaming:_.isStreaming()}},showCSATFeedback(c){!W&&$()&&Rt(!0,"system");let g=ve.querySelector(".persona-feedback-container");g&&g.remove();let y=rl({onSubmit:async(b,T)=>{var D;_.isClientTokenMode()&&await _.submitCSATFeedback(b,T),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,T)},onDismiss:c==null?void 0:c.onDismiss,...c});ve.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!W&&$()&&Rt(!0,"system");let g=ve.querySelector(".persona-feedback-container");g&&g.remove();let y=ol({onSubmit:async(b,T)=>{var D;_.isClientTokenMode()&&await _.submitNPSFeedback(b,T),(D=c==null?void 0:c.onSubmit)==null||D.call(c,b,T)},onDismiss:c==null?void 0:c.onDismiss,...c});ve.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,g){return _.submitCSATFeedback(c,g)},async submitNPSFeedback(c,g){return _.submitNPSFeedback(c,g)},destroy(){hr!=null&&(clearInterval(hr),hr=null),ft.forEach(c=>c()),J.remove(),we==null||we.remove(),Me==null||Me.destroy(),Ge==null||Ge.remove(),Dn&&Ue.removeEventListener("click",Dn)}};if((((pc=t==null?void 0:t.debugTools)!=null?pc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,g={controller:Qt,getMessages:Qt.getMessages,getStatus:Qt.getStatus,getMetadata:Qt.getPersistentMetadata,updateMetadata:Qt.updatePersistentMetadata,clearHistory:()=>Qt.clearChat(),setVoiceActive:y=>y?Qt.startVoiceRecognition():Qt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ft.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=q=>{let I=q.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Qt.focusInput()};if(window.addEventListener("persona:focusInput",g),ft.push(()=>{window.removeEventListener("persona:focusInput",g)}),pe){let q=be=>{let le=be.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&Qt.showEventStream()},I=be=>{let le=be.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&Qt.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",I),ft.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",I)})}let y=q=>{let I=q.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Qt.showArtifacts()},b=q=>{let I=q.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Qt.hideArtifacts()},T=q=>{let I=q.detail;I!=null&&I.instanceId&&I.instanceId!==c||I!=null&&I.artifact&&Qt.upsertArtifact(I.artifact)},D=q=>{let I=q.detail;I!=null&&I.instanceId&&I.instanceId!==c||typeof(I==null?void 0:I.id)=="string"&&Qt.selectArtifact(I.id)},N=q=>{let I=q.detail;(!(I!=null&&I.instanceId)||I.instanceId===c)&&Qt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",N),ft.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",N)})}let Jn=tb(r.persistState);if(Jn&&$()){let c=nb(Jn.storage),g=`${Jn.keyPrefix}widget-open`,y=`${Jn.keyPrefix}widget-voice`,b=`${Jn.keyPrefix}widget-voice-mode`;if(c){let T=((uc=Jn.persist)==null?void 0:uc.openState)&&c.getItem(g)==="true",D=((mc=Jn.persist)==null?void 0:mc.voiceState)&&c.getItem(y)==="true",N=((gc=Jn.persist)==null?void 0:gc.voiceState)&&c.getItem(b)==="true";if(T&&setTimeout(()=>{Qt.open(),setTimeout(()=>{var q;if(D||N)Qt.startVoiceRecognition();else if((q=Jn.persist)!=null&&q.focusInput){let I=e.querySelector("textarea");I&&I.focus()}},100)},0),(fc=Jn.persist)!=null&&fc.openState&&(o.on("widget:opened",()=>{c.setItem(g,"true")}),o.on("widget:closed",()=>{c.setItem(g,"false")})),(hc=Jn.persist)!=null&&hc.voiceState&&(o.on("voice:state",q=>{c.setItem(y,q.active?"true":"false")}),o.on("user:message",q=>{c.setItem(b,q.viaVoice?"true":"false")})),Jn.clearOnChatClear){let q=()=>{c.removeItem(g),c.removeItem(y),c.removeItem(b)},I=()=>q();window.addEventListener("persona:clear-chat",I),ft.push(()=>{window.removeEventListener("persona:clear-chat",I)})}}}return u&&$()&&setTimeout(()=>{Qt.open()},0),Lr(),Qt};var rb=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,n*parseFloat(s[1])/100):420},Nu=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},dl=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Ou=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",dl(e)},il=e=>{e.style.transition=""},ll=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},cl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ii=(e,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},ob=(e,n,t,r,s)=>{s?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},sb=(e,n,t,r,s,o)=>{let a=o?n:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Fu=(e,n,t,r,s,o,a)=>{var v,x,S,A,k,R;let i=lr(o),d=i.reveal==="push";ob(e,n,t,r,d),sb(e,n,t,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,u=(x=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,p=(A=(S=o==null?void 0:o.launcher)==null?void 0:S.mobileBreakpoint)!=null?A:640,f=l!=null?l.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ll(n),il(r),Ou(r),cl(t),ii(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((R=(k=o==null?void 0:o.launcher)==null?void 0:k.zIndex)!=null?R:gn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Ou(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",ll(n),il(r),cl(t),ii(s,r);let H=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":L;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=H,r.style.transform=w,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",il(r),dl(r),ii(s,r);let H=rb(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",B=i.side==="right"?a?`translateX(-${H}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${H}px)`;n.style.display="flex",n.style.flexDirection="row",n.style.flex="0 0 auto",n.style.minHeight="0",n.style.minWidth="0",n.style.alignItems="stretch",n.style.height="100%",n.style.width=`${L+H}px`,n.style.transition=w,n.style.transform=B,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${L}px`,t.style.maxWidth=`${L}px`,t.style.minWidth=`${L}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",ll(n),dl(r),cl(t),ii(s,r);let H=i.reveal==="emerge";H?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",B=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${L}`,r.style.width=L,r.style.maxWidth=L,r.style.minWidth=L,r.style.minHeight="0",r.style.position="relative",r.style.overflow=H||B?"hidden":"visible",r.style.transition=w,H&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},ab=(e,n)=>{let t=e.ownerDocument.createElement("div");return Nu(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Nu(t,r)},destroy(){t.remove()}}},ib=(e,n)=>{var k,R,H,L;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),l=t.createElement("aside"),u=t.createElement("div"),p=(R=(k=n==null?void 0:n.launcher)==null?void 0:k.enabled)==null||R?(L=(H=n==null?void 0:n.launcher)==null?void 0:H.autoExpand)!=null?L:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",l.appendChild(u),r.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),lr(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Fu(a,i,d,l,u,n,p)}),f.observe(a))},x=()=>{Fu(a,i,d,l,u,n,p),v()},S=a.ownerDocument.defaultView,A=()=>{x()};return S==null||S.addEventListener("resize",A),lr(n).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),x(),{mode:"docked",host:u,shell:a,syncWidgetState(w){let B=w.launcherEnabled?w.open:!0;p!==B&&(p=B,x())},updateConfig(w){var B,F;n=w,((F=(B=n==null?void 0:n.launcher)==null?void 0:B.enabled)!=null?F:!0)===!1&&(p=!0),x()},destroy(){S==null||S.removeEventListener("resize",A),m(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},li=(e,n)=>on(n)?ib(e,n):ab(e,n);var pl={},lb=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},cb=()=>{try{if(typeof pl!="undefined"&&pl.url)return new URL("../widget.css",pl.url).href}catch{}return null},$u=(e,n)=>{let t=cb(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},_u=e=>{var S;let n=lb(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=li(n,s),a,i=[],d=(A,k)=>{var w,B;let H=!((B=(w=k==null?void 0:k.launcher)==null?void 0:w.enabled)!=null?B:!0)||on(k),L=r.createElement("div");if(L.setAttribute("data-persona-root","true"),H&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),t){let F=A.attachShadow({mode:"open"});F.appendChild(L),$u(F,r)}else A.appendChild(L),$u(A,r);return n.id&&L.setAttribute("data-persona-instance",n.id),L},l=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(A=>A()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},p=()=>{let A=d(o.host,s);a=al(A,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(A=>A()),i=[],a.destroy()};p(),(S=e.onReady)==null||S.call(e);let m=A=>{f(),o.destroy(),o=li(n,A),s=A,p()},v={update(A){var B,F,$,W,O,V;let k={...s,...A,launcher:{...(B=s==null?void 0:s.launcher)!=null?B:{},...(F=A==null?void 0:A.launcher)!=null?F:{},dock:{...(W=($=s==null?void 0:s.launcher)==null?void 0:$.dock)!=null?W:{},...(V=(O=A==null?void 0:A.launcher)==null?void 0:O.dock)!=null?V:{}}}},R=on(s),H=on(k),L=Zr(s),w=Zr(k);if(R!==H||L!==w){m(k);return}s=k,o.updateConfig(s),a.update(A),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(A,k,R){if(k==="host")return o.host;if(k in A)return Reflect.get(A,k,R);let H=a[k];return typeof H=="function"?H.bind(a):H}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var Vu=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),db=new Set(["button","a","input","select","textarea","details","summary"]),pb=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ul=/\b(product|card|item|listing|result)\b/i,gl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,ub=3e3,mb=100;function Ku(e){let n=typeof e.className=="string"?e.className:"";if(ul.test(n)||e.id&&ul.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&ul.test(r.value))return!0}return!1}function Ju(e){var n;return gl.test(((n=e.textContent)!=null?n:"").trim())}function Gu(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function gb(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ju(e){let n=e.match(gl);return n?n[0]:null}function Uu(e){var r,s,o;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function fb(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var hb="commerce-card",yb="result-card";function qu(e){return!Ku(e)||!Ju(e)||!Gu(e)&&!gb(e)?0:5200}function zu(e){var r;return!Ku(e)||Ju(e)||!Gu(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 Xu=[{id:hb,scoreElement(e){return qu(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||gl.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,l,u;if(qu(e)===0)return null;let{title:t,href:r}=Uu(e),s=(u=(l=ju(((d=e.textContent)!=null?d:"").trim()))!=null?l:ju(n.text))!=null?u:"",o=fb(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
108
+ `)}},{id:yb,scoreElement(e){return zu(e)},formatSummary(e,n){if(zu(e)===0)return null;let{title:t,href:r}=Uu(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
109
+ `)}}];function bb(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function xb(e){var u,p,f,m,v,x,S,A,k,R,H,L,w;let n=(u=e.options)!=null?u:{},t=(f=(p=n.maxElements)!=null?p:e.maxElements)!=null?f:80,r=(v=(m=n.excludeSelector)!=null?m:e.excludeSelector)!=null?v:".persona-host",s=(S=(x=n.maxTextLength)!=null?x:e.maxTextLength)!=null?S:200,o=(k=(A=n.visibleOnly)!=null?A:e.visibleOnly)!=null?k:!0,a=(R=n.root)!=null?R:e.root,i=(H=n.mode)!=null?H:"structured",d=(L=n.maxCandidates)!=null?L:Math.max(500,t*10),l=(w=e.rules)!=null?w:Xu;return i==="simple"&&e.rules&&e.rules.length>0?(bb(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function ml(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var vb=["data-testid","data-product","data-action","data-id","data-name","data-type"];function wb(e){let n=e.tagName.toLowerCase(),t=e.getAttribute("role");return n==="a"&&e.hasAttribute("href")?"navigable":n==="input"||n==="select"||n==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":n==="button"||t==="button"||db.has(n)||t&&pb.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Yu(e){if(e.hidden)return!1;try{let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Cb(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let s=e.getAttribute("aria-label");s&&(n["aria-label"]=s);let o=e.getAttribute("type");o&&(n.type=o);let a=e.getAttribute("value");a&&(n.value=a);let i=e.getAttribute("name");i&&(n.name=i);let d=e.getAttribute("role");d&&(n.role=d);for(let l=0;l<e.attributes.length;l++){let u=e.attributes[l];u.name.startsWith("data-")&&(n[u.name]=u.value)}return n}function Qu(e){let n=e.tagName.toLowerCase();if(e.id){let s=`#${ml(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of vb){let o=e.getAttribute(s);if(o){let a=`${n}[${s}="${ml(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(t.length>0){let s=`${n}.${t.map(a=>ml(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(o>=0)return`${n}:nth-of-type(${o+1})`}return n}function Ab(e){return e==="static"?mb:ub}function Zu(e,n){var s;let t=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,n);return{selector:Qu(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:wb(e),attributes:Cb(e)}}function Sb(e,n,t,r){let s=Ab(n.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function Eb(e,n){var t;for(let r of e)if(n.el!==r.el&&(t=r.formattingRule)!=null&&t.shouldSuppressDescendant&&r.el.contains(n.el)&&r.formattingRule.shouldSuppressDescendant(r.el,n.el,n.enriched))return!0;return!1}function Tb(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,u=l.tagName.toLowerCase();if(Vu.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Yu(l)){i=a.nextNode();continue}let p=Zu(l,e.maxTextLength),f=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(S=>S==="role");if(!f&&!m){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:v,formattingRule:x}=Sb(l,p,e.rules,t);s.push({el:l,domIndex:o,enriched:p,score:v,formattingRule:x}),o+=1}i=a.nextNode()}s.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;Eb(d,l)||d.push(l)}return d.sort((l,u)=>{let p=l.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&u.score!==l.score?u.score-l.score:l.domIndex-u.domIndex}),d.map(l=>{var f;let u;if((f=l.formattingRule)!=null&&f.formatSummary){let m=l.formattingRule.formatSummary(l.el,l.enriched,t);m&&(u=m)}let p={...l.enriched};return u&&(p.formattedSummary=u),p})}function Mb(e,n){let t=[],r=new Set,s=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(Vu.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Yu(d)){o=s.nextNode();continue}let u=Zu(d,e.maxTextLength),p=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!p&&!f){o=s.nextNode();continue}r.has(u.selector)||(r.add(u.selector),t.push(u))}o=s.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function kb(e={}){var r;let n=xb(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?Mb(n,t):Tb(n,t):[]}var ci=100;function Lb(e,n={}){var o;if(e.length===0)return"No page elements found.";let t=(o=n.mode)!=null?o:"structured",r=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
103
110
  ${a.map(i=>`- ${i.split(`
104
111
  `).join(`
105
112
  `)}`).join(`
106
- `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Za)}" (clickable)`);r.push(`Interactive elements:
113
+ `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,ci)}" (clickable)`);r.push(`Interactive elements:
107
114
  ${a.join(`
108
- `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Za)}" (navigable)`);r.push(`Navigation links:
115
+ `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,ci)}" (navigable)`);r.push(`Navigation links:
109
116
  ${a.join(`
110
- `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Za)}" (input)`);r.push(`Form inputs:
117
+ `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,ci)}" (input)`);r.push(`Form inputs:
111
118
  ${a.join(`
112
- `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Za)}"`);r.push(`Content:
119
+ `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,ci)}"`);r.push(`Content:
113
120
  ${a.join(`
114
121
  `)}`)}return r.join(`
115
122
 
116
- `)}var Bu={name:"@runtypelabs/persona",version:"3.21.2",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var ts=Bu.version;function Hr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function sb(e){if(e)return{getHeaders:Hr(e.getHeaders),onFeedback:Hr(e.onFeedback),onCopy:Hr(e.onCopy),requestMiddleware:Hr(e.requestMiddleware),actionHandlers:Hr(e.actionHandlers),actionParsers:Hr(e.actionParsers),postprocessMessage:Hr(e.postprocessMessage),contextProviders:Hr(e.contextProviders),streamParser:Hr(e.streamParser)}}var Du=`({ text, message }: any) => {
123
+ `)}var em={name:"@runtypelabs/persona",version:"3.22.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"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./smart-dom-reader":{types:"./dist/smart-dom-reader.d.ts",import:"./dist/smart-dom-reader.js",require:"./dist/smart-dom-reader.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor && pnpm run build:testing && pnpm run build:smart-dom-reader && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:smart-dom-reader":"tsup src/smart-dom-reader.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --dts --out-dir dist/animations --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":`tsup src/index.ts --format esm,cjs --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"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:{"@mcp-b/webmcp-polyfill":"^3.0.0",dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var ts=em.version;function Hr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function Ib(e){if(e)return{getHeaders:Hr(e.getHeaders),onFeedback:Hr(e.onFeedback),onCopy:Hr(e.onCopy),requestMiddleware:Hr(e.requestMiddleware),actionHandlers:Hr(e.actionHandlers),actionParsers:Hr(e.actionParsers),postprocessMessage:Hr(e.postprocessMessage),contextProviders:Hr(e.contextProviders),streamParser:Hr(e.streamParser)}}var tm=`({ text, message }: any) => {
117
124
  const jsonSource = (message as any).rawContent || text || message.content;
118
125
  if (!jsonSource || typeof jsonSource !== 'string') return null;
119
126
  let cleanJson = jsonSource
@@ -126,7 +133,7 @@ ${a.join(`
126
133
  if (parsed.action) return { type: parsed.action, payload: parsed };
127
134
  } catch (e) { return null; }
128
135
  return null;
129
- }`,Nu=`function(ctx) {
136
+ }`,nm=`function(ctx) {
130
137
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
131
138
  if (!jsonSource || typeof jsonSource !== 'string') return null;
132
139
  var cleanJson = jsonSource
@@ -139,7 +146,7 @@ ${a.join(`
139
146
  if (parsed.action) return { type: parsed.action, payload: parsed };
140
147
  } catch (e) { return null; }
141
148
  return null;
142
- }`,Fu=`(action: any, context: any) => {
149
+ }`,rm=`(action: any, context: any) => {
143
150
  if (action.type !== 'nav_then_click') return;
144
151
  const payload = action.payload || action.raw || {};
145
152
  const url = payload?.page;
@@ -156,7 +163,7 @@ ${a.join(`
156
163
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
157
164
  window.location.href = targetUrl;
158
165
  return { handled: true, displayText: text };
159
- }`,Ou=`function(action, context) {
166
+ }`,om=`function(action, context) {
160
167
  if (action.type !== 'nav_then_click') return;
161
168
  var payload = action.payload || action.raw || {};
162
169
  var url = payload.page;
@@ -173,26 +180,26 @@ ${a.join(`
173
180
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
174
181
  window.location.href = targetUrl;
175
182
  return { handled: true, displayText: text };
176
- }`,ab=`(parsed: any) => {
183
+ }`,Wb=`(parsed: any) => {
177
184
  if (!parsed || typeof parsed !== 'object') return null;
178
185
  if (parsed.action === 'nav_then_click') return 'Navigating...';
179
186
  if (parsed.action === 'message') return parsed.text || '';
180
187
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
181
188
  return parsed.text || null;
182
- }`,ib=`function(parsed) {
189
+ }`,Rb=`function(parsed) {
183
190
  if (!parsed || typeof parsed !== 'object') return null;
184
191
  if (parsed.action === 'nav_then_click') return 'Navigating...';
185
192
  if (parsed.action === 'message') return parsed.text || '';
186
193
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
187
194
  return parsed.text || null;
188
- }`;function lb(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function ei(e){var n,t;return(t=(n=e.parserType)!=null?n:lb(e.streamParser))!=null?t:"plain"}function ti(e,n){let t=[];return e.toolCall&&(t.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&t.push(`${n} ${r}: "${o}",`)}),t.push(`${n}},`)),t}function ni(e,n,t){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(o||s)&&(r.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${n} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${a}: ${i},`))}),t!=null&&t.onFeedback&&r.push(`${n} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&r.push(`${n} onCopy: ${t.onCopy},`),r.push(`${n}},`)),r}function ri(e,n){let t=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(t.push(`${n}markdown: {`),r&&(t.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?t.push(`${n} ${s}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${s}: ${a},`)}),t.push(`${n} },`)),o&&t.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${n}},`))}return t}function oi(e,n){let t=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(t.push(`${n}layout: {`),r&&(t.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?t.push(`${n} ${s}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${s}: ${a},`))}),t.push(`${n} },`)),o&&(t.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${n} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?t.push(`${n} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${n} ${i}: ${d},`)}),t.push(`${n} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${n} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?t.push(`${n} ${d}: "${l}",`):typeof l=="boolean"&&t.push(`${n} ${d}: ${l},`))}),t.push(`${n} },`)):typeof a=="string"?t.push(`${n} ${s}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${s}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function ol(e,n){let t=[];return e&&(e.getHeaders&&t.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${n}streamParser: ${e.streamParser},`)),t}function $u(e,n,t){Object.entries(n).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${t}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${t}${r}: {`),$u(e,o,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(o)},`)}})}function so(e,n,t,r){t&&(e.push(`${r}${n}: {`),$u(e,t,`${r} `),e.push(`${r}},`))}function cb(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=t?{...t,hooks:sb(t.hooks)}:void 0;return n==="esm"?db(r,o):n==="script-installer"?mb(r,o):n==="script-advanced"?fb(r,o):n==="react-component"?pb(r,o):n==="react-advanced"?ub(r,o):gb(r,o)}function db(e,n){let t=n==null?void 0:n.hooks,r=ei(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&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&so(s,"theme",e.theme," "),e.launcher&&so(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(...ti(e," ")),s.push(...ni(e," ",t)),s.push(...ri(e," ")),s.push(...oi(e," ")),s.push(...ol(t," ")),e.debug&&s.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?s.push(` postprocessMessage: ${t.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
189
- `)}function pb(e,n){let t=n==null?void 0:n.hooks,r=ei(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&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&so(s,"theme",e.theme," "),e.launcher&&so(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(...ti(e," ")),s.push(...ni(e," ",t)),s.push(...ri(e," ")),s.push(...oi(e," ")),s.push(...ol(t," ")),e.debug&&s.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?s.push(` postprocessMessage: ${t.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
190
- `)}function ub(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&so(r,"theme",e.theme," "),e.launcher&&so(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(...ti(e," ")),r.push(...ni(e," ",t)),r.push(...ri(e," ")),r.push(...oi(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${ab}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Du}`),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(` ${Du}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Fu}`),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(` ${Fu}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
191
- `)}function _u(e){var o;let n=ei(e),t=n!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),t&&(r.parserType=n),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(r.markdown=s)}if(e.layout){let s={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(l[u]=p)}),Object.keys(l).length>0&&(a.timestamp=l)}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 mb(e,n){let t=_u(e),r=n!=null&&n.windowKey?{config:t,windowKey:n.windowKey}:t,o=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ts}/dist/install.global.js" data-config='${o}'></script>`}function gb(e,n){let t=n==null?void 0:n.hooks,r=ei(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ts}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ts}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," 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&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&so(s,"theme",e.theme," "),e.launcher&&so(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(...ti(e," ")),s.push(...ni(e," ",t)),s.push(...ri(e," ")),s.push(...oi(e," ")),s.push(...ol(t," ")),e.debug&&s.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?s.push(` postprocessMessage: ${t.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
192
- `)}function fb(e,n){let t=n==null?void 0:n.hooks,r=_u(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
195
+ }`;function Hb(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function di(e){var n,t;return(t=(n=e.parserType)!=null?n:Hb(e.streamParser))!=null?t:"plain"}function pi(e,n){let t=[];return e.toolCall&&(t.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&t.push(`${n} ${r}: "${s}",`)}),t.push(`${n}},`)),t}function ui(e,n,t){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(s||o)&&(r.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${n} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${a}: ${i},`))}),t!=null&&t.onFeedback&&r.push(`${n} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&r.push(`${n} onCopy: ${t.onCopy},`),r.push(`${n}},`)),r}function mi(e,n){let t=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(t.push(`${n}markdown: {`),r&&(t.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`)}),t.push(`${n} },`)),s&&t.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${n}},`))}return t}function gi(e,n){let t=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(t.push(`${n}layout: {`),r&&(t.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),s&&(t.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${n} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?t.push(`${n} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${n} ${i}: ${d},`)}),t.push(`${n} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${n} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?t.push(`${n} ${d}: "${l}",`):typeof l=="boolean"&&t.push(`${n} ${d}: ${l},`))}),t.push(`${n} },`)):typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function fl(e,n){let t=[];return e&&(e.getHeaders&&t.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${n}streamParser: ${e.streamParser},`)),t}function sm(e,n,t){Object.entries(n).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${r}: {`),sm(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(s)},`)}})}function ao(e,n,t,r){t&&(e.push(`${r}${n}: {`),sm(e,t,`${r} `),e.push(`${r}},`))}function Bb(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=t?{...t,hooks:Ib(t.hooks)}:void 0;return n==="esm"?Db(r,s):n==="script-installer"?Fb(r,s):n==="script-advanced"?_b(r,s):n==="react-component"?Nb(r,s):n==="react-advanced"?Ob(r,s):$b(r,s)}function Db(e,n){let t=n==null?void 0:n.hooks,r=di(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(o,"theme",e.theme," "),e.launcher&&ao(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...pi(e," ")),o.push(...ui(e," ",t)),o.push(...mi(e," ")),o.push(...gi(e," ")),o.push(...fl(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
196
+ `)}function Nb(e,n){let t=n==null?void 0:n.hooks,r=di(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(o,"theme",e.theme," "),e.launcher&&ao(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...pi(e," ")),o.push(...ui(e," ",t)),o.push(...mi(e," ")),o.push(...gi(e," ")),o.push(...fl(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
197
+ `)}function Ob(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(r,"theme",e.theme," "),e.launcher&&ao(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...pi(e," ")),r.push(...ui(e," ",t)),r.push(...mi(e," ")),r.push(...gi(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${Wb}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${tm}`),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(` ${tm}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${rm}`),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(` ${rm}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
198
+ `)}function am(e){var s;let n=di(e),t=n!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),t&&(r.parserType=n),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(l[u]=p)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function Fb(e,n){let t=am(e),r=n!=null&&n.windowKey?{config:t,windowKey:n.windowKey}:t,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ts}/dist/install.global.js" data-config='${s}'></script>`}function $b(e,n){let t=n==null?void 0:n.hooks,r=di(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ts}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ts}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ao(o,"theme",e.theme," "),e.launcher&&ao(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...pi(e," ")),o.push(...ui(e," ",t)),o.push(...mi(e," ")),o.push(...gi(e," ")),o.push(...fl(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
199
+ `)}function _b(e,n){let t=n==null?void 0:n.hooks,r=am(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
193
200
  `).map((a,i)=>i===0?a:" "+a).join(`
194
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ts}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(s.push(` widgetConfig.getHeaders = ${t.getHeaders};`),s.push("")),t!=null&&t.contextProviders&&(s.push(` widgetConfig.contextProviders = ${t.contextProviders};`),s.push("")),t!=null&&t.streamParser?s.push(` widgetConfig.streamParser = ${t.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${ib});`),s.push(" };")),s.push(""),t!=null&&t.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${t.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Nu}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Nu}`),s.push(" ];")),s.push(""),t!=null&&t.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${t.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Ou}`),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(` ${Ou}`),s.push(" ];")),s.push(""),t!=null&&t.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${t.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),t!=null&&t.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," 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(`
195
- `)}var ju={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Uu=.1,qu=.15,zu=1.5,sl=24,Vu=40,hb=`
201
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ts}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(o.push(` widgetConfig.getHeaders = ${t.getHeaders};`),o.push("")),t!=null&&t.contextProviders&&(o.push(` widgetConfig.contextProviders = ${t.contextProviders};`),o.push("")),t!=null&&t.streamParser?o.push(` widgetConfig.streamParser = ${t.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${Rb});`),o.push(" };")),o.push(""),t!=null&&t.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${t.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${nm}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${nm}`),o.push(" ];")),o.push(""),t!=null&&t.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${t.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${om}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${om}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
202
+ `)}var im={desktop:{w:1280,h:800},mobile:{w:390,h:844}},lm=.1,cm=.15,dm=1.5,hl=24,pm=40,jb=`
196
203
  /* \u2500\u2500 Root \u2500\u2500 */
197
204
  .persona-dc-root {
198
205
  display: flex;
@@ -343,7 +350,7 @@ ${a.join(`
343
350
  .persona-dc-stage {
344
351
  height: 550px;
345
352
  min-height: 400px;
346
- padding: ${sl}px;
353
+ padding: ${hl}px;
347
354
  overflow: auto;
348
355
  background: #f0f1f3;
349
356
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -433,5 +440,5 @@ ${a.join(`
433
440
  min-height: 300px;
434
441
  }
435
442
  }
436
- `;function yb(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=hb,document.head.appendChild(e)}function bb(e,n){let t=e.clientWidth-sl*2-Vu,r=e.clientHeight-sl*2-Vu;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function xb(e,n,t,r,o){e.style.width=`${t.w*r}px`,e.style.height=`${t.h*r}px`,e.style.borderRadius=o==="mobile"?`${32*r}px`:"10px",n.style.width=`${t.w}px`,n.style.height=`${t.h}px`,n.style.transformOrigin="top left",n.style.transform=`scale(${r})`}function vb(e,n){let{items:t,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=n;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");yb();let u=Math.max(0,Math.min(r,t.length-1)),p=o,f=s,g=null,C=1,x=!1,T=h("div","persona-dc-root"),A=h("div","persona-dc-toolbar"),k=h("div","persona-dc-toolbar-lead"),B=h("div","persona-dc-toolbar-trail"),D=jt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>We(-1)}),L=h("div");L.style.position="relative";let S=h("button","persona-dc-title-btn");S.type="button",S.setAttribute("aria-expanded","false"),S.setAttribute("aria-haspopup","listbox");let F=h("span","persona-dc-title-text"),$=h("span","persona-dc-title-chevron"),j=ge("chevron-down",12,"currentColor",2);j&&$.appendChild(j),S.append(F,$);let W=h("div","persona-dc-dropdown");W.setAttribute("role","listbox"),W.style.display="none";let O=!1;function V(){W.innerHTML="";for(let K=0;K<t.length;K++){let z=t[K],xe=h("button","persona-dc-dropdown-item");xe.type="button",xe.setAttribute("role","option"),xe.setAttribute("aria-current",K===u?"true":"false");let Oe=h("span");if(Oe.textContent=z.title,xe.appendChild(Oe),z.description){let ne=h("span","persona-dc-dropdown-desc");ne.textContent=z.description,xe.appendChild(ne)}xe.addEventListener("click",()=>{Pe(),Ze(K)}),W.appendChild(xe)}}function oe(){O=!O,W.style.display=O?"":"none",S.setAttribute("aria-expanded",O?"true":"false"),O&&V()}function Pe(){O&&(O=!1,W.style.display="none",S.setAttribute("aria-expanded","false"))}S.addEventListener("click",K=>{K.stopPropagation(),oe()});let ke=()=>Pe();document.addEventListener("click",ke),L.append(S,W);let Ge=jt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>We(1)}),de=h("span","persona-dc-counter");k.append(D,L,Ge,de);let pe=null;i&&(pe=Ba({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:K=>{p=K,Q.dataset.device=p,g=null,J()}}),B.appendChild(pe.element));let Me=null;if(a){let K=h("div","persona-dc-zoom-controls"),z=jt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ne=g!=null?g:C;g=Math.max(qu,ne-Uu),J()}});Me=h("span","persona-dc-zoom-level"),Me.title="Reset to 100%",Me.style.cursor="pointer",Me.addEventListener("click",()=>{g=1,J()});let xe=jt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ne=g!=null?g:C;g=Math.min(zu,ne+Uu),J()}}),Oe=jt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,J()}});K.append(z,Me,xe,Oe),B.appendChild(K)}if(d){let K=h("div","persona-dc-separator");B.appendChild(K);let z=Ba({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:xe=>{f=xe,Q.dataset.colorScheme=f,Re()}});B.appendChild(z.element)}let _e=h("div","persona-dc-separator");B.appendChild(_e);let ee=jt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});B.appendChild(ee),A.append(k,B);let Ae=h("div","persona-dc-stage"),Q=h("div","persona-dc-iframe-wrapper");Q.dataset.device=p,Q.dataset.colorScheme=f;let ae=h("iframe","persona-dc-iframe");ae.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ae.setAttribute("loading","lazy"),ae.title=t[u].title,Q.appendChild(ae),Ae.appendChild(Q),T.append(A,Ae),e.appendChild(T);function Re(){var K;try{let z=(K=ae.contentDocument)==null?void 0:K.body;if(!z)return;f==="dark"?z.classList.add("theme-dark"):z.classList.remove("theme-dark")}catch{}}ae.addEventListener("load",()=>Re());function ce(){let K=t[u];F.textContent=K.title,de.textContent=`${u+1} / ${t.length}`,ae.title=K.title}function We(K){let z=((u+K)%t.length+t.length)%t.length;Ze(z)}function Ze(K){K<0||K>=t.length||(u=K,ae.src=t[u].url,ce(),l==null||l(u,t[u]))}function J(){var xe;if(x)return;let K=(xe=ju[p])!=null?xe:ju.desktop;C=bb(Ae,K);let z=Math.max(qu,Math.min(zu,g!=null?g:C));xb(Q,ae,K,z,p),Me&&(Me.textContent=`${Math.round(z*100)}%`)}let se=new ResizeObserver(()=>J());se.observe(Ae),ce(),ae.src=t[u].url,requestAnimationFrame(()=>J());function Fe(){x||(x=!0,se.disconnect(),document.removeEventListener("click",ke),T.remove())}return{element:T,goTo:Ze,next:()=>We(1),prev:()=>We(-1),getIndex:()=>u,setDevice(K){p=K,Q.dataset.device=K,pe==null||pe.setSelected(K),g=null,J()},setColorScheme(K){f=K,Q.dataset.colorScheme=K},setZoom(K){g=K,J()},destroy:Fe}}function Cb(){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, #0f0f0f)"}}}function wb(){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 Ab(e){return{name:"@persona/brand",version:"1.0.0",transform(n){var r;let t={...n.palette};return(r=e.colors)!=null&&r.primary&&(t.colors={...t.colors,primary:{50:xr(e.colors.primary,.95),100:xr(e.colors.primary,.9),200:xr(e.colors.primary,.8),300:xr(e.colors.primary,.7),400:xr(e.colors.primary,.6),500:e.colors.primary,600:xr(e.colors.primary,.8),700:xr(e.colors.primary,.7),800:xr(e.colors.primary,.6),900:xr(e.colors.primary,.5),950:xr(e.colors.primary,.45)}}),{...n,palette:t}}}}function Sb(){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 Eb(){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 xr(e,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(o+(255-o)*(1-n));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Tb(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Mb={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Ju={components:{panel:{borderRadius:"0",shadow:"none"}}},Ku={id:"shop",label:"Shopping Assistant",config:{theme:Mb,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Gn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Gu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ju}},Qu={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ju}},Xu={shop:Ku,minimal:Gu,fullscreen:Qu};function kb(e){return Xu[e]}var Gw=wu;export{Up as ASK_USER_QUESTION_TOOL_NAME,_o as AgentWidgetClient,Ss as AgentWidgetSession,qo as AttachmentManager,hp as DEFAULT_COMPONENTS,mi as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,Gn as DEFAULT_FLOATING_LAUNCHER_WIDTH,gp as DEFAULT_PALETTE,fp as DEFAULT_SEMANTIC,$t as DEFAULT_WIDGET_CONFIG,Xu as PRESETS,Qu as PRESET_FULLSCREEN,Gu as PRESET_MINIMAL,Ku as PRESET_SHOP,Df as THEME_ZONES,ts as VERSION,Cb as accessibilityPlugin,wb as animationsPlugin,So as applyThemeVariables,Vo as attachHeaderToContainer,Ab as brandPlugin,Fs as buildComposer,Lp as buildDefaultHeader,Zr as buildHeader,Ns as buildHeaderWithLayout,Pp as buildMinimalHeader,nb as collectEnrichedPageContext,oo as componentRegistry,Ga as createActionManager,Gi as createAgentExperience,Gh as createAskUserQuestionBubble,ui as createBestAvailableVoiceProvider,bh as createBubbleWithLayout,Vi as createCSATFeedback,Ai as createComboButton,Sy as createComponentMiddleware,ji as createComponentStreamParser,tp as createDefaultSanitizer,vb as createDemoCarousel,tm as createDirectivePostprocessor,Eo as createDropdownMenu,cm as createFlexibleJsonStreamParser,jt as createIconButton,xm as createImagePart,ci as createJsonStreamParser,Ha as createLabelButton,_i as createLocalStorageAdapter,ca as createMarkdownProcessor,Fo as createMarkdownProcessorFromConfig,Op as createMessageActions,Ji as createNPSFeedback,ii as createPlainTextParser,Tb as createPlugin,li as createRegexJsonParser,Os as createStandardBubble,ya as createTextPart,Ts as createTheme,yi as createThemeObserver,Ba as createToggleGroup,Jo as createTypingIndicator,Uo as createVoiceProvider,Ya as createWidgetHostLayout,di as createXmlParser,Gw as default,Zo as defaultActionHandlers,Ka as defaultJsonActionParser,Iu as defaultParseRules,Aa as detectColorScheme,nm as directivePostprocessor,_s as ensureAskUserQuestionSheet,Oo as escapeHtml,zi as extractComponentDirectiveFromMessage,vm as fileToImagePart,rb as formatEnrichedContext,jo as generateAssistantMessageId,cb as generateCodeSnippet,gm as generateMessageId,Ru as generateStableSelector,ws as generateUserMessageId,Ms as getActiveTheme,vp as getColorScheme,hm as getDisplayText,Ip as getHeaderLayout,bm as getImageParts,kb as getPreset,qi as hasComponentDirective,ym as hasImages,Si as headerLayouts,Eb as highContrastPlugin,wu as initAgentWidget,eo as isAskUserQuestionMessage,Ay as isComponentDirectiveType,on as isDockedMountMode,Ca as isVoiceSupported,Vf as listRegisteredStreamAnimations,Yd as markdownPostprocessor,gi as mergeWithDefaults,fm as normalizeContent,to as parseAskUserQuestionPayload,Ja as pluginRegistry,Sb as reducedMotionPlugin,qf as registerStreamAnimationPlugin,Mo as removeAskUserQuestionSheet,Ui as renderComponentDirective,Fp as renderLoadingIndicatorWithFallback,ge as renderLucideIcon,lr as resolveDockConfig,xs as resolveSanitizer,fi as resolveTokens,hi as themeToCssVariables,zf as unregisterStreamAnimationPlugin,Cm as validateImageFile,yp as validateTheme};
443
+ `;function Ub(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=jb,document.head.appendChild(e)}function qb(e,n){let t=e.clientWidth-hl*2-pm,r=e.clientHeight-hl*2-pm;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function zb(e,n,t,r,s){e.style.width=`${t.w*r}px`,e.style.height=`${t.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",n.style.width=`${t.w}px`,n.style.height=`${t.h}px`,n.style.transformOrigin="top left",n.style.transform=`scale(${r})`}function Vb(e,n){let{items:t,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=n;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Ub();let u=Math.max(0,Math.min(r,t.length-1)),p=s,f=o,m=null,v=1,x=!1,S=h("div","persona-dc-root"),A=h("div","persona-dc-toolbar"),k=h("div","persona-dc-toolbar-lead"),R=h("div","persona-dc-toolbar-trail"),H=_t({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Re(-1)}),L=h("div");L.style.position="relative";let w=h("button","persona-dc-title-btn");w.type="button",w.setAttribute("aria-expanded","false"),w.setAttribute("aria-haspopup","listbox");let B=h("span","persona-dc-title-text"),F=h("span","persona-dc-title-chevron"),$=fe("chevron-down",12,"currentColor",2);$&&F.appendChild($),w.append(B,F);let W=h("div","persona-dc-dropdown");W.setAttribute("role","listbox"),W.style.display="none";let O=!1;function V(){W.innerHTML="";for(let J=0;J<t.length;J++){let z=t[J],we=h("button","persona-dc-dropdown-item");we.type="button",we.setAttribute("role","option"),we.setAttribute("aria-current",J===u?"true":"false");let $e=h("span");if($e.textContent=z.title,we.appendChild($e),z.description){let ne=h("span","persona-dc-dropdown-desc");ne.textContent=z.description,we.appendChild(ne)}we.addEventListener("click",()=>{Ie(),tt(J)}),W.appendChild(we)}}function oe(){O=!O,W.style.display=O?"":"none",w.setAttribute("aria-expanded",O?"true":"false"),O&&V()}function Ie(){O&&(O=!1,W.style.display="none",w.setAttribute("aria-expanded","false"))}w.addEventListener("click",J=>{J.stopPropagation(),oe()});let Pe=()=>Ie();document.addEventListener("click",Pe),L.append(w,W);let ze=_t({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Re(1)}),pe=h("span","persona-dc-counter");k.append(H,L,ze,pe);let ce=null;i&&(ce=za({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:p,onSelect:J=>{p=J,G.dataset.device=p,m=null,K()}}),R.appendChild(ce.element));let Ee=null;if(a){let J=h("div","persona-dc-zoom-controls"),z=_t({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ne=m!=null?m:v;m=Math.max(cm,ne-lm),K()}});Ee=h("span","persona-dc-zoom-level"),Ee.title="Reset to 100%",Ee.style.cursor="pointer",Ee.addEventListener("click",()=>{m=1,K()});let we=_t({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ne=m!=null?m:v;m=Math.min(dm,ne+lm),K()}}),$e=_t({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,K()}});J.append(z,Ee,we,$e),R.appendChild(J)}if(d){let J=h("div","persona-dc-separator");R.appendChild(J);let z=za({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:we=>{f=we,G.dataset.colorScheme=f,He()}});R.appendChild(z.element)}let je=h("div","persona-dc-separator");R.appendChild(je);let te=_t({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});R.appendChild(te),A.append(k,R);let xe=h("div","persona-dc-stage"),G=h("div","persona-dc-iframe-wrapper");G.dataset.device=p,G.dataset.colorScheme=f;let ae=h("iframe","persona-dc-iframe");ae.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ae.setAttribute("loading","lazy"),ae.title=t[u].title,G.appendChild(ae),xe.appendChild(G),S.append(A,xe),e.appendChild(S);function He(){var J;try{let z=(J=ae.contentDocument)==null?void 0:J.body;if(!z)return;f==="dark"?z.classList.add("theme-dark"):z.classList.remove("theme-dark")}catch{}}ae.addEventListener("load",()=>He());function ue(){let J=t[u];B.textContent=J.title,pe.textContent=`${u+1} / ${t.length}`,ae.title=J.title}function Re(J){let z=((u+J)%t.length+t.length)%t.length;tt(z)}function tt(J){J<0||J>=t.length||(u=J,ae.src=t[u].url,ue(),l==null||l(u,t[u]))}function K(){var we;if(x)return;let J=(we=im[p])!=null?we:im.desktop;v=qb(xe,J);let z=Math.max(cm,Math.min(dm,m!=null?m:v));zb(G,ae,J,z,p),Ee&&(Ee.textContent=`${Math.round(z*100)}%`)}let se=new ResizeObserver(()=>K());se.observe(xe),ue(),ae.src=t[u].url,requestAnimationFrame(()=>K());function Oe(){x||(x=!0,se.disconnect(),document.removeEventListener("click",Pe),S.remove())}return{element:S,goTo:tt,next:()=>Re(1),prev:()=>Re(-1),getIndex:()=>u,setDevice(J){p=J,G.dataset.device=J,ce==null||ce.setSelected(J),m=null,K()},setColorScheme(J){f=J,G.dataset.colorScheme=J},setZoom(J){m=J,K()},destroy:Oe}}function Kb(){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, #0f0f0f)"}}}function Jb(){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 Gb(e){return{name:"@persona/brand",version:"1.0.0",transform(n){var r;let t={...n.palette};return(r=e.colors)!=null&&r.primary&&(t.colors={...t.colors,primary:{50:xr(e.colors.primary,.95),100:xr(e.colors.primary,.9),200:xr(e.colors.primary,.8),300:xr(e.colors.primary,.7),400:xr(e.colors.primary,.6),500:e.colors.primary,600:xr(e.colors.primary,.8),700:xr(e.colors.primary,.7),800:xr(e.colors.primary,.6),900:xr(e.colors.primary,.5),950:xr(e.colors.primary,.45)}}),{...n,palette:t}}}}function Xb(){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 Yb(){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 xr(e,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(s+(255-s)*(1-n));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Qb(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Zb={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},um={components:{panel:{borderRadius:"0",shadow:"none"}}},mm={id:"shop",label:"Shopping Assistant",config:{theme:Zb,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Gn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},gm={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:um}},fm={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:um}},hm={shop:mm,minimal:gm,fullscreen:fm};function ex(e){return hm[e]}var TA=_u;export{lu as ASK_USER_QUESTION_TOOL_NAME,_o as AgentWidgetClient,ks as AgentWidgetSession,qo as AttachmentManager,Hp as DEFAULT_COMPONENTS,Si as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,Gn as DEFAULT_FLOATING_LAUNCHER_WIDTH,Wp as DEFAULT_PALETTE,Rp as DEFAULT_SEMANTIC,Ft as DEFAULT_WIDGET_CONFIG,hm as PRESETS,fm as PRESET_FULLSCREEN,gm as PRESET_MINIMAL,mm as PRESET_SHOP,lh as THEME_ZONES,ts as VERSION,ya as WEBMCP_TOOL_PREFIX,As as WebMcpBridge,Kb as accessibilityPlugin,Jb as animationsPlugin,So as applyThemeVariables,Vo as attachHeaderToContainer,Gb as brandPlugin,js as buildComposer,Jp as buildDefaultHeader,eo as buildHeader,_s as buildHeaderWithLayout,Gp as buildMinimalHeader,kb as collectEnrichedPageContext,so as componentRegistry,si as createActionManager,al as createAgentExperience,wy as createAskUserQuestionBubble,Ai as createBestAvailableVoiceProvider,qh as createBubbleWithLayout,rl as createCSATFeedback,Hi as createComboButton,Xy as createComponentMiddleware,Zi as createComponentStreamParser,yp as createDefaultSanitizer,Vb as createDemoCarousel,vm as createDirectivePostprocessor,Eo as createDropdownMenu,Bm as createFlexibleJsonStreamParser,_t as createIconButton,zm as createImagePart,vi as createJsonStreamParser,qa as createLabelButton,Qi as createLocalStorageAdapter,fa as createMarkdownProcessor,Oo as createMarkdownProcessorFromConfig,ou as createMessageActions,ol as createNPSFeedback,bi as createPlainTextParser,Qb as createPlugin,xi as createRegexJsonParser,Us as createStandardBubble,Ta as createTextPart,Ps as createTheme,ki as createThemeObserver,za as createToggleGroup,Ko as createTypingIndicator,Uo as createVoiceProvider,li as createWidgetHostLayout,wi as createXmlParser,TA as default,Zo as defaultActionHandlers,oi as defaultJsonActionParser,Xu as defaultParseRules,Wa as detectColorScheme,wm as directivePostprocessor,zs as ensureAskUserQuestionSheet,Fo as escapeHtml,nl as extractComponentDirectiveFromMessage,Vm as fileToImagePart,Lb as formatEnrichedContext,jo as generateAssistantMessageId,Bb as generateCodeSnippet,$m as generateMessageId,Qu as generateStableSelector,Ts as generateUserMessageId,Is as getActiveTheme,Op as getColorScheme,jm as getDisplayText,Xp as getHeaderLayout,qm as getImageParts,ex as getPreset,tl as hasComponentDirective,Um as hasImages,Bi as headerLayouts,Yb as highContrastPlugin,_u as initAgentWidget,to as isAskUserQuestionMessage,Gy as isComponentDirectiveType,on as isDockedMountMode,Pa as isVoiceSupported,ba as isWebMcpToolName,bh as listRegisteredStreamAnimations,gp as markdownPostprocessor,Ei as mergeWithDefaults,_m as normalizeContent,no as parseAskUserQuestionPayload,ri as pluginRegistry,Xb as reducedMotionPlugin,hh as registerStreamAnimationPlugin,Mo as removeAskUserQuestionSheet,el as renderComponentDirective,ru as renderLoadingIndicatorWithFallback,fe as renderLucideIcon,lr as resolveDockConfig,Cs as resolveSanitizer,Ti as resolveTokens,bp as stripWebMcpPrefix,Mi as themeToCssVariables,yh as unregisterStreamAnimationPlugin,Km as validateImageFile,Bp as validateTheme};
437
444
  //# sourceMappingURL=index.js.map