@runtypelabs/persona 4.14.0 → 4.15.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 (81) hide show
  1. package/README.md +4 -4
  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-DveIaNx6.d.cts → types-BpWGm7_6.d.cts} +17 -0
  5. package/dist/animations/{types-DveIaNx6.d.ts → types-BpWGm7_6.d.ts} +17 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/chunk-QJ4LV2KW.js +1 -0
  9. package/dist/codegen.cjs +12 -11
  10. package/dist/codegen.js +14 -13
  11. package/dist/{context-mentions-ONG7A7M6.js → context-mentions-BTSTIBFC.js} +1 -1
  12. package/dist/context-mentions.cjs +11 -8
  13. package/dist/context-mentions.d.cts +241 -16
  14. package/dist/context-mentions.d.ts +241 -16
  15. package/dist/context-mentions.js +11 -8
  16. package/dist/index.cjs +67 -66
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +301 -41
  19. package/dist/index.d.ts +301 -41
  20. package/dist/index.global.js +59 -56
  21. package/dist/index.global.js.map +1 -1
  22. package/dist/index.js +67 -66
  23. package/dist/index.js.map +1 -1
  24. package/dist/launcher.global.js +5 -2
  25. package/dist/launcher.global.js.map +1 -1
  26. package/dist/smart-dom-reader.d.cts +241 -16
  27. package/dist/smart-dom-reader.d.ts +241 -16
  28. package/dist/theme-editor-preview.cjs +66 -66
  29. package/dist/theme-editor-preview.d.cts +255 -17
  30. package/dist/theme-editor-preview.d.ts +255 -17
  31. package/dist/theme-editor-preview.js +56 -56
  32. package/dist/theme-editor.cjs +5 -5
  33. package/dist/theme-editor.d.cts +242 -17
  34. package/dist/theme-editor.d.ts +242 -17
  35. package/dist/theme-editor.js +7 -7
  36. package/dist/theme-reference.cjs +1 -1
  37. package/dist/theme-reference.d.cts +38 -0
  38. package/dist/theme-reference.d.ts +38 -0
  39. package/dist/theme-reference.js +1 -1
  40. package/dist/widget.css +1 -1
  41. package/package.json +1 -1
  42. package/src/ask-user-question-tool.ts +10 -7
  43. package/src/components/artifact-preview.ts +1 -1
  44. package/src/components/composer-parts.test.ts +103 -4
  45. package/src/components/composer-parts.ts +53 -15
  46. package/src/components/messages.ts +5 -2
  47. package/src/components/panel.ts +31 -5
  48. package/src/components/pill-composer-builder.test.ts +18 -0
  49. package/src/components/suggestions.test.ts +233 -0
  50. package/src/components/suggestions.ts +463 -81
  51. package/src/components/widget-view.ts +4 -0
  52. package/src/defaults.ts +5 -3
  53. package/src/generated/runtype-openapi-contract.ts +17 -0
  54. package/src/index-core.ts +18 -2
  55. package/src/launcher-global.ts +1 -1
  56. package/src/plugins/types.ts +71 -3
  57. package/src/presets.ts +3 -3
  58. package/src/session.ts +10 -8
  59. package/src/styles/widget-styles.test.ts +162 -0
  60. package/src/styles/widget.css +430 -0
  61. package/src/suggest-replies-tool.test.ts +233 -2
  62. package/src/suggest-replies-tool.ts +115 -39
  63. package/src/theme-editor/preview-utils.test.ts +34 -0
  64. package/src/theme-editor/preview-utils.ts +77 -2
  65. package/src/theme-editor/sections.test.ts +33 -0
  66. package/src/theme-editor/sections.ts +53 -5
  67. package/src/theme-reference.ts +9 -2
  68. package/src/types/theme.ts +32 -0
  69. package/src/types.ts +152 -16
  70. package/src/ui.detached-panel.test.ts +1 -1
  71. package/src/ui.suggest-replies.test.ts +1066 -1
  72. package/src/ui.ts +268 -20
  73. package/src/utils/artifact-file.test.ts +1 -1
  74. package/src/utils/code-generators.test.ts +40 -0
  75. package/src/utils/code-generators.ts +22 -0
  76. package/src/utils/config-merge.test.ts +24 -0
  77. package/src/utils/icons.test.ts +26 -0
  78. package/src/utils/icons.ts +8 -0
  79. package/src/utils/theme.test.ts +79 -0
  80. package/src/utils/tokens.ts +64 -0
  81. package/dist/chunk-MMUPR2JW.js +0 -1
@@ -1,14 +1,14 @@
1
- "use strict";var Dm=Object.create;var xi=Object.defineProperty;var Nm=Object.getOwnPropertyDescriptor;var Om=Object.getOwnPropertyNames;var Fm=Object.getPrototypeOf,_m=Object.prototype.hasOwnProperty;var bt=(t,e)=>()=>(t&&(e=t(t=0)),e);var or=(t,e)=>{for(var n in e)xi(t,n,{get:e[n],enumerable:!0})},ep=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Om(e))!_m.call(t,r)&&r!==n&&xi(t,r,{get:()=>e[r],enumerable:!(o=Nm(e,r))||o.enumerable});return t};var tp=(t,e,n)=>(n=t!=null?Dm(Fm(t)):{},ep(e||!t||!t.__esModule?xi(n,"default",{value:t,enumerable:!0}):n,t)),$m=t=>ep(xi({},"__esModule",{value:!0}),t);var rp={};or(rp,{DOMPurify:()=>op.default,Marked:()=>np.Marked});var np,op,sp=bt(()=>{"use strict";np=require("marked"),op=tp(require("dompurify"),1)});var y,Cp,we,zn,tt=bt(()=>{"use strict";y=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Cp=()=>document.createDocumentFragment(),we=(t,e={},...n)=>{let o=document.createElement(t);if(e.className&&(o.className=e.className),e.text!==void 0&&(o.textContent=e.text),e.attrs)for(let[s,i]of Object.entries(e.attrs))o.setAttribute(s,i);if(e.style){let s=o.style,i=e.style;for(let l of Object.keys(i)){let p=i[l];p!=null&&(s[l]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},zn=(...t)=>t.filter(Boolean).join(" ")});var gr,Pl=bt(()=>{"use strict";gr=class{constructor(e=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=e;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(e*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let r=new Uint8Array(this.remainder.length+e.length);r.set(this.remainder),r.set(e,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,e.length,this.sampleRate);o.getChannelData(0).set(e);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let i=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of i)l()}r.onended=()=>{let i=this.activeSources.indexOf(r);i!==-1&&this.activeSources.splice(i,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),o=new Float32Array(n),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let i=r.getInt16(s*2,!0);o[s]=i/32768}return o}}});function Zh(t){return t.replace(/\/+$/,"")}async function ey(t){try{let e=await t.json();return e.detail?`${e.error??`Runtype TTS ${t.status}`}: ${e.detail}`:e.error??`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var Fi,Zp=bt(()=>{"use strict";Pl();Fi=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new gr(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(e=>this.player=e))}speak(e,n){let o=++this.generation;this.run(o,e,n)}async run(e,n,o){try{let r=await this.ensurePlayer();if(e!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.generation&&o.onStart?.()}),r.onFinished(()=>{e===this.generation&&o.onEnd?.()});let s=`${Zh(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!i.ok||!i.body)throw new Error(await ey(i));let l=i.body.getReader();for(;;){let{done:p,value:c}=await l.read();if(e!==this.generation){await l.cancel().catch(()=>{});return}if(p)break;c&&c.byteLength>0&&r.enqueue(c)}r.markStreamEnd()}catch(r){if(e!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var _i,eu=bt(()=>{"use strict";_i=class{constructor(e,n,o={}){this.primary=e;this.fallback=n;this.options=o;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let o=!1;this.primary.speak(e,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var tu={};or(tu,{FallbackSpeechEngine:()=>_i,RuntypeSpeechEngine:()=>Fi});var nu=bt(()=>{"use strict";Zp();eu()});var ru={};or(ru,{createReconnectController:()=>ny});function ny(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let m=n;n=null,m()}},i=()=>{let m=t.getStatus();m!=="resuming"&&m!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||i()},p=()=>{i()},c=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",p),r=!0)},d=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},u=m=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},m)}),b=()=>{let m=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,d(),t.setAbortController(null);let C=!1;for(let H of t.getMessages())H.streaming&&(H.streaming=!1,C=!0);let R=t.buildErrorContent("Connection lost and the response could not be resumed.");R?t.appendMessage({id:`reconnect-failed-${m?.executionId??t.nextSequence()}`,role:"assistant",content:R,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):C&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},f=async()=>{let m=t.config.reconnect?.backoffMs??ty,C=t.config.reconnect?.maxAttempts??m.length,R=t.config.reconnectStream;if(!R){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let H=t.getResumable(),L=H.lastEventId,T=new AbortController;t.setAbortController(T),t.emitReconnect({phase:"resuming",handle:H,attempt:e});let k=null;try{let $=await R({executionId:H.executionId,after:H.lastEventId,signal:T.signal});$&&$.ok&&$.body&&(k=$.body)}catch{k=null}if(T.signal.aborted)return;if(k){let $=t.getMessages().find(w=>w.id===H.assistantMessageId)?.content,G=typeof $=="string"?$:"";try{await t.resumeConnect(k,H.assistantMessageId,G)}catch{}if(T.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,d(),t.emitReconnect({phase:"resumed",handle:H});return}t.getResumable().lastEventId!==L&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await u(m[Math.min(e-1,m.length-1)]??1e3),T.signal.aborted))return}t.getResumable()&&b()};return{begin(){e=0,c(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,d()},wake:s}}var ty,su=bt(()=>{"use strict";ty=[1e3,2e3,4e3,8e3,8e3]});function iy(t,e,n,o){if(!Array.isArray(t))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let i=s[0],l=s[1];if(!l)return;let p=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([c,d])=>{c!=="stroke"&&p.setAttribute(c,String(d))}),r.appendChild(p)}),r}var S,sy,ae,St=bt(()=>{"use strict";S=require("lucide"),sy={activity:S.Activity,"arrow-down":S.ArrowDown,"arrow-up":S.ArrowUp,"arrow-up-right":S.ArrowUpRight,bot:S.Bot,"chevron-down":S.ChevronDown,"chevron-up":S.ChevronUp,"chevron-right":S.ChevronRight,"chevron-left":S.ChevronLeft,check:S.Check,clipboard:S.Clipboard,"clipboard-copy":S.ClipboardCopy,"code-xml":S.CodeXml,copy:S.Copy,file:S.File,"file-code":S.FileCode,"file-spreadsheet":S.FileSpreadsheet,"file-text":S.FileText,"image-plus":S.ImagePlus,loader:S.Loader,"loader-circle":S.LoaderCircle,mic:S.Mic,paperclip:S.Paperclip,"refresh-cw":S.RefreshCw,search:S.Search,send:S.Send,"shield-alert":S.ShieldAlert,"shield-check":S.ShieldCheck,"shield-x":S.ShieldX,square:S.Square,"thumbs-down":S.ThumbsDown,"thumbs-up":S.ThumbsUp,upload:S.Upload,"volume-2":S.Volume2,x:S.X,user:S.User,mail:S.Mail,phone:S.Phone,calendar:S.Calendar,clock:S.Clock,building:S.Building,"map-pin":S.MapPin,lock:S.Lock,key:S.Key,"credit-card":S.CreditCard,"at-sign":S.AtSign,hash:S.Hash,globe:S.Globe,link:S.Link,"circle-check":S.CircleCheck,"circle-x":S.CircleX,"triangle-alert":S.TriangleAlert,info:S.Info,ban:S.Ban,shield:S.Shield,"arrow-left":S.ArrowLeft,"arrow-right":S.ArrowRight,"external-link":S.ExternalLink,ellipsis:S.Ellipsis,"ellipsis-vertical":S.EllipsisVertical,menu:S.Menu,house:S.House,plus:S.Plus,minus:S.Minus,pencil:S.Pencil,trash:S.Trash,"trash-2":S.Trash2,save:S.Save,download:S.Download,share:S.Share,funnel:S.Funnel,settings:S.Settings,"rotate-cw":S.RotateCw,maximize:S.Maximize,minimize:S.Minimize,"shopping-cart":S.ShoppingCart,"shopping-bag":S.ShoppingBag,package:S.Package,truck:S.Truck,tag:S.Tag,gift:S.Gift,receipt:S.Receipt,wallet:S.Wallet,store:S.Store,"dollar-sign":S.DollarSign,percent:S.Percent,play:S.Play,pause:S.Pause,"volume-x":S.VolumeX,camera:S.Camera,image:S.Image,film:S.Film,headphones:S.Headphones,"message-circle":S.MessageCircle,"message-square":S.MessageSquare,bell:S.Bell,heart:S.Heart,star:S.Star,eye:S.Eye,"eye-off":S.EyeOff,bookmark:S.Bookmark,"calendar-days":S.CalendarDays,history:S.History,timer:S.Timer,folder:S.Folder,"folder-open":S.FolderOpen,files:S.Files,sparkles:S.Sparkles,zap:S.Zap,sun:S.Sun,moon:S.Moon,flag:S.Flag,monitor:S.Monitor,smartphone:S.Smartphone},ae=(t,e=24,n="currentColor",o=2)=>{let r=sy[t];return r?iy(r,e,n,o):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)}});function cy(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
2
- `:o===""||lu.test(o)}function dy(t,e,n="@",o="anywhere",r=!1){if(!n||e<=0||e>t.length)return null;let s=e-1;for(;s>=0;){let i=t[s];if(i===n)return cy(t,s,o)?{triggerIndex:s,query:t.slice(s+1,e)}:null;if(i===`
3
- `||i==="\uFFFC"||!r&&lu.test(i))return null;s--}return null}function ms(t,e,n){for(let o of n){let r=dy(t,e,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function cu(t){return t?t!=="insertFromPaste"&&t!=="insertFromDrop":!0}function du(t,e,n){return{value:t.slice(0,e.triggerIndex)+t.slice(n),caret:e.triggerIndex}}var lu,ji=bt(()=>{"use strict";lu=/\s/});function Ui(t){let e={trigger:t.trigger??"@",position:t.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(t.sources)?t.sources:[],searchPlaceholder:t.searchPlaceholder,showButton:t.showButton!==!1,buttonIconName:t.buttonIconName,buttonTooltipText:t.buttonTooltipText},n=(t.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[e,...n]}var Bl=bt(()=>{"use strict"});function fu(t){let{ref:e,config:n,onRemove:o}=t;if(n.renderMentionChip){let f="resolving",m,C=n.renderMentionChip({ref:e,status:f,payload:m,remove:o});return{get el(){return C},setStatus:(H,L)=>{if(H===f&&L===m)return;f=H,m=L;let T=n.renderMentionChip({ref:e,status:f,payload:m,remove:o});C.replaceWith(T),C=T}}}let r=e.iconName??n.chipIconName??"at-sign",s=we("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),i=y("span","persona-mention-chip-icon"),l=f=>{i.replaceChildren();let m=ae(f,13,"currentColor",2);m&&i.appendChild(m)};l(r);let p=y("span","persona-mention-chip-spinner"),c=we("span",{className:"persona-mention-chip-label",text:e.label}),d=we("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),u=ae("x",11,"currentColor",2.5);return u?d.appendChild(u):d.textContent="\xD7",d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),o()}),s.appendChild(p),s.appendChild(c),s.appendChild(d),{el:s,setStatus:f=>{s.setAttribute("data-status",f),f==="resolving"?(p.parentNode!==s&&s.insertBefore(p,c),i.parentNode===s&&i.remove(),s.setAttribute("title",e.label)):(p.parentNode===s&&p.remove(),i.parentNode!==s&&s.insertBefore(i,c),f==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${e.label} to context`)):(l(r),s.setAttribute("title",e.label)))}}}var gu=bt(()=>{"use strict";tt();St()});function gy(t){let e=0;for(let n of t.split(`
4
- `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function Fl(t,e){let n="`".repeat(Math.max(3,gy(e)+1));return`${n}${t}
1
+ "use strict";var rh=Object.create;var Ti=Object.defineProperty;var sh=Object.getOwnPropertyDescriptor;var ih=Object.getOwnPropertyNames;var ah=Object.getPrototypeOf,lh=Object.prototype.hasOwnProperty;var ht=(t,e)=>()=>(t&&(e=t(t=0)),e);var ar=(t,e)=>{for(var n in e)Ti(t,n,{get:e[n],enumerable:!0})},bp=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ih(e))!lh.call(t,r)&&r!==n&&Ti(t,r,{get:()=>e[r],enumerable:!(o=sh(e,r))||o.enumerable});return t};var vp=(t,e,n)=>(n=t!=null?rh(ah(t)):{},bp(e||!t||!t.__esModule?Ti(n,"default",{value:t,enumerable:!0}):n,t)),ch=t=>bp(Ti({},"__esModule",{value:!0}),t);var wp={};ar(wp,{DOMPurify:()=>Cp.default,Marked:()=>xp.Marked});var xp,Cp,Ap=ht(()=>{"use strict";xp=require("marked"),Cp=vp(require("dompurify"),1)});var v,Fp,Ce,Vn,Je=ht(()=>{"use strict";v=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Fp=()=>document.createDocumentFragment(),Ce=(t,e={},...n)=>{let o=document.createElement(t);if(e.className&&(o.className=e.className),e.text!==void 0&&(o.textContent=e.text),e.attrs)for(let[s,i]of Object.entries(e.attrs))o.setAttribute(s,i);if(e.style){let s=o.style,i=e.style;for(let l of Object.keys(i)){let p=i[l];p!=null&&(s[l]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Vn=(...t)=>t.filter(Boolean).join(" ")});var br,Bl=ht(()=>{"use strict";br=class{constructor(e=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=e;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(e*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let r=new Uint8Array(this.remainder.length+e.length);r.set(this.remainder),r.set(e,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,e.length,this.sampleRate);o.getChannelData(0).set(e);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let i=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of i)l()}r.onended=()=>{let i=this.activeSources.indexOf(r);i!==-1&&this.activeSources.splice(i,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),o=new Float32Array(n),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let i=r.getInt16(s*2,!0);o[s]=i/32768}return o}}});function wy(t){return t.replace(/\/+$/,"")}async function Ay(t){try{let e=await t.json();return e.detail?`${e.error??`Runtype TTS ${t.status}`}: ${e.detail}`:e.error??`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var Vi,yu=ht(()=>{"use strict";Bl();Vi=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new br(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(e=>this.player=e))}speak(e,n){let o=++this.generation;this.run(o,e,n)}async run(e,n,o){try{let r=await this.ensurePlayer();if(e!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.generation&&o.onStart?.()}),r.onFinished(()=>{e===this.generation&&o.onEnd?.()});let s=`${wy(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!i.ok||!i.body)throw new Error(await Ay(i));let l=i.body.getReader();for(;;){let{done:p,value:c}=await l.read();if(e!==this.generation){await l.cancel().catch(()=>{});return}if(p)break;c&&c.byteLength>0&&r.enqueue(c)}r.markStreamEnd()}catch(r){if(e!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var qi,bu=ht(()=>{"use strict";qi=class{constructor(e,n,o={}){this.primary=e;this.fallback=n;this.options=o;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let o=!1;this.primary.speak(e,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var vu={};ar(vu,{FallbackSpeechEngine:()=>qi,RuntypeSpeechEngine:()=>Vi});var xu=ht(()=>{"use strict";yu();bu()});var wu={};ar(wu,{createReconnectController:()=>My});function My(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let h=n;n=null,h()}},i=()=>{let h=t.getStatus();h!=="resuming"&&h!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||i()},p=()=>{i()},c=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",p),r=!0)},d=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},u=h=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},h)}),b=()=>{let h=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,d(),t.setAbortController(null);let C=!1;for(let B of t.getMessages())B.streaming&&(B.streaming=!1,C=!0);let L=t.buildErrorContent("Connection lost and the response could not be resumed.");L?t.appendMessage({id:`reconnect-failed-${h?.executionId??t.nextSequence()}`,role:"assistant",content:L,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):C&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},g=async()=>{let h=t.config.reconnect?.backoffMs??Sy,C=t.config.reconnect?.maxAttempts??h.length,L=t.config.reconnectStream;if(!L){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let B=t.getResumable(),k=B.lastEventId,S=new AbortController;t.setAbortController(S),t.emitReconnect({phase:"resuming",handle:B,attempt:e});let E=null;try{let z=await L({executionId:B.executionId,after:B.lastEventId,signal:S.signal});z&&z.ok&&z.body&&(E=z.body)}catch{E=null}if(S.signal.aborted)return;if(E){let z=t.getMessages().find(A=>A.id===B.assistantMessageId)?.content,G=typeof z=="string"?z:"";try{await t.resumeConnect(E,B.assistantMessageId,G)}catch{}if(S.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,d(),t.emitReconnect({phase:"resumed",handle:B});return}t.getResumable().lastEventId!==k&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await u(h[Math.min(e-1,h.length-1)]??1e3),S.signal.aborted))return}t.getResumable()&&b()};return{begin(){e=0,c(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,d()},wake:s}}var Sy,Au=ht(()=>{"use strict";Sy=[1e3,2e3,4e3,8e3,8e3]});function Ly(t,e,n,o){if(!Array.isArray(t))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let i=s[0],l=s[1];if(!l)return;let p=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([c,d])=>{c!=="stroke"&&p.setAttribute(c,String(d))}),r.appendChild(p)}),r}var M,ky,ae,wt=ht(()=>{"use strict";M=require("lucide"),ky={activity:M.Activity,"arrow-down":M.ArrowDown,"arrow-up":M.ArrowUp,"arrow-up-right":M.ArrowUpRight,bot:M.Bot,"chevron-down":M.ChevronDown,"chevron-up":M.ChevronUp,"chevron-right":M.ChevronRight,"chevron-left":M.ChevronLeft,check:M.Check,clipboard:M.Clipboard,"clipboard-copy":M.ClipboardCopy,"code-xml":M.CodeXml,copy:M.Copy,file:M.File,"file-code":M.FileCode,"file-spreadsheet":M.FileSpreadsheet,"file-text":M.FileText,"image-plus":M.ImagePlus,loader:M.Loader,"loader-circle":M.LoaderCircle,mic:M.Mic,paperclip:M.Paperclip,"refresh-cw":M.RefreshCw,search:M.Search,send:M.Send,"shield-alert":M.ShieldAlert,"shield-check":M.ShieldCheck,"shield-x":M.ShieldX,square:M.Square,"thumbs-down":M.ThumbsDown,"thumbs-up":M.ThumbsUp,upload:M.Upload,"volume-2":M.Volume2,x:M.X,user:M.User,mail:M.Mail,phone:M.Phone,calendar:M.Calendar,clock:M.Clock,building:M.Building,"map-pin":M.MapPin,lock:M.Lock,key:M.Key,"credit-card":M.CreditCard,"at-sign":M.AtSign,hash:M.Hash,globe:M.Globe,link:M.Link,"circle-check":M.CircleCheck,"circle-x":M.CircleX,"triangle-alert":M.TriangleAlert,info:M.Info,ban:M.Ban,shield:M.Shield,"arrow-left":M.ArrowLeft,"arrow-right":M.ArrowRight,"external-link":M.ExternalLink,ellipsis:M.Ellipsis,"ellipsis-vertical":M.EllipsisVertical,menu:M.Menu,house:M.House,plus:M.Plus,minus:M.Minus,pencil:M.Pencil,"pen-line":M.PenLine,trash:M.Trash,"trash-2":M.Trash2,save:M.Save,download:M.Download,share:M.Share,funnel:M.Funnel,settings:M.Settings,"rotate-cw":M.RotateCw,maximize:M.Maximize,minimize:M.Minimize,"shopping-cart":M.ShoppingCart,"shopping-bag":M.ShoppingBag,package:M.Package,truck:M.Truck,tag:M.Tag,gift:M.Gift,receipt:M.Receipt,wallet:M.Wallet,store:M.Store,"dollar-sign":M.DollarSign,percent:M.Percent,play:M.Play,pause:M.Pause,"volume-x":M.VolumeX,camera:M.Camera,image:M.Image,film:M.Film,headphones:M.Headphones,"message-circle":M.MessageCircle,"message-square":M.MessageSquare,bell:M.Bell,heart:M.Heart,star:M.Star,eye:M.Eye,"eye-off":M.EyeOff,bookmark:M.Bookmark,"calendar-days":M.CalendarDays,history:M.History,timer:M.Timer,folder:M.Folder,"folder-open":M.FolderOpen,files:M.Files,"chart-column":M.ChartColumn,sparkles:M.Sparkles,zap:M.Zap,sun:M.Sun,moon:M.Moon,flag:M.Flag,lightbulb:M.Lightbulb,monitor:M.Monitor,smartphone:M.Smartphone},ae=(t,e=24,n="currentColor",o=2)=>{let r=ky[t];return r?Ly(r,e,n,o):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)}});function Ry(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
2
+ `:o===""||Tu.test(o)}function Wy(t,e,n="@",o="anywhere",r=!1){if(!n||e<=0||e>t.length)return null;let s=e-1;for(;s>=0;){let i=t[s];if(i===n)return Ry(t,s,o)?{triggerIndex:s,query:t.slice(s+1,e)}:null;if(i===`
3
+ `||i==="\uFFFC"||!r&&Tu.test(i))return null;s--}return null}function As(t,e,n){for(let o of n){let r=Wy(t,e,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Eu(t){return t?t!=="insertFromPaste"&&t!=="insertFromDrop":!0}function ku(t,e,n){return{value:t.slice(0,e.triggerIndex)+t.slice(n),caret:e.triggerIndex}}var Tu,Qi=ht(()=>{"use strict";Tu=/\s/});function Xi(t){let e={trigger:t.trigger??"@",position:t.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(t.sources)?t.sources:[],searchPlaceholder:t.searchPlaceholder,showButton:t.showButton!==!1,buttonIconName:t.buttonIconName,buttonTooltipText:t.buttonTooltipText},n=(t.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[e,...n]}var _l=ht(()=>{"use strict"});function Iu(t){let{ref:e,config:n,onRemove:o}=t;if(n.renderMentionChip){let g="resolving",h,C=n.renderMentionChip({ref:e,status:g,payload:h,remove:o});return{get el(){return C},setStatus:(B,k)=>{if(B===g&&k===h)return;g=B,h=k;let S=n.renderMentionChip({ref:e,status:g,payload:h,remove:o});C.replaceWith(S),C=S}}}let r=e.iconName??n.chipIconName??"at-sign",s=Ce("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),i=v("span","persona-mention-chip-icon"),l=g=>{i.replaceChildren();let h=ae(g,13,"currentColor",2);h&&i.appendChild(h)};l(r);let p=v("span","persona-mention-chip-spinner"),c=Ce("span",{className:"persona-mention-chip-label",text:e.label}),d=Ce("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),u=ae("x",11,"currentColor",2.5);return u?d.appendChild(u):d.textContent="\xD7",d.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),o()}),s.appendChild(p),s.appendChild(c),s.appendChild(d),{el:s,setStatus:g=>{s.setAttribute("data-status",g),g==="resolving"?(p.parentNode!==s&&s.insertBefore(p,c),i.parentNode===s&&i.remove(),s.setAttribute("title",e.label)):(p.parentNode===s&&p.remove(),i.parentNode!==s&&s.insertBefore(i,c),g==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${e.label} to context`)):(l(r),s.setAttribute("title",e.label)))}}}var Ru=ht(()=>{"use strict";Je();wt()});function Ny(t){let e=0;for(let n of t.split(`
4
+ `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function jl(t,e){let n="`".repeat(Math.max(3,Ny(e)+1));return`${n}${t}
5
5
  ${e}
6
- ${n}`}function my(t,e,n){return e.includes("</document_content>")?Fl(t,e):`<document index="${n+1}">
6
+ ${n}`}function Oy(t,e,n){return e.includes("</document_content>")?jl(t,e):`<document index="${n+1}">
7
7
  <source>${t}</source>
8
8
  <document_content>
9
9
  ${e}
10
10
  </document_content>
11
- </document>`}function mu(t,e,n="fenced"){if(typeof n=="function")try{return n(t,e)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),Fl(t.label,t.text)}return n==="document"?my(t.label,t.text,e):Fl(t.label,t.text)}var hu=bt(()=>{"use strict"});function qi(t,e){return{sourceId:t.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var yu,Ki,_l=bt(()=>{"use strict";gu();hu();yu=(t,e)=>`${t}\0${e}`,Ki=class{constructor(e){this.mentions=[];this.opts=e,this.updateRowVisibility()}get maxMentions(){return this.opts.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(e,n,o=""){let r=yu(e.id,n.id);if(this.mentions.some(l=>l.key===r))return this.reject(e,n,"duplicate");if(this.atLimit())return this.reject(e,n,"limit");let s=qi(e,n),i={key:r,source:e,item:n,ref:s,status:"resolving",args:o};return i.chip=fu({ref:s,config:this.opts.mentionConfig,onRemove:()=>this.remove(r)}),this.opts.contextRow.appendChild(i.chip.el),this.startPending(i),this.updateRowVisibility(),!0}atLimit(){return this.mentions.length>=this.maxMentions}admit(e,n){return this.atLimit()?this.reject(e,n,"limit"):!0}track(e,n,o,r="",s){let i={key:e,source:n,item:o,ref:qi(n,o),status:"resolving",args:r,reportStatus:s};this.startPending(i)}reject(e,n,o){return this.opts.mentionConfig.onMentionRejected?.(n,o),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:o}),!1}startPending(e){this.mentions.push(e),e.source.resolveOn==="submit"?(e.status="ready",e.chip?.setStatus("ready"),e.reportStatus?.("resolved")):e.resolvePromise=this.resolvePending(e),this.opts.announce(`Added ${e.ref.label} to context`)}buildResolveContext(e,n,o=this.opts.getComposerText()){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:o,args:n,signal:e}}async resolvePending(e){let n=new AbortController;e.abort=n;try{let o=await e.source.resolve(e.item,this.buildResolveContext(n.signal,e.args));if(n.signal.aborted)return;e.payload=o,e.status="ready",e.chip?.setStatus("ready",o),e.reportStatus?.("resolved")}catch(o){if(n.signal.aborted)return;e.status="error",e.chip?.setStatus("error"),e.reportStatus?.("error"),(this.opts.announceError??this.opts.announce)(`Couldn't attach ${e.ref.label} to context`),this.opts.mentionConfig.onMentionResolveError?.(e.item,o),this.opts.emit?.("resolve-error",{sourceId:e.source.id,itemId:e.item.id})}}remove(e){let n=this.mentions.findIndex(r=>r.key===e);if(n===-1)return;let[o]=this.mentions.splice(n,1);o.abort?.abort(),o.chip?.el.remove(),this.updateRowVisibility(),this.opts.announce(`Removed ${o.ref.label} from context`)}removeLast(){let e=this.mentions[this.mentions.length-1];return e?(this.remove(e.key),!0):!1}clear(){for(let e of this.mentions)e.abort?.abort(),e.chip?.el.remove();this.mentions.length=0,this.updateRowVisibility()}collectForSubmit(){let e=[...this.mentions],n=e.map(s=>s.ref),o=this.opts.getComposerText();for(let s of e)s.chip?.el.remove();return this.mentions.length=0,this.updateRowVisibility(),{refs:n,finalize:async()=>{var d;let s=await Promise.all(e.map(async u=>{try{return u.source.resolveOn==="submit"?await u.source.resolve(u.item,this.buildResolveContext(new AbortController().signal,u.args,o)):(u.resolvePromise&&await u.resolvePromise,u.payload??null)}catch(b){try{this.opts.mentionConfig.onMentionResolveError?.(u.item,b)}catch(f){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",f)}return this.opts.emit?.("resolve-error",{sourceId:u.source.id,itemId:u.item.id}),null}})),i=[],l=[],p={},c=new Set;for(let u=0;u<e.length;u++){let b=e[u],f=s[u];if(!f)continue;let m=yu(b.source.id,b.item.id);if(!c.has(m)){if(c.add(m),f.llmAppend&&f.llmAppend.trim())try{i.push(mu({label:b.ref.label,text:f.llmAppend,ref:b.ref,item:b.item},i.length,this.opts.mentionConfig.llmFormat))}catch(C){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",C)}f.contentParts?.length&&l.push(...f.contentParts),f.context&&((p[d=b.source.id]??(p[d]={}))[b.item.id]=f.context)}}return{blocks:i,contentParts:l,context:p}}}}updateRowVisibility(){this.opts.contextRow.style.display=this.mentions.length>0?"flex":"none"}}});function bu(t){let e=t.getRootNode?.();return e instanceof ShadowRoot||e instanceof Document?e:t.ownerDocument??document}function Gi(t,e,n){let o=t instanceof Document?t.head:t,r=e.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let i=(t instanceof Document?t:t.ownerDocument??document).createElement("style");i.setAttribute("data-persona-plugin-style",e),i.textContent=n,o.appendChild(i)}function vu(t,e,n){if(t instanceof Document||t instanceof ShadowRoot){Gi(t,e,n);return}let o=t;if(o.isConnected){Gi(bu(o),e,n);return}let r=o.ownerDocument??document;Gi(r,e,n),queueMicrotask(()=>{let s=bu(o);s!==r&&Gi(s,e,n)})}function hy(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function Qi(t){let{anchor:e,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:p=2147483e3,onOpen:c,onDismiss:d}=t,u=t.container??hy(e),b=!1,f=null,m=()=>{if(!b)return;let H=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${H.width}px`),i&&(n.style.maxWidth=`${H.width}px`);let L=n.getBoundingClientRect(),T=l?.()??null,k=T!=null?H.top+T:H.top,$=o==="top-start"||o==="top-end"?k-r-L.height:H.bottom+r,w=o==="bottom-end"||o==="top-end"?H.right-L.width:H.left,F=i?.()??null;if(F!=null){let D=Math.max(H.left,H.right-L.width);w=Math.min(Math.max(H.left+F,H.left),D)}n.style.top=`${$}px`,n.style.left=`${w}px`},C=()=>{b&&(b=!1,f&&(f(),f=null),n.remove())},R=()=>{if(b)return;b=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),m();let H=(e.ownerDocument??document).defaultView??window,L=e.ownerDocument??document,T=()=>{if(!e.isConnected){C(),d?.("anchor-removed");return}m()},k=G=>{let w=typeof G.composedPath=="function"?G.composedPath():[];w.includes(n)||w.includes(e)||(C(),d?.("outside"))},$=H.setTimeout(()=>{L.addEventListener("pointerdown",k,!0)},0);H.addEventListener("scroll",T,!0),H.addEventListener("resize",T),f=()=>{H.clearTimeout($),L.removeEventListener("pointerdown",k,!0),H.removeEventListener("scroll",T,!0),H.removeEventListener("resize",T)},c?.()};return{get isOpen(){return b},open:R,close:C,toggle:()=>b?C():R(),reposition:m,destroy:C}}function xu(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var $l=bt(()=>{"use strict"});var Cu,wu=bt(()=>{"use strict";Cu=`
11
+ </document>`}function Wu(t,e,n="fenced"){if(typeof n=="function")try{return n(t,e)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),jl(t.label,t.text)}return n==="document"?Oy(t.label,t.text,e):jl(t.label,t.text)}var Hu=ht(()=>{"use strict"});function Yi(t,e){return{sourceId:t.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var Bu,Zi,Vl=ht(()=>{"use strict";Ru();Hu();Bu=(t,e)=>`${t}\0${e}`,Zi=class{constructor(e){this.mentions=[];this.opts=e,this.updateRowVisibility()}get maxMentions(){return this.opts.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(e,n,o=""){let r=Bu(e.id,n.id);if(this.mentions.some(l=>l.key===r))return this.reject(e,n,"duplicate");if(this.atLimit())return this.reject(e,n,"limit");let s=Yi(e,n),i={key:r,source:e,item:n,ref:s,status:"resolving",args:o};return i.chip=Iu({ref:s,config:this.opts.mentionConfig,onRemove:()=>this.remove(r)}),this.opts.contextRow.appendChild(i.chip.el),this.startPending(i),this.updateRowVisibility(),!0}atLimit(){return this.mentions.length>=this.maxMentions}admit(e,n){return this.atLimit()?this.reject(e,n,"limit"):!0}track(e,n,o,r="",s){let i={key:e,source:n,item:o,ref:Yi(n,o),status:"resolving",args:r,reportStatus:s};this.startPending(i)}reject(e,n,o){return this.opts.mentionConfig.onMentionRejected?.(n,o),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:o}),!1}startPending(e){this.mentions.push(e),e.source.resolveOn==="submit"?(e.status="ready",e.chip?.setStatus("ready"),e.reportStatus?.("resolved")):e.resolvePromise=this.resolvePending(e),this.opts.announce(`Added ${e.ref.label} to context`)}buildResolveContext(e,n,o=this.opts.getComposerText()){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:o,args:n,signal:e}}async resolvePending(e){let n=new AbortController;e.abort=n;try{let o=await e.source.resolve(e.item,this.buildResolveContext(n.signal,e.args));if(n.signal.aborted)return;e.payload=o,e.status="ready",e.chip?.setStatus("ready",o),e.reportStatus?.("resolved")}catch(o){if(n.signal.aborted)return;e.status="error",e.chip?.setStatus("error"),e.reportStatus?.("error"),(this.opts.announceError??this.opts.announce)(`Couldn't attach ${e.ref.label} to context`),this.opts.mentionConfig.onMentionResolveError?.(e.item,o),this.opts.emit?.("resolve-error",{sourceId:e.source.id,itemId:e.item.id})}}remove(e){let n=this.mentions.findIndex(r=>r.key===e);if(n===-1)return;let[o]=this.mentions.splice(n,1);o.abort?.abort(),o.chip?.el.remove(),this.updateRowVisibility(),this.opts.announce(`Removed ${o.ref.label} from context`)}removeLast(){let e=this.mentions[this.mentions.length-1];return e?(this.remove(e.key),!0):!1}clear(){for(let e of this.mentions)e.abort?.abort(),e.chip?.el.remove();this.mentions.length=0,this.updateRowVisibility()}collectForSubmit(){let e=[...this.mentions],n=e.map(s=>s.ref),o=this.opts.getComposerText();for(let s of e)s.chip?.el.remove();return this.mentions.length=0,this.updateRowVisibility(),{refs:n,finalize:async()=>{var d;let s=await Promise.all(e.map(async u=>{try{return u.source.resolveOn==="submit"?await u.source.resolve(u.item,this.buildResolveContext(new AbortController().signal,u.args,o)):(u.resolvePromise&&await u.resolvePromise,u.payload??null)}catch(b){try{this.opts.mentionConfig.onMentionResolveError?.(u.item,b)}catch(g){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",g)}return this.opts.emit?.("resolve-error",{sourceId:u.source.id,itemId:u.item.id}),null}})),i=[],l=[],p={},c=new Set;for(let u=0;u<e.length;u++){let b=e[u],g=s[u];if(!g)continue;let h=Bu(b.source.id,b.item.id);if(!c.has(h)){if(c.add(h),g.llmAppend&&g.llmAppend.trim())try{i.push(Wu({label:b.ref.label,text:g.llmAppend,ref:b.ref,item:b.item},i.length,this.opts.mentionConfig.llmFormat))}catch(C){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",C)}g.contentParts?.length&&l.push(...g.contentParts),g.context&&((p[d=b.source.id]??(p[d]={}))[b.item.id]=g.context)}}return{blocks:i,contentParts:l,context:p}}}}updateRowVisibility(){this.opts.contextRow.style.display=this.mentions.length>0?"flex":"none"}}});function Du(t){let e=t.getRootNode?.();return e instanceof ShadowRoot||e instanceof Document?e:t.ownerDocument??document}function ea(t,e,n){let o=t instanceof Document?t.head:t,r=e.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let i=(t instanceof Document?t:t.ownerDocument??document).createElement("style");i.setAttribute("data-persona-plugin-style",e),i.textContent=n,o.appendChild(i)}function Nu(t,e,n){if(t instanceof Document||t instanceof ShadowRoot){ea(t,e,n);return}let o=t;if(o.isConnected){ea(Du(o),e,n);return}let r=o.ownerDocument??document;ea(r,e,n),queueMicrotask(()=>{let s=Du(o);s!==r&&ea(s,e,n)})}function Fy(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function ta(t){let{anchor:e,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:p=2147483e3,onOpen:c,onDismiss:d}=t,u=t.container??Fy(e),b=!1,g=null,h=()=>{if(!b)return;let B=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${B.width}px`),i&&(n.style.maxWidth=`${B.width}px`);let k=n.getBoundingClientRect(),S=l?.()??null,E=S!=null?B.top+S:B.top,z=o==="top-start"||o==="top-end"?E-r-k.height:B.bottom+r,A=o==="bottom-end"||o==="top-end"?B.right-k.width:B.left,O=i?.()??null;if(O!=null){let D=Math.max(B.left,B.right-k.width);A=Math.min(Math.max(B.left+O,B.left),D)}n.style.top=`${z}px`,n.style.left=`${A}px`},C=()=>{b&&(b=!1,g&&(g(),g=null),n.remove())},L=()=>{if(b)return;b=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),h();let B=(e.ownerDocument??document).defaultView??window,k=e.ownerDocument??document,S=()=>{if(!e.isConnected){C(),d?.("anchor-removed");return}h()},E=G=>{let A=typeof G.composedPath=="function"?G.composedPath():[];A.includes(n)||A.includes(e)||(C(),d?.("outside"))},z=B.setTimeout(()=>{k.addEventListener("pointerdown",E,!0)},0);B.addEventListener("scroll",S,!0),B.addEventListener("resize",S),g=()=>{B.clearTimeout(z),k.removeEventListener("pointerdown",E,!0),B.removeEventListener("scroll",S,!0),B.removeEventListener("resize",S)},c?.()};return{get isOpen(){return b},open:L,close:C,toggle:()=>b?C():L(),reposition:h,destroy:C}}function Ou(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var ql=ht(()=>{"use strict"});var Fu,_u=ht(()=>{"use strict";Fu=`
12
12
  .persona-mention-menu {
13
13
  box-sizing: border-box;
14
14
  display: flex;
@@ -166,42 +166,42 @@ ${e}
166
166
  min-height: 36px;
167
167
  }
168
168
  }
169
- `});function Xi(t){let e=t.replace(/^\s+/,""),n=e.search(/\s/);return n===-1?{name:e,args:""}:{name:e.slice(0,n),args:e.slice(n+1).trim()}}var Au=bt(()=>{"use strict"});function Mu(t){let{config:e,listboxId:n}=t,o=we("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=we("div",{className:"persona-mention-search",style:{display:"none"}}),s=y("span","persona-mention-search-icon"),i=ae("search",15,"currentColor",2);i&&s.appendChild(i);let l=we("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":e.searchPlaceholder??"Search context",placeholder:e.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>t.onSearchInput?.(l.value)),l.addEventListener("keydown",B=>t.onSearchKeydown?.(B));let p=we("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,p);let c=[],d=[],u=-1,b=new Map,f=(B,P)=>`${B}\0${P}`,m=B=>`${n}-opt-${B}`,C=B=>`${n}-grp-${B}`,R=(B,P)=>{let I=c[B];I&&(P?I.setAttribute("data-active","true"):I.removeAttribute("data-active"),I.setAttribute("aria-selected",P?"true":"false"),d[B]?.(P))},H=(B,P=!0)=>{u>=0&&u!==B&&R(u,!1),u=B;let I=c[B];I?(R(B,!0),P&&I.scrollIntoView?.({block:"nearest"}),p.setAttribute("aria-activedescendant",I.id),l.setAttribute("aria-activedescendant",I.id)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},L=(B,P)=>{let I=C(P),j=we("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":I}});return j.appendChild(we("div",{className:"persona-mention-group-header",attrs:{id:I},text:B})),j},T=()=>{let B=we("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),P=y("span","persona-mention-option-icon");B.appendChild(P);let I="",j=y("span","persona-mention-option-text"),pe=y("span","persona-mention-option-labelline"),ue=y("span","persona-mention-option-label");pe.appendChild(ue),j.appendChild(pe),B.appendChild(j);let ge=null,Z=null,oe={el:B,index:0,update:(Q,se,te)=>{oe.index=se,B.id=m(se),B.setAttribute("aria-setsize",String(te)),B.setAttribute("aria-posinset",String(se+1)),B.removeAttribute("data-active"),B.setAttribute("aria-selected","false");let fe=Q.iconName??e.chipIconName??"at-sign";if(fe!==I){I=fe;let he=yy(fe,15,2);P.replaceChildren(...he?[he]:[])}ue.textContent!==Q.label&&(ue.textContent=Q.label);let be=Q.commandArgsPlaceholder?`\u2039${Q.commandArgsPlaceholder}\u203A`:null;be?(ge||(ge=y("span","persona-mention-option-arghint"),pe.appendChild(ge)),ge.textContent!==be&&(ge.textContent=be)):ge&&(ge.remove(),ge=null),Q.description?(Z||(Z=y("span","persona-mention-option-desc"),j.appendChild(Z)),Z.textContent!==Q.description&&(Z.textContent=Q.description)):Z&&(Z.remove(),Z=null)}};return B.addEventListener("mousedown",Q=>{Q.button===0&&(Q.preventDefault(),t.onSelectIndex(oe.index))}),B.addEventListener("mouseenter",()=>t.onHoverIndex(oe.index)),oe},k=(B,P,I,j,pe)=>{let ue=we("div",{className:"persona-mention-option",attrs:{role:"option",id:m(j),"aria-selected":"false","aria-setsize":String(pe),"aria-posinset":String(j+1)}}),ge=Z=>{ue.replaceChildren(e.renderMentionItem({item:B,source:P,query:I,active:Z,index:j}))};return ge(!1),ue.addEventListener("mousedown",Z=>{Z.button===0&&(Z.preventDefault(),t.onSelectIndex(j))}),ue.addEventListener("mouseenter",()=>t.onHoverIndex(j)),{el:ue,paint:ge}},$=B=>{let P=we("div",{className:"persona-mention-status persona-mention-error"});if(P.appendChild(we("span",{className:"persona-mention-error-text",text:`Couldn't load ${B.label}`})),t.onRetry){let I=we("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});I.addEventListener("mousedown",j=>j.preventDefault()),I.addEventListener("click",j=>{j.preventDefault(),t.onRetry(B.id)}),P.appendChild(I)}return P};return{el:o,render:B=>{p.replaceChildren(),c=[],d=[],u=-1;let P=new Set,I=0,j=0,pe=0,ue=0,ge=0,Z=B.groups.reduce((oe,Q)=>Q.status==="ready"?oe+Q.items.length:oe,0);for(let oe of B.groups)if(oe.status==="loading"){pe++;let Q=L(oe.source.label,ge++);Q.appendChild(we("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),p.appendChild(Q)}else if(oe.status==="error"){ue++;let Q=L(oe.source.label,ge++);Q.appendChild($(oe.source)),p.appendChild(Q)}else if(oe.status==="ready"&&oe.items.length>0){let Q=new Map;for(let te of oe.items){let fe=te.group??oe.source.label,be=Q.get(fe);be?be.push(te):Q.set(fe,[te])}let se=Array.from(Q.entries());se.forEach(([te,fe],be)=>{let he=L(te,ge++);for(let Ce of fe){let $e=I++,Ee;if(e.renderMentionItem){let ke=k(Ce,oe.source,B.query,$e,Z);Ee=ke.el,d.push(ke.paint)}else{let ke=f(oe.source.id,Ce.id),ze=P.has(ke)?void 0:b.get(ke);ze||(ze=T(),P.has(ke)||b.set(ke,ze)),P.add(ke),ze.update(Ce,$e,Z),Ee=ze.el,d.push(null)}c.push(Ee),he.appendChild(Ee),j++}oe.truncated&&be===se.length-1&&he.appendChild(we("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),p.appendChild(he)})}for(let oe of b.keys())P.has(oe)||b.delete(oe);j===0&&pe===0&&ue===0&&p.appendChild(we("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),c.length>0?H(Math.min(Math.max(0,B.activeIndex),c.length-1)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:H,destroy:()=>{p.replaceChildren(),c=[],b.clear(),o.remove()},showSearch:(B,P)=>{l.value=B,P&&(l.placeholder=P),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var Su,yy,Tu=bt(()=>{"use strict";tt();St();Su=new Map,yy=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=Su.get(o);return r===void 0&&(r=ae(t,e,"currentColor",n),Su.set(o,r)),r?r.cloneNode(!0):null}});var by,vy,Ji,Eu=bt(()=>{"use strict";$l();wu();ji();Bl();Au();Tu();_l();by=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",vy=0,Ji=class{constructor(e){this.popover=null;this.resizeObserver=null;this.isOpenState=!1;this.query="";this.triggerMatch=null;this.activeIndex=0;this.activeKey=null;this.pickerMode=!1;this.pickerTrigger=null;this.groups=[];this.flat=[];this.searchToken=0;this.searchAbort=null;this.debounceTimer=null;this.knownAsync=new Set;this.invokedForToken=new Set;this.lastAnnouncedCount=-1;this.triggerAnchorOffset=null;this.measuredTriggerIndex=null;this.opts=e;let n=e.mentionConfig,o=Ui(n),r=o.filter(i=>i.sources.length>0);this.channels=r.length>0?r:[o[0]],this.activeChannel=this.channels[0],this.maxPerGroup=n.maxItemsPerGroup??6,this.debounceMs=n.searchDebounceMs??150,this.listboxId=`persona-mention-listbox-${++vy}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():Mu({config:e.mentionConfig,listboxId:this.listboxId,onSelectIndex:i=>this.selectIndex(i),onHoverIndex:i=>this.setActiveIndex(i,!1),onRetry:i=>this.retrySource(i),onSearchInput:i=>this.setQuery(i),onSearchKeydown:i=>{this.handleKeydown(i)}});let s=e.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.listboxId)}get input(){return this.opts.composerInput}createHostMenu(){let e=document.createElement("div");e.setAttribute("data-persona-mention-menu",""),e.setAttribute("role","listbox"),e.id=this.listboxId;let n=()=>{let o=this.opts.mentionConfig.renderMentionMenu({query:this.query,groups:this.groups.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.groups.map(r=>[r.source.id,r.status])),activeIndex:this.activeIndex,select:r=>{let s=this.groups.find(i=>i.items.includes(r));s&&this.commit(s.source,r)},close:()=>this.close()});e.replaceChildren(o)};return{el:e,render:n,setActiveIndex:n,destroy:()=>e.remove()}}isOpen(){return this.isOpenState}openFromButton(e){let n=e&&this.channels.find(i=>i.trigger===e)||this.channels[0],o=this.input.getSelection().start,r=ms(this.input.getLogicalText(),o,[n]);if(r){this.pickerMode=!1,this.triggerMatch=r.match,this.isOpenState?(this.switchChannel(n),this.setQuery(r.match.query)):this.open(r.match.query,n),this.input.focus();return}let s=this.pickerTrigger;this.pickerMode=!0,this.pickerTrigger=n.trigger,this.triggerMatch=null,this.isOpenState?(s&&s!==n.trigger&&this.opts.onPickerOpenChange?.(!1,s,this.listboxId),this.switchChannel(n),this.setQuery("")):this.open("",n),this.menu.showSearch?this.menu.showSearch("",n.searchPlaceholder):this.input.focus(),this.opts.onPickerOpenChange?.(!0,n.trigger,this.listboxId)}onInput(){let e=this.input.getSelection().start,n=ms(this.input.getLogicalText(),e,this.channels);if(!n){this.isOpenState&&this.close();return}if(this.isInlineArgTail(n.channel,n.match.query)){this.triggerMatch=null,this.isOpenState&&this.close(!1);return}this.triggerMatch=n.match,this.isOpenState?(this.switchChannel(n.channel),this.measuredTriggerIndex!==n.match.triggerIndex&&this.updateTriggerAnchor(),this.setQuery(n.match.query)):this.open(n.match.query,n.channel)}switchChannel(e){e!==this.activeChannel&&(this.activeChannel=e,this.groups=[],this.activeIndex=0)}open(e,n){if(this.isOpenState=!0,this.activeChannel=n,this.groups=[],this.activeIndex=0,this.lastAnnouncedCount=-1,!this.popover){let o=this.canAnchorMenu();if(this.popover=Qi({anchor:this.opts.anchor,content:this.menu.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.opts.popoverContainer,horizontalOffset:o?()=>this.triggerAnchorOffset?.x??null:void 0,verticalOffset:o?()=>this.triggerAnchorOffset?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.opts.anchor.getBoundingClientRect().width;this.menu.el.style.minWidth=`${Math.min(220,r)}px`}}this.updateTriggerAnchor(),this.popover.open(),vu(this.menu.el,"persona-mention-menu",Cu),this.observeComposerResize(),this.opts.emit?.("opened",{trigger:n.trigger}),this.setQuery(e)}observeComposerResize(){typeof ResizeObserver>"u"||this.resizeObserver||(this.resizeObserver=new ResizeObserver(()=>{this.isOpenState&&(this.updateTriggerAnchor(),this.popover?.reposition())}),this.resizeObserver.observe(this.opts.anchor))}disconnectComposerResize(){this.resizeObserver?.disconnect(),this.resizeObserver=null}canAnchorMenu(){return this.isInlineDisplay()&&!!this.input.getLogicalRangeRect}updateTriggerAnchor(){let e=this.triggerMatch,n=this.input.getLogicalRangeRect;if(this.measuredTriggerIndex=e?.triggerIndex??null,this.triggerAnchorOffset=null,!e||!n)return;let o=n(e.triggerIndex,e.triggerIndex+1);if(!o)return;let r=this.opts.anchor.getBoundingClientRect(),s=o.top-r.top,i=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(i).direction==="rtl";this.triggerAnchorOffset={x:l?null:o.left-r.left,y:s}}close(e=!0){this.isOpenState&&(this.isOpenState=!1,this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.searchToken++,this.popover?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.pickerMode&&(this.pickerMode=!1,this.menu.hideSearch?.(),this.opts.onPickerOpenChange?.(!1,this.pickerTrigger??this.activeChannel.trigger,this.listboxId),this.pickerTrigger=null,e&&this.input.focus()))}setQuery(e){this.query=e,this.activeIndex=0,this.activeKey=null;let n=++this.searchToken;this.invokedForToken.clear(),this.searchAbort?.abort(),this.searchAbort=new AbortController;for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)?this.setGroupStatus(o.id,"loading"):(this.invokedForToken.add(o.id),this.invokeSource(o,n));this.render(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{if(n===this.searchToken)for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)&&!this.invokedForToken.has(o.id)&&this.invokeSource(o,n)},this.debounceMs)}invokeSource(e,n){let o={messages:this.opts.getMessages(),config:this.opts.getConfig(),signal:this.searchAbort.signal},r;try{r=e.search(this.query,o)}catch{this.setGroupStatus(e.id,"error"),this.render();return}by(r)?(this.knownAsync.add(e.id),this.setGroupStatus(e.id,"loading"),r.then(s=>{n===this.searchToken&&(this.setGroupItems(e.id,s),this.render())}).catch(()=>{n===this.searchToken&&(this.setGroupStatus(e.id,"error"),this.render())})):this.setGroupItems(e.id,r)}getOrCreateGroup(e){let n=this.groups.find(o=>o.source.id===e.id);if(!n){n={source:e,items:[],status:"loading",truncated:!1};let o=this.activeChannel.sources;this.groups.push(n),this.groups.sort((r,s)=>o.findIndex(i=>i.id===r.source.id)-o.findIndex(i=>i.id===s.source.id))}return n}setGroupStatus(e,n){let o=this.activeChannel.sources.find(r=>r.id===e);o&&(this.getOrCreateGroup(o).status=n)}setGroupItems(e,n){let o=this.activeChannel.sources.find(s=>s.id===e);if(!o)return;let r=this.getOrCreateGroup(o);r.truncated=n.length>this.maxPerGroup,r.items=n.slice(0,this.maxPerGroup),r.status=r.items.length===0?"empty":"ready"}keyOf(e){return JSON.stringify([e.source.id,e.item.id])}rebuildFlat(){this.flat=[];for(let e of this.groups)if(e.status==="ready")for(let n of e.items)this.flat.push({source:e.source,item:n});if(this.activeKey){let e=this.flat.findIndex(n=>this.keyOf(n)===this.activeKey);this.activeIndex=e>=0?e:Math.min(this.activeIndex,Math.max(0,this.flat.length-1))}else this.activeIndex>=this.flat.length&&(this.activeIndex=Math.max(0,this.flat.length-1))}viewModel(){return{query:this.query,groups:this.groups,activeIndex:this.activeIndex}}render(){this.rebuildFlat(),this.menu.render(this.viewModel()),this.syncActiveDescendant(),this.popover?.reposition();let e=this.groups.some(n=>n.status==="loading");this.flat.length===0&&e||this.flat.length!==this.lastAnnouncedCount&&(this.lastAnnouncedCount=this.flat.length,this.opts.announce(this.flat.length===0?"No matches":this.flat.length===1?"1 result":`${this.flat.length} results`),this.opts.emit?.("searched",{query:this.query,results:this.flat.length}))}setActiveIndex(e,n=!0){e<0||e>=this.flat.length||(this.activeIndex=e,this.activeKey=this.keyOf(this.flat[e]),this.menu.setActiveIndex(e,n),this.syncActiveDescendant())}syncActiveDescendant(){this.isOpenState&&!this.pickerMode&&this.activeIndex>=0&&this.activeIndex<this.flat.length?this.input.element.setAttribute("aria-activedescendant",`${this.listboxId}-opt-${this.activeIndex}`):this.input.element.removeAttribute("aria-activedescendant")}retrySource(e){let n=this.activeChannel.sources.find(o=>o.id===e);!n||!this.searchAbort||(this.setGroupStatus(e,"loading"),this.render(),this.invokeSource(n,this.searchToken),this.render())}handleKeydown(e){if(!this.isOpenState)return!1;switch(e.key){case"ArrowDown":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex+1)%this.flat.length)),!0;case"ArrowUp":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex-1+this.flat.length)%this.flat.length)),!0;case"Home":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(0)),!0;case"End":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(this.flat.length-1)),!0;case"Enter":case"Tab":return this.flat.length===0?(this.close(),!1):(e.preventDefault(),this.selectIndex(this.activeIndex),!0);case"Escape":return e.preventDefault(),this.close(),!0;case"Backspace":return this.query.length===0&&this.close(),!1;default:return!1}}selectIndex(e){let n=this.flat[e];n&&this.commit(n.source,n.item)}deriveArgs(e){return Xi(e).args}isInlineCommand(e){return e.command==="server"||e.commandArgsPlaceholder!=null}commit(e,n){let o=n.command;if(this.isInlineCommand(n)){this.completeCommandInline(e,n);return}if(o==="action"){let s=this.deriveArgs(this.query);this.stripQuery(),this.close(),this.runAction(n,s),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.deriveArgs(this.query),i=this.captureStripTarget();this.close(),this.runPromptMacro(e,n,s,i),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"prompt",args:s});return}if(this.isInlineDisplay()){this.commitInlineMention(e,n);return}this.opts.onSelect(e,n,"")&&(this.stripQuery(),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}isInlineDisplay(){return this.opts.mentionConfig.display==="inline"&&!!this.opts.onInsertMention&&!!this.input.insertMentionAtTrigger}commitInlineMention(e,n){if(this.opts.admitMention&&!this.opts.admitMention(e,n)){this.close(),this.input.focus();return}let o=qi(e,n),r=this.triggerMatch?this.input.insertMentionAtTrigger(o,this.triggerMatch):this.input.insertMentionAtSelection?.(o)??null;r?(this.opts.onInsertMention(r,e,n,""),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})):(this.opts.mentionConfig.onMentionRejected?.(n,"stale"),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:"stale"})),this.triggerMatch=null,this.close(),this.input.focus()}completeCommandInline(e,n){let o=`${this.activeChannel.trigger}${n.label} `,r=this.input.getSelection().start,s=this.triggerMatch?this.triggerMatch.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let i=this.input.getValue();this.input.setValueWithCaret(i.slice(0,s)+o+i.slice(r),s+o.length)}this.triggerMatch=null,this.close(),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}isInlineArgTail(e,n){let{name:o}=Xi(n);return!o||n.length<=o.length?!1:e.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.isInlineCommand(s)})}matchInlineCommand(e){for(let n of this.channels){if(!n.trigger)continue;let o=n.position==="anywhere"?[e]:n.position==="line-start"?e.split(`
169
+ `});function na(t){let e=t.replace(/^\s+/,""),n=e.search(/\s/);return n===-1?{name:e,args:""}:{name:e.slice(0,n),args:e.slice(n+1).trim()}}var $u=ht(()=>{"use strict"});function Uu(t){let{config:e,listboxId:n}=t,o=Ce("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=Ce("div",{className:"persona-mention-search",style:{display:"none"}}),s=v("span","persona-mention-search-icon"),i=ae("search",15,"currentColor",2);i&&s.appendChild(i);let l=Ce("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":e.searchPlaceholder??"Search context",placeholder:e.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>t.onSearchInput?.(l.value)),l.addEventListener("keydown",W=>t.onSearchKeydown?.(W));let p=Ce("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,p);let c=[],d=[],u=-1,b=new Map,g=(W,P)=>`${W}\0${P}`,h=W=>`${n}-opt-${W}`,C=W=>`${n}-grp-${W}`,L=(W,P)=>{let I=c[W];I&&(P?I.setAttribute("data-active","true"):I.removeAttribute("data-active"),I.setAttribute("aria-selected",P?"true":"false"),d[W]?.(P))},B=(W,P=!0)=>{u>=0&&u!==W&&L(u,!1),u=W;let I=c[W];I?(L(W,!0),P&&I.scrollIntoView?.({block:"nearest"}),p.setAttribute("aria-activedescendant",I.id),l.setAttribute("aria-activedescendant",I.id)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},k=(W,P)=>{let I=C(P),j=Ce("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":I}});return j.appendChild(Ce("div",{className:"persona-mention-group-header",attrs:{id:I},text:W})),j},S=()=>{let W=Ce("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),P=v("span","persona-mention-option-icon");W.appendChild(P);let I="",j=v("span","persona-mention-option-text"),pe=v("span","persona-mention-option-labelline"),ge=v("span","persona-mention-option-label");pe.appendChild(ge),j.appendChild(pe),W.appendChild(j);let se=null,Y=null,oe={el:W,index:0,update:(J,ie,ee)=>{oe.index=ie,W.id=h(ie),W.setAttribute("aria-setsize",String(ee)),W.setAttribute("aria-posinset",String(ie+1)),W.removeAttribute("data-active"),W.setAttribute("aria-selected","false");let fe=J.iconName??e.chipIconName??"at-sign";if(fe!==I){I=fe;let he=_y(fe,15,2);P.replaceChildren(...he?[he]:[])}ge.textContent!==J.label&&(ge.textContent=J.label);let be=J.commandArgsPlaceholder?`\u2039${J.commandArgsPlaceholder}\u203A`:null;be?(se||(se=v("span","persona-mention-option-arghint"),pe.appendChild(se)),se.textContent!==be&&(se.textContent=be)):se&&(se.remove(),se=null),J.description?(Y||(Y=v("span","persona-mention-option-desc"),j.appendChild(Y)),Y.textContent!==J.description&&(Y.textContent=J.description)):Y&&(Y.remove(),Y=null)}};return W.addEventListener("mousedown",J=>{J.button===0&&(J.preventDefault(),t.onSelectIndex(oe.index))}),W.addEventListener("mouseenter",()=>t.onHoverIndex(oe.index)),oe},E=(W,P,I,j,pe)=>{let ge=Ce("div",{className:"persona-mention-option",attrs:{role:"option",id:h(j),"aria-selected":"false","aria-setsize":String(pe),"aria-posinset":String(j+1)}}),se=Y=>{ge.replaceChildren(e.renderMentionItem({item:W,source:P,query:I,active:Y,index:j}))};return se(!1),ge.addEventListener("mousedown",Y=>{Y.button===0&&(Y.preventDefault(),t.onSelectIndex(j))}),ge.addEventListener("mouseenter",()=>t.onHoverIndex(j)),{el:ge,paint:se}},z=W=>{let P=Ce("div",{className:"persona-mention-status persona-mention-error"});if(P.appendChild(Ce("span",{className:"persona-mention-error-text",text:`Couldn't load ${W.label}`})),t.onRetry){let I=Ce("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});I.addEventListener("mousedown",j=>j.preventDefault()),I.addEventListener("click",j=>{j.preventDefault(),t.onRetry(W.id)}),P.appendChild(I)}return P};return{el:o,render:W=>{p.replaceChildren(),c=[],d=[],u=-1;let P=new Set,I=0,j=0,pe=0,ge=0,se=0,Y=W.groups.reduce((oe,J)=>J.status==="ready"?oe+J.items.length:oe,0);for(let oe of W.groups)if(oe.status==="loading"){pe++;let J=k(oe.source.label,se++);J.appendChild(Ce("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),p.appendChild(J)}else if(oe.status==="error"){ge++;let J=k(oe.source.label,se++);J.appendChild(z(oe.source)),p.appendChild(J)}else if(oe.status==="ready"&&oe.items.length>0){let J=new Map;for(let ee of oe.items){let fe=ee.group??oe.source.label,be=J.get(fe);be?be.push(ee):J.set(fe,[ee])}let ie=Array.from(J.entries());ie.forEach(([ee,fe],be)=>{let he=k(ee,se++);for(let we of fe){let ve=I++,Te;if(e.renderMentionItem){let Me=E(we,oe.source,W.query,ve,Y);Te=Me.el,d.push(Me.paint)}else{let Me=g(oe.source.id,we.id),_e=P.has(Me)?void 0:b.get(Me);_e||(_e=S(),P.has(Me)||b.set(Me,_e)),P.add(Me),_e.update(we,ve,Y),Te=_e.el,d.push(null)}c.push(Te),he.appendChild(Te),j++}oe.truncated&&be===ie.length-1&&he.appendChild(Ce("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),p.appendChild(he)})}for(let oe of b.keys())P.has(oe)||b.delete(oe);j===0&&pe===0&&ge===0&&p.appendChild(Ce("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),c.length>0?B(Math.min(Math.max(0,W.activeIndex),c.length-1)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:B,destroy:()=>{p.replaceChildren(),c=[],b.clear(),o.remove()},showSearch:(W,P)=>{l.value=W,P&&(l.placeholder=P),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var zu,_y,ju=ht(()=>{"use strict";Je();wt();zu=new Map,_y=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=zu.get(o);return r===void 0&&(r=ae(t,e,"currentColor",n),zu.set(o,r)),r?r.cloneNode(!0):null}});var $y,zy,oa,Vu=ht(()=>{"use strict";ql();_u();Qi();_l();$u();ju();Vl();$y=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",zy=0,oa=class{constructor(e){this.popover=null;this.resizeObserver=null;this.isOpenState=!1;this.query="";this.triggerMatch=null;this.activeIndex=0;this.activeKey=null;this.pickerMode=!1;this.pickerTrigger=null;this.groups=[];this.flat=[];this.searchToken=0;this.searchAbort=null;this.debounceTimer=null;this.knownAsync=new Set;this.invokedForToken=new Set;this.lastAnnouncedCount=-1;this.triggerAnchorOffset=null;this.measuredTriggerIndex=null;this.opts=e;let n=e.mentionConfig,o=Xi(n),r=o.filter(i=>i.sources.length>0);this.channels=r.length>0?r:[o[0]],this.activeChannel=this.channels[0],this.maxPerGroup=n.maxItemsPerGroup??6,this.debounceMs=n.searchDebounceMs??150,this.listboxId=`persona-mention-listbox-${++zy}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():Uu({config:e.mentionConfig,listboxId:this.listboxId,onSelectIndex:i=>this.selectIndex(i),onHoverIndex:i=>this.setActiveIndex(i,!1),onRetry:i=>this.retrySource(i),onSearchInput:i=>this.setQuery(i),onSearchKeydown:i=>{this.handleKeydown(i)}});let s=e.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.listboxId)}get input(){return this.opts.composerInput}createHostMenu(){let e=document.createElement("div");e.setAttribute("data-persona-mention-menu",""),e.setAttribute("role","listbox"),e.id=this.listboxId;let n=()=>{let o=this.opts.mentionConfig.renderMentionMenu({query:this.query,groups:this.groups.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.groups.map(r=>[r.source.id,r.status])),activeIndex:this.activeIndex,select:r=>{let s=this.groups.find(i=>i.items.includes(r));s&&this.commit(s.source,r)},close:()=>this.close()});e.replaceChildren(o)};return{el:e,render:n,setActiveIndex:n,destroy:()=>e.remove()}}isOpen(){return this.isOpenState}openFromButton(e){let n=e&&this.channels.find(i=>i.trigger===e)||this.channels[0],o=this.input.getSelection().start,r=As(this.input.getLogicalText(),o,[n]);if(r){this.pickerMode=!1,this.triggerMatch=r.match,this.isOpenState?(this.switchChannel(n),this.setQuery(r.match.query)):this.open(r.match.query,n),this.input.focus();return}let s=this.pickerTrigger;this.pickerMode=!0,this.pickerTrigger=n.trigger,this.triggerMatch=null,this.isOpenState?(s&&s!==n.trigger&&this.opts.onPickerOpenChange?.(!1,s,this.listboxId),this.switchChannel(n),this.setQuery("")):this.open("",n),this.menu.showSearch?this.menu.showSearch("",n.searchPlaceholder):this.input.focus(),this.opts.onPickerOpenChange?.(!0,n.trigger,this.listboxId)}onInput(){let e=this.input.getSelection().start,n=As(this.input.getLogicalText(),e,this.channels);if(!n){this.isOpenState&&this.close();return}if(this.isInlineArgTail(n.channel,n.match.query)){this.triggerMatch=null,this.isOpenState&&this.close(!1);return}this.triggerMatch=n.match,this.isOpenState?(this.switchChannel(n.channel),this.measuredTriggerIndex!==n.match.triggerIndex&&this.updateTriggerAnchor(),this.setQuery(n.match.query)):this.open(n.match.query,n.channel)}switchChannel(e){e!==this.activeChannel&&(this.activeChannel=e,this.groups=[],this.activeIndex=0)}open(e,n){if(this.isOpenState=!0,this.activeChannel=n,this.groups=[],this.activeIndex=0,this.lastAnnouncedCount=-1,!this.popover){let o=this.canAnchorMenu();if(this.popover=ta({anchor:this.opts.anchor,content:this.menu.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.opts.popoverContainer,horizontalOffset:o?()=>this.triggerAnchorOffset?.x??null:void 0,verticalOffset:o?()=>this.triggerAnchorOffset?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.opts.anchor.getBoundingClientRect().width;this.menu.el.style.minWidth=`${Math.min(220,r)}px`}}this.updateTriggerAnchor(),this.popover.open(),Nu(this.menu.el,"persona-mention-menu",Fu),this.observeComposerResize(),this.opts.emit?.("opened",{trigger:n.trigger}),this.setQuery(e)}observeComposerResize(){typeof ResizeObserver>"u"||this.resizeObserver||(this.resizeObserver=new ResizeObserver(()=>{this.isOpenState&&(this.updateTriggerAnchor(),this.popover?.reposition())}),this.resizeObserver.observe(this.opts.anchor))}disconnectComposerResize(){this.resizeObserver?.disconnect(),this.resizeObserver=null}canAnchorMenu(){return this.isInlineDisplay()&&!!this.input.getLogicalRangeRect}updateTriggerAnchor(){let e=this.triggerMatch,n=this.input.getLogicalRangeRect;if(this.measuredTriggerIndex=e?.triggerIndex??null,this.triggerAnchorOffset=null,!e||!n)return;let o=n(e.triggerIndex,e.triggerIndex+1);if(!o)return;let r=this.opts.anchor.getBoundingClientRect(),s=o.top-r.top,i=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(i).direction==="rtl";this.triggerAnchorOffset={x:l?null:o.left-r.left,y:s}}close(e=!0){this.isOpenState&&(this.isOpenState=!1,this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.searchToken++,this.popover?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.pickerMode&&(this.pickerMode=!1,this.menu.hideSearch?.(),this.opts.onPickerOpenChange?.(!1,this.pickerTrigger??this.activeChannel.trigger,this.listboxId),this.pickerTrigger=null,e&&this.input.focus()))}setQuery(e){this.query=e,this.activeIndex=0,this.activeKey=null;let n=++this.searchToken;this.invokedForToken.clear(),this.searchAbort?.abort(),this.searchAbort=new AbortController;for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)?this.setGroupStatus(o.id,"loading"):(this.invokedForToken.add(o.id),this.invokeSource(o,n));this.render(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{if(n===this.searchToken)for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)&&!this.invokedForToken.has(o.id)&&this.invokeSource(o,n)},this.debounceMs)}invokeSource(e,n){let o={messages:this.opts.getMessages(),config:this.opts.getConfig(),signal:this.searchAbort.signal},r;try{r=e.search(this.query,o)}catch{this.setGroupStatus(e.id,"error"),this.render();return}$y(r)?(this.knownAsync.add(e.id),this.setGroupStatus(e.id,"loading"),r.then(s=>{n===this.searchToken&&(this.setGroupItems(e.id,s),this.render())}).catch(()=>{n===this.searchToken&&(this.setGroupStatus(e.id,"error"),this.render())})):this.setGroupItems(e.id,r)}getOrCreateGroup(e){let n=this.groups.find(o=>o.source.id===e.id);if(!n){n={source:e,items:[],status:"loading",truncated:!1};let o=this.activeChannel.sources;this.groups.push(n),this.groups.sort((r,s)=>o.findIndex(i=>i.id===r.source.id)-o.findIndex(i=>i.id===s.source.id))}return n}setGroupStatus(e,n){let o=this.activeChannel.sources.find(r=>r.id===e);o&&(this.getOrCreateGroup(o).status=n)}setGroupItems(e,n){let o=this.activeChannel.sources.find(s=>s.id===e);if(!o)return;let r=this.getOrCreateGroup(o);r.truncated=n.length>this.maxPerGroup,r.items=n.slice(0,this.maxPerGroup),r.status=r.items.length===0?"empty":"ready"}keyOf(e){return JSON.stringify([e.source.id,e.item.id])}rebuildFlat(){this.flat=[];for(let e of this.groups)if(e.status==="ready")for(let n of e.items)this.flat.push({source:e.source,item:n});if(this.activeKey){let e=this.flat.findIndex(n=>this.keyOf(n)===this.activeKey);this.activeIndex=e>=0?e:Math.min(this.activeIndex,Math.max(0,this.flat.length-1))}else this.activeIndex>=this.flat.length&&(this.activeIndex=Math.max(0,this.flat.length-1))}viewModel(){return{query:this.query,groups:this.groups,activeIndex:this.activeIndex}}render(){this.rebuildFlat(),this.menu.render(this.viewModel()),this.syncActiveDescendant(),this.popover?.reposition();let e=this.groups.some(n=>n.status==="loading");this.flat.length===0&&e||this.flat.length!==this.lastAnnouncedCount&&(this.lastAnnouncedCount=this.flat.length,this.opts.announce(this.flat.length===0?"No matches":this.flat.length===1?"1 result":`${this.flat.length} results`),this.opts.emit?.("searched",{query:this.query,results:this.flat.length}))}setActiveIndex(e,n=!0){e<0||e>=this.flat.length||(this.activeIndex=e,this.activeKey=this.keyOf(this.flat[e]),this.menu.setActiveIndex(e,n),this.syncActiveDescendant())}syncActiveDescendant(){this.isOpenState&&!this.pickerMode&&this.activeIndex>=0&&this.activeIndex<this.flat.length?this.input.element.setAttribute("aria-activedescendant",`${this.listboxId}-opt-${this.activeIndex}`):this.input.element.removeAttribute("aria-activedescendant")}retrySource(e){let n=this.activeChannel.sources.find(o=>o.id===e);!n||!this.searchAbort||(this.setGroupStatus(e,"loading"),this.render(),this.invokeSource(n,this.searchToken),this.render())}handleKeydown(e){if(!this.isOpenState)return!1;switch(e.key){case"ArrowDown":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex+1)%this.flat.length)),!0;case"ArrowUp":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex-1+this.flat.length)%this.flat.length)),!0;case"Home":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(0)),!0;case"End":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(this.flat.length-1)),!0;case"Enter":case"Tab":return this.flat.length===0?(this.close(),!1):(e.preventDefault(),this.selectIndex(this.activeIndex),!0);case"Escape":return e.preventDefault(),this.close(),!0;case"Backspace":return this.query.length===0&&this.close(),!1;default:return!1}}selectIndex(e){let n=this.flat[e];n&&this.commit(n.source,n.item)}deriveArgs(e){return na(e).args}isInlineCommand(e){return e.command==="server"||e.commandArgsPlaceholder!=null}commit(e,n){let o=n.command;if(this.isInlineCommand(n)){this.completeCommandInline(e,n);return}if(o==="action"){let s=this.deriveArgs(this.query);this.stripQuery(),this.close(),this.runAction(n,s),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.deriveArgs(this.query),i=this.captureStripTarget();this.close(),this.runPromptMacro(e,n,s,i),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"prompt",args:s});return}if(this.isInlineDisplay()){this.commitInlineMention(e,n);return}this.opts.onSelect(e,n,"")&&(this.stripQuery(),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}isInlineDisplay(){return this.opts.mentionConfig.display==="inline"&&!!this.opts.onInsertMention&&!!this.input.insertMentionAtTrigger}commitInlineMention(e,n){if(this.opts.admitMention&&!this.opts.admitMention(e,n)){this.close(),this.input.focus();return}let o=Yi(e,n),r=this.triggerMatch?this.input.insertMentionAtTrigger(o,this.triggerMatch):this.input.insertMentionAtSelection?.(o)??null;r?(this.opts.onInsertMention(r,e,n,""),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})):(this.opts.mentionConfig.onMentionRejected?.(n,"stale"),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:"stale"})),this.triggerMatch=null,this.close(),this.input.focus()}completeCommandInline(e,n){let o=`${this.activeChannel.trigger}${n.label} `,r=this.input.getSelection().start,s=this.triggerMatch?this.triggerMatch.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let i=this.input.getValue();this.input.setValueWithCaret(i.slice(0,s)+o+i.slice(r),s+o.length)}this.triggerMatch=null,this.close(),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}isInlineArgTail(e,n){let{name:o}=na(n);return!o||n.length<=o.length?!1:e.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.isInlineCommand(s)})}matchInlineCommand(e){for(let n of this.channels){if(!n.trigger)continue;let o=n.position==="anywhere"?[e]:n.position==="line-start"?e.split(`
170
170
  `):[e.split(`
171
- `)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:i}=Xi(r.slice(n.trigger.length));if(s)for(let l of n.sources){let p=l.matchCommand?.(s);if(p&&this.isInlineCommand(p))return{source:l,item:p,args:i}}}}return null}async dispatchInlineCommand(e){let n=this.matchInlineCommand(e);if(!n)return null;let{source:o,item:r,args:s}=n,i=r.command??"prompt";if(this.opts.emit?.("command",{sourceId:o.id,itemId:r.id,kind:i,args:s}),i==="action")return this.runAction(r,s),{kind:"action"};if(i==="prompt"){let p;try{p=await o.resolve(r,this.resolveContext(s,e))}catch(c){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",c),null}return{kind:"prompt",sendText:p.insertText??p.llmAppend??e}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let p=await o.resolve(r,this.resolveContext(s,e)),c={};return p.context&&(c[o.id]={[r.id]:p.context}),{blocks:[],contentParts:p.contentParts??[],context:c}}}}}resolveContext(e,n){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:n,args:e,signal:new AbortController().signal}}runAction(e,n){if(e.action)try{Promise.resolve(e.action({args:n,config:this.opts.getConfig(),messages:this.opts.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}captureStripTarget(){return this.triggerMatch?{value:this.input.getValue(),start:this.triggerMatch.triggerIndex,end:this.input.getSelection().start}:null}async runPromptMacro(e,n,o,r){let s=this.input,i;try{i=await e.resolve(n,{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(p){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",p);return}let l=i.insertText??i.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}stripQuery(){if(!this.triggerMatch)return;let e=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.triggerMatch.triggerIndex,e,"");else{let n=du(this.input.getValue(),this.triggerMatch,e);this.input.setValueWithCaret(n.value,n.caret)}this.input.dispatchInput(),this.triggerMatch=null}destroy(){this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.popover?.destroy(),this.menu.destroy();let e=this.input.element;e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-controls"),e.removeAttribute("aria-activedescendant")}}});function zl(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function ku(t){let e=()=>{t.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:t,getValue:()=>t.value,getLogicalText:()=>t.value,getSelection:()=>({start:t.selectionStart??0,end:t.selectionEnd??0}),setSelection:(n,o=n)=>{t.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{t.value=n,t.setSelectionRange(o,o)},setValue:n=>{t.value=n,t.setSelectionRange(n.length,n.length),e(),t.focus()},submit:()=>zl(t.form),dispatchInput:e,focus:()=>t.focus()}}var jl=bt(()=>{"use strict"});function Ul(t,e){let n=document.createElement("div");n.className="persona-sr-only",n.setAttribute("aria-live",t),n.setAttribute("aria-atomic","true"),n.setAttribute("role",t==="assertive"?"alert":"status"),n.setAttribute("data-persona-mention-live-region","");let o=e.getRootNode();typeof ShadowRoot<"u"&&o instanceof ShadowRoot?(Object.assign(n.style,xy),document.body.appendChild(n)):e.appendChild(n);let s;return{announce:i=>{s!==void 0&&clearTimeout(s),n.textContent="",s=setTimeout(()=>{s=void 0,n.textContent=i},0)},destroy:()=>{s!==void 0&&clearTimeout(s),n.remove()}}}var xy,Lu=bt(()=>{"use strict";xy={position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}});function Pu(t){let e=t.composerInput??ku(t.textarea),n=Ul("polite",t.liveRegionHost),o=Ul("assertive",t.liveRegionHost),r=c=>n.announce(c),s=c=>o.announce(c),i=new Ki({mentionConfig:t.mentionConfig,contextRow:t.contextRow,getMessages:t.getMessages,getConfig:t.getConfig,getComposerText:()=>e.getValue(),announce:r,announceError:s,emit:t.emit}),l=()=>new Ji({mentionConfig:t.mentionConfig,composerInput:e,anchor:t.anchor,getMessages:t.getMessages,getConfig:t.getConfig,onSelect:(c,d,u)=>i.add(c,d,u),onInsertMention:(c,d,u,b)=>i.track(c,d,u,b,f=>e.setMentionStatus?.(c,f)),admitMention:(c,d)=>i.admit(c,d),announce:r,popoverContainer:t.popoverContainer,onPickerOpenChange:t.onPickerOpenChange,emit:t.emit}),p=l();return{openMenu:c=>p.openFromButton(c),isMenuOpen:()=>p.isOpen(),handleInput:()=>p.onInput(),handleKeydown:c=>p.handleKeydown(c),hasMentions:()=>i.hasMentions(),removeLastChip:()=>i.removeLast(),dispatchInlineCommand:c=>p.dispatchInlineCommand(c),collectForSubmit:()=>i.hasMentions()?i.collectForSubmit():null,untrackMention:c=>i.remove(c),rebindComposer:c=>{c!==e&&(p.destroy(),e=c,p=l())},clear:()=>i.clear(),destroy:()=>{p.destroy(),i.clear(),n.destroy(),o.destroy()}}}var Iu=bt(()=>{"use strict";_l();Eu();jl();Lu()});var Ru={};or(Ru,{mountContextMentions:()=>Pu});var Wu=bt(()=>{"use strict";Iu()});function Kl(t){return t.kind==="text"?t.value.length:1}function Gl(t){let e=[],n=r=>{let s=e[e.length-1];s&&s.kind==="text"?s.value+=r:e.push({kind:"text",value:r})};(t.length===0||t[0].kind!=="text")&&e.push({kind:"text",value:""});for(let r of t){if(r.kind==="text"){n(r.value);continue}let s=e[e.length-1];(!s||s.kind!=="text")&&e.push({kind:"text",value:""}),e.push({kind:"mention",id:r.id,ref:r.ref}),e.push({kind:"text",value:""})}let o=e[e.length-1];return(!o||o.kind!=="text")&&e.push({kind:"text",value:""}),e}function Hu(){return{blocks:[{kind:"text",value:""}]}}function Ql(t){return{blocks:[{kind:"text",value:t}]}}function Xl(t){return t.blocks.map(e=>e.kind==="text"?e.value:`${wy}${e.ref.label}`).join("")}function Zi(t){return t.blocks.map(e=>e.kind==="text"?e.value:"\uFFFC").join("")}function ea(t){return t.blocks.reduce((e,n)=>e+Kl(n),0)}function Ay(t){let e=[];for(let n of t.blocks)n.kind==="mention"&&e.push({id:n.id,ref:n.ref});return e}function Yi(t,e){let n=[],o=[],r=0;for(let s of t){let i=Kl(s),l=r+i;if(l<=e)n.push(s);else if(r>=e)o.push(s);else if(s.kind==="text"){let p=e-r;p>0&&n.push({kind:"text",value:s.value.slice(0,p)}),p<i&&o.push({kind:"text",value:s.value.slice(p)})}else o.push(s);r=l}return{left:n,right:o}}function Jl(t,e,n,o){let r=Yi(t.blocks,e.start).left,s=Yi(t.blocks,e.end).right,i=s[0],l=i?.kind==="text"?i.value.charAt(0):"",p=l!==" "&&l!==" "&&l!==`
172
- `,c=Gl([...r,{kind:"mention",id:o,ref:n},...p?[{kind:"text",value:" "}]:[],...s]),d=e.start+1+(l===`
173
- `?0:1);return{doc:{blocks:c},caret:d}}function Bu(t,e){let n=0,o=0,r=!1;for(let i of t.blocks)i.kind==="mention"&&i.id===e&&(n=o,r=!0),o+=Kl(i);return r?{doc:{blocks:Gl(t.blocks.filter(i=>!(i.kind==="mention"&&i.id===e)))},caret:n}:{doc:t,caret:o}}function ta(t,e,n,o){let r=ea(t),s=Math.max(0,Math.min(e,n,r)),i=Math.min(r,Math.max(e,n,0)),l=Yi(t.blocks,s).left,p=Yi(t.blocks,i).right;return{doc:{blocks:Gl([...l,{kind:"text",value:o},...p])},caret:s+o.length}}function Du(t){let e=[];for(let n of t.blocks)n.kind==="text"?n.value.length>0&&e.push({kind:"text",text:n.value}):e.push({kind:"mention",ref:n.ref});return{content:Xl(t),contextMentions:Ay(t).map(n=>n.ref),contentSegments:e}}var wy,Yl=bt(()=>{"use strict";ji();wy="@"});function vs(t){return t.nodeType===1&&t.hasAttribute(bs)}function Fu(t){return t.nodeType===1&&t.tagName==="BR"}function na(t){return t.nodeType===3?t.data.length:vs(t)||Fu(t)?1:t.textContent?.length??0}function Nu(t,e,n){let o=0;for(let r of Array.from(t.childNodes)){if(r===e)return r.nodeType===3?o+n:o+(n>0?na(r):0);if(r.contains(e))return vs(r)?o+1:o+My(r,e,n);o+=na(r)}if(e===t){let r=0,s=Array.from(t.childNodes);for(let i=0;i<Math.min(n,s.length);i++)r+=na(s[i]);return r}return o}function My(t,e,n){let o=0,r=s=>{if(s===e)return o+=s.nodeType===3?n:0,!0;if(s.nodeType===3)return o+=s.data.length,!1;for(let i of Array.from(s.childNodes))if(r(i))return!0;return!1};return r(t),o}function ys(t,e){let n=0,o=Array.from(t.childNodes);for(let r=0;r<o.length;r++){let s=o[r],i=na(s);if(e<=n+i)return s.nodeType===3?{node:s,offset:e-n}:{node:t,offset:e<=n?r:r+1};n+=i}return{node:t,offset:o.length}}function Ty(t,e){let n=[];for(let o of Array.from(t.childNodes))if(vs(o)){let r=o.getAttribute(bs),s=e.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(Fu(o))n.push({kind:"text",value:Ou});else if(o.nodeType===3)n.push({kind:"text",value:o.data});else{let r=o.textContent??"";r&&n.push({kind:"text",value:r})}return n.length===0&&n.push({kind:"text",value:""}),{blocks:n}}function _u(t){let e=t.renderToken,n=new Map,o=t.element??document.createElement("div");o.setAttribute("contenteditable","true"),o.setAttribute("data-persona-composer-input",""),o.setAttribute("role","textbox"),o.setAttribute("aria-multiline","true"),o.classList.add("persona-composer-contenteditable"),t.placeholder!=null&&o.setAttribute("data-placeholder",t.placeholder);let r=!1,s=0,i=()=>Ty(o,n),l=F=>{o.replaceChildren();for(let D of F.blocks)if(D.kind==="text")D.value.length>0&&o.appendChild(document.createTextNode(D.value));else{n.set(D.id,D.ref);let B=e(D.ref);B.setAttribute("contenteditable","false"),B.setAttribute(bs,D.id),o.appendChild(B)}},p=()=>{let D=o.getRootNode().activeElement;return D===o||D!=null&&o.contains(D)},c=(F,D)=>{if(s=F,!D?.focus&&!p())return;let B=typeof window<"u"?window.getSelection():null;if(!B)return;let P=ys(o,F);try{let I=document.createRange();I.setStart(P.node,P.offset),I.collapse(!0),B.removeAllRanges(),B.addRange(I)}catch{}},d=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},u=()=>{let F={start:s,end:s},D=typeof window<"u"?window.getSelection():null;if(!D||D.rangeCount===0)return F;let B=D.getRangeAt(0);if(!o.contains(B.startContainer))return F;let P=Nu(o,B.startContainer,B.startOffset),I=B.collapsed?P:Nu(o,B.endContainer,B.endOffset);return{start:Math.min(P,I),end:Math.max(P,I)}},b=()=>{let F=new Set;for(let D of Array.from(o.childNodes))vs(D)&&F.add(D.getAttribute(bs));for(let D of Array.from(n.keys()))F.has(D)||(n.delete(D),t.onMentionRemoved?.(D))},f=()=>{r||n.size!==0&&b()},m=()=>{r=!0},C=()=>{r=!1,b()},R=F=>{F.preventDefault();let D=F.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,D);else{let{start:B,end:P}=u(),I=ta(i(),B,P,D);l(I.doc),c(I.caret,{focus:!0}),b()}d()},H=F=>{if(r)return;let D=F.inputType;if(D==="insertParagraph"){F.preventDefault();let{start:oe,end:Q}=u(),se=ta(i(),oe,Q,Ou);l(se.doc),c(se.caret,{focus:!0}),n.size>0&&b(),d();return}if(D!=="deleteContentBackward"&&D!=="deleteContentForward"||n.size===0)return;let{start:B,end:P}=u();if(B!==P)return;let I=i(),j=Zi(I),pe=D==="deleteContentBackward"?B-1:B;if(pe<0||pe>=j.length||j[pe]!=="\uFFFC")return;let ue=0,ge=null;for(let oe of I.blocks){let Q=oe.kind==="text"?oe.value.length:1;if(oe.kind==="mention"&&pe>=ue&&pe<ue+Q){ge=oe.id;break}ue+=Q}if(!ge)return;F.preventDefault();let Z=Bu(I,ge);l(Z.doc),c(Z.caret,{focus:!0}),b(),d()},L=(F,D)=>{l(Ql(F)),c(D)},T=(F,D)=>{if(!Number.isFinite(F)||!Number.isFinite(D)||D<=F)return null;try{let B=ys(o,F),P=ys(o,D),I=document.createRange();I.setStart(B.node,B.offset),I.setEnd(P.node,P.offset);let j=I.getBoundingClientRect();return j.width===0&&j.height===0?null:j}catch{return null}},k=(F,D,B)=>{let P=ta(i(),F,D,B);l(P.doc),c(P.caret,{focus:!0})},$=(F,D)=>{let B=i(),P=Zi(B),I=D.triggerIndex,j=D.triggerIndex+1+D.query.length;if(I<0||j>P.length||P.slice(I+1,j)!==D.query)return null;let pe=t.generateId(),ue=Jl(B,{start:I,end:j},F,pe);return l(ue.doc),c(ue.caret,{focus:!0}),t.onMentionInserted?.(pe,F),d(),pe},G=F=>{let D=i(),B=u(),I=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:B.start,end:B.end}:{start:ea(D),end:ea(D)},j=t.generateId(),pe=Jl(D,I,F,j);return l(pe.doc),c(pe.caret,{focus:!0}),t.onMentionInserted?.(j,F),d(),j},w=(F,D)=>{for(let B of Array.from(o.childNodes))if(vs(B)&&B.getAttribute(bs)===F){let P=D==="error";if(B.classList.toggle(Sy,P),P){B.hasAttribute(hs)||(B.setAttribute(hs,B.getAttribute("aria-label")??""),B.setAttribute(Zl,B.getAttribute("title")??""));let I=n.get(F)?.label??"";B.setAttribute("title",`${I}: failed to attach context`),B.setAttribute("aria-label",`${I}, failed to attach context`)}else if(B.hasAttribute(hs)){let I=B.getAttribute(hs),j=B.getAttribute(Zl);I?B.setAttribute("aria-label",I):B.removeAttribute("aria-label"),j?B.setAttribute("title",j):B.removeAttribute("title"),B.removeAttribute(hs),B.removeAttribute(Zl)}return}};return o.addEventListener("input",f),o.addEventListener("compositionstart",m),o.addEventListener("compositionend",C),o.addEventListener("paste",R),o.addEventListener("beforeinput",H),l(Hu()),{element:o,getValue:()=>Xl(i()),getLogicalText:()=>Zi(i()),getDocument:i,getSelection:u,setSelection:(F,D=F)=>{let B=typeof window<"u"?window.getSelection():null;if(B)try{let P=ys(o,F),I=ys(o,D),j=document.createRange();j.setStart(P.node,P.offset),j.setEnd(I.node,I.offset),B.removeAllRanges(),B.addRange(j)}catch{}},setValueWithCaret:L,getLogicalRangeRect:T,setValue:F=>{l(Ql(F)),o.focus(),c(F.length,{focus:!0}),d()},replaceLogicalRange:k,insertMentionAtTrigger:$,insertMentionAtSelection:G,setMentionStatus:w,submit:()=>zl(o.closest("form")),dispatchInput:d,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",f),o.removeEventListener("compositionstart",m),o.removeEventListener("compositionend",C),o.removeEventListener("paste",R),o.removeEventListener("beforeinput",H)}}}var Sy,bs,hs,Zl,Ou,$u=bt(()=>{"use strict";Yl();jl();Sy="persona-mention-token-error",bs="data-mention-id",hs="data-mention-prev-label",Zl="data-mention-prev-title",Ou=`
174
- `});function Ly(t,e){e.className=`${t.className} persona-composer-contenteditable`.trim();for(let r=0;r<t.style.length;r++){let s=t.style.item(r);s!=="height"&&e.style.setProperty(s,t.style.getPropertyValue(s),t.style.getPropertyPriority(s))}let n=t.getAttribute("placeholder");n&&(e.setAttribute("data-placeholder",n),e.setAttribute("aria-placeholder",n));let o=t.getAttribute("aria-label")??n;o&&e.setAttribute("aria-label",o)}function Py(t,e,n){Object.defineProperty(t,"value",{configurable:!0,get:()=>e.getValue(),set:o=>{e.setValueWithCaret(o,o.length),e.dispatchInput()}}),Object.defineProperty(t,"placeholder",{configurable:!0,get:()=>t.getAttribute("data-placeholder")??"",set:o=>{o?(t.setAttribute("data-placeholder",o),t.setAttribute("aria-placeholder",o),n||t.setAttribute("aria-label",o)):(t.removeAttribute("data-placeholder"),t.removeAttribute("aria-placeholder"),n||t.removeAttribute("aria-label"))}}),Object.defineProperty(t,"selectionStart",{configurable:!0,get:()=>e.getSelection().start}),Object.defineProperty(t,"selectionEnd",{configurable:!0,get:()=>e.getSelection().end}),t.setSelectionRange=(o,r)=>e.setSelection(o??0,r??o??0)}function zu(t){let{textarea:e}=t,n={generateId:ky,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=_u(n),r=o.element,s=e.getAttribute("aria-label")!=null;Ly(e,r),Py(r,o,s),r.getInlineMessageFields=()=>Du(o.getDocument?.()??{blocks:[]});let i=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,i),{input:o,element:r,destroy:o.destroy}}var Ey,ky,ju=bt(()=>{"use strict";$u();Yl();Ey=0,ky=()=>`pmention-${++Ey}`});var Uu={};or(Uu,{mountInlineComposer:()=>zu});var Vu=bt(()=>{"use strict";ju()});var Bx={};or(Bx,{createThemePreview:()=>Ug});module.exports=$m(Bx);var rr=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:d=>{o=d,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:d=>{r=d},getSync:()=>r}};var{setLoader:zx,load:zm,provide:jx,getSync:ml}=rr({fallbackImport:()=>Promise.resolve().then(()=>(sp(),rp))}),Ci=new Set,jm=()=>{let t=[...Ci];Ci.clear();for(let e of t)try{e()}catch{}};var Um=()=>{let t=ml();return t?Promise.resolve(t):zm().then(e=>(jm(),e))},wi=t=>ml()?()=>{}:(Ci.add(t),Um().catch(()=>{}),()=>{Ci.delete(t)});var _n=ml;var Vm=t=>{if(t)return t},hl=t=>{let e=null;return n=>{let o=_n();if(!o)return ao(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let i=Vm(t?.renderer);i&&e.use({renderer:i})}return e.parse(n)}},Ai=t=>t?hl({markedOptions:t.options,renderer:t.renderer}):hl(),qx=hl();var ao=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var qm={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"]},Km=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Gm=()=>{let t=null;return e=>{let n=_n();if(!n)return ao(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let i=s.attrValue;i.toLowerCase().startsWith("data:")&&!Km.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,qm)}},Si=t=>t===!1?null:typeof t=="function"?t:Gm();var ip=/^\s*\|?[\s:|-]*-[\s:|-]*$/,ap=t=>t.includes("|"),lp=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},Qm=t=>`| ${t.join(" | ")} |`,Xm=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,Jm=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),cp=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
175
- `),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!ap(r)||ip.test(r)||!ip.test(s))continue;let i=lp(r).length;if(i<1)continue;let l=Xm(i);e[o+1]!==l&&(e[o+1]=l,n=!0);let p=o+2;for(;p<e.length;p++){let c=e[p];if(c.trim()===""||!ap(c))break;let d=Qm(Jm(lp(c),i));e[p]!==d&&(e[p]=d,n=!0)}o=p-1}return n?e.join(`
176
- `):t};var dp="var(--persona-md-table-scroll-fade, 24px)",pp=new WeakSet;function fp(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function up(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,r=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":dp),t.style.setProperty("--persona-fade-r",r<=1?"0px":dp)}function yl(t){pp.has(t)||(pp.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&up(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(up)}var $n="webmcp:",bl=new Map,gp=t=>{bl.clear();for(let e of t){let n=e.title?.trim();n&&bl.set(e.name,n)}},ns=t=>bl.get(bp(t)),Mi={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},mp=null;function yp(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${Ym(e.join(""))}`}function hp(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Ym(t){let e=hp(t,0).toString(36),n=hp(t,2654435761).toString(36);return`${e}.${n}`}var Ti=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(r){return Mi.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}gp(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},i=eh(r.inputSchema);return i&&(s.parametersSchema=i),s})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Mn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let m=typeof document<"u"&&!!document.modelContext;return Mn(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 s=bp(e),i;try{i=await r.getTools()}catch(m){let C=m instanceof Error?m.message:String(m);return Mn(`Failed to read WebMCP registry: ${C}`)}gp(i);let l=i.find(m=>m.name===s);if(!l)return Mn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Mn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Mn("Aborted by cancel()");let p=ns(s),c={toolName:s,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(c))return Mn("User declined the tool call.");if(o?.aborted)return Mn("Aborted by cancel()");let d=new AbortController,u=!1,b=setTimeout(()=>{u=!0,d.abort()},this.timeoutMs),f=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",f,{once:!0}));try{let m=await r.executeTool(l,rh(n),{signal:d.signal});return th(m)}catch(m){if(u)return Mn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Mn("Aborted by cancel()");let C=m instanceof Error?m.message:String(m);return Mn(C)}finally{clearTimeout(b),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(mp?await mp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Mi.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Mi.warn("document.modelContext is present but does not expose getTools()/executeTool(): 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):e}async requestConfirm(e){let n=this.confirmHandler??nh;try{return await n(e)}catch(o){return Mi.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Zm(e,o))}},bp=t=>t.startsWith($n)?t.slice($n.length):t,sr=t=>t.startsWith($n),Zm=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},eh=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},th=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:sh(e)}]}},Mn=t=>({isError:!0,content:[{type:"text",text:t}]}),nh=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=oh(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
171
+ `)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:i}=na(r.slice(n.trigger.length));if(s)for(let l of n.sources){let p=l.matchCommand?.(s);if(p&&this.isInlineCommand(p))return{source:l,item:p,args:i}}}}return null}async dispatchInlineCommand(e){let n=this.matchInlineCommand(e);if(!n)return null;let{source:o,item:r,args:s}=n,i=r.command??"prompt";if(this.opts.emit?.("command",{sourceId:o.id,itemId:r.id,kind:i,args:s}),i==="action")return this.runAction(r,s),{kind:"action"};if(i==="prompt"){let p;try{p=await o.resolve(r,this.resolveContext(s,e))}catch(c){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",c),null}return{kind:"prompt",sendText:p.insertText??p.llmAppend??e}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let p=await o.resolve(r,this.resolveContext(s,e)),c={};return p.context&&(c[o.id]={[r.id]:p.context}),{blocks:[],contentParts:p.contentParts??[],context:c}}}}}resolveContext(e,n){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:n,args:e,signal:new AbortController().signal}}runAction(e,n){if(e.action)try{Promise.resolve(e.action({args:n,config:this.opts.getConfig(),messages:this.opts.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}captureStripTarget(){return this.triggerMatch?{value:this.input.getValue(),start:this.triggerMatch.triggerIndex,end:this.input.getSelection().start}:null}async runPromptMacro(e,n,o,r){let s=this.input,i;try{i=await e.resolve(n,{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(p){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",p);return}let l=i.insertText??i.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}stripQuery(){if(!this.triggerMatch)return;let e=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.triggerMatch.triggerIndex,e,"");else{let n=ku(this.input.getValue(),this.triggerMatch,e);this.input.setValueWithCaret(n.value,n.caret)}this.input.dispatchInput(),this.triggerMatch=null}destroy(){this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.popover?.destroy(),this.menu.destroy();let e=this.input.element;e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-controls"),e.removeAttribute("aria-activedescendant")}}});function Kl(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function qu(t){let e=()=>{t.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:t,getValue:()=>t.value,getLogicalText:()=>t.value,getSelection:()=>({start:t.selectionStart??0,end:t.selectionEnd??0}),setSelection:(n,o=n)=>{t.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{t.value=n,t.setSelectionRange(o,o)},setValue:n=>{t.value=n,t.setSelectionRange(n.length,n.length),e(),t.focus()},submit:()=>Kl(t.form),dispatchInput:e,focus:()=>t.focus()}}var Gl=ht(()=>{"use strict"});function Ql(t,e){let n=document.createElement("div");n.className="persona-sr-only",n.setAttribute("aria-live",t),n.setAttribute("aria-atomic","true"),n.setAttribute("role",t==="assertive"?"alert":"status"),n.setAttribute("data-persona-mention-live-region","");let o=e.getRootNode();typeof ShadowRoot<"u"&&o instanceof ShadowRoot?(Object.assign(n.style,Uy),document.body.appendChild(n)):e.appendChild(n);let s;return{announce:i=>{s!==void 0&&clearTimeout(s),n.textContent="",s=setTimeout(()=>{s=void 0,n.textContent=i},0)},destroy:()=>{s!==void 0&&clearTimeout(s),n.remove()}}}var Uy,Ku=ht(()=>{"use strict";Uy={position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}});function Gu(t){let e=t.composerInput??qu(t.textarea),n=Ql("polite",t.liveRegionHost),o=Ql("assertive",t.liveRegionHost),r=c=>n.announce(c),s=c=>o.announce(c),i=new Zi({mentionConfig:t.mentionConfig,contextRow:t.contextRow,getMessages:t.getMessages,getConfig:t.getConfig,getComposerText:()=>e.getValue(),announce:r,announceError:s,emit:t.emit}),l=()=>new oa({mentionConfig:t.mentionConfig,composerInput:e,anchor:t.anchor,getMessages:t.getMessages,getConfig:t.getConfig,onSelect:(c,d,u)=>i.add(c,d,u),onInsertMention:(c,d,u,b)=>i.track(c,d,u,b,g=>e.setMentionStatus?.(c,g)),admitMention:(c,d)=>i.admit(c,d),announce:r,popoverContainer:t.popoverContainer,onPickerOpenChange:t.onPickerOpenChange,emit:t.emit}),p=l();return{openMenu:c=>p.openFromButton(c),isMenuOpen:()=>p.isOpen(),handleInput:()=>p.onInput(),handleKeydown:c=>p.handleKeydown(c),hasMentions:()=>i.hasMentions(),removeLastChip:()=>i.removeLast(),dispatchInlineCommand:c=>p.dispatchInlineCommand(c),collectForSubmit:()=>i.hasMentions()?i.collectForSubmit():null,untrackMention:c=>i.remove(c),rebindComposer:c=>{c!==e&&(p.destroy(),e=c,p=l())},clear:()=>i.clear(),destroy:()=>{p.destroy(),i.clear(),n.destroy(),o.destroy()}}}var Qu=ht(()=>{"use strict";Vl();Vu();Gl();Ku()});var Xu={};ar(Xu,{mountContextMentions:()=>Gu});var Ju=ht(()=>{"use strict";Qu()});function Yl(t){return t.kind==="text"?t.value.length:1}function Zl(t){let e=[],n=r=>{let s=e[e.length-1];s&&s.kind==="text"?s.value+=r:e.push({kind:"text",value:r})};(t.length===0||t[0].kind!=="text")&&e.push({kind:"text",value:""});for(let r of t){if(r.kind==="text"){n(r.value);continue}let s=e[e.length-1];(!s||s.kind!=="text")&&e.push({kind:"text",value:""}),e.push({kind:"mention",id:r.id,ref:r.ref}),e.push({kind:"text",value:""})}let o=e[e.length-1];return(!o||o.kind!=="text")&&e.push({kind:"text",value:""}),e}function Yu(){return{blocks:[{kind:"text",value:""}]}}function ec(t){return{blocks:[{kind:"text",value:t}]}}function tc(t){return t.blocks.map(e=>e.kind==="text"?e.value:`${Vy}${e.ref.label}`).join("")}function sa(t){return t.blocks.map(e=>e.kind==="text"?e.value:"\uFFFC").join("")}function ia(t){return t.blocks.reduce((e,n)=>e+Yl(n),0)}function qy(t){let e=[];for(let n of t.blocks)n.kind==="mention"&&e.push({id:n.id,ref:n.ref});return e}function ra(t,e){let n=[],o=[],r=0;for(let s of t){let i=Yl(s),l=r+i;if(l<=e)n.push(s);else if(r>=e)o.push(s);else if(s.kind==="text"){let p=e-r;p>0&&n.push({kind:"text",value:s.value.slice(0,p)}),p<i&&o.push({kind:"text",value:s.value.slice(p)})}else o.push(s);r=l}return{left:n,right:o}}function nc(t,e,n,o){let r=ra(t.blocks,e.start).left,s=ra(t.blocks,e.end).right,i=s[0],l=i?.kind==="text"?i.value.charAt(0):"",p=l!==" "&&l!==" "&&l!==`
172
+ `,c=Zl([...r,{kind:"mention",id:o,ref:n},...p?[{kind:"text",value:" "}]:[],...s]),d=e.start+1+(l===`
173
+ `?0:1);return{doc:{blocks:c},caret:d}}function Zu(t,e){let n=0,o=0,r=!1;for(let i of t.blocks)i.kind==="mention"&&i.id===e&&(n=o,r=!0),o+=Yl(i);return r?{doc:{blocks:Zl(t.blocks.filter(i=>!(i.kind==="mention"&&i.id===e)))},caret:n}:{doc:t,caret:o}}function aa(t,e,n,o){let r=ia(t),s=Math.max(0,Math.min(e,n,r)),i=Math.min(r,Math.max(e,n,0)),l=ra(t.blocks,s).left,p=ra(t.blocks,i).right;return{doc:{blocks:Zl([...l,{kind:"text",value:o},...p])},caret:s+o.length}}function eg(t){let e=[];for(let n of t.blocks)n.kind==="text"?n.value.length>0&&e.push({kind:"text",text:n.value}):e.push({kind:"mention",ref:n.ref});return{content:tc(t),contextMentions:qy(t).map(n=>n.ref),contentSegments:e}}var Vy,oc=ht(()=>{"use strict";Qi();Vy="@"});function Es(t){return t.nodeType===1&&t.hasAttribute(Ts)}function og(t){return t.nodeType===1&&t.tagName==="BR"}function la(t){return t.nodeType===3?t.data.length:Es(t)||og(t)?1:t.textContent?.length??0}function tg(t,e,n){let o=0;for(let r of Array.from(t.childNodes)){if(r===e)return r.nodeType===3?o+n:o+(n>0?la(r):0);if(r.contains(e))return Es(r)?o+1:o+Gy(r,e,n);o+=la(r)}if(e===t){let r=0,s=Array.from(t.childNodes);for(let i=0;i<Math.min(n,s.length);i++)r+=la(s[i]);return r}return o}function Gy(t,e,n){let o=0,r=s=>{if(s===e)return o+=s.nodeType===3?n:0,!0;if(s.nodeType===3)return o+=s.data.length,!1;for(let i of Array.from(s.childNodes))if(r(i))return!0;return!1};return r(t),o}function Ms(t,e){let n=0,o=Array.from(t.childNodes);for(let r=0;r<o.length;r++){let s=o[r],i=la(s);if(e<=n+i)return s.nodeType===3?{node:s,offset:e-n}:{node:t,offset:e<=n?r:r+1};n+=i}return{node:t,offset:o.length}}function Qy(t,e){let n=[];for(let o of Array.from(t.childNodes))if(Es(o)){let r=o.getAttribute(Ts),s=e.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(og(o))n.push({kind:"text",value:ng});else if(o.nodeType===3)n.push({kind:"text",value:o.data});else{let r=o.textContent??"";r&&n.push({kind:"text",value:r})}return n.length===0&&n.push({kind:"text",value:""}),{blocks:n}}function rg(t){let e=t.renderToken,n=new Map,o=t.element??document.createElement("div");o.setAttribute("contenteditable","true"),o.setAttribute("data-persona-composer-input",""),o.setAttribute("role","textbox"),o.setAttribute("aria-multiline","true"),o.classList.add("persona-composer-contenteditable"),t.placeholder!=null&&o.setAttribute("data-placeholder",t.placeholder);let r=!1,s=0,i=()=>Qy(o,n),l=O=>{o.replaceChildren();for(let D of O.blocks)if(D.kind==="text")D.value.length>0&&o.appendChild(document.createTextNode(D.value));else{n.set(D.id,D.ref);let W=e(D.ref);W.setAttribute("contenteditable","false"),W.setAttribute(Ts,D.id),o.appendChild(W)}},p=()=>{let D=o.getRootNode().activeElement;return D===o||D!=null&&o.contains(D)},c=(O,D)=>{if(s=O,!D?.focus&&!p())return;let W=typeof window<"u"?window.getSelection():null;if(!W)return;let P=Ms(o,O);try{let I=document.createRange();I.setStart(P.node,P.offset),I.collapse(!0),W.removeAllRanges(),W.addRange(I)}catch{}},d=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},u=()=>{let O={start:s,end:s},D=typeof window<"u"?window.getSelection():null;if(!D||D.rangeCount===0)return O;let W=D.getRangeAt(0);if(!o.contains(W.startContainer))return O;let P=tg(o,W.startContainer,W.startOffset),I=W.collapsed?P:tg(o,W.endContainer,W.endOffset);return{start:Math.min(P,I),end:Math.max(P,I)}},b=()=>{let O=new Set;for(let D of Array.from(o.childNodes))Es(D)&&O.add(D.getAttribute(Ts));for(let D of Array.from(n.keys()))O.has(D)||(n.delete(D),t.onMentionRemoved?.(D))},g=()=>{r||n.size!==0&&b()},h=()=>{r=!0},C=()=>{r=!1,b()},L=O=>{O.preventDefault();let D=O.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,D);else{let{start:W,end:P}=u(),I=aa(i(),W,P,D);l(I.doc),c(I.caret,{focus:!0}),b()}d()},B=O=>{if(r)return;let D=O.inputType;if(D==="insertParagraph"){O.preventDefault();let{start:oe,end:J}=u(),ie=aa(i(),oe,J,ng);l(ie.doc),c(ie.caret,{focus:!0}),n.size>0&&b(),d();return}if(D!=="deleteContentBackward"&&D!=="deleteContentForward"||n.size===0)return;let{start:W,end:P}=u();if(W!==P)return;let I=i(),j=sa(I),pe=D==="deleteContentBackward"?W-1:W;if(pe<0||pe>=j.length||j[pe]!=="\uFFFC")return;let ge=0,se=null;for(let oe of I.blocks){let J=oe.kind==="text"?oe.value.length:1;if(oe.kind==="mention"&&pe>=ge&&pe<ge+J){se=oe.id;break}ge+=J}if(!se)return;O.preventDefault();let Y=Zu(I,se);l(Y.doc),c(Y.caret,{focus:!0}),b(),d()},k=(O,D)=>{l(ec(O)),c(D)},S=(O,D)=>{if(!Number.isFinite(O)||!Number.isFinite(D)||D<=O)return null;try{let W=Ms(o,O),P=Ms(o,D),I=document.createRange();I.setStart(W.node,W.offset),I.setEnd(P.node,P.offset);let j=I.getBoundingClientRect();return j.width===0&&j.height===0?null:j}catch{return null}},E=(O,D,W)=>{let P=aa(i(),O,D,W);l(P.doc),c(P.caret,{focus:!0})},z=(O,D)=>{let W=i(),P=sa(W),I=D.triggerIndex,j=D.triggerIndex+1+D.query.length;if(I<0||j>P.length||P.slice(I+1,j)!==D.query)return null;let pe=t.generateId(),ge=nc(W,{start:I,end:j},O,pe);return l(ge.doc),c(ge.caret,{focus:!0}),t.onMentionInserted?.(pe,O),d(),pe},G=O=>{let D=i(),W=u(),I=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:W.start,end:W.end}:{start:ia(D),end:ia(D)},j=t.generateId(),pe=nc(D,I,O,j);return l(pe.doc),c(pe.caret,{focus:!0}),t.onMentionInserted?.(j,O),d(),j},A=(O,D)=>{for(let W of Array.from(o.childNodes))if(Es(W)&&W.getAttribute(Ts)===O){let P=D==="error";if(W.classList.toggle(Ky,P),P){W.hasAttribute(Ss)||(W.setAttribute(Ss,W.getAttribute("aria-label")??""),W.setAttribute(rc,W.getAttribute("title")??""));let I=n.get(O)?.label??"";W.setAttribute("title",`${I}: failed to attach context`),W.setAttribute("aria-label",`${I}, failed to attach context`)}else if(W.hasAttribute(Ss)){let I=W.getAttribute(Ss),j=W.getAttribute(rc);I?W.setAttribute("aria-label",I):W.removeAttribute("aria-label"),j?W.setAttribute("title",j):W.removeAttribute("title"),W.removeAttribute(Ss),W.removeAttribute(rc)}return}};return o.addEventListener("input",g),o.addEventListener("compositionstart",h),o.addEventListener("compositionend",C),o.addEventListener("paste",L),o.addEventListener("beforeinput",B),l(Yu()),{element:o,getValue:()=>tc(i()),getLogicalText:()=>sa(i()),getDocument:i,getSelection:u,setSelection:(O,D=O)=>{let W=typeof window<"u"?window.getSelection():null;if(W)try{let P=Ms(o,O),I=Ms(o,D),j=document.createRange();j.setStart(P.node,P.offset),j.setEnd(I.node,I.offset),W.removeAllRanges(),W.addRange(j)}catch{}},setValueWithCaret:k,getLogicalRangeRect:S,setValue:O=>{l(ec(O)),o.focus(),c(O.length,{focus:!0}),d()},replaceLogicalRange:E,insertMentionAtTrigger:z,insertMentionAtSelection:G,setMentionStatus:A,submit:()=>Kl(o.closest("form")),dispatchInput:d,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",g),o.removeEventListener("compositionstart",h),o.removeEventListener("compositionend",C),o.removeEventListener("paste",L),o.removeEventListener("beforeinput",B)}}}var Ky,Ts,Ss,rc,ng,sg=ht(()=>{"use strict";oc();Gl();Ky="persona-mention-token-error",Ts="data-mention-id",Ss="data-mention-prev-label",rc="data-mention-prev-title",ng=`
174
+ `});function Yy(t,e){e.className=`${t.className} persona-composer-contenteditable`.trim();for(let r=0;r<t.style.length;r++){let s=t.style.item(r);s!=="height"&&e.style.setProperty(s,t.style.getPropertyValue(s),t.style.getPropertyPriority(s))}let n=t.getAttribute("placeholder");n&&(e.setAttribute("data-placeholder",n),e.setAttribute("aria-placeholder",n));let o=t.getAttribute("aria-label")??n;o&&e.setAttribute("aria-label",o)}function Zy(t,e,n){Object.defineProperty(t,"value",{configurable:!0,get:()=>e.getValue(),set:o=>{e.setValueWithCaret(o,o.length),e.dispatchInput()}}),Object.defineProperty(t,"placeholder",{configurable:!0,get:()=>t.getAttribute("data-placeholder")??"",set:o=>{o?(t.setAttribute("data-placeholder",o),t.setAttribute("aria-placeholder",o),n||t.setAttribute("aria-label",o)):(t.removeAttribute("data-placeholder"),t.removeAttribute("aria-placeholder"),n||t.removeAttribute("aria-label"))}}),Object.defineProperty(t,"selectionStart",{configurable:!0,get:()=>e.getSelection().start}),Object.defineProperty(t,"selectionEnd",{configurable:!0,get:()=>e.getSelection().end}),t.setSelectionRange=(o,r)=>e.setSelection(o??0,r??o??0)}function ig(t){let{textarea:e}=t,n={generateId:Jy,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=rg(n),r=o.element,s=e.getAttribute("aria-label")!=null;Yy(e,r),Zy(r,o,s),r.getInlineMessageFields=()=>eg(o.getDocument?.()??{blocks:[]});let i=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,i),{input:o,element:r,destroy:o.destroy}}var Xy,Jy,ag=ht(()=>{"use strict";sg();oc();Xy=0,Jy=()=>`pmention-${++Xy}`});var lg={};ar(lg,{mountInlineComposer:()=>ig});var cg=ht(()=>{"use strict";ag()});var lC={};ar(lC,{createThemePreview:()=>lm});module.exports=ch(lC);var lr=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:d=>{o=d,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:d=>{r=d},getSync:()=>r}};var{setLoader:mC,load:dh,provide:hC,getSync:Cl}=lr({fallbackImport:()=>Promise.resolve().then(()=>(Ap(),wp))}),Ei=new Set,ph=()=>{let t=[...Ei];Ei.clear();for(let e of t)try{e()}catch{}};var uh=()=>{let t=Cl();return t?Promise.resolve(t):dh().then(e=>(ph(),e))},ki=t=>Cl()?()=>{}:(Ei.add(t),uh().catch(()=>{}),()=>{Ei.delete(t)});var Un=Cl;var gh=t=>{if(t)return t},wl=t=>{let e=null;return n=>{let o=Un();if(!o)return po(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let i=gh(t?.renderer);i&&e.use({renderer:i})}return e.parse(n)}},Li=t=>t?wl({markedOptions:t.options,renderer:t.renderer}):wl(),vC=wl();var po=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var fh={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"]},mh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,hh=()=>{let t=null;return e=>{let n=Un();if(!n)return po(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let i=s.attrValue;i.toLowerCase().startsWith("data:")&&!mh.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,fh)}},Pi=t=>t===!1?null:typeof t=="function"?t:hh();var Sp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Mp=t=>t.includes("|"),Tp=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},yh=t=>`| ${t.join(" | ")} |`,bh=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,vh=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Ep=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
175
+ `),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!Mp(r)||Sp.test(r)||!Sp.test(s))continue;let i=Tp(r).length;if(i<1)continue;let l=bh(i);e[o+1]!==l&&(e[o+1]=l,n=!0);let p=o+2;for(;p<e.length;p++){let c=e[p];if(c.trim()===""||!Mp(c))break;let d=yh(vh(Tp(c),i));e[p]!==d&&(e[p]=d,n=!0)}o=p-1}return n?e.join(`
176
+ `):t};var kp="var(--persona-md-table-scroll-fade, 24px)",Lp=new WeakSet;function Ip(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Pp(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,r=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":kp),t.style.setProperty("--persona-fade-r",r<=1?"0px":kp)}function Al(t){Lp.has(t)||(Lp.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Pp(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Pp)}var jn="webmcp:",Sl=new Map,Rp=t=>{Sl.clear();for(let e of t){let n=e.title?.trim();n&&Sl.set(e.name,n)}},cs=t=>Sl.get(Dp(t)),Ii={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Wp=null;function Bp(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${xh(e.join(""))}`}function Hp(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function xh(t){let e=Hp(t,0).toString(36),n=Hp(t,2654435761).toString(36);return`${e}.${n}`}var Ri=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(r){return Ii.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Rp(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},i=wh(r.inputSchema);return i&&(s.parametersSchema=i),s})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return En("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let h=typeof document<"u"&&!!document.modelContext;return En(h?"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 s=Dp(e),i;try{i=await r.getTools()}catch(h){let C=h instanceof Error?h.message:String(h);return En(`Failed to read WebMCP registry: ${C}`)}Rp(i);let l=i.find(h=>h.name===s);if(!l)return En(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return En(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return En("Aborted by cancel()");let p=cs(s),c={toolName:s,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(c))return En("User declined the tool call.");if(o?.aborted)return En("Aborted by cancel()");let d=new AbortController,u=!1,b=setTimeout(()=>{u=!0,d.abort()},this.timeoutMs),g=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",g,{once:!0}));try{let h=await r.executeTool(l,Th(n),{signal:d.signal});return Ah(h)}catch(h){if(u)return En(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return En("Aborted by cancel()");let C=h instanceof Error?h.message:String(h);return En(C)}finally{clearTimeout(b),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Wp?await Wp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Ii.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ii.warn("document.modelContext is present but does not expose getTools()/executeTool(): 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):e}async requestConfirm(e){let n=this.confirmHandler??Sh;try{return await n(e)}catch(o){return Ii.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Ch(e,o))}},Dp=t=>t.startsWith(jn)?t.slice(jn.length):t,cr=t=>t.startsWith(jn),Ch=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},wh=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Ah=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Eh(e)}]}},En=t=>({isError:!0,content:[{type:"text",text:t}]}),Sh=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=Mh(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
177
177
 
178
178
  Arguments:
179
179
  ${e}`:"")+(t.description?`
180
180
 
181
- ${t.description}`:"");return window.confirm(n)},oh=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},rh=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},sh=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function hn(t){return t==="card"?"collapsed":t}function ir(t){return t.split(";",1)[0].trim().toLowerCase()}function ih(t,e){if(!t)return;let n=Object.entries(t);for(let[r,s]of n)if(ir(r)===e)return{mode:hn(s),selector:ir(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,s]of n)if(ir(r)===o)return{mode:hn(s),selector:o}}function ah(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:hn(o.files),matchedBy:{type:"files"}};let l=e.file.mimeType?ir(e.file.mimeType):void 0,p=l?ih(o.files.byMediaType,l):void 0;if(l&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:l,selector:p.selector}};if(o.files.default)return{mode:hn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[e.artifactType];if(r)return{mode:hn(r),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let s=o.byType?.[e.artifactType];if(s)return{mode:hn(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let i=e.presentation?.preferredMode;return i?{mode:hn(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:hn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function lo(t,e){return ah(t,e).mode}function os(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var lh="agent_",ch="flow_";function vp(t){return t.startsWith(lh)?{kind:"agentId",agentId:t}:t.startsWith(ch)?{kind:"flowId",flowId:t}:null}function xp(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let c=vp(l);if(c)return c;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=e?.[i];if(!p)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=vp(n);if(r)return r;let s=e?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var co=require("partial-json");tt();var vl="ask_user_question",rs=8,ar="data-persona-ask-sheet-for",dh="Other",ph="Other\u2026",Ap="Type your own answer here",Sp="Send",uh="Next",fh="Back",gh="Submit all",mh="Skip",hh=3,xl="data-ask-current-index",Cl="data-ask-question-count",Mp="data-ask-answers",wl="data-ask-grouped",Tp="data-ask-layout",yh=t=>t.layout==="pills"?"pills":"rows",bh=t=>t.getAttribute(Tp)==="pills"?"pills":"rows",wp=!1,Ep=t=>t.replace(/["\\]/g,"\\$&"),Ho=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===vl,Al=t=>t?.features?.askUserQuestion??{},lr=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,co.parse)(r,co.STR|co.OBJ|co.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ss=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>rs&&!wp&&(wp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${rs}.`)),e.slice(0,rs)},vh=t=>ss(t)[0]??null,xh=(t,e)=>ss(t)[e]??null,Ch=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},kp=(t,e,n)=>{if(t!=="rows")return null;let o=y("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=y("span","persona-ask-row-check");o.appendChild(r)}else{let r=y("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},wh=(t,e,n,o)=>{let s=y("button",n==="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",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let i=y("span","persona-ask-row-content"),l=y("span","persona-ask-row-label");if(l.textContent=t.label,i.appendChild(l),t.description){let c=y("span","persona-ask-row-description");c.textContent=t.description,i.appendChild(c)}s.appendChild(i);let p=kp(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},Ah=t=>{let n=y("span",t==="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 n.setAttribute("aria-hidden","true"),n},Sh=(t,e,n,o)=>{let s=y("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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let i=!!t?.multiSelect,p=(Array.isArray(t?.options)?t.options:[]).filter(d=>d&&typeof d.label=="string"&&d.label.length>0);if(p.length===0&&!n){for(let d=0;d<hh;d++)s.appendChild(Ah(o));return s}if(p.forEach((d,u)=>{s.appendChild(wh(d,u,o,i))}),t?.allowFreeText!==!1){let d=o==="rows"?dh:ph;if(o==="rows"){let u=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let b=y("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=e.freeTextPlaceholder??Ap,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",e.freeTextLabel??d),b.appendChild(f),u.appendChild(b);let m=kp(o,i,p.length);m&&u.appendChild(m),s.appendChild(u)}else{let u=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=e.freeTextLabel??d,s.appendChild(u)}}return s},Lp=(t,e)=>{let o=y("div",e==="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");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=t.freeTextPlaceholder??Ap,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=y("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??Sp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Mh=t=>{let e=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??Sp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},Th=(t,e,n)=>{let o=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=y("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??fh,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=y("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??mh,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=y("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=t===e-1;return l.textContent=p?n.submitAllLabel??gh:n.nextLabel??uh,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Bo=t=>{let e=t.getAttribute(Mp);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},Pp=(t,e)=>{t.setAttribute(Mp,JSON.stringify(e))},yn=t=>{let e=Number(t.getAttribute(xl)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Eh=(t,e)=>{t.setAttribute(xl,String(Math.max(0,Math.floor(e))))},cr=t=>{let e=Number(t.getAttribute(Cl)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},po=t=>t.getAttribute(wl)==="true",kh=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},Lh=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},Ei=(t,e)=>{let{payload:n}=lr(e),o=ss(n),r=Bo(t),s={},i=new Set;return o.forEach((l,p)=>{let c=typeof l?.question=="string"?l.question:"";c&&(i.has(c)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),i.add(c),Object.prototype.hasOwnProperty.call(r,p)&&(s[c]=r[p]))}),s},Ip=t=>{let e=Bo(t),n=yn(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let c=p.getAttribute("data-option-label")??"",d=r.has(c);p.setAttribute("aria-pressed",d?"true":"false"),p.classList.toggle("persona-ask-pill-selected",d)});let i=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Rp=t=>{if(!po(t))return;let e=Bo(t),n=yn(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let i=t.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},Sl=(t,e,n)=>{let o=Al(n),r=bh(t),{payload:s,complete:i}=lr(e),l=po(t),p=yn(t),c=cr(t),d=l?xh(s,p):vh(s),u=!!d?.multiSelect,b=t.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=l?`${p+1}/${c}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let m=t.querySelector('[data-ask-question="true"]');if(m){let L=typeof d?.question=="string"?d.question:"";m.textContent=L,m.classList.toggle("persona-ask-question-skeleton",!L&&!i)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let L=Sh(d,o,i,r);C.replaceWith(L)}if(r!=="rows"){let L=t.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Lp(o,r))}let R=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!R?t.appendChild(Mh(o)):(!u||l)&&R&&R.remove(),t.setAttribute("data-multi-select",u?"true":"false");let H=t.querySelector('[data-ask-nav-row="true"]');if(l){let L=Th(p,c,o);H?H.replaceWith(L):t.appendChild(L)}else H&&H.remove();Ip(t),Rp(t)},Ph=(t,e,n)=>{let o=Al(e),r=yh(o),s=t.toolCall.id,i=ss(n),l=Math.max(1,i.length),p=l>1,c=kh(t,i),d=p?Lh(t,l):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ar,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(Cl,String(l)),u.setAttribute(xl,String(d)),u.setAttribute(wl,p?"true":"false"),u.setAttribute(Tp,r),Pp(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Ch(u,o);let b=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",b.appendChild(f);let m=y("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",b.appendChild(m),u.appendChild(b);let R=y("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");return R.setAttribute("data-ask-pill-list","true"),R.setAttribute("role","group"),u.appendChild(R),r!=="rows"&&u.appendChild(Lp(o,r)),Sl(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Ih=(t,e,n)=>{let{payload:o}=lr(e),r=Math.max(1,ss(o).length);r>cr(t)&&(t.setAttribute(Cl,String(r)),r>1&&!po(t)&&t.setAttribute(wl,"true")),Sl(t,e,n)};var ki=(t,e,n)=>{if(!n||!Ho(t)||Al(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${ar}]`).forEach(c=>{c.getAttribute(ar)!==r&&c.remove()});let i=n.querySelector(`[${ar}="${Ep(r)}"]`);if(i){Ih(i,t,e);return}let{payload:l}=lr(t),p=Ph(t,e,l);n.appendChild(p)},dr=(t,e)=>{if(!t)return;let n=e?`[${ar}="${Ep(e)}"]`:`[${ar}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Ml=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),uo=(t,e)=>{let n=Bo(t),o=yn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,Pp(t,n),Ip(t),Rp(t)},Li=(t,e,n,o)=>{let r=cr(t),s=Math.max(0,Math.min(r-1,o));Eh(t,s),Sl(t,e,n)};var jn="suggest_replies";var Rh={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Wp={name:jn,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Rh,origin:"sdk",annotations:{readOnlyHint:!0}},Tl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),El=t=>t.variant==="tool"&&t.toolCall?.name===jn,Wh=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Hp=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!El(n))continue;let o=Wh(n.toolCall?.args);return o.length>0?o:null}return null},Bp=t=>{let e=t?.features?.suggestReplies;return e?.expose===!0&&e.enabled!==!1};var Hh={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:rs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Bh={name:vl,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Hh,origin:"sdk",annotations:{readOnlyHint:!0}},Pi=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(Bh),Bp(t)&&e.push(Wp),e};var pr=require("partial-json"),Dp=t=>t.replace(/\\n/g,`
182
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),fo=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},Dh=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Np=t=>t.status==="complete"?Dh(t):t.status==="pending"?"Waiting":"",Nh=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Op=t=>t.status==="complete"?Nh(t):"Using tool...",Ii=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},as=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return Ii(e)},Ri=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return Ii(e)},kl=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=as(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Wi=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&is(o,n.slice(s,i.index),[]),i[1]!==void 0?is(o,i[1],["bold"]):i[2]!==void 0?is(o,i[2],["italic"]):i[3]!==void 0&&is(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&is(o,n.slice(s),[]),o},is=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},Oh=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
181
+ ${t.description}`:"");return window.confirm(n)},Mh=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},Th=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Eh=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function bn(t){return t==="card"?"collapsed":t}function dr(t){return t.split(";",1)[0].trim().toLowerCase()}function kh(t,e){if(!t)return;let n=Object.entries(t);for(let[r,s]of n)if(dr(r)===e)return{mode:bn(s),selector:dr(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,s]of n)if(dr(r)===o)return{mode:bn(s),selector:o}}function Lh(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:bn(o.files),matchedBy:{type:"files"}};let l=e.file.mimeType?dr(e.file.mimeType):void 0,p=l?kh(o.files.byMediaType,l):void 0;if(l&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:l,selector:p.selector}};if(o.files.default)return{mode:bn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[e.artifactType];if(r)return{mode:bn(r),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let s=o.byType?.[e.artifactType];if(s)return{mode:bn(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let i=e.presentation?.preferredMode;return i?{mode:bn(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:bn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function uo(t,e){return Lh(t,e).mode}function ds(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var Ph="agent_",Ih="flow_";function Np(t){return t.startsWith(Ph)?{kind:"agentId",agentId:t}:t.startsWith(Ih)?{kind:"flowId",flowId:t}:null}function Op(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let c=Np(l);if(c)return c;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=e?.[i];if(!p)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=Np(n);if(r)return r;let s=e?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var go=require("partial-json");Je();var Ml="ask_user_question",ps=8,pr="data-persona-ask-sheet-for",Rh="Other",Wh="Other\u2026",$p="Type your own answer here",zp="Send",Hh="Next",Bh="Back",Dh="Submit all",Nh="Skip",Oh=3,Tl="data-ask-current-index",El="data-ask-question-count",Up="data-ask-answers",kl="data-ask-grouped",jp="data-ask-layout",Fh=t=>t.layout==="pills"?"pills":"rows",_h=t=>t.getAttribute(jp)==="pills"?"pills":"rows",_p=!1,Vp=t=>t.replace(/["\\]/g,"\\$&"),Oo=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Ml,Ll=t=>t?.features?.askUserQuestion??{},ur=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,go.parse)(r,go.STR|go.OBJ|go.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},us=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>ps&&!_p&&(_p=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${ps}.`)),e.slice(0,ps)},$h=t=>us(t)[0]??null,zh=(t,e)=>us(t)[e]??null,Uh=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},qp=(t,e,n)=>{if(t!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},jh=(t,e,n,o)=>{let s=v("button",n==="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",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let i=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=t.label,i.appendChild(l),t.description){let c=v("span","persona-ask-row-description");c.textContent=t.description,i.appendChild(c)}s.appendChild(i);let p=qp(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},Vh=t=>{let n=v("span",t==="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 n.setAttribute("aria-hidden","true"),n},qh=(t,e,n,o)=>{let s=v("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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let i=!!t?.multiSelect,p=(Array.isArray(t?.options)?t.options:[]).filter(d=>d&&typeof d.label=="string"&&d.label.length>0);if(p.length===0&&!n){for(let d=0;d<Oh;d++)s.appendChild(Vh(o));return s}if(p.forEach((d,u)=>{s.appendChild(jh(d,u,o,i))}),t?.allowFreeText!==!1){let d=o==="rows"?Rh:Wh;if(o==="rows"){let u=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let b=v("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=e.freeTextPlaceholder??$p,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",e.freeTextLabel??d),b.appendChild(g),u.appendChild(b);let h=qp(o,i,p.length);h&&u.appendChild(h),s.appendChild(u)}else{let u=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=e.freeTextLabel??d,s.appendChild(u)}}return s},Kp=(t,e)=>{let o=v("div",e==="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");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=t.freeTextPlaceholder??$p,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??zp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Kh=t=>{let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??zp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},Gh=(t,e,n)=>{let o=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Bh,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=v("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??Nh,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=t===e-1;return l.textContent=p?n.submitAllLabel??Dh:n.nextLabel??Hh,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Fo=t=>{let e=t.getAttribute(Up);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},Gp=(t,e)=>{t.setAttribute(Up,JSON.stringify(e))},vn=t=>{let e=Number(t.getAttribute(Tl)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Qh=(t,e)=>{t.setAttribute(Tl,String(Math.max(0,Math.floor(e))))},gr=t=>{let e=Number(t.getAttribute(El)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},fo=t=>t.getAttribute(kl)==="true",Xh=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},Jh=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},Wi=(t,e)=>{let{payload:n}=ur(e),o=us(n),r=Fo(t),s={},i=new Set;return o.forEach((l,p)=>{let c=typeof l?.question=="string"?l.question:"";c&&(i.has(c)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),i.add(c),Object.prototype.hasOwnProperty.call(r,p)&&(s[c]=r[p]))}),s},Qp=t=>{let e=Fo(t),n=vn(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let c=p.getAttribute("data-option-label")??"",d=r.has(c);p.setAttribute("aria-pressed",d?"true":"false"),p.classList.toggle("persona-ask-pill-selected",d)});let i=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Xp=t=>{if(!fo(t))return;let e=Fo(t),n=vn(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let i=t.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},Pl=(t,e,n)=>{let o=Ll(n),r=_h(t),{payload:s,complete:i}=ur(e),l=fo(t),p=vn(t),c=gr(t),d=l?zh(s,p):$h(s),u=!!d?.multiSelect,b=t.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=l?`${p+1}/${c}`:"");let g=t.querySelector('[data-ask-stepper="true"]');g&&g.remove();let h=t.querySelector('[data-ask-question="true"]');if(h){let k=typeof d?.question=="string"?d.question:"";h.textContent=k,h.classList.toggle("persona-ask-question-skeleton",!k&&!i)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let k=qh(d,o,i,r);C.replaceWith(k)}if(r!=="rows"){let k=t.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(Kp(o,r))}let L=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!L?t.appendChild(Kh(o)):(!u||l)&&L&&L.remove(),t.setAttribute("data-multi-select",u?"true":"false");let B=t.querySelector('[data-ask-nav-row="true"]');if(l){let k=Gh(p,c,o);B?B.replaceWith(k):t.appendChild(k)}else B&&B.remove();Qp(t),Xp(t)},Yh=(t,e,n)=>{let o=Ll(e),r=Fh(o),s=t.toolCall.id,i=us(n),l=Math.max(1,i.length),p=l>1,c=Xh(t,i),d=p?Jh(t,l):0,u=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(pr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(El,String(l)),u.setAttribute(Tl,String(d)),u.setAttribute(kl,p?"true":"false"),u.setAttribute(jp,r),Gp(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Uh(u,o);let b=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=v("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",b.appendChild(g);let h=v("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",b.appendChild(h),u.appendChild(b);let L=v("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");return L.setAttribute("data-ask-pill-list","true"),L.setAttribute("role","group"),u.appendChild(L),r!=="rows"&&u.appendChild(Kp(o,r)),Pl(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Zh=(t,e,n)=>{let{payload:o}=ur(e),r=Math.max(1,us(o).length);r>gr(t)&&(t.setAttribute(El,String(r)),r>1&&!fo(t)&&t.setAttribute(kl,"true")),Pl(t,e,n)};var Hi=(t,e,n)=>{if(!n||!Oo(t)||Ll(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${pr}]`).forEach(c=>{c.getAttribute(pr)!==r&&c.remove()});let i=n.querySelector(`[${pr}="${Vp(r)}"]`);if(i){Zh(i,t,e);return}let{payload:l}=ur(t),p=Yh(t,e,l);n.appendChild(p)},fr=(t,e)=>{if(!t)return;let n=e?`[${pr}="${Vp(e)}"]`:`[${pr}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Il=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),mo=(t,e)=>{let n=Fo(t),o=vn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,Gp(t,n),Qp(t),Xp(t)},Bi=(t,e,n,o)=>{let r=gr(t),s=Math.max(0,Math.min(r-1,o));Qh(t,s),Pl(t,e,n)};var qn="suggest_replies";var ey={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},Yp={name:qn,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:ey,origin:"sdk",annotations:{readOnlyHint:!0}},Rl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),gs=t=>t.variant==="tool"&&t.toolCall?.name===qn,ty=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let i={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(i.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(i.description=s.description.trim()),[i]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Zp=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!gs(n))continue;let o=ty(n.toolCall?.args);return o.length>0?o:null}return null},Jp=new Set,ny=(t,e,n)=>{let o=`${t}:${e}:${n}`;Jp.has(o)||(Jp.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},ho=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=i=>{let l=e?.[i],p=n?.[i];l===void 0||p===void 0||l!==p&&ny(i,p,l)};t&&(o("enabled"),o("expose"));let r=e?.enabled??n?.enabled??!0,s=r?e?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var oy={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ps,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},ry={name:Ml,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:oy,origin:"sdk",annotations:{readOnlyHint:!0}},Di=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(ry),ho(t).expose&&e.push(Yp),e};var mr=require("partial-json"),eu=t=>t.replace(/\\n/g,`
182
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),yo=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},sy=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},tu=t=>t.status==="complete"?sy(t):t.status==="pending"?"Waiting":"",iy=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var nu=t=>t.status==="complete"?iy(t):"Using tool...",Ni=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},ms=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return Ni(e)},Oi=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return Ni(e)},Wl=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=ms(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Fi=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&fs(o,n.slice(s,i.index),[]),i[1]!==void 0?fs(o,i[1],["bold"]):i[2]!==void 0?fs(o,i[2],["italic"]):i[3]!==void 0&&fs(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&fs(o,n.slice(s),[]),o},fs=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},ay=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
183
183
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
184
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},ls=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Fp=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},_p=()=>{let t=Oh();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},$p=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=(0,pr.parse)(n,pr.STR|pr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?Dp(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=Dp(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var zp=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var jp="4.14.0";var cs=jp;var _h="https://api.runtype.com/v1/dispatch",Hi="https://api.runtype.com";function $h(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Ll=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function zh(t){switch(t){case"json":return $p;case"regex-json":return _p;case"xml":return zp;default:return Fp}}var Up=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function jh(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=Up(n);if(!Up(o))return t;if(!r||o===n||o.startsWith(n))return e;let i=ls(t);return ls(e)!==null&&i===null?e:t}var ds=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??_h,this.headers={"Content-Type":"application/json","X-Persona-Version":cs,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??zh(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=e.webmcp?.enabled===!0?new Ti(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=xp(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(e){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Hi}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":cs},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let i=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(i.sessionId),{sessionId:i.sessionId,expiresAt:new Date(i.expiresAt),flow:i.flow,config:{welcomeMessage:i.config.welcomeMessage,placeholder:i.config.placeholder,theme:i.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Hi}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":cs},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let c=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:c}),c}let r=await this.buildPayload(e.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([c])=>c!=="sessionId"&&c!=="session_id")):void 0,i={sessionId:o.sessionId,messages:e.messages.filter(Ll).map(c=>({id:c.id,role:c.role,content:c.contentParts??c.llmContent??c.rawContent??c.content})),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,c=>{let d={...i,...c};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":cs},body:JSON.stringify(d),signal:e.signal})});if(!l.ok){let c=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(c.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let d=new Error(c.error||"Failed to send message");throw n({type:"error",error:d}),d}if(!l.body){let c=new Error("No response body received");throw n({type:"error",error:c}),c}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Hi}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),i=s?yp(n):void 0,l=this.clientToolsFingerprintSessionId===e,p=s&&l&&this.lastSentClientToolsFingerprint===i,c=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,d=!1,u;for(let b=0;;b++){if(u=await o({...s&&(d||!p)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),u.status===409&&b===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Hi}/resume`,i;r&&(i=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(i&&(p.sessionId=i),r&&i){let c=[...Pi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:d,commit:u}=await this.sendWithClientToolsDiff(i,c,b=>{let f={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return d.ok&&u(),d}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(e){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=e.slice().filter(Ll).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Pi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(e);return i&&(r.context=i),r}async buildPayload(e){let n=e.slice().filter(Ll).sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let s=[...Pi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(e);if(i&&(r.context=i),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(e,n,o,r,s,i){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let p=d=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...d!==void 0&&{partId:d}};return o.current=u,r(u),u},c=d=>o.current?o.current:p(d);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(i.current=l.partId);let d=c(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),i=new TextDecoder,l="",p=Date.now(),c=0,d=()=>p+c++,u=M=>{let U=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,v=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,N=M.tools?M.tools.map(E=>({...E,chunks:E.chunks?[...E.chunks]:void 0})):void 0;return{...M,reasoning:U,toolCall:v,tools:N}},b=M=>{if(M.role!=="assistant"||M.variant)return!0;let U=Array.isArray(M.contentParts)&&M.contentParts.length>0,v=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||U||v||!!M.stopReason},f=M=>{b(M)&&n({type:"message",message:u(M)})},m=null,C=null,R={current:null},H={current:null},L=null,T="",k=new Map,$=new Map,G=new Map,w=new Map,F=new Map,D={lastId:null,byStep:new Map},B={lastId:null,byCall:new Map},P=M=>{if(M==null)return null;try{return String(M)}catch{return null}},I=M=>P(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),j=M=>P(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),pe=o,ue=!1,ge=()=>{if(m)return m;let M,U="",v=L;return!ue&&pe?(M=pe,ue=!0,U=r??""):pe&&v?M=`${pe}_${v}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:M,role:"assistant",content:U,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},f(m),m},Z=(M,U)=>{D.lastId=U,M&&D.byStep.set(M,U)},oe=(M,U)=>{let v=M.reasoningId??M.id,N=I(M);if(v){let O=String(v);return Z(N,O),O}if(N){let O=D.byStep.get(N);if(O)return D.lastId=O,O}if(D.lastId&&!U)return D.lastId;if(!U)return null;let E=`reason-${d()}`;return Z(N,E),E},Q=M=>{let U=w.get(M);if(U)return U;let v={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:M,status:"streaming",chunks:[]}};return w.set(M,v),f(v),v},se=(M,U)=>{B.lastId=U,M&&B.byCall.set(M,U)},te=new Set,fe=new Map,be=new Set,he=new Map,Ce=M=>{if(!M)return!1;let U=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return U==="emit_artifact_markdown"||U==="emit_artifact_component"},$e=(M,U)=>{let v=M.toolId??M.id,N=j(M);if(v){let O=String(v);return se(N,O),O}if(N){let O=B.byCall.get(N);if(O)return B.lastId=O,O}if(B.lastId&&!U)return B.lastId;if(!U)return null;let E=`tool-${d()}`;return se(N,E),E},Ee=M=>{let U=F.get(M);if(U)return U;let v={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:M,status:"pending"}};return F.set(M,v),f(v),v},ke=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let U=Number(M);if(!Number.isNaN(U)&&Number.isFinite(U))return U;let v=Date.parse(M);if(!Number.isNaN(v))return v}return Date.now()},ze=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},Ke=new Map,Le=new Map,Re=new Map,Je=(M,U,v)=>{let N=Re.get(M);N||(N=[],Re.set(M,N));let E=0,O=N.length;for(;E<O;){let z=E+O>>>1;N[z].seq<U?E=z+1:O=z}N[E]?.seq===U?N[E]={seq:U,text:v}:N.splice(E,0,{seq:U,text:v});let J="";for(let z=0;z<N.length;z++)J+=N[z].text;return J},Ot=(M,U)=>{let v=ze(U),N=Le.get(M.id),E=jh(N,v);M.rawContent=E;let O=Ke.get(M.id),J=Be=>{let Ye=M.content??"";Be.trim()!==""&&(Ye.trim().length===0||Be.startsWith(Ye)||Be.trimStart().startsWith(Ye.trim()))&&(M.content=Be)},z=()=>{if(O){let Be=O.close?.();Be instanceof Promise&&Be.catch(()=>{})}Ke.delete(M.id),Le.delete(M.id),M.streaming=!1,f(M)};if(!O){J(v),z();return}let K=ls(E);if(K!==null&&K.trim()!==""){J(K),z();return}let ne=Be=>{let Ye=typeof Be=="string"?Be:Be?.text??null;if(Ye!==null&&Ye.trim()!=="")return Ye;let it=O.getExtractedText();return it!==null&&it.trim()!==""?it:v},Ge;try{Ge=O.processChunk(E)}catch{J(v),z();return}if(Ge instanceof Promise){Ge.then(Be=>{J(ne(Be)),z()}).catch(()=>{J(v),z()});return}J(ne(Ge)),z()},Bt=null,Xt=(M,U,v,N)=>{M.rawContent=U,Ke.has(M.id)||Ke.set(M.id,this.createStreamParser());let E=Ke.get(M.id),O=U.trim().startsWith("{")||U.trim().startsWith("[");if(O&&Le.set(M.id,U),E.__isPlainTextParser===!0){M.content=N!==void 0?U:M.content+v,Le.delete(M.id),Ke.delete(M.id),M.rawContent=void 0,f(M);return}let z=E.processChunk(U);if(z instanceof Promise)z.then(K=>{let ne=typeof K=="string"?K:K?.text??null;ne!==null&&ne.trim()!==""?(M.content=ne,f(M)):!O&&!U.trim().startsWith("<")&&(M.content=N!==void 0?U:M.content+v,Le.delete(M.id),Ke.delete(M.id),M.rawContent=void 0,f(M))}).catch(()=>{M.content=N!==void 0?U:M.content+v,Le.delete(M.id),Ke.delete(M.id),M.rawContent=void 0,f(M)});else{let K=typeof z=="string"?z:z?.text??null;K!==null&&K.trim()!==""?(M.content=K,f(M)):!O&&!U.trim().startsWith("<")&&(M.content=N!==void 0?U:M.content+v,Le.delete(M.id),Ke.delete(M.id),M.rawContent=void 0,f(M))}},Mt=(M,U)=>{let v=U??M.content;if(v==null||v===""){M.streaming=!1,f(M);return}let E=Le.get(M.id)??ze(v);M.rawContent=E;let O=Ke.get(M.id),J=null,z=!1;if(O&&(J=O.getExtractedText(),J===null&&(J=ls(E)),J===null)){let K=O.processChunk(E);K instanceof Promise?(z=!0,K.then(ne=>{let Ge=typeof ne=="string"?ne:ne?.text??null;Ge!==null&&(M.content=Ge,M.streaming=!1,Ke.delete(M.id),Le.delete(M.id),f(M))}).catch(()=>{})):J=typeof K=="string"?K:K?.text??null}if(!z){J!==null&&J.trim()!==""?M.content=J:Le.has(M.id)||(M.content=ze(v));let K=Ke.get(M.id);if(K){let ne=K.close?.();ne instanceof Promise&&ne.catch(()=>{}),Ke.delete(M.id)}Le.delete(M.id),M.streaming=!1,f(M)}},Ne=(M,U,v)=>{let N=$.get(M);if(N)return N;let E={id:`nested-${U}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:U}};return $.set(M,E),f(E),E},me=[],nt,He=new Map,ve=0,ce="agent",We=!1,ct=null,ye=null,Me=new Map,re=this.config.iterationDisplay??"separate";for(nt=()=>{for(let M=0;M<me.length;M++){let U=me[M].payloadType,v=me[M].payload;if(!We&&ce!=="flow"&&typeof v.stepType=="string"&&(ce="flow"),U==="reasoning_start"){let N=typeof v.id=="string"?v.id:null,E=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(N&&E){k.set(N,E),Ne(N,E,"reasoning");continue}let O=oe(v,!0)??`reason-${d()}`,J=Q(O);J.reasoning=J.reasoning??{id:O,status:"streaming",chunks:[]},J.reasoning.startedAt=J.reasoning.startedAt??ke(v.startedAt??v.timestamp),J.reasoning.completedAt=void 0,J.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(J.reasoning.scope=v.scope),J.streaming=!0,J.reasoning.status="streaming",f(J)}else if(U==="reasoning_delta"){let N=typeof v.id=="string"?v.id:null;if(N&&k.has(N)&&$.has(N)){let z=$.get(N),K=v.reasoningText??v.text??v.delta??"";K&&v.hidden!==!0&&z.reasoning&&(z.reasoning.chunks.push(String(K)),f(z));continue}let E=oe(v,!1)??oe(v,!0)??`reason-${d()}`,O=Q(E);O.reasoning=O.reasoning??{id:E,status:"streaming",chunks:[]},O.reasoning.startedAt=O.reasoning.startedAt??ke(v.startedAt??v.timestamp);let J=v.reasoningText??v.text??v.delta??"";if(J&&v.hidden!==!0){let z=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(z!==void 0){let K=Je(E,z,String(J));O.reasoning.chunks=[K]}else O.reasoning.chunks.push(String(J))}if(O.reasoning.status=v.done?"complete":"streaming",v.done){O.reasoning.completedAt=ke(v.completedAt??v.timestamp);let z=O.reasoning.startedAt??Date.now();O.reasoning.durationMs=Math.max(0,(O.reasoning.completedAt??Date.now())-z)}O.streaming=O.reasoning.status!=="complete",f(O)}else if(U==="reasoning_complete"){let N=typeof v.id=="string"?v.id:null;if(N&&k.has(N)&&$.has(N)){let K=$.get(N);if(K.reasoning){let ne=typeof v.text=="string"?v.text:"";ne&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ne),K.reasoning.status="complete",K.streaming=!1,f(K)}k.delete(N),$.delete(N);continue}let E=oe(v,!1)??oe(v,!0)??`reason-${d()}`,O=typeof v.text=="string"?v.text:"";!w.get(E)&&(O||v.scope==="loop")&&Q(E);let J=w.get(E);if(J?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(J.reasoning.scope=v.scope),O&&J.reasoning.chunks.length===0&&J.reasoning.chunks.push(O),J.reasoning.status="complete",J.reasoning.completedAt=ke(v.completedAt??v.timestamp);let K=J.reasoning.startedAt??Date.now();J.reasoning.durationMs=Math.max(0,(J.reasoning.completedAt??Date.now())-K),J.streaming=!1,f(J)}let z=I(v);z&&D.byStep.delete(z)}else if(U==="tool_start"){m&&(m.streaming=!1,f(m),m=null),typeof v.iteration=="number"&&(ve=v.iteration);let N=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??$e(v,!0)??`tool-${d()}`,E=v.toolName??v.name;if(Ce(E)){te.add(N);continue}se(j(v),N);let O=Ee(N),J=O.toolCall??{id:N,status:"pending"};J.name=E??J.name,J.status="running",v.parameters!==void 0?J.args=v.parameters:v.args!==void 0&&(J.args=v.args),J.startedAt=J.startedAt??ke(v.startedAt??v.timestamp),J.completedAt=void 0,J.durationMs=void 0,O.toolCall=J,O.streaming=!0,v.executionId&&(O.agentMetadata={executionId:v.executionId,iteration:v.iteration}),f(O)}else if(U==="tool_output_delta"){let N=$e(v,!1)??$e(v,!0)??`tool-${d()}`;if(te.has(N))continue;let E=Ee(N),O=E.toolCall??{id:N,status:"running"};O.startedAt=O.startedAt??ke(v.startedAt??v.timestamp);let J=v.text??v.delta??v.message??"";J&&(O.chunks=O.chunks??[],O.chunks.push(String(J))),O.status="running",E.toolCall=O,E.streaming=!0;let z=v.agentContext;(z||v.executionId)&&(E.agentMetadata=E.agentMetadata??{executionId:z?.executionId??v.executionId,iteration:z?.iteration??v.iteration}),f(E)}else if(U==="tool_complete"){let N=$e(v,!1)??$e(v,!0)??`tool-${d()}`;if(te.has(N)){te.delete(N);continue}let E=Ee(N),O=E.toolCall??{id:N,status:"running"};O.status="complete",v.result!==void 0&&(O.result=v.result),typeof v.duration=="number"&&(O.duration=v.duration),O.completedAt=ke(v.completedAt??v.timestamp);let J=v.duration??v.executionTime;if(typeof J=="number")O.durationMs=J;else{let ne=O.startedAt??Date.now();O.durationMs=Math.max(0,(O.completedAt??Date.now())-ne)}E.toolCall=O,E.streaming=!1;let z=v.agentContext;(z||v.executionId)&&(E.agentMetadata=E.agentMetadata??{executionId:z?.executionId??v.executionId,iteration:z?.iteration??v.iteration}),f(E);let K=j(v);K&&B.byCall.delete(K)}else if(U==="await"&&v.toolName){let N=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,E=N??v.toolId??`local-${d()}`,O=Ee(E),J=v.toolName,z=v.origin==="webmcp"&&!sr(J)?`webmcp:${J}`:J,K=sr(z),ne=O.toolCall??{id:E,status:"pending"};ne.name=z,ne.args=v.parameters,ne.status=K?"running":"complete",ne.chunks=ne.chunks??[],ne.startedAt=ne.startedAt??ke(v.startedAt??v.timestamp??v.awaitedAt),K?(ne.completedAt=void 0,ne.duration=void 0,ne.durationMs=void 0):ne.completedAt=ne.completedAt??ne.startedAt,O.toolCall=ne,O.streaming=!1,O.agentMetadata={...O.agentMetadata,executionId:v.executionId??O.agentMetadata?.executionId,awaitingLocalTool:!0,...N?{webMcpToolCallId:N}:{}},f(O)}else if(U==="text_start"){let N=typeof v.id=="string"?v.id:null,E=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(N&&E){k.set(N,E);continue}let O=m;O&&(ce==="flow"?(Mt(O),Bt=O):(O.streaming=!1,f(O)),m=null),L=typeof v.id=="string"?v.id:L,T=""}else if(U==="text_delta"){let N=typeof v.id=="string"?v.id:null,E=N?k.get(N):void 0;if(N&&E){let J=typeof v.delta=="string"?v.delta:"",z=(G.get(N)??"")+J;if(G.set(N,z),z.trim()==="")continue;let K=Ne(N,E);K.agentMetadata={...K.agentMetadata,executionId:v.executionId,parentToolId:E},Xt(K,z,J,void 0);continue}if(L=typeof v.id=="string"?v.id:L,ce==="flow"){let J=typeof v.delta=="string"?v.delta:"";if(T+=J,T.trim()==="")continue;let z=ge();z.agentMetadata={executionId:v.executionId,iteration:v.iteration},Xt(z,T,J,void 0),C=z;continue}let O=ge();O.content+=v.delta??"",O.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:ct??void 0,agentName:ye?.agentName},C=O,f(O)}else if(U==="text_complete"){let N=typeof v.id=="string"?v.id:null;if(N&&k.has(N)){let O=$.get(N);O&&Mt(O),k.delete(N),G.delete(N),$.delete(N);continue}let E=m;E&&(ce==="flow"?(Mt(E),Bt=E):((E.content??"")===""&&typeof v.text=="string"&&(E.content=v.text),E.streaming=!1,f(E)),m=null),L=null,T=""}else if(U==="step_complete"){let N=v.stepType,E=v.executionType;if(N==="tool"||E==="context")continue;if(v.success===!1){let O=v.error,J=typeof O=="string"&&O!==""?O:O!=null&&typeof O=="object"&&Reflect.has(O,"message")?String(O.message??"Step failed"):"Step failed";n({type:"error",error:new Error(J)});let z=m;z&&z.streaming&&(z.streaming=!1,f(z)),n({type:"status",status:"idle"});continue}{let O=Bt;Bt=null;let J=v.stopReason,z=v.result?.response;if(O)J&&(O.stopReason=J),z!=null?Ot(O,z):O.streaming!==!1&&(Ke.delete(O.id),Le.delete(O.id),O.streaming=!1,f(O));else{let K=z!=null&&z!=="";if(K||J){let ne=ge();J&&(ne.stopReason=J),K?Mt(ne,z):(ne.streaming=!1,f(ne))}}continue}}else if(U==="execution_start")ce=v.kind==="flow"?"flow":"agent",We=!0,ce==="agent"&&(ye={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:ke(v.startedAt)});else if(U==="turn_start"){let N=typeof v.iteration=="number"?v.iteration:ve;if(N!==ve){if(ye&&(ye.currentIteration=N),re==="separate"&&N>1){let E=m;E&&(E.streaming=!1,f(E),Me.set(N-1,E),m=null)}ve=N}ct=typeof v.id=="string"?v.id:null,C=null}else if(U==="tool_input_delta"){let N=v.toolCallId??B.lastId;if(N){let E=F.get(N);E?.toolCall&&(E.toolCall.chunks=E.toolCall.chunks??[],E.toolCall.chunks.push(v.delta??""),f(E))}}else{if(U==="tool_input_complete")continue;if(U==="turn_complete"){let N=v.stopReason,E=m??C;if(N&&E!==null){let O=v.id;(!O||E.agentMetadata?.turnId===O)&&(E.stopReason=N,f(E))}ct===v.id&&(ct=null)}else if(U==="media_start"){let N=String(v.id);He.set(N,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(U==="media_delta"){let N=He.get(String(v.id));N&&typeof v.delta=="string"&&N.parts.push(v.delta)}else if(U==="media_complete"){let N=String(v.id),E=He.get(N);He.delete(N);let O=(typeof v.mediaType=="string"?v.mediaType:void 0)??E?.mediaType??"application/octet-stream",J=typeof v.data=="string"?v.data:void 0,z=typeof v.url=="string"?v.url:E&&E.parts.length>0?E.parts.join(""):void 0,K=null;if(J)K={type:"media",data:J,mediaType:O};else if(z){let Ye=O.toLowerCase();K={type:Ye==="image"||Ye.startsWith("image/")?"image-url":"file-url",url:z,mediaType:O}}let ne=v.toolCallId??E?.toolCallId,Ge=K?[K]:[],Be=[];for(let Ye of Ge){if(!Ye||typeof Ye!="object")continue;let it=Ye,X=typeof it.type=="string"?it.type:void 0,je=typeof it.mediaType=="string"?it.mediaType.toLowerCase():"",Ae=null,Ue="";if(X==="media"){let Oe=typeof it.data=="string"?it.data:void 0;if(!Oe)continue;Ue=je.length>0?je:"application/octet-stream",Ae=`data:${Ue};base64,${Oe}`}else if(X==="image-url"){let Oe=typeof it.url=="string"?it.url:void 0;if(!Oe)continue;Ue=je,Ae=Oe}else if(X==="file-url"){let Oe=typeof it.url=="string"?it.url:void 0;if(!Oe)continue;Ue=je,Ae=Oe}else continue;if(Ae)if(X==="image-url"||Ue.startsWith("image/"))Be.push({type:"image",image:Ae,...Ue.includes("/")?{mimeType:Ue}:{}});else if(Ue.startsWith("audio/"))Be.push({type:"audio",audio:Ae,mimeType:Ue});else if(Ue.startsWith("video/"))Be.push({type:"video",video:Ae,mimeType:Ue});else{let Oe=Ue||"application/octet-stream";Be.push({type:"file",data:Ae,mimeType:Oe,filename:$h(Oe)})}}if(Be.length>0){let Ye=d(),it=ne,je={id:`agent-media-${typeof it=="string"&&it.length>0?`${it}-${Ye}`:String(Ye)}`,role:"assistant",content:"",contentParts:Be,createdAt:new Date().toISOString(),streaming:!1,sequence:Ye,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:ve}};f(je);let Ae=m;Ae&&(Ae.streaming=!1,f(Ae)),m=null,R.current=null}}else if(U==="execution_complete"){let N=v.kind??ce;N==="agent"&&ye&&(ye.status=v.success?"complete":"error",ye.completedAt=ke(v.completedAt),ye.stopReason=v.stopReason);let E=m;E&&(N==="flow"&&E.streaming!==!1?Mt(E):(E.streaming=!1,f(E)),m=null),L=null,T="",Bt=null,n({type:"status",status:"idle",terminal:!0})}else if(U==="execution_error"){let N=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(N)})}else if(U!=="ping"){if(U==="approval_start"){let N=v.approvalId??`approval-${d()}`,E={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:N,status:"pending",agentId:ye?.agentId??"virtual",executionId:v.executionId??ye?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};f(E)}else if(U==="step_await"&&v.awaitReason==="approval_required"){let N=v.approvalId??`approval-${d()}`,E={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:N,status:"pending",agentId:ye?.agentId??"virtual",executionId:v.executionId??ye?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};f(E)}else if(U==="approval_complete"){let N=v.approvalId;if(N){let O={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:N,status:v.decision??"approved",agentId:ye?.agentId??"virtual",executionId:v.executionId??ye?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};f(O)}}else if(U==="artifact_start"||U==="artifact_delta"||U==="artifact_update"||U==="artifact_complete"){if(U==="artifact_start"){let N=v.artifactType,E=String(v.id),O=typeof v.title=="string"?v.title:void 0,J=v.file,z;J&&typeof J=="object"&&!Array.isArray(J)&&typeof J.path=="string"&&typeof J.mimeType=="string"&&(z={path:J.path,mimeType:J.mimeType,...typeof J.language=="string"?{language:J.language}:{}}),n({type:"artifact_start",id:E,artifactType:N,title:O,component:typeof v.component=="string"?v.component:void 0,...z?{file:z}:{}});let K=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(he.set(E,{markdown:"",title:O,file:z,...K?{props:K}:{}}),!be.has(E)){be.add(E);let ne=lo(this.config.features?.artifacts,{artifactType:N,...z?{file:z}:{}}),Ge=typeof v.component=="string"?v.component:void 0,Be={id:`artifact-ref-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:os(ne,{artifactId:E,title:O,artifactType:N,status:"streaming",...z?{file:z}:{},...Ge?{component:Ge}:{}})};fe.set(E,Be),f(Be)}}else if(U==="artifact_delta"){let N=String(v.id),E=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:N,artDelta:E});let O=he.get(N);O&&(O.markdown+=E)}else if(U==="artifact_update"){let N=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:N,component:typeof v.component=="string"?v.component:void 0});let E=he.get(String(v.id));E&&(E.props={...E.props??{},...N})}else if(U==="artifact_complete"){let N=String(v.id);n({type:"artifact_complete",id:N});let E=fe.get(N);if(E){E.streaming=!1;try{let O=JSON.parse(E.rawContent??"{}");if(O.props){O.props.status="complete";let J=he.get(N);J?.markdown&&(O.props.markdown=J.markdown),J?.file&&(O.props.file=J.file),O.component==="PersonaArtifactInline"&&J?.props&&Object.keys(J.props).length>0&&(O.props.componentProps=J.props)}E.rawContent=JSON.stringify(O)}catch{}he.delete(N),f(E),fe.delete(N)}}}else if(U==="transcript_insert"){let N=v.message;if(!N||typeof N!="object")continue;let E=String(N.id??`msg-${d()}`),O=N.role,z={id:E,role:O==="user"?"user":O==="system"?"system":"assistant",content:typeof N.content=="string"?N.content:"",rawContent:typeof N.rawContent=="string"?N.rawContent:void 0,createdAt:typeof N.createdAt=="string"?N.createdAt:new Date().toISOString(),streaming:N.streaming===!0,...typeof N.variant=="string"?{variant:N.variant}:{},sequence:d()};if(f(z),z.rawContent)try{let ne=JSON.parse(z.rawContent)?.props?.artifactId;typeof ne=="string"&&be.add(ne)}catch{}m=null,R.current=null,Ke.delete(E),Le.delete(E)}else if(U==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let N=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(N)});let E=m;E&&E.streaming&&(E.streaming=!1,f(E)),n({type:"status",status:"idle"})}}else if(U==="step_error"||U==="dispatch_error"||U==="flow_error"){let N=null;if(v.error instanceof Error)N=v.error;else if(U==="dispatch_error"){let E=v.message??v.error;E!=null&&E!==""&&(N=new Error(String(E)))}else{let E=v.error;typeof E=="string"&&E!==""?N=new Error(E):E!=null&&typeof E=="object"&&Reflect.has(E,"message")&&(N=new Error(String(E.message??E)))}if(N){n({type:"error",error:N});let E=m;E&&E.streaming&&(E.streaming=!1,f(E)),n({type:"status",status:"idle"})}}}}}me.length=0};;){let{done:M,value:U}=await s.read();if(M)break;l+=i.decode(U,{stream:!0});let v=l.split(`
184
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},hs=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},ou=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},ru=()=>{let t=ay();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},su=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=(0,mr.parse)(n,mr.STR|mr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?eu(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=eu(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var iu=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var au="4.15.0";var ys=au;var cy="https://api.runtype.com/v1/dispatch",_i="https://api.runtype.com";function dy(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Hl=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function py(t){switch(t){case"json":return su;case"regex-json":return ru;case"xml":return iu;default:return ou}}var lu=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function uy(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=lu(n);if(!lu(o))return t;if(!r||o===n||o.startsWith(n))return e;let i=hs(t);return hs(e)!==null&&i===null?e:t}var bs=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??cy,this.headers={"Content-Type":"application/json","X-Persona-Version":ys,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??py(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=e.webmcp?.enabled===!0?new Ri(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=Op(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(e){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||_i}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ys},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let i=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(i.sessionId),{sessionId:i.sessionId,expiresAt:new Date(i.expiresAt),flow:i.flow,config:{welcomeMessage:i.config.welcomeMessage,placeholder:i.config.placeholder,theme:i.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||_i}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ys},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let c=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:c}),c}let r=await this.buildPayload(e.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([c])=>c!=="sessionId"&&c!=="session_id")):void 0,i={sessionId:o.sessionId,messages:e.messages.filter(Hl).map(c=>({id:c.id,role:c.role,content:c.contentParts??c.llmContent??c.rawContent??c.content})),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,c=>{let d={...i,...c};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ys},body:JSON.stringify(d),signal:e.signal})});if(!l.ok){let c=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(c.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let d=new Error(c.error||"Failed to send message");throw n({type:"error",error:d}),d}if(!l.body){let c=new Error("No response body received");throw n({type:"error",error:c}),c}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||_i}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),i=s?Bp(n):void 0,l=this.clientToolsFingerprintSessionId===e,p=s&&l&&this.lastSentClientToolsFingerprint===i,c=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,d=!1,u;for(let b=0;;b++){if(u=await o({...s&&(d||!p)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),u.status===409&&b===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||_i}/resume`,i;r&&(i=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(i&&(p.sessionId=i),r&&i){let c=[...Di(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:d,commit:u}=await this.sendWithClientToolsDiff(i,c,b=>{let g={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return d.ok&&u(),d}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(e){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=e.slice().filter(Hl).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Di(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(e);return i&&(r.context=i),r}async buildPayload(e){let n=e.slice().filter(Hl).sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let s=[...Di(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(e);if(i&&(r.context=i),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(e,n,o,r,s,i){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let p=d=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...d!==void 0&&{partId:d}};return o.current=u,r(u),u},c=d=>o.current?o.current:p(d);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(i.current=l.partId);let d=c(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),i=new TextDecoder,l="",p=Date.now(),c=0,d=()=>p+c++,u=w=>{let K=w.reasoning?{...w.reasoning,chunks:[...w.reasoning.chunks]}:void 0,y=w.toolCall?{...w.toolCall,chunks:w.toolCall.chunks?[...w.toolCall.chunks]:void 0}:void 0,H=w.tools?w.tools.map(N=>({...N,chunks:N.chunks?[...N.chunks]:void 0})):void 0;return{...w,reasoning:K,toolCall:y,tools:H}},b=w=>{if(w.role!=="assistant"||w.variant)return!0;let K=Array.isArray(w.contentParts)&&w.contentParts.length>0,y=typeof w.rawContent=="string"&&w.rawContent.trim()!=="";return typeof w.content=="string"&&w.content.trim()!==""||K||y||!!w.stopReason},g=w=>{b(w)&&n({type:"message",message:u(w)})},h=null,C=null,L={current:null},B={current:null},k=null,S="",E=new Map,z=new Map,G=new Map,A=new Map,O=new Map,D={lastId:null,byStep:new Map},W={lastId:null,byCall:new Map},P=w=>{if(w==null)return null;try{return String(w)}catch{return null}},I=w=>P(w.stepId??w.step_id??w.step??w.parentId??w.flowStepId??w.flow_step_id),j=w=>P(w.callId??w.call_id??w.requestId??w.request_id??w.toolCallId??w.tool_call_id??w.stepId??w.step_id),pe=o,ge=!1,se=()=>{if(h)return h;let w,K="",y=k;return!ge&&pe?(w=pe,ge=!0,K=r??""):pe&&y?w=`${pe}_${y}`:w=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:w,role:"assistant",content:K,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},g(h),h},Y=(w,K)=>{D.lastId=K,w&&D.byStep.set(w,K)},oe=(w,K)=>{let y=w.reasoningId??w.id,H=I(w);if(y){let $=String(y);return Y(H,$),$}if(H){let $=D.byStep.get(H);if($)return D.lastId=$,$}if(D.lastId&&!K)return D.lastId;if(!K)return null;let N=`reason-${d()}`;return Y(H,N),N},J=w=>{let K=A.get(w);if(K)return K;let y={id:`reason-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:w,status:"streaming",chunks:[]}};return A.set(w,y),g(y),y},ie=(w,K)=>{W.lastId=K,w&&W.byCall.set(w,K)},ee=new Set,fe=new Map,be=new Set,he=new Map,we=w=>{if(!w)return!1;let K=w.replace(/_+/g,"_").replace(/^_|_$/g,"");return K==="emit_artifact_markdown"||K==="emit_artifact_component"},ve=(w,K)=>{let y=w.toolId??w.id,H=j(w);if(y){let $=String(y);return ie(H,$),$}if(H){let $=W.byCall.get(H);if($)return W.lastId=$,$}if(W.lastId&&!K)return W.lastId;if(!K)return null;let N=`tool-${d()}`;return ie(H,N),N},Te=w=>{let K=O.get(w);if(K)return K;let y={id:`tool-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:w,status:"pending"}};return O.set(w,y),g(y),y},Me=w=>{if(typeof w=="number"&&Number.isFinite(w))return w;if(typeof w=="string"){let K=Number(w);if(!Number.isNaN(K)&&Number.isFinite(K))return K;let y=Date.parse(w);if(!Number.isNaN(y))return y}return Date.now()},_e=w=>{if(typeof w=="string")return w;if(w==null)return"";try{return JSON.stringify(w)}catch{return String(w)}},Ve=new Map,ke=new Map,Re=new Map,Ge=(w,K,y)=>{let H=Re.get(w);H||(H=[],Re.set(w,H));let N=0,$=H.length;for(;N<$;){let F=N+$>>>1;H[F].seq<K?N=F+1:$=F}H[N]?.seq===K?H[N]={seq:K,text:y}:H.splice(N,0,{seq:K,text:y});let U="";for(let F=0;F<H.length;F++)U+=H[F].text;return U},Nt=(w,K)=>{let y=_e(K),H=ke.get(w.id),N=uy(H,y);w.rawContent=N;let $=Ve.get(w.id),U=Se=>{let rt=w.content??"";Se.trim()!==""&&(rt.trim().length===0||Se.startsWith(rt)||Se.trimStart().startsWith(rt.trim()))&&(w.content=Se)},F=()=>{if($){let Se=$.close?.();Se instanceof Promise&&Se.catch(()=>{})}Ve.delete(w.id),ke.delete(w.id),w.streaming=!1,g(w)};if(!$){U(y),F();return}let te=hs(N);if(te!==null&&te.trim()!==""){U(te),F();return}let de=Se=>{let rt=typeof Se=="string"?Se:Se?.text??null;if(rt!==null&&rt.trim()!=="")return rt;let ot=$.getExtractedText();return ot!==null&&ot.trim()!==""?ot:y},Le;try{Le=$.processChunk(N)}catch{U(y),F();return}if(Le instanceof Promise){Le.then(Se=>{U(de(Se)),F()}).catch(()=>{U(y),F()});return}U(de(Le)),F()},Bt=null,Xt=(w,K,y,H)=>{w.rawContent=K,Ve.has(w.id)||Ve.set(w.id,this.createStreamParser());let N=Ve.get(w.id),$=K.trim().startsWith("{")||K.trim().startsWith("[");if($&&ke.set(w.id,K),N.__isPlainTextParser===!0){w.content=H!==void 0?K:w.content+y,ke.delete(w.id),Ve.delete(w.id),w.rawContent=void 0,g(w);return}let F=N.processChunk(K);if(F instanceof Promise)F.then(te=>{let de=typeof te=="string"?te:te?.text??null;de!==null&&de.trim()!==""?(w.content=de,g(w)):!$&&!K.trim().startsWith("<")&&(w.content=H!==void 0?K:w.content+y,ke.delete(w.id),Ve.delete(w.id),w.rawContent=void 0,g(w))}).catch(()=>{w.content=H!==void 0?K:w.content+y,ke.delete(w.id),Ve.delete(w.id),w.rawContent=void 0,g(w)});else{let te=typeof F=="string"?F:F?.text??null;te!==null&&te.trim()!==""?(w.content=te,g(w)):!$&&!K.trim().startsWith("<")&&(w.content=H!==void 0?K:w.content+y,ke.delete(w.id),Ve.delete(w.id),w.rawContent=void 0,g(w))}},Mt=(w,K)=>{let y=K??w.content;if(y==null||y===""){w.streaming=!1,g(w);return}let N=ke.get(w.id)??_e(y);w.rawContent=N;let $=Ve.get(w.id),U=null,F=!1;if($&&(U=$.getExtractedText(),U===null&&(U=hs(N)),U===null)){let te=$.processChunk(N);te instanceof Promise?(F=!0,te.then(de=>{let Le=typeof de=="string"?de:de?.text??null;Le!==null&&(w.content=Le,w.streaming=!1,Ve.delete(w.id),ke.delete(w.id),g(w))}).catch(()=>{})):U=typeof te=="string"?te:te?.text??null}if(!F){U!==null&&U.trim()!==""?w.content=U:ke.has(w.id)||(w.content=_e(y));let te=Ve.get(w.id);if(te){let de=te.close?.();de instanceof Promise&&de.catch(()=>{}),Ve.delete(w.id)}ke.delete(w.id),w.streaming=!1,g(w)}},De=(w,K,y)=>{let H=z.get(w);if(H)return H;let N={id:`nested-${K}-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...y?{variant:y}:{},...y==="reasoning"?{reasoning:{id:w,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:K}};return z.set(w,N),g(N),N},ye=[],Ye,He=new Map,xe=0,ue="agent",We=!1,Jt=null,gt=null,bt=new Map,Q=this.config.iterationDisplay??"separate";for(Ye=()=>{for(let w=0;w<ye.length;w++){let K=ye[w].payloadType,y=ye[w].payload;if(!We&&ue!=="flow"&&typeof y.stepType=="string"&&(ue="flow"),K==="reasoning_start"){let H=typeof y.id=="string"?y.id:null,N=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(H&&N){E.set(H,N),De(H,N,"reasoning");continue}let $=oe(y,!0)??`reason-${d()}`,U=J($);U.reasoning=U.reasoning??{id:$,status:"streaming",chunks:[]},U.reasoning.startedAt=U.reasoning.startedAt??Me(y.startedAt??y.timestamp),U.reasoning.completedAt=void 0,U.reasoning.durationMs=void 0,(y.scope==="loop"||y.scope==="turn")&&(U.reasoning.scope=y.scope),U.streaming=!0,U.reasoning.status="streaming",g(U)}else if(K==="reasoning_delta"){let H=typeof y.id=="string"?y.id:null;if(H&&E.has(H)&&z.has(H)){let F=z.get(H),te=y.reasoningText??y.text??y.delta??"";te&&y.hidden!==!0&&F.reasoning&&(F.reasoning.chunks.push(String(te)),g(F));continue}let N=oe(y,!1)??oe(y,!0)??`reason-${d()}`,$=J(N);$.reasoning=$.reasoning??{id:N,status:"streaming",chunks:[]},$.reasoning.startedAt=$.reasoning.startedAt??Me(y.startedAt??y.timestamp);let U=y.reasoningText??y.text??y.delta??"";if(U&&y.hidden!==!0){let F=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(F!==void 0){let te=Ge(N,F,String(U));$.reasoning.chunks=[te]}else $.reasoning.chunks.push(String(U))}if($.reasoning.status=y.done?"complete":"streaming",y.done){$.reasoning.completedAt=Me(y.completedAt??y.timestamp);let F=$.reasoning.startedAt??Date.now();$.reasoning.durationMs=Math.max(0,($.reasoning.completedAt??Date.now())-F)}$.streaming=$.reasoning.status!=="complete",g($)}else if(K==="reasoning_complete"){let H=typeof y.id=="string"?y.id:null;if(H&&E.has(H)&&z.has(H)){let te=z.get(H);if(te.reasoning){let de=typeof y.text=="string"?y.text:"";de&&te.reasoning.chunks.length===0&&te.reasoning.chunks.push(de),te.reasoning.status="complete",te.streaming=!1,g(te)}E.delete(H),z.delete(H);continue}let N=oe(y,!1)??oe(y,!0)??`reason-${d()}`,$=typeof y.text=="string"?y.text:"";!A.get(N)&&($||y.scope==="loop")&&J(N);let U=A.get(N);if(U?.reasoning){(y.scope==="loop"||y.scope==="turn")&&(U.reasoning.scope=y.scope),$&&U.reasoning.chunks.length===0&&U.reasoning.chunks.push($),U.reasoning.status="complete",U.reasoning.completedAt=Me(y.completedAt??y.timestamp);let te=U.reasoning.startedAt??Date.now();U.reasoning.durationMs=Math.max(0,(U.reasoning.completedAt??Date.now())-te),U.streaming=!1,g(U)}let F=I(y);F&&D.byStep.delete(F)}else if(K==="tool_start"){h&&(h.streaming=!1,g(h),h=null),typeof y.iteration=="number"&&(xe=y.iteration);let H=(typeof y.toolCallId=="string"?y.toolCallId:void 0)??ve(y,!0)??`tool-${d()}`,N=y.toolName??y.name;if(we(N)){ee.add(H);continue}ie(j(y),H);let $=Te(H),U=$.toolCall??{id:H,status:"pending"};U.name=N??U.name,U.status="running",y.parameters!==void 0?U.args=y.parameters:y.args!==void 0&&(U.args=y.args),U.startedAt=U.startedAt??Me(y.startedAt??y.timestamp),U.completedAt=void 0,U.durationMs=void 0,$.toolCall=U,$.streaming=!0,y.executionId&&($.agentMetadata={executionId:y.executionId,iteration:y.iteration}),g($)}else if(K==="tool_output_delta"){let H=ve(y,!1)??ve(y,!0)??`tool-${d()}`;if(ee.has(H))continue;let N=Te(H),$=N.toolCall??{id:H,status:"running"};$.startedAt=$.startedAt??Me(y.startedAt??y.timestamp);let U=y.text??y.delta??y.message??"";U&&($.chunks=$.chunks??[],$.chunks.push(String(U))),$.status="running",N.toolCall=$,N.streaming=!0;let F=y.agentContext;(F||y.executionId)&&(N.agentMetadata=N.agentMetadata??{executionId:F?.executionId??y.executionId,iteration:F?.iteration??y.iteration}),g(N)}else if(K==="tool_complete"){let H=ve(y,!1)??ve(y,!0)??`tool-${d()}`;if(ee.has(H)){ee.delete(H);continue}let N=Te(H),$=N.toolCall??{id:H,status:"running"};$.status="complete",y.result!==void 0&&($.result=y.result),typeof y.duration=="number"&&($.duration=y.duration),$.completedAt=Me(y.completedAt??y.timestamp);let U=y.duration??y.executionTime;if(typeof U=="number")$.durationMs=U;else{let de=$.startedAt??Date.now();$.durationMs=Math.max(0,($.completedAt??Date.now())-de)}N.toolCall=$,N.streaming=!1;let F=y.agentContext;(F||y.executionId)&&(N.agentMetadata=N.agentMetadata??{executionId:F?.executionId??y.executionId,iteration:F?.iteration??y.iteration}),g(N);let te=j(y);te&&W.byCall.delete(te)}else if(K==="await"&&y.toolName){let H=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:void 0,N=H??y.toolId??`local-${d()}`,$=Te(N),U=y.toolName,F=y.origin==="webmcp"&&!cr(U)?`webmcp:${U}`:U,te=cr(F),de=$.toolCall??{id:N,status:"pending"};de.name=F,de.args=y.parameters,de.status=te?"running":"complete",de.chunks=de.chunks??[],de.startedAt=de.startedAt??Me(y.startedAt??y.timestamp??y.awaitedAt),te?(de.completedAt=void 0,de.duration=void 0,de.durationMs=void 0):de.completedAt=de.completedAt??de.startedAt,$.toolCall=de,$.streaming=!1,$.agentMetadata={...$.agentMetadata,executionId:y.executionId??$.agentMetadata?.executionId,awaitingLocalTool:!0,...H?{webMcpToolCallId:H}:{}},g($)}else if(K==="text_start"){let H=typeof y.id=="string"?y.id:null,N=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(H&&N){E.set(H,N);continue}let $=h;$&&(ue==="flow"?(Mt($),Bt=$):($.streaming=!1,g($)),h=null),k=typeof y.id=="string"?y.id:k,S=""}else if(K==="text_delta"){let H=typeof y.id=="string"?y.id:null,N=H?E.get(H):void 0;if(H&&N){let U=typeof y.delta=="string"?y.delta:"",F=(G.get(H)??"")+U;if(G.set(H,F),F.trim()==="")continue;let te=De(H,N);te.agentMetadata={...te.agentMetadata,executionId:y.executionId,parentToolId:N},Xt(te,F,U,void 0);continue}if(k=typeof y.id=="string"?y.id:k,ue==="flow"){let U=typeof y.delta=="string"?y.delta:"";if(S+=U,S.trim()==="")continue;let F=se();F.agentMetadata={executionId:y.executionId,iteration:y.iteration},Xt(F,S,U,void 0),C=F;continue}let $=se();$.content+=y.delta??"",$.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:Jt??void 0,agentName:gt?.agentName},C=$,g($)}else if(K==="text_complete"){let H=typeof y.id=="string"?y.id:null;if(H&&E.has(H)){let $=z.get(H);$&&Mt($),E.delete(H),G.delete(H),z.delete(H);continue}let N=h;N&&(ue==="flow"?(Mt(N),Bt=N):((N.content??"")===""&&typeof y.text=="string"&&(N.content=y.text),N.streaming=!1,g(N)),h=null),k=null,S=""}else if(K==="step_complete"){let H=y.stepType,N=y.executionType;if(H==="tool"||N==="context")continue;if(y.success===!1){let $=y.error,U=typeof $=="string"&&$!==""?$:$!=null&&typeof $=="object"&&Reflect.has($,"message")?String($.message??"Step failed"):"Step failed";n({type:"error",error:new Error(U)});let F=h;F&&F.streaming&&(F.streaming=!1,g(F)),n({type:"status",status:"idle"});continue}{let $=Bt;Bt=null;let U=y.stopReason,F=y.result?.response;if($)U&&($.stopReason=U),F!=null?Nt($,F):$.streaming!==!1&&(Ve.delete($.id),ke.delete($.id),$.streaming=!1,g($));else{let te=F!=null&&F!=="";if(te||U){let de=se();U&&(de.stopReason=U),te?Mt(de,F):(de.streaming=!1,g(de))}}continue}}else if(K==="execution_start")ue=y.kind==="flow"?"flow":"agent",We=!0,ue==="agent"&&(gt={executionId:y.executionId,agentId:y.agentId??"virtual",agentName:y.agentName??"",status:"running",currentIteration:0,maxTurns:y.maxTurns??1,startedAt:Me(y.startedAt)});else if(K==="turn_start"){let H=typeof y.iteration=="number"?y.iteration:xe;if(H!==xe){if(gt&&(gt.currentIteration=H),Q==="separate"&&H>1){let N=h;N&&(N.streaming=!1,g(N),bt.set(H-1,N),h=null)}xe=H}Jt=typeof y.id=="string"?y.id:null,C=null}else if(K==="tool_input_delta"){let H=y.toolCallId??W.lastId;if(H){let N=O.get(H);N?.toolCall&&(N.toolCall.chunks=N.toolCall.chunks??[],N.toolCall.chunks.push(y.delta??""),g(N))}}else{if(K==="tool_input_complete")continue;if(K==="turn_complete"){let H=y.stopReason,N=h??C;if(H&&N!==null){let $=y.id;(!$||N.agentMetadata?.turnId===$)&&(N.stopReason=H,g(N))}Jt===y.id&&(Jt=null)}else if(K==="media_start"){let H=String(y.id);He.set(H,{mediaType:typeof y.mediaType=="string"?y.mediaType:void 0,role:typeof y.role=="string"?y.role:void 0,toolCallId:y.toolCallId,parts:[]})}else if(K==="media_delta"){let H=He.get(String(y.id));H&&typeof y.delta=="string"&&H.parts.push(y.delta)}else if(K==="media_complete"){let H=String(y.id),N=He.get(H);He.delete(H);let $=(typeof y.mediaType=="string"?y.mediaType:void 0)??N?.mediaType??"application/octet-stream",U=typeof y.data=="string"?y.data:void 0,F=typeof y.url=="string"?y.url:N&&N.parts.length>0?N.parts.join(""):void 0,te=null;if(U)te={type:"media",data:U,mediaType:$};else if(F){let rt=$.toLowerCase();te={type:rt==="image"||rt.startsWith("image/")?"image-url":"file-url",url:F,mediaType:$}}let de=y.toolCallId??N?.toolCallId,Le=te?[te]:[],Se=[];for(let rt of Le){if(!rt||typeof rt!="object")continue;let ot=rt,ze=typeof ot.type=="string"?ot.type:void 0,Ze=typeof ot.mediaType=="string"?ot.mediaType.toLowerCase():"",X=null,Ue="";if(ze==="media"){let Ne=typeof ot.data=="string"?ot.data:void 0;if(!Ne)continue;Ue=Ze.length>0?Ze:"application/octet-stream",X=`data:${Ue};base64,${Ne}`}else if(ze==="image-url"){let Ne=typeof ot.url=="string"?ot.url:void 0;if(!Ne)continue;Ue=Ze,X=Ne}else if(ze==="file-url"){let Ne=typeof ot.url=="string"?ot.url:void 0;if(!Ne)continue;Ue=Ze,X=Ne}else continue;if(X)if(ze==="image-url"||Ue.startsWith("image/"))Se.push({type:"image",image:X,...Ue.includes("/")?{mimeType:Ue}:{}});else if(Ue.startsWith("audio/"))Se.push({type:"audio",audio:X,mimeType:Ue});else if(Ue.startsWith("video/"))Se.push({type:"video",video:X,mimeType:Ue});else{let Ne=Ue||"application/octet-stream";Se.push({type:"file",data:X,mimeType:Ne,filename:dy(Ne)})}}if(Se.length>0){let rt=d(),ot=de,Ze={id:`agent-media-${typeof ot=="string"&&ot.length>0?`${ot}-${rt}`:String(rt)}`,role:"assistant",content:"",contentParts:Se,createdAt:new Date().toISOString(),streaming:!1,sequence:rt,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:xe}};g(Ze);let X=h;X&&(X.streaming=!1,g(X)),h=null,L.current=null}}else if(K==="execution_complete"){let H=y.kind??ue;H==="agent"&&gt&&(gt.status=y.success?"complete":"error",gt.completedAt=Me(y.completedAt),gt.stopReason=y.stopReason);let N=h;N&&(H==="flow"&&N.streaming!==!1?Mt(N):(N.streaming=!1,g(N)),h=null),k=null,S="",Bt=null,n({type:"status",status:"idle",terminal:!0})}else if(K==="execution_error"){let H=typeof y.error=="string"?y.error:y.error?.message??"Execution error";n({type:"error",error:new Error(H)})}else if(K!=="ping"){if(K==="approval_start"){let H=y.approvalId??`approval-${d()}`,N={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:H,status:"pending",agentId:gt?.agentId??"virtual",executionId:y.executionId??gt?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};g(N)}else if(K==="step_await"&&y.awaitReason==="approval_required"){let H=y.approvalId??`approval-${d()}`,N={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:H,status:"pending",agentId:gt?.agentId??"virtual",executionId:y.executionId??gt?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};g(N)}else if(K==="approval_complete"){let H=y.approvalId;if(H){let $={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:H,status:y.decision??"approved",agentId:gt?.agentId??"virtual",executionId:y.executionId??gt?.executionId??"",toolName:y.toolName??"",description:y.description??"",resolvedAt:Date.now()}};g($)}}else if(K==="artifact_start"||K==="artifact_delta"||K==="artifact_update"||K==="artifact_complete"){if(K==="artifact_start"){let H=y.artifactType,N=String(y.id),$=typeof y.title=="string"?y.title:void 0,U=y.file,F;U&&typeof U=="object"&&!Array.isArray(U)&&typeof U.path=="string"&&typeof U.mimeType=="string"&&(F={path:U.path,mimeType:U.mimeType,...typeof U.language=="string"?{language:U.language}:{}}),n({type:"artifact_start",id:N,artifactType:H,title:$,component:typeof y.component=="string"?y.component:void 0,...F?{file:F}:{}});let te=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?{...y.props}:void 0;if(he.set(N,{markdown:"",title:$,file:F,...te?{props:te}:{}}),!be.has(N)){be.add(N);let de=uo(this.config.features?.artifacts,{artifactType:H,...F?{file:F}:{}}),Le=typeof y.component=="string"?y.component:void 0,Se={id:`artifact-ref-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:ds(de,{artifactId:N,title:$,artifactType:H,status:"streaming",...F?{file:F}:{},...Le?{component:Le}:{}})};fe.set(N,Se),g(Se)}}else if(K==="artifact_delta"){let H=String(y.id),N=typeof y.delta=="string"?y.delta:String(y.delta??"");n({type:"artifact_delta",id:H,artDelta:N});let $=he.get(H);$&&($.markdown+=N)}else if(K==="artifact_update"){let H=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};n({type:"artifact_update",id:String(y.id),props:H,component:typeof y.component=="string"?y.component:void 0});let N=he.get(String(y.id));N&&(N.props={...N.props??{},...H})}else if(K==="artifact_complete"){let H=String(y.id);n({type:"artifact_complete",id:H});let N=fe.get(H);if(N){N.streaming=!1;try{let $=JSON.parse(N.rawContent??"{}");if($.props){$.props.status="complete";let U=he.get(H);U?.markdown&&($.props.markdown=U.markdown),U?.file&&($.props.file=U.file),$.component==="PersonaArtifactInline"&&U?.props&&Object.keys(U.props).length>0&&($.props.componentProps=U.props)}N.rawContent=JSON.stringify($)}catch{}he.delete(H),g(N),fe.delete(H)}}}else if(K==="transcript_insert"){let H=y.message;if(!H||typeof H!="object")continue;let N=String(H.id??`msg-${d()}`),$=H.role,F={id:N,role:$==="user"?"user":$==="system"?"system":"assistant",content:typeof H.content=="string"?H.content:"",rawContent:typeof H.rawContent=="string"?H.rawContent:void 0,createdAt:typeof H.createdAt=="string"?H.createdAt:new Date().toISOString(),streaming:H.streaming===!0,...typeof H.variant=="string"?{variant:H.variant}:{},sequence:d()};if(g(F),F.rawContent)try{let de=JSON.parse(F.rawContent)?.props?.artifactId;typeof de=="string"&&be.add(de)}catch{}h=null,L.current=null,Ve.delete(N),ke.delete(N)}else if(K==="error"){if(y.recoverable===!1&&y.error!=null&&y.error!==""){let H=typeof y.error=="string"?y.error:y.error?.message!=null?String(y.error.message):"Execution error";n({type:"error",error:new Error(H)});let N=h;N&&N.streaming&&(N.streaming=!1,g(N)),n({type:"status",status:"idle"})}}else if(K==="step_error"||K==="dispatch_error"||K==="flow_error"){let H=null;if(y.error instanceof Error)H=y.error;else if(K==="dispatch_error"){let N=y.message??y.error;N!=null&&N!==""&&(H=new Error(String(N)))}else{let N=y.error;typeof N=="string"&&N!==""?H=new Error(N):N!=null&&typeof N=="object"&&Reflect.has(N,"message")&&(H=new Error(String(N.message??N)))}if(H){n({type:"error",error:H});let N=h;N&&N.streaming&&(N.streaming=!1,g(N)),n({type:"status",status:"idle"})}}}}}ye.length=0};;){let{done:w,value:K}=await s.read();if(w)break;l+=i.decode(K,{stream:!0});let y=l.split(`
185
185
 
186
- `);l=v.pop()??"";for(let N of v){let E=N.split(`
187
- `),O="message",J="",z=null;for(let Be of E)Be.startsWith("event:")?O=Be.replace("event:","").trim():Be.startsWith("data:")?J+=Be.replace("data:","").trim():Be.startsWith("id:")&&(z=Be.slice(3).trim());let K=()=>{z!==null&&z!==""&&n({type:"cursor",id:z})};if(!J){K();continue}let ne;try{ne=JSON.parse(J)}catch(Be){n({type:"error",error:Be instanceof Error?Be:new Error("Failed to parse chat stream payload")});continue}let Ge=O!=="message"?O:ne.type??"message";if(this.onSSEEvent?.(Ge,ne),this.parseSSEEvent){R.current=m;let Be=await this.handleCustomSSEEvent(ne,n,R,f,d,H);if(R.current&&R.current!==m&&(m=R.current),Be){K();continue}}me.push({payloadType:Ge,payload:ne}),nt(),K()}}nt()}};function Bi(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ur(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var Di="[Image]";function Vp(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function fr(t){return{type:"text",text:t}}var qp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Uh=["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"],Un=[...qp,...Uh];function Vh(t){return qp.includes(t)||t.startsWith("image/")}function Ni(t){return Vh(t.type)}async function Kp(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ni(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function Gp(t,e=Un,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function qh(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Qp(t,e){let n=qh(e).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"}[t]||n||"FILE"}Pl();var Xp=16e3,Kh=24e3,Gh=4096,Qh=1380533830;function Xh(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===Qh?new Uint8Array(t,44):new Uint8Array(t)}function Jh(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var ps=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Xp,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:Xp});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new gr(Kh);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let c=`${Jh(o)}/ws/agents/${encodeURIComponent(e)}/voice`,d=new WebSocket(c,["runtype.bearer",n]);d.binaryType="arraybuffer",this.ws=d,d.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,d,r))},d.onmessage=u=>this.handleMessage(u,r),d.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},d.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let b=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${b}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let i=e.createScriptProcessor(Gh,1,1);this.processor=i,i.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),c=new Int16Array(p.length);for(let d=0;d<p.length;d++){let u=Math.max(-1,Math.min(1,p[d]));c[d]=u<0?u*32768:u*32767}o.send(c.buffer)},s.connect(i),i.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=Xh(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var Do=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function mr(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new ps(t.runtype);case"browser":if(!Do.isSupported())throw new Error("Browser speech recognition not supported");return new Do(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function Jp(t){if(t?.type==="custom"&&t.custom)return mr({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return mr({type:"runtype",runtype:t.runtype});if(Do.isSupported())return mr({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Il(t){try{return Jp(t),!0}catch{return!1}}function Oi(t){let e=["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 n of e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var hr=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let i=s.find(l=>l.name===e.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Oi(s));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var us=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function Rl(t){if(!t)return"";let e=Yh(t);return Yp(e!==null?e:t)}function Yh(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Yp(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
186
+ `);l=y.pop()??"";for(let H of y){let N=H.split(`
187
+ `),$="message",U="",F=null;for(let Se of N)Se.startsWith("event:")?$=Se.replace("event:","").trim():Se.startsWith("data:")?U+=Se.replace("data:","").trim():Se.startsWith("id:")&&(F=Se.slice(3).trim());let te=()=>{F!==null&&F!==""&&n({type:"cursor",id:F})};if(!U){te();continue}let de;try{de=JSON.parse(U)}catch(Se){n({type:"error",error:Se instanceof Error?Se:new Error("Failed to parse chat stream payload")});continue}let Le=$!=="message"?$:de.type??"message";if(this.onSSEEvent?.(Le,de),this.parseSSEEvent){L.current=h;let Se=await this.handleCustomSSEEvent(de,n,L,g,d,B);if(L.current&&L.current!==h&&(h=L.current),Se){te();continue}}ye.push({payloadType:Le,payload:de}),Ye(),te()}}Ye()}};function $i(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function hr(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var zi="[Image]";function cu(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function yr(t){return{type:"text",text:t}}var du=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],gy=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Kn=[...du,...gy];function fy(t){return du.includes(t)||t.startsWith("image/")}function Ui(t){return fy(t.type)}async function pu(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ui(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function uu(t,e=Kn,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function my(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function gu(t,e){let n=my(e).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"}[t]||n||"FILE"}Bl();var fu=16e3,hy=24e3,yy=4096,by=1380533830;function vy(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===by?new Uint8Array(t,44):new Uint8Array(t)}function xy(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var vs=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:fu,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:fu});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new br(hy);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let c=`${xy(o)}/ws/agents/${encodeURIComponent(e)}/voice`,d=new WebSocket(c,["runtype.bearer",n]);d.binaryType="arraybuffer",this.ws=d,d.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,d,r))},d.onmessage=u=>this.handleMessage(u,r),d.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},d.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let b=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${b}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let i=e.createScriptProcessor(yy,1,1);this.processor=i,i.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),c=new Int16Array(p.length);for(let d=0;d<p.length;d++){let u=Math.max(-1,Math.min(1,p[d]));c[d]=u<0?u*32768:u*32767}o.send(c.buffer)},s.connect(i),i.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=vy(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var _o=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function vr(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new vs(t.runtype);case"browser":if(!_o.isSupported())throw new Error("Browser speech recognition not supported");return new _o(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function mu(t){if(t?.type==="custom"&&t.custom)return vr({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return vr({type:"runtype",runtype:t.runtype});if(_o.isSupported())return vr({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Dl(t){try{return mu(t),!0}catch{return!1}}function ji(t){let e=["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 n of e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var xr=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let i=s.find(l=>l.name===e.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):ji(s));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var xs=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function Nl(t){if(!t)return"";let e=Cy(t);return hu(e!==null?e:t)}function Cy(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function hu(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
188
188
  `),e=e.replace(/\n{2,}/g,`
189
- `),e.trim()}var ou=null;var Wl=()=>ou?ou():Promise.resolve().then(()=>(nu(),tu));var oy=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function ry(t,e){return oy.some(n=>t[n]!==e[n])}function Hl(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: 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 n.message?`${o}
189
+ `),e.trim()}var Cu=null;var Ol=()=>Cu?Cu():Promise.resolve().then(()=>(xu(),vu));var Ty=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Ey(t,e){return Ty.some(n=>t[n]!==e[n])}function Fl(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: 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 n.message?`${o}
190
190
 
191
- _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]}),iu=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,au=t=>sr(t)||t===jn,$i=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=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.readAloud=new us(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(sr(n.name)||n.name===jn&&this.config.features?.suggestReplies?.enabled!==!1);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.messages=[...e.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new ds(e),this.wireDefaultWebMcpConfirm();for(let o of e.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Wl().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Il(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=hr.isSupported()?new hr({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=e.browserFallback!==!1;if(o&&r&&s)return Wl().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let c=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return i&&n?new p(c,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):c});if(i&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=mr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,i,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:i,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:i,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!ry(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new ds(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:i,createdAt:l,sequence:p,streaming:c=!1,voiceProcessing:d,rawContent:u}=e,f={id:i??(n==="user"?Bi():n==="assistant"?ur():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:c,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...d!==void 0&&{voiceProcessing:d},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:i,contentParts:l,id:p,createdAt:c,sequence:d,streaming:u=!1,voiceProcessing:b,rawContent:f}=o,C={id:p??(r==="user"?Bi():r==="assistant"?ur():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:c??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...b!==void 0&&{voiceProcessing:b},...f!==void 0&&{rawContent:f}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:p}=e,c={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
191
+ _Details: ${n.message}_`:o}var Cs=t=>({isError:!0,content:[{type:"text",text:t}]}),Su=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Mu=t=>cr(t)||t===qn,Ki=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=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.readAloud=new xs(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(cr(n.name)||n.name===qn&&ho(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.messages=[...e.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new bs(e),this.wireDefaultWebMcpConfirm();for(let o of e.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Ol().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Dl(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=xr.isSupported()?new xr({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=e.browserFallback!==!1;if(o&&r&&s)return Ol().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let c=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return i&&n?new p(c,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):c});if(i&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=vr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,i,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:i,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:i,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!Ey(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new bs(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:i,createdAt:l,sequence:p,streaming:c=!1,voiceProcessing:d,rawContent:u}=e,g={id:i??(n==="user"?$i():n==="assistant"?hr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:c,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...d!==void 0&&{voiceProcessing:d},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:i,contentParts:l,id:p,createdAt:c,sequence:d,streaming:u=!1,voiceProcessing:b,rawContent:g}=o,C={id:p??(r==="user"?$i():r==="assistant"?hr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:c??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...b!==void 0&&{voiceProcessing:b},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:p}=e,c={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
192
192
 
193
193
  `),i=[s,n].filter(Boolean).join(`
194
194
 
195
- `),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,p=r.contentParts.length>0;if(l){let c=[];s&&c.push(fr(s)),c.push(...r.contentParts),c.push(...e.contentParts),e.contentParts=c}else if(p){let c=[];i&&c.push(fr(i)),c.push(...r.contentParts),e.contentParts=c}else s&&(e.llmContent=i);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Bi(),s=ur();this.activeAssistantMessageId=null;let i=n?.contentParts&&Vp(n.contentParts)?Di:"",l={id:r,role:"user",content:o||i,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let d=this.messages.find(u=>u.id===r)??l;if(await this.applyMentionBundle(d,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!u){let b=Hl(d,this.config.errorMessage);if(b){let f={id:s,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(d instanceof Error?this.callbacks.onError?.(d):this.callbacks.onError?.(new Error(String(d))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let e=ur();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=Hl(r,this.config.errorMessage);if(i){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},i=this.messages.find(d=>d.id===r),l={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,c=p&&typeof p=="object"?p.onDecision:void 0;try{let d;if(c?d=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):d=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),d){let u=null;if(d instanceof Response){if(!d.ok){let b=await d.json().catch(()=>null);throw new Error(b?.error??`Approval request failed: ${d.status}`)}u=d.body}else d instanceof ReadableStream&&(u=d);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.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(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(d=>d.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let d=e.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===1){let b=typeof u[0]?.question=="string"?u[0].question:"";b&&(i={[b]:n})}}this.markAskUserQuestionResolved(e,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,p=e.toolCall?.args,c=Array.isArray(p?.questions)?p.questions:[];if(c.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([u,b])=>`${u}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let d=i??{};c.forEach((u,b)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let m=d[f],C=Array.isArray(m)?m.join(", "):typeof m=="string"?m:"";this.appendMessage({id:`ask-user-q-${l}-${b}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${b}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let d=await this.client.resumeFlow(r,{[s]:n});if(!d.ok){let u=await d.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${d.status}`)}d.body?await this.connectStream(d.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==jn?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),s){this.messages.some(i=>i.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let i=await Promise.all(n.map(async p=>{let c=p.toolCall?.name,d=p.toolCall?.id;if(!c||!d)return null;let u=`${e}:${d}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let b=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??c;if(c===jn)return{dedupeKey:u,resumeKey:f,output:Tl(),toolMessage:p,startedAt:b,completedAt:Date.now()};let m=new AbortController;this.webMcpResolveControllers.add(m),r.push(m);let C=this.client.executeWebMcpToolCall(c,p.toolCall?.args,m.signal),R;if(!C)R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{R=await C}catch(H){let L=H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"));return L||this.callbacks.onError?.(H instanceof Error?H:new Error(String(H))),this.markWebMcpToolComplete(p,fs(L?"Aborted by cancel()":iu(H)),b),this.webMcpInflightKeys.delete(u),null}return m.signal.aborted?(this.markWebMcpToolComplete(p,fs("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:R,toolMessage:p,startedAt:b,completedAt:Date.now()}})),l=[];try{if(l=i.filter(d=>d!==null),l.length===0)return;let p={};for(let d of l)p[d.resumeKey]=d.output;let c=await this.client.resumeFlow(e,p,{signal:s.signal});if(!c.ok){let d=await c.json().catch(()=>null);throw new Error(d?.error??`Resume failed: ${c.status}`)}for(let d of l)this.webMcpResolvedKeys.add(d.dedupeKey),this.markWebMcpToolComplete(d.toolMessage,d.output,d.startedAt,d.completedAt,d.toolMessage.toolCall?.name===jn?{suggestRepliesResolved:!0}:void 0);c.body&&await this.connectStream(c.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let d of l)this.markWebMcpToolComplete(d.toolMessage,fs("Aborted by cancel()"),d.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let m=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m))return;this.webMcpInflightKeys.add(m);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(m)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(m)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let i=this.markWebMcpToolRunning(e),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let c=o===jn,d=e.toolCall?.args,u=c?null:this.client.executeWebMcpToolCall(o,d,p),b="execute",f=i;try{let m;if(c?m=Tl():u?m=await u:m={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(e,fs("Aborted by cancel()"),i);return}let C=e.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,C,m,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,m,i,f,c?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(m){let C=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));(b==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(e,fs(C||p.aborted?"Aborted by cancel()":iu(m)),i),C||this.callbacks.onError?.(m instanceof Error?m:new Error(String(m)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal});if(!s.ok){let i=await s.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=lo(this.config.features?.artifacts,e),r=os(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),s=this.messages.find(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=lo(this.config.features?.artifacts,n),s=os(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(su(),ru)).then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>Hl(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=ur(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=Rl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Oi(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=Rl(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let i={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let d=r.approval,u=n.approval;i.approval={...d,...u,executionId:u.executionId||d.executionId,toolName:u.toolName||d.toolName,description:u.description||d.description,toolType:u.toolType??d.toolType,reason:u.reason??d.reason,parameters:u.parameters??d.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,c=n.toolCall?.id;if(l&&au(l)&&p&&c&&n.agentMetadata?.awaitingLocalTool===!0){let d=`${p}:${c}`,u=this.webMcpInflightKeys.has(d),b=this.webMcpResolvedKeys.has(d),f=r.toolCall?.name,m=r.agentMetadata?.executionId===p&&r.toolCall?.id===c&&f!==void 0&&au(f)&&r.toolCall?.status==="complete";(u||b||m)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};tt();St();var zi={allowedTypes:Un,maxFileSize:10*1024*1024,maxFiles:4};function ay(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ly(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var gs=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??zi.allowedTypes,maxFileSize:e.maxFileSize??zi.maxFileSize,maxFiles:e.maxFiles??zi.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:zi.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(e.length){for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=Gp(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await Kp(n),s=Ni(n)?URL.createObjectURL(n):null,i={id:ay(),file:n,previewUrl:s,contentPart:r};this.attachments.push(i),this.renderPreview(i)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=Ni(e.file),o=y("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let i=y("img");i.src=e.previewUrl,i.alt=e.file.name,i.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",o.appendChild(i)}else{let i=y("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--persona-container, #f3f4f6)",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let l=ly(e.file.type),p=ae(l,20,"var(--persona-muted, #6b7280)",1.5);p&&i.appendChild(p);let c=y("span");c.textContent=Qp(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",i.appendChild(c),o.appendChild(i)}let r=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ae("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n})}};tt();ji();Bl();tt();St();var Wt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Qt=1e5,Vi=Qt+1;var py=8,uy=8,Dl=10,Nl=new WeakMap,pu=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,fy=t=>{let e=t.getRootNode?.();return pu(e)?e:t.ownerDocument.body},Ol=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n));function jt(t){Nl.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,enabled:r=!0,gap:s=py,viewportPadding:i=uy}=t,l=()=>e.ownerDocument,p=()=>l().defaultView??window,c=null,d=null,u=null,b=!1,f=!1,m=!1,C=()=>(typeof o=="function"?o():o).trim(),R=()=>{u?.(),u=null,c?.remove(),c=null,d=null},H=()=>{if(!c)return;let B=l(),P=p(),I=e.getBoundingClientRect(),j=c.getBoundingClientRect(),pe=B.documentElement.clientWidth||P.innerWidth,ue=B.documentElement.clientHeight||P.innerHeight,ge=pe-i-j.width,Z=I.left+I.width/2-j.width/2,oe=Ol(Z,i,ge),Q=I.top-i,se=ue-i-I.bottom,te=j.height+s,fe=Q>=te||Q>=se?"top":"bottom",be=fe==="top"?I.top-s-j.height:I.bottom+s,he=ue-i-j.height,Ce=Ol(be,i,he),$e=I.left+I.width/2,Ee=Math.max(Dl,j.width-Dl),ke=Ol($e-oe,Dl,Ee);c.dataset.placement=fe,c.style.left=`${oe}px`,c.style.top=`${Ce}px`,c.style.setProperty("--persona-tooltip-arrow-x",`${ke}px`)},L=()=>{if(m||!r||c||!e.isConnected)return;let B=C(),P=fy(e);if(!B||!P)return;let I=l(),j=p();c=I.createElement("div"),c.className="persona-control-tooltip",c.setAttribute("role","tooltip"),c.dataset.state="measuring",c.style.zIndex=String(Vi),d=I.createElement("span"),d.className="persona-control-tooltip__label",d.textContent=B,c.appendChild(d);let pe=I.createElement("span");pe.className="persona-control-tooltip__arrow",c.appendChild(pe),P.appendChild(c),H(),c.dataset.state="open";let ue=()=>{if(!e.isConnected){R();return}d&&(d.textContent=C()),H()};j.addEventListener("scroll",ue,!0),j.addEventListener("resize",ue);let ge=e.getRootNode(),Z=pu(ge)?ge:I.documentElement,oe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||R()});oe?.observe(Z,{childList:!0,subtree:!0}),u=()=>{j.removeEventListener("scroll",ue,!0),j.removeEventListener("resize",ue),oe?.disconnect()}},T=()=>{b||f?L():R()},k=()=>{let B=p();(!B.matchMedia||!B.matchMedia("(hover: none)").matches)&&(b=!0,T())},$=()=>{b=!1,T()},G=()=>{f=!0,T()},w=()=>{f=!1,T()},F=B=>{B.key==="Escape"&&(b=!1,f=!1,R())};n.addEventListener("mouseenter",k),n.addEventListener("mouseleave",$),e.addEventListener("focus",G),e.addEventListener("blur",w),e.addEventListener("keydown",F);let D={get isOpen(){return c!==null},show:L,hide:R,reposition:H,destroy:()=>{m||(m=!0,R(),n.removeEventListener("mouseenter",k),n.removeEventListener("mouseleave",$),e.removeEventListener("focus",G),e.removeEventListener("blur",w),e.removeEventListener("keydown",F),Nl.delete(e))}};return Nl.set(e,D),D}function uu(t){let{config:e,onOpen:n}=t,o=t.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),i=e.buttonIconName??"plus",l=e.buttonTooltipText??"Add context",p=y("div","persona-send-button-wrapper"),c=we("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),d=ae(i,s,"currentColor",1.5);return d?c.appendChild(d):c.textContent="+",c.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(c),jt({anchor:c,trigger:p,text:()=>c.getAttribute("aria-label")??l}),{button:c,wrapper:p}}var{setLoader:Uw,load:Cy}=rr({fallbackImport:()=>Promise.resolve().then(()=>(Wu(),Ru))});var Vl=Cy;var{setLoader:nA,load:Iy}=rr({fallbackImport:()=>Promise.resolve().then(()=>(Vu(),Uu)),resetOnSetLoader:!0});var qu=Iy;tt();St();function xs(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=we("span",{className:zn("persona-mention-token",e.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":t.sourceId,title:t.label,role:"img","aria-label":`${t.label} mention`}});t.color&&n.style.setProperty("--persona-mention-token-accent",t.color);let o=ae(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=y("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(we("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function Ku(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=Ui(e).filter(T=>T.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(T=>T.sources.some(k=>typeof k.matchCommand=="function")),r=T=>o.some(k=>k.trigger?k.position==="line-start"?T.split(`
196
- `).some(G=>G.startsWith(k.trigger)):(k.position==="anywhere"?T:T.split(`
197
- `)[0]).startsWith(k.trigger):!1),s=(T,k)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:k}))}catch{}},i=we("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,c=t.textarea,d=null,u=null,b=null,f=null,m=()=>{if(l)return Promise.resolve(l);if(p)return p;let T=Vl().then(k=>(l=k.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:d??void 0,anchor:t.anchor,contextRow:i,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:L,emit:s}),l)).catch(k=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",k),p===T&&(p=null),null));return p=T,T},C=()=>{qu().then(T=>{let k=T.mountInlineComposer({textarea:t.textarea,renderToken:G=>xs(G,{render:e.renderMentionToken}),onMentionRemoved:G=>l?.untrackMention(G)});d=k.input,u=k.destroy;let $=c;$.replaceWith(k.element),c=k.element,f={next:k.element,prev:$},b?.(k.element,$),l?l.rebindComposer(k.input):p&&p.then(G=>G?.rebindComposer(k.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};e.display==="inline"&&C();let R=[],H=new Map;for(let T of n){if(!T.showButton)continue;let k=uu({config:{...e,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},buttonSize:t.config.sendButton?.size,onOpen:()=>{m().then($=>$?.openMenu(T.trigger))}});R.push(k),H.set(T.trigger,k.button)}let L=(T,k,$)=>{let G=H.get(k);G&&(G.setAttribute("aria-expanded",T?"true":"false"),T?G.setAttribute("aria-controls",$):G.removeAttribute("aria-controls"))};return{affordanceButtons:R.map(T=>T.wrapper),contextRow:i,handleInput:T=>{if(l){l.handleInput();return}if(!cu(T))return;let k=c,$=k.selectionStart??0;ms(k.value,$,n)&&m().then(G=>G?.handleInput())},handleKeydown:T=>{if(l?.isMenuOpen())return l.handleKeydown(T);if(T.key==="Backspace"&&l?.hasMentions()&&!f){let k=c,$=k.selectionStart===0&&k.selectionEnd===0;if((k.value.length===0||$)&&l.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async T=>r(T)?(l??await m())?.dispatchInlineCommand(T)??null:null,clear:()=>l?.clear(),prefetch:()=>{Vl().catch(()=>{})},onComposerSwap:T=>{b=T,f&&T(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let T of R)T.wrapper.remove();i.remove()}}}var Gu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Cs(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];Gu(s)&&Gu(r)?n[o]=Cs(s,r):n[o]=r}return n}var Vn="min(440px, calc(100vw - 24px))",Xu="440px",Ry={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:Vn,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)"},lt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Ry,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:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",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 Qu(t,e){if(!(!t&&!e))return t?e?Cs(t,e):t:e}function oa(t){return t?{...lt,...t,theme:Qu(lt.theme,t.theme),darkTheme:Qu(lt.darkTheme,t.darkTheme),launcher:{...lt.launcher,...t.launcher,dock:{...lt.launcher?.dock,...t.launcher?.dock},clearChat:{...lt.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...lt.copy,...t.copy},sendButton:{...lt.sendButton,...t.sendButton},statusIndicator:{...lt.statusIndicator,...t.statusIndicator},voiceRecognition:{...lt.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=lt.features?.artifacts,n=t.features?.artifacts,o=lt.features?.scrollToBottom,r=t.features?.scrollToBottom,s=lt.features?.scrollBehavior,i=t.features?.scrollBehavior,l=lt.features?.streamAnimation,p=t.features?.streamAnimation,c=lt.features?.askUserQuestion,d=t.features?.askUserQuestion,u=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&i===void 0?void 0:{...s,...i},m=l===void 0&&p===void 0?void 0:{...l,...p},C=c===void 0&&d===void 0?void 0:{...c,...d,styles:{...c?.styles,...d?.styles}};return{...lt.features,...t.features,...b!==void 0?{scrollToBottom:b}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...m!==void 0?{streamAnimation:m}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:t.suggestionChips??lt.suggestionChips,suggestionChipsConfig:{...lt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...lt.layout,...t.layout,header:{...lt.layout?.header,...t.layout?.header},messages:{...lt.layout?.messages,...t.layout?.messages,avatar:{...lt.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...lt.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...lt.layout?.slots,...t.layout?.slots}},markdown:{...lt.markdown,...t.markdown,options:{...lt.markdown?.options,...t.markdown?.options}},messageActions:{...lt.messageActions,...t.messageActions}}:lt}var ra="16px",sa="transparent",Wy={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"}},Hy={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"}},By={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",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",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:Vn,maxWidth:Xu,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ra,canvasBackground:sa},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:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.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:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",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 Yt(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Yt(t,o):o}function Ju(t){let e={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let p=Yt(t,i);p!==void 0&&(e[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&n(i,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function Dy(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function Yu(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Yu(s,r):n[o]=r}return n}function Ny(t,e){return e?Yu(t,e):t}function yr(t,e={}){let n={palette:Wy,semantic:Hy,components:By},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:Ny(n.components,t?.components)};if(e.validate!==!1){let r=Dy(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(e.plugins)for(let r of e.plugins)o=r.transform(o);return o}function Zu(t){let e=Ju(t),n={};for(let[w,F]of Object.entries(e)){let D=w.replace(/\./g,"-");n[`--persona-${D}`]=F.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??ra,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??sa,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=t.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let c=t.components,d=c?.iconButton;d&&(d.background&&(n["--persona-icon-btn-bg"]=d.background),d.border&&(n["--persona-icon-btn-border"]=d.border),d.color&&(n["--persona-icon-btn-color"]=d.color),d.padding&&(n["--persona-icon-btn-padding"]=d.padding),d.borderRadius&&(n["--persona-icon-btn-radius"]=d.borderRadius),d.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=d.hoverBackground),d.hoverColor&&(n["--persona-icon-btn-hover-color"]=d.hoverColor),d.activeBackground&&(n["--persona-icon-btn-active-bg"]=d.activeBackground),d.activeBorder&&(n["--persona-icon-btn-active-border"]=d.activeBorder));let u=c?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let b=c?.toggleGroup;b&&(b.gap&&(n["--persona-toggle-group-gap"]=b.gap),b.borderRadius&&(n["--persona-toggle-group-radius"]=b.borderRadius));let f=c?.artifact;if(f?.toolbar){let w=f.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Yt(t,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(f?.tab){let w=f.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(f?.pane){let w=f.pane;if(w.toolbarBackground){let F=Yt(t,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=F}}if(f?.card){let w=f.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(f?.inline){let w=f.inline;w.background&&(n["--persona-artifact-inline-bg"]=Yt(t,w.background)??w.background),w.border&&(n["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(n["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Yt(t,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Yt(t,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Yt(t,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Yt(t,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let m=c?.code;m&&(m.keywordColor&&(n["--persona-code-keyword-color"]=m.keywordColor),m.stringColor&&(n["--persona-code-string-color"]=m.stringColor),m.commentColor&&(n["--persona-code-comment-color"]=m.commentColor),m.numberColor&&(n["--persona-code-number-color"]=m.numberColor),m.tagColor&&(n["--persona-code-tag-color"]=m.tagColor),m.attrColor&&(n["--persona-code-attr-color"]=m.attrColor),m.propertyColor&&(n["--persona-code-property-color"]=m.propertyColor),m.lineNumberColor&&(n["--persona-code-line-number-color"]=m.lineNumberColor),m.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=m.gutterBorderColor),m.background&&(n["--persona-code-bg"]=Yt(t,m.background)??m.background));let C=n["--persona-surface"],R=n["--persona-container"],H=n["--persona-palette-colors-gray-100"]??"#f3f4f6",L=n["--persona-palette-colors-gray-200"]??"#e5e7eb",T=n["--persona-palette-colors-gray-300"]??"#d1d5db",k=!R||R===C,$=k?H:R,G=k?L:R;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??$,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??G,k&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??T),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??$,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??$,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??$,n}var Oy={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"}}},ef=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},ec=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Fy=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":ec()},tf=t=>Fy(t),_y=t=>yr(t),$y=t=>yr({...t,palette:{...t?.palette,colors:{...Oy.colors,...t?.palette?.colors}}},{validate:!1}),br=t=>{let e=tf(t),n=ef(t?.theme),o=ef(t?.darkTheme);return e==="dark"?$y(Cs(n??{},o??{})):_y(n)},zy=t=>Zu(t),ws=(t,e)=>{let n=br(e),o=zy(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",tf(e))},ia=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(ec())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(ec());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};St();tt();function Pn(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function nf(t){let e=Pn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function aa(t){if(typeof t!="string")return"";let e=t.indexOf(`
195
+ `),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,p=r.contentParts.length>0;if(l){let c=[];s&&c.push(yr(s)),c.push(...r.contentParts),c.push(...e.contentParts),e.contentParts=c}else if(p){let c=[];i&&c.push(yr(i)),c.push(...r.contentParts),e.contentParts=c}else s&&(e.llmContent=i);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=$i(),s=hr();this.activeAssistantMessageId=null;let i=n?.contentParts&&cu(n.contentParts)?zi:"",l={id:r,role:"user",content:o||i,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let d=this.messages.find(u=>u.id===r)??l;if(await this.applyMentionBundle(d,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!u){let b=Fl(d,this.config.errorMessage);if(b){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(d instanceof Error?this.callbacks.onError?.(d):this.callbacks.onError?.(new Error(String(d))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let e=hr();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=Fl(r,this.config.errorMessage);if(i){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},i=this.messages.find(d=>d.id===r),l={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,c=p&&typeof p=="object"?p.onDecision:void 0;try{let d;if(c?d=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):d=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),d){let u=null;if(d instanceof Response){if(!d.ok){let b=await d.json().catch(()=>null);throw new Error(b?.error??`Approval request failed: ${d.status}`)}u=d.body}else d instanceof ReadableStream&&(u=d);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.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(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(d=>d.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let d=e.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===1){let b=typeof u[0]?.question=="string"?u[0].question:"";b&&(i={[b]:n})}}this.markAskUserQuestionResolved(e,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,p=e.toolCall?.args,c=Array.isArray(p?.questions)?p.questions:[];if(c.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([u,b])=>`${u}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let d=i??{};c.forEach((u,b)=>{let g=typeof u?.question=="string"?u.question:"";if(!g)return;let h=d[g],C=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";this.appendMessage({id:`ask-user-q-${l}-${b}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${b}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let d=await this.client.resumeFlow(r,{[s]:n});if(!d.ok){let u=await d.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${d.status}`)}d.body?await this.connectStream(d.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==qn?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),s){this.messages.some(i=>i.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let i=await Promise.all(n.map(async p=>{let c=p.toolCall?.name,d=p.toolCall?.id;if(!c||!d)return null;let u=`${e}:${d}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let b=this.markWebMcpToolRunning(p),g=p.agentMetadata?.webMcpToolCallId??c;if(c===qn)return{dedupeKey:u,resumeKey:g,output:Rl(),toolMessage:p,startedAt:b,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),r.push(h);let C=this.client.executeWebMcpToolCall(c,p.toolCall?.args,h.signal),L;if(!C)L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{L=await C}catch(B){let k=B instanceof Error&&(B.name==="AbortError"||B.message.includes("aborted")||B.message.includes("abort"));return k||this.callbacks.onError?.(B instanceof Error?B:new Error(String(B))),this.markWebMcpToolComplete(p,Cs(k?"Aborted by cancel()":Su(B)),b),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,Cs("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:g,output:L,toolMessage:p,startedAt:b,completedAt:Date.now()}})),l=[];try{if(l=i.filter(d=>d!==null),l.length===0)return;let p={};for(let d of l)p[d.resumeKey]=d.output;let c=await this.client.resumeFlow(e,p,{signal:s.signal});if(!c.ok){let d=await c.json().catch(()=>null);throw new Error(d?.error??`Resume failed: ${c.status}`)}for(let d of l)this.webMcpResolvedKeys.add(d.dedupeKey),this.markWebMcpToolComplete(d.toolMessage,d.output,d.startedAt,d.completedAt,d.toolMessage.toolCall?.name===qn?{suggestRepliesResolved:!0}:void 0);c.body&&await this.connectStream(c.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let d of l)this.markWebMcpToolComplete(d.toolMessage,Cs("Aborted by cancel()"),d.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let h=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(h)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(h)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let i=this.markWebMcpToolRunning(e),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let c=o===qn,d=e.toolCall?.args,u=c?null:this.client.executeWebMcpToolCall(o,d,p),b="execute",g=i;try{let h;if(c?h=Rl():u?h=await u:h={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),p.aborted){this.markWebMcpToolComplete(e,Cs("Aborted by cancel()"),i);return}let C=e.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,C,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,h,i,g,c?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let C=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(b==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(e,Cs(C||p.aborted?"Aborted by cancel()":Su(h)),i),C||this.callbacks.onError?.(h instanceof Error?h:new Error(String(h)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal});if(!s.ok){let i=await s.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=uo(this.config.features?.artifacts,e),r=ds(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),s=this.messages.find(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=uo(this.config.features?.artifacts,n),s=ds(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Au(),wu)).then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>Fl(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=hr(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=Nl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return ji(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=Nl(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let i={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let d=r.approval,u=n.approval;i.approval={...d,...u,executionId:u.executionId||d.executionId,toolName:u.toolName||d.toolName,description:u.description||d.description,toolType:u.toolType??d.toolType,reason:u.reason??d.reason,parameters:u.parameters??d.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,c=n.toolCall?.id;if(l&&Mu(l)&&p&&c&&n.agentMetadata?.awaitingLocalTool===!0){let d=`${p}:${c}`,u=this.webMcpInflightKeys.has(d),b=this.webMcpResolvedKeys.has(d),g=r.toolCall?.name,h=r.agentMetadata?.executionId===p&&r.toolCall?.id===c&&g!==void 0&&Mu(g)&&r.toolCall?.status==="complete";(u||b||h)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};Je();wt();var Gi={allowedTypes:Kn,maxFileSize:10*1024*1024,maxFiles:4};function Py(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Iy(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var ws=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??Gi.allowedTypes,maxFileSize:e.maxFileSize??Gi.maxFileSize,maxFiles:e.maxFiles??Gi.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Gi.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(e.length){for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=uu(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await pu(n),s=Ui(n)?URL.createObjectURL(n):null,i={id:Py(),file:n,previewUrl:s,contentPart:r};this.attachments.push(i),this.renderPreview(i)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=Ui(e.file),o=v("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let i=v("img");i.src=e.previewUrl,i.alt=e.file.name,i.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",o.appendChild(i)}else{let i=v("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--persona-container, #f3f4f6)",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let l=Iy(e.file.type),p=ae(l,20,"var(--persona-muted, #6b7280)",1.5);p&&i.appendChild(p);let c=v("span");c.textContent=gu(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",i.appendChild(c),o.appendChild(i)}let r=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ae("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n})}};Je();Qi();_l();Je();wt();var Wt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Qt=1e5,Ji=Qt+1;var Hy=8,By=8,$l=10,zl=new WeakMap,Lu=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,Dy=t=>{let e=t.getRootNode?.();return Lu(e)?e:t.ownerDocument.body},Ul=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n));function Ut(t){zl.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,enabled:r=!0,gap:s=Hy,viewportPadding:i=By}=t,l=()=>e.ownerDocument,p=()=>l().defaultView??window,c=null,d=null,u=null,b=!1,g=!1,h=!1,C=()=>(typeof o=="function"?o():o).trim(),L=()=>{u?.(),u=null,c?.remove(),c=null,d=null},B=()=>{if(!c)return;let W=l(),P=p(),I=e.getBoundingClientRect(),j=c.getBoundingClientRect(),pe=W.documentElement.clientWidth||P.innerWidth,ge=W.documentElement.clientHeight||P.innerHeight,se=pe-i-j.width,Y=I.left+I.width/2-j.width/2,oe=Ul(Y,i,se),J=I.top-i,ie=ge-i-I.bottom,ee=j.height+s,fe=J>=ee||J>=ie?"top":"bottom",be=fe==="top"?I.top-s-j.height:I.bottom+s,he=ge-i-j.height,we=Ul(be,i,he),ve=I.left+I.width/2,Te=Math.max($l,j.width-$l),Me=Ul(ve-oe,$l,Te);c.dataset.placement=fe,c.style.left=`${oe}px`,c.style.top=`${we}px`,c.style.setProperty("--persona-tooltip-arrow-x",`${Me}px`)},k=()=>{if(h||!r||c||!e.isConnected)return;let W=C(),P=Dy(e);if(!W||!P)return;let I=l(),j=p();c=I.createElement("div"),c.className="persona-control-tooltip",c.setAttribute("role","tooltip"),c.dataset.state="measuring",c.style.zIndex=String(Ji),d=I.createElement("span"),d.className="persona-control-tooltip__label",d.textContent=W,c.appendChild(d);let pe=I.createElement("span");pe.className="persona-control-tooltip__arrow",c.appendChild(pe),P.appendChild(c),B(),c.dataset.state="open";let ge=()=>{if(!e.isConnected){L();return}d&&(d.textContent=C()),B()};j.addEventListener("scroll",ge,!0),j.addEventListener("resize",ge);let se=e.getRootNode(),Y=Lu(se)?se:I.documentElement,oe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||L()});oe?.observe(Y,{childList:!0,subtree:!0}),u=()=>{j.removeEventListener("scroll",ge,!0),j.removeEventListener("resize",ge),oe?.disconnect()}},S=()=>{b||g?k():L()},E=()=>{let W=p();(!W.matchMedia||!W.matchMedia("(hover: none)").matches)&&(b=!0,S())},z=()=>{b=!1,S()},G=()=>{g=!0,S()},A=()=>{g=!1,S()},O=W=>{W.key==="Escape"&&(b=!1,g=!1,L())};n.addEventListener("mouseenter",E),n.addEventListener("mouseleave",z),e.addEventListener("focus",G),e.addEventListener("blur",A),e.addEventListener("keydown",O);let D={get isOpen(){return c!==null},show:k,hide:L,reposition:B,destroy:()=>{h||(h=!0,L(),n.removeEventListener("mouseenter",E),n.removeEventListener("mouseleave",z),e.removeEventListener("focus",G),e.removeEventListener("blur",A),e.removeEventListener("keydown",O),zl.delete(e))}};return zl.set(e,D),D}function Pu(t){let{config:e,onOpen:n}=t,o=t.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),i=e.buttonIconName??"plus",l=e.buttonTooltipText??"Add context",p=v("div","persona-send-button-wrapper"),c=Ce("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),d=ae(i,s,"currentColor",1.5);return d?c.appendChild(d):c.textContent="+",c.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(c),Ut({anchor:c,trigger:p,text:()=>c.getAttribute("aria-label")??l}),{button:c,wrapper:p}}var{setLoader:yA,load:jy}=lr({fallbackImport:()=>Promise.resolve().then(()=>(Ju(),Xu))});var Xl=jy;var{setLoader:LA,load:eb}=lr({fallbackImport:()=>Promise.resolve().then(()=>(cg(),lg)),resetOnSetLoader:!0});var dg=eb;Je();wt();function ks(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=Ce("span",{className:Vn("persona-mention-token",e.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":t.sourceId,title:t.label,role:"img","aria-label":`${t.label} mention`}});t.color&&n.style.setProperty("--persona-mention-token-accent",t.color);let o=ae(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Ce("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function pg(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=Xi(e).filter(S=>S.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(S=>S.sources.some(E=>typeof E.matchCommand=="function")),r=S=>o.some(E=>E.trigger?E.position==="line-start"?S.split(`
196
+ `).some(G=>G.startsWith(E.trigger)):(E.position==="anywhere"?S:S.split(`
197
+ `)[0]).startsWith(E.trigger):!1),s=(S,E)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${S}`,{detail:E}))}catch{}},i=Ce("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,c=t.textarea,d=null,u=null,b=null,g=null,h=()=>{if(l)return Promise.resolve(l);if(p)return p;let S=Xl().then(E=>(l=E.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:d??void 0,anchor:t.anchor,contextRow:i,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:k,emit:s}),l)).catch(E=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",E),p===S&&(p=null),null));return p=S,S},C=()=>{dg().then(S=>{let E=S.mountInlineComposer({textarea:t.textarea,renderToken:G=>ks(G,{render:e.renderMentionToken}),onMentionRemoved:G=>l?.untrackMention(G)});d=E.input,u=E.destroy;let z=c;z.replaceWith(E.element),c=E.element,g={next:E.element,prev:z},b?.(E.element,z),l?l.rebindComposer(E.input):p&&p.then(G=>G?.rebindComposer(E.input))}).catch(S=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",S)})};e.display==="inline"&&C();let L=[],B=new Map;for(let S of n){if(!S.showButton)continue;let E=Pu({config:{...e,buttonIconName:S.buttonIconName,buttonTooltipText:S.buttonTooltipText},buttonSize:t.config.sendButton?.size,onOpen:()=>{h().then(z=>z?.openMenu(S.trigger))}});L.push(E),B.set(S.trigger,E.button)}let k=(S,E,z)=>{let G=B.get(E);G&&(G.setAttribute("aria-expanded",S?"true":"false"),S?G.setAttribute("aria-controls",z):G.removeAttribute("aria-controls"))};return{affordanceButtons:L.map(S=>S.wrapper),contextRow:i,handleInput:S=>{if(l){l.handleInput();return}if(!Eu(S))return;let E=c,z=E.selectionStart??0;As(E.value,z,n)&&h().then(G=>G?.handleInput())},handleKeydown:S=>{if(l?.isMenuOpen())return l.handleKeydown(S);if(S.key==="Backspace"&&l?.hasMentions()&&!g){let E=c,z=E.selectionStart===0&&E.selectionEnd===0;if((E.value.length===0||z)&&l.removeLastChip())return S.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async S=>r(S)?(l??await h())?.dispatchInlineCommand(S)??null:null,clear:()=>l?.clear(),prefetch:()=>{Xl().catch(()=>{})},onComposerSwap:S=>{b=S,g&&S(g.next,g.prev)},destroy:()=>{l?.destroy(),u?.();for(let S of L)S.wrapper.remove();i.remove()}}}var ug=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Ls(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];ug(s)&&ug(r)?n[o]=Ls(s,r):n[o]=r}return n}var Gn="min(440px, calc(100vw - 24px))",fg="440px",tb={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)"},it={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:tb,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:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",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:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],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 gg(t,e){if(!(!t&&!e))return t?e?Ls(t,e):t:e}function ca(t){return t?{...it,...t,theme:gg(it.theme,t.theme),darkTheme:gg(it.darkTheme,t.darkTheme),launcher:{...it.launcher,...t.launcher,dock:{...it.launcher?.dock,...t.launcher?.dock},clearChat:{...it.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...it.copy,...t.copy},sendButton:{...it.sendButton,...t.sendButton},statusIndicator:{...it.statusIndicator,...t.statusIndicator},voiceRecognition:{...it.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=it.features?.artifacts,n=t.features?.artifacts,o=it.features?.scrollToBottom,r=t.features?.scrollToBottom,s=it.features?.scrollBehavior,i=t.features?.scrollBehavior,l=it.features?.streamAnimation,p=t.features?.streamAnimation,c=it.features?.askUserQuestion,d=t.features?.askUserQuestion,u=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},g=s===void 0&&i===void 0?void 0:{...s,...i},h=l===void 0&&p===void 0?void 0:{...l,...p},C=c===void 0&&d===void 0?void 0:{...c,...d,styles:{...c?.styles,...d?.styles}};return{...it.features,...t.features,...b!==void 0?{scrollToBottom:b}:{},...g!==void 0?{scrollBehavior:g}:{},...u!==void 0?{artifacts:u}:{},...h!==void 0?{streamAnimation:h}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:t.suggestionChips??it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...it.layout,...t.layout,header:{...it.layout?.header,...t.layout?.header},messages:{...it.layout?.messages,...t.layout?.messages,avatar:{...it.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...it.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...it.layout?.slots,...t.layout?.slots}},markdown:{...it.markdown,...t.markdown,options:{...it.markdown?.options,...t.markdown?.options}},messageActions:{...it.messageActions,...t.messageActions}}:it}var da="16px",pa="transparent",nb={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"}},ob={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"}},rb={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",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",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:fg,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:da,canvasBackground:pa},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:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.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:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",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 en(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?en(t,o):o}function mg(t){let e={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let p=en(t,i);p!==void 0&&(e[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&n(i,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function sb(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function hg(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=hg(s,r):n[o]=r}return n}function ib(t,e){return e?hg(t,e):t}function Cr(t,e={}){let n={palette:nb,semantic:ob,components:rb},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:ib(n.components,t?.components)};if(e.validate!==!1){let r=sb(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(e.plugins)for(let r of e.plugins)o=r.transform(o);return o}function yg(t){let e=mg(t),n={};for(let[A,O]of Object.entries(e)){let D=A.replace(/\./g,"-");n[`--persona-${D}`]=O.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??da,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??pa,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=t.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let c=t.components,d=c?.iconButton;d&&(d.background&&(n["--persona-icon-btn-bg"]=d.background),d.border&&(n["--persona-icon-btn-border"]=d.border),d.color&&(n["--persona-icon-btn-color"]=d.color),d.padding&&(n["--persona-icon-btn-padding"]=d.padding),d.borderRadius&&(n["--persona-icon-btn-radius"]=d.borderRadius),d.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=d.hoverBackground),d.hoverColor&&(n["--persona-icon-btn-hover-color"]=d.hoverColor),d.activeBackground&&(n["--persona-icon-btn-active-bg"]=d.activeBackground),d.activeBorder&&(n["--persona-icon-btn-active-border"]=d.activeBorder));let u=c?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let b=c?.toggleGroup;b&&(b.gap&&(n["--persona-toggle-group-gap"]=b.gap),b.borderRadius&&(n["--persona-toggle-group-radius"]=b.borderRadius));let g=c?.artifact;if(g?.toolbar){let A=g.toolbar;A.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=A.iconHoverColor),A.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=A.iconHoverBackground),A.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=A.iconPadding),A.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=A.iconBorderRadius),A.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=A.iconBorder),A.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=A.toggleGroupGap),A.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=A.toggleBorderRadius),A.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=A.toggleGroupPadding),A.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=A.toggleGroupBorder),A.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=A.toggleGroupBorderRadius),A.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=en(t,A.toggleGroupBackground)??A.toggleGroupBackground),A.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=A.copyBackground),A.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=A.copyBorder),A.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=A.copyColor),A.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=A.copyBorderRadius),A.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=A.copyPadding),A.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=A.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??A.copyMenuBackground),A.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=A.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??A.copyMenuBorder),A.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=A.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??A.copyMenuShadow),A.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=A.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??A.copyMenuBorderRadius),A.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=A.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??A.copyMenuItemHoverBackground),A.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=A.iconBackground),A.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=A.toolbarBorder)}if(g?.tab){let A=g.tab;A.background&&(n["--persona-artifact-tab-bg"]=A.background),A.activeBackground&&(n["--persona-artifact-tab-active-bg"]=A.activeBackground),A.activeBorder&&(n["--persona-artifact-tab-active-border"]=A.activeBorder),A.borderRadius&&(n["--persona-artifact-tab-radius"]=A.borderRadius),A.textColor&&(n["--persona-artifact-tab-color"]=A.textColor),A.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=A.hoverBackground),A.listBackground&&(n["--persona-artifact-tab-list-bg"]=A.listBackground),A.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=A.listBorderColor),A.listPadding&&(n["--persona-artifact-tab-list-padding"]=A.listPadding)}if(g?.pane){let A=g.pane;if(A.toolbarBackground){let O=en(t,A.toolbarBackground)??A.toolbarBackground;n["--persona-artifact-toolbar-bg"]=O}}if(g?.card){let A=g.card;A.background&&(n["--persona-artifact-card-bg"]=A.background),A.border&&(n["--persona-artifact-card-border"]=A.border),A.borderRadius&&(n["--persona-artifact-card-radius"]=A.borderRadius),A.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=A.hoverBackground),A.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=A.hoverBorderColor)}if(g?.inline){let A=g.inline;A.background&&(n["--persona-artifact-inline-bg"]=en(t,A.background)??A.background),A.border&&(n["--persona-artifact-inline-border"]=A.border),A.borderRadius&&(n["--persona-artifact-inline-radius"]=A.borderRadius),A.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=en(t,A.chromeBackground)??A.chromeBackground),A.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=en(t,A.chromeBorder)??A.chromeBorder),A.titleColor&&(n["--persona-artifact-inline-title-color"]=en(t,A.titleColor)??A.titleColor),A.mutedColor&&(n["--persona-artifact-inline-muted-color"]=en(t,A.mutedColor)??A.mutedColor),A.frameHeight&&(n["--persona-artifact-inline-frame-height"]=A.frameHeight)}let h=c?.code;h&&(h.keywordColor&&(n["--persona-code-keyword-color"]=h.keywordColor),h.stringColor&&(n["--persona-code-string-color"]=h.stringColor),h.commentColor&&(n["--persona-code-comment-color"]=h.commentColor),h.numberColor&&(n["--persona-code-number-color"]=h.numberColor),h.tagColor&&(n["--persona-code-tag-color"]=h.tagColor),h.attrColor&&(n["--persona-code-attr-color"]=h.attrColor),h.propertyColor&&(n["--persona-code-property-color"]=h.propertyColor),h.lineNumberColor&&(n["--persona-code-line-number-color"]=h.lineNumberColor),h.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=h.gutterBorderColor),h.background&&(n["--persona-code-bg"]=en(t,h.background)??h.background));let C=n["--persona-surface"],L=n["--persona-container"],B=n["--persona-palette-colors-gray-100"]??"#f3f4f6",k=n["--persona-palette-colors-gray-200"]??"#e5e7eb",S=n["--persona-palette-colors-gray-300"]??"#d1d5db",E=!L||L===C,z=E?B:L,G=E?k:L;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??z,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??G,E&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??S),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??z,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??z,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??z,n}var ab={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"}}},bg=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},sc=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",lb=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":sc()},vg=t=>lb(t),cb=t=>Cr(t),db=t=>Cr({...t,palette:{...t?.palette,colors:{...ab.colors,...t?.palette?.colors}}},{validate:!1}),wr=t=>{let e=vg(t),n=bg(t?.theme),o=bg(t?.darkTheme);return e==="dark"?db(Ls(n??{},o??{})):cb(n)},pb=t=>yg(t),Ps=(t,e)=>{let n=wr(e),o=pb(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",vg(e))},ua=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(sc())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(sc());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};wt();Je();function Wn(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function xg(t){let e=Wn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function ga(t){if(typeof t!="string")return"";let e=t.indexOf(`
198
198
  `);if(e===-1||!t.slice(0,e).startsWith("```"))return t;let o=t.slice(e+1),r=o.lastIndexOf(`
199
- `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function As(t){let e=nf(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function go(t){switch(As(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=nf(t.path);return e?e.toUpperCase():"File"}}}function of(t){let e=t.markdown??"";return t.file?{filename:Pn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:aa(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}tt();tt();var tc="http://www.w3.org/2000/svg";function rf(t){let e=document.createElementNS(tc,"svg");e.setAttribute("class",zn("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(tc,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(tc,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}tt();tt();var mo=(t,e,n)=>{let o=n;for(let r of e){let s=y("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o};function sf(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),mo(t,e,0)}var nc="persona-artifact-status-label",af="persona-artifact-status-detail",lf="data-artifact-status-label",oc=new Map,cf=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function vr(t){t&&oc.delete(t)}function jy(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?go(e):t.artifactType==="component"?"Component":"Document"}function xr(t,e,n){let o=jy(t),r=`Generating ${o.toLowerCase()}...`,s=e?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let i=t.id,l=oc.get(i);t.status!=="complete"&&l===void 0&&(l=cf(),oc.set(i,l));let p=l===void 0?0:Math.max(0,cf()-l),c=t.artifactType==="component",d=!c&&typeof t.markdown=="string"?t.markdown:"",u=c?0:d.length,b=c||d===""?0:d.split(`
200
- `).length,f=t.artifactType==="markdown"?t.file:void 0,m={artifactId:i,artifactType:t.artifactType,title:t.title,typeLabel:o,file:f,chars:u,lines:b,elapsedMs:p,content:()=>c?"":d,surface:n};try{let C=s(m);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function Uy(t){t.className=nc,t.removeAttribute("data-preserve-animation"),t.style.removeProperty("--persona-tool-anim-duration"),t.style.removeProperty("--persona-tool-anim-color"),t.style.removeProperty("--persona-tool-anim-secondary-color"),t.replaceChildren()}function No(t,e,n){let o=t.querySelector(`:scope > .${nc}`);o||(o=y("span",nc),t.appendChild(o)),o.getAttribute(lf)!==e.label&&(Uy(o),sf(o,e.label,n),o.setAttribute(lf,e.label));let r=t.querySelector(`:scope > .${af}`),s=e.detail;s?(r||(r=y("span",af),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}tt();var Vy={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},qy=15e4,la={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function Ky(t,e){let n=(t||"").trim().toLowerCase();if(n&&la[n])return la[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(la[r])return la[r]}}return null}function ca(t,e){let n=[],o=0,r=0,s=i=>{i>r&&n.push({type:"plain",value:t.slice(r,i)})};for(;o<t.length;){let i=!1;for(let l of e){l.re.lastIndex=o;let p=l.re.exec(t);if(p&&p.index===o&&p[0].length>0){s(o);let c=l.map?l.map(p[0]):l.type;n.push({type:c,value:p[0]}),o+=p[0].length,r=o,i=!0;break}}i||(o+=1)}return s(t.length),n}var Gy=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),Qy=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:t=>Gy.has(t)?"keyword":"plain"}];function df(t){return ca(t,Qy)}var Xy=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:t=>t==="true"||t==="false"||t==="null"?"keyword":"plain"}];function Jy(t){let e=ca(t,Xy);for(let n=0;n<e.length;n+=1){if(e[n].type!=="string")continue;let o=n+1;for(;o<e.length&&e[o].value.trim()==="";)o+=1;let r=e[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(e[n].type="property")}return e}var Yy=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function pf(t){let e=ca(t,Yy),n="";for(let o=0;o<e.length;o+=1){let r=e[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let i=o+1;for(;i<e.length&&e[i].value.trim()==="";)i+=1;let l=e[i];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return e}var Zy=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function eb(t){let e=[],n=(s,i)=>{i&&e.push({type:s,value:i})},o=t.length,r=0;for(;r<o;){if(t.startsWith("<!--",r)){let i=t.indexOf("-->",r+4),l=i===-1?o:i+3;n("comment",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&t[r+1]==="!"){let i=t.indexOf(">",r),l=i===-1?o:i+1;n("tag",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&/[A-Za-z/]/.test(t[r+1]||"")){let i=t.indexOf(">",r),l=i===-1?o:i+1,p=t.slice(r,l);for(let d of ca(p,Zy))e.push(d);r=l;let c=/^<\s*(script|style)\b/i.exec(p);if(c&&!/\/>\s*$/.test(p)){let d=c[1].toLowerCase(),b=new RegExp("</\\s*"+d+"\\s*>","i").exec(t.slice(r)),f=b?r+b.index:o,m=t.slice(r,f),C=d==="script"?df(m):pf(m);for(let R of C)e.push(R);r=f}continue}let s=t.indexOf("<",r);if(s===r)n("plain",t[r]),r+=1;else{let i=s===-1?o:s;n("plain",t.slice(r,i)),r=i}}return e}function tb(t,e){switch(e){case"html":return eb(t);case"css":return pf(t);case"js":return df(t);case"json":return Jy(t)}}function nb(t){let e=Cp(),n=y("span","persona-code-line"),o=(r,s)=>{if(!s)return;let i=Vy[r];if(i){let l=y("span",i);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
199
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Is(t){let e=xg(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function bo(t){switch(Is(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=xg(t.path);return e?e.toUpperCase():"File"}}}function Cg(t){let e=t.markdown??"";return t.file?{filename:Wn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:ga(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}Je();Je();var ic="http://www.w3.org/2000/svg";function wg(t){let e=document.createElementNS(ic,"svg");e.setAttribute("class",Vn("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(ic,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(ic,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}Je();Je();var vo=(t,e,n)=>{let o=n;for(let r of e){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o};function Ag(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),vo(t,e,0)}var ac="persona-artifact-status-label",Sg="persona-artifact-status-detail",Mg="data-artifact-status-label",lc=new Map,Tg=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Ar(t){t&&lc.delete(t)}function ub(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?bo(e):t.artifactType==="component"?"Component":"Document"}function Sr(t,e,n){let o=ub(t),r=`Generating ${o.toLowerCase()}...`,s=e?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let i=t.id,l=lc.get(i);t.status!=="complete"&&l===void 0&&(l=Tg(),lc.set(i,l));let p=l===void 0?0:Math.max(0,Tg()-l),c=t.artifactType==="component",d=!c&&typeof t.markdown=="string"?t.markdown:"",u=c?0:d.length,b=c||d===""?0:d.split(`
200
+ `).length,g=t.artifactType==="markdown"?t.file:void 0,h={artifactId:i,artifactType:t.artifactType,title:t.title,typeLabel:o,file:g,chars:u,lines:b,elapsedMs:p,content:()=>c?"":d,surface:n};try{let C=s(h);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function gb(t){t.className=ac,t.removeAttribute("data-preserve-animation"),t.style.removeProperty("--persona-tool-anim-duration"),t.style.removeProperty("--persona-tool-anim-color"),t.style.removeProperty("--persona-tool-anim-secondary-color"),t.replaceChildren()}function $o(t,e,n){let o=t.querySelector(`:scope > .${ac}`);o||(o=v("span",ac),t.appendChild(o)),o.getAttribute(Mg)!==e.label&&(gb(o),Ag(o,e.label,n),o.setAttribute(Mg,e.label));let r=t.querySelector(`:scope > .${Sg}`),s=e.detail;s?(r||(r=v("span",Sg),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}Je();var fb={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},mb=15e4,fa={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function hb(t,e){let n=(t||"").trim().toLowerCase();if(n&&fa[n])return fa[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(fa[r])return fa[r]}}return null}function ma(t,e){let n=[],o=0,r=0,s=i=>{i>r&&n.push({type:"plain",value:t.slice(r,i)})};for(;o<t.length;){let i=!1;for(let l of e){l.re.lastIndex=o;let p=l.re.exec(t);if(p&&p.index===o&&p[0].length>0){s(o);let c=l.map?l.map(p[0]):l.type;n.push({type:c,value:p[0]}),o+=p[0].length,r=o,i=!0;break}}i||(o+=1)}return s(t.length),n}var yb=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),bb=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:t=>yb.has(t)?"keyword":"plain"}];function Eg(t){return ma(t,bb)}var vb=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:t=>t==="true"||t==="false"||t==="null"?"keyword":"plain"}];function xb(t){let e=ma(t,vb);for(let n=0;n<e.length;n+=1){if(e[n].type!=="string")continue;let o=n+1;for(;o<e.length&&e[o].value.trim()==="";)o+=1;let r=e[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(e[n].type="property")}return e}var Cb=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function kg(t){let e=ma(t,Cb),n="";for(let o=0;o<e.length;o+=1){let r=e[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let i=o+1;for(;i<e.length&&e[i].value.trim()==="";)i+=1;let l=e[i];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return e}var wb=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function Ab(t){let e=[],n=(s,i)=>{i&&e.push({type:s,value:i})},o=t.length,r=0;for(;r<o;){if(t.startsWith("<!--",r)){let i=t.indexOf("-->",r+4),l=i===-1?o:i+3;n("comment",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&t[r+1]==="!"){let i=t.indexOf(">",r),l=i===-1?o:i+1;n("tag",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&/[A-Za-z/]/.test(t[r+1]||"")){let i=t.indexOf(">",r),l=i===-1?o:i+1,p=t.slice(r,l);for(let d of ma(p,wb))e.push(d);r=l;let c=/^<\s*(script|style)\b/i.exec(p);if(c&&!/\/>\s*$/.test(p)){let d=c[1].toLowerCase(),b=new RegExp("</\\s*"+d+"\\s*>","i").exec(t.slice(r)),g=b?r+b.index:o,h=t.slice(r,g),C=d==="script"?Eg(h):kg(h);for(let L of C)e.push(L);r=g}continue}let s=t.indexOf("<",r);if(s===r)n("plain",t[r]),r+=1;else{let i=s===-1?o:s;n("plain",t.slice(r,i)),r=i}}return e}function Sb(t,e){switch(e){case"html":return Ab(t);case"css":return kg(t);case"js":return Eg(t);case"json":return xb(t)}}function Mb(t){let e=Fp(),n=v("span","persona-code-line"),o=(r,s)=>{if(!s)return;let i=fb[r];if(i){let l=v("span",i);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
201
201
  `);for(let i=0;i<s.length;i+=1)i>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
202
- `)),n=y("span","persona-code-line")),o(r.type,s[i])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function uf(t,e,n){let o=t.length<=qy?Ky(e,n):null,r=o?tb(t,o):[{type:"plain",value:t}];return nb(r)}tt();St();tt();St();function Cr(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=t,i=y("div","persona-dropdown-menu persona-hidden");i.setAttribute("role","menu"),i.setAttribute("data-persona-theme-zone","dropdown"),s?(i.style.position="fixed",i.style.zIndex=String(Vi)):(i.style.position="absolute",i.style.top="100%",i.style.marginTop="4px",r==="bottom-right"?i.style.right="0":i.style.left="0");for(let f of e){if(f.dividerBefore){let R=document.createElement("hr");i.appendChild(R)}let m=document.createElement("button");if(m.type="button",m.setAttribute("role","menuitem"),m.setAttribute("data-dropdown-item-id",f.id),f.destructive&&m.setAttribute("data-destructive",""),f.icon){let R=ae(f.icon,16,"currentColor",1.5);R&&m.appendChild(R)}let C=document.createElement("span");C.textContent=f.label,m.appendChild(C),m.addEventListener("click",R=>{R.stopPropagation(),d(),n(f.id)}),i.appendChild(m)}let l=null;function p(){if(!s)return;let f=o.getBoundingClientRect();i.style.top=`${f.bottom+4}px`,r==="bottom-right"?(i.style.right=`${window.innerWidth-f.right}px`,i.style.left="auto"):(i.style.left=`${f.left}px`,i.style.right="auto")}function c(){p(),i.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=m=>{!i.contains(m.target)&&!o.contains(m.target)&&d()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function d(){i.classList.add("persona-hidden"),l?.(),l=null}function u(){i.classList.contains("persona-hidden")?c():d()}function b(){d(),i.remove()}return s&&s.appendChild(i),{element:i,show:c,hide:d,toggle:u,destroy:b}}function Ht(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,onClick:i,aria:l}=t,p=y("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let c=ae(e,o??16,"currentColor",r??2);if(c&&p.appendChild(c),i&&p.addEventListener("click",i),l)for(let[d,u]of Object.entries(l))p.setAttribute(d,u);return p}function Oo(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:p}=t,c="persona-label-btn";o!=="default"&&(c+=" persona-label-btn--"+o),c+=" persona-label-btn--"+r,i&&(c+=" "+i);let d=y("button",c);if(d.type="button",d.setAttribute("aria-label",n),e){let b=ae(e,s??14,"currentColor",2);b&&d.appendChild(b)}let u=y("span");if(u.textContent=n,d.appendChild(u),l&&d.addEventListener("click",l),p)for(let[b,f]of Object.entries(p))d.setAttribute(b,f);return d}function da(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=y("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function p(){for(let d of l)d.btn.setAttribute("aria-pressed",d.id===i?"true":"false")}for(let d of e){let u;d.icon?u=Ht({icon:d.icon,label:d.label,className:d.className,onClick:()=>{i=d.id,p(),o(d.id)}}):(u=y("button","persona-icon-btn"+(d.className?" "+d.className:"")),u.type="button",u.setAttribute("aria-label",d.label),u.title=d.label,u.textContent=d.label,u.addEventListener("click",()=>{i=d.id,p(),o(d.id)})),u.setAttribute("aria-pressed",d.id===i?"true":"false"),l.push({id:d.id,btn:u}),s.appendChild(u)}function c(d){i=d,p()}return{element:s,setSelected:c}}function ff(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:p}=t,c=y("div","persona-combo-btn"+(l?" "+l:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let d=y("span","persona-combo-btn-label");d.textContent=e,c.appendChild(d);let u=ae(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),p&&(c.style.borderRadius=p.borderRadius??"10px",c.style.padding=p.padding??"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=p.background??"",c.style.borderColor=p.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let b=Cr({items:o,onSelect:f=>{c.setAttribute("aria-expanded","false"),r(f)},anchor:c,position:s,portal:i});return i||c.appendChild(b.element),c.addEventListener("click",f=>{f.stopPropagation();let m=!b.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",m?"false":"true"),b.toggle()}),c.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),c.click())}),{element:c,setLabel:f=>{d.textContent=f,c.setAttribute("aria-label",f)},open:()=>{c.setAttribute("aria-expanded","true"),b.show()},close:()=>{c.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let f=!b.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",f?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),c.remove()}}}tt();var pa="persona-artifact-custom-action-btn";function wr(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+pa+(n?" persona-artifact-doc-copy-btn":"");o=y("button",r)}else{let r="persona-icon-btn "+pa+(n?" persona-artifact-doc-icon-btn":"");o=y("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=y("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=Oo({icon:t.icon,label:t.label,className:pa+(n?" persona-artifact-doc-copy-btn":"")}):o=Ht({icon:t.icon,label:t.label,className:pa+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function Ss(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}function gf(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?Pn(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",i=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",p=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0,c=n?go(n):l==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&d.setAttribute("data-open-artifact",s);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.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 b=document.createElement("div");b.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let f=document.createElement("div");f.className="persona-truncate persona-text-sm persona-font-medium",f.style.color="var(--persona-text, #1f2937)",f.textContent=r;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",i==="streaming"){let C=e?.config?.features?.artifacts,R={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},H=xr(R,C,"card");No(m,H,C)}else s&&vr(s),m.textContent=c;if(b.append(f,m),d.append(u,b),i==="complete"){let C=e?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let H={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let L of C)try{if(L.visible===void 0||L.visible(H)){let T=wr(L);T.setAttribute("data-artifact-custom-action",L.id),T.className=`${T.className} persona-flex-shrink-0`,d.append(T)}}catch{}}let R=Oo({label:"Download",className:"persona-flex-shrink-0"});R.title=`Download ${r}`,R.setAttribute("data-download-artifact",s),d.append(R)}return d}var ua=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",i=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:e.config,defaultRenderer:()=>gf(t,e)});if(l)return l}return gf(t,e)};tt();St();var ho=new WeakMap;function rc(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=ho.get(r);if(!s)return;let i=o.get(r.getAttribute("data-artifact-inline")??"");i&&s(i,n)})}function vf(t){return ho.has(t)}function ob(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete",r=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0;if(t.artifactType==="component"){let i=t.componentProps,l=i&&typeof i=="object"&&!Array.isArray(i)?i:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:l,...r?{presentation:r}:{}}}let s=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function mf(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?Pn(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?go(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function rb(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}var hf=180,sb=240,ib=.8,ab=300,lb=500,cb="cubic-bezier(0.2, 0, 0, 1)",yf=240,db=.35;function pb(t,e,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let i=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&i.push(l.animate([{opacity:1},{opacity:0}],{duration:hf,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let H of i)H.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let p=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!p||Math.abs(p-e)<1){l(),r();return}let c=Math.abs(e-p),d=Math.round(Math.min(lb,Math.max(ab,sb+c*ib))),u=Math.round(d*db),b=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,f=b?b.animate([{opacity:0},{opacity:1}],{duration:yf,delay:u,easing:"ease-out",fill:"backwards"}):null,m=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:d,easing:cb});t.style.height=`${p}px`;let C=!1,R=()=>{C||(C=!0,l(),r())};Promise.allSettled([m.finished,f?.finished].filter(Boolean)).then(R),window.setTimeout(R,Math.max(d,u+yf)+120)},hf)}function ub(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Ms="--persona-artifact-inline-body-height";function fb(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,i=e?.height;typeof i=="number"||i==="auto"?(r=i,s=i):i&&typeof i=="object"&&(r=i.streaming??320,s=i.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:e?.followOutput!==!1,c,d,u=e?.fadeMask;u===!0?(c=!0,d=!0):u===!1?(c=!1,d=!1):u&&typeof u=="object"?(c=u.top===!0,d=u.bottom===!0):l==="clip"?(c=!1,d=!0):(c=!0,d=!0);let b=e?.transition==="none"?"none":"auto",f=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:c,fadeBottom:d,transition:b,completeDisplay:f}}function bf(t,e){let n=ob(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:i,showViewToggle:l}=ub(o),p=o?.inlineActions??[],c=fb(o),d=c.completeDisplay==="card",u=null,b=n,f=y("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let m=Q=>ua(rb(Q),e),C=Q=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Ms),f.replaceChildren(m(Q)),ho.set(f,se=>{f.replaceChildren(m(se))})};if(d&&n.status==="complete")return C(n),f;let R=fa(n,{config:e.config,bodyLayout:c,resolveViewMode:()=>u??c.viewMode}),H=y("div","persona-artifact-inline-body");H.appendChild(R.el);let L=Q=>{let se=Q.status!=="complete",te=se?c.streamingHeight:c.completeHeight,fe=typeof te=="number";fe?f.style.setProperty(Ms,`${te}px`):f.style.removeProperty(Ms);let be=!!R.el.querySelector(".persona-code-pre"),he=!!R.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");H.classList.toggle("persona-artifact-content-flush",be),H.classList.toggle("persona-artifact-inline-body--sized",fe&&he),H.classList.toggle("persona-artifact-inline-body--cap",!se&&!he&&typeof c.completeHeight=="number")},T=n.status,k=(Q,se)=>{T!=="complete"&&Q.status==="complete"?(typeof c.completeHeight=="number"?f.style.setProperty(Ms,`${c.completeHeight}px`):f.style.removeProperty(Ms),Cf(H,se?.suppressTransition?"none":c.transition,Q.id,()=>{R.update(Q),L(Q)})):R.update(Q),L(Q),T=Q.status};L(n);let $=c.overflow==="clip"&&i&&!!n.id;if($&&(H.setAttribute("data-expand-artifact-inline",n.id),H.setAttribute("role","button"),H.setAttribute("tabindex","0"),H.classList.add("persona-cursor-pointer"),H.setAttribute("aria-label",`Open ${mf(n).title} in panel`)),!r)return f.appendChild(H),ho.set(f,k),f;let G=y("div","persona-artifact-inline-chrome");G.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=y("div","persona-artifact-inline-chrome-lead"),F=y("span","persona-flex persona-items-center persona-flex-shrink-0"),D=ae("file-text",16,"currentColor",2);D&&F.appendChild(D);let B=y("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),P=y("span","persona-artifact-inline-type");w.append(F,B,P);let I=y("div","persona-artifact-inline-chrome-actions"),j=y("span","persona-flex persona-items-center persona-gap-1"),pe=()=>u??c.viewMode,ue=l?da({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:pe(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Q=>{let se=Q==="source"?"source":"rendered";se!==pe()&&(u=se,R.update(b),L(b))}}):null,ge=s?Ht({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ge&&n.id&&ge.setAttribute("data-copy-artifact",n.id);let Z=i?Ht({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Z&&n.id&&Z.setAttribute("data-expand-artifact-inline",n.id),I.appendChild(j),ue&&I.appendChild(ue.element),ge&&I.appendChild(ge),Z&&I.appendChild(Z),G.append(w,I),f.append(G,H);let oe=Q=>{let{title:se,typeLabel:te}=mf(Q);B.textContent=se,B.title=se,$&&H.setAttribute("aria-label",`Open ${se} in panel`);let fe=Q.status!=="complete";if(fe){P.classList.contains("persona-artifact-inline-status")||(P.className="persona-artifact-inline-status",P.removeAttribute("data-preserve-animation"),P.replaceChildren());let be=xr(Q,o,"inline-chrome");No(P,be,o)}else vr(Q.id),P.className="persona-artifact-inline-type",P.removeAttribute("data-preserve-animation"),P.replaceChildren(),P.textContent=te;if(ge&&ge.classList.toggle("persona-hidden",fe),ue){let be=Q.artifactType==="markdown"?Q.file:void 0,he=!1;if(!fe&&be&&c.viewMode!=="source"){let Ce=As(be);Ce==="markdown"?he=!0:(Ce==="html"||Ce==="svg")&&(he=o?.filePreview?.enabled!==!1)}ue.element.classList.toggle("persona-hidden",!he),ue.setSelected(pe())}if(j.replaceChildren(),!fe&&p.length>0){let be=Ss(Q);if(be)for(let he of p)try{if(he.visible===void 0||he.visible(be)){let Ce=wr(he,{documentChrome:!0});Ce.setAttribute("data-artifact-custom-action",he.id),Ce.classList.add("persona-flex-shrink-0"),j.appendChild(Ce)}}catch{}}};return oe(n),ho.set(f,(Q,se)=>{if(d&&T!=="complete"&&Q.status==="complete"){let te=f.isConnected?f.getBoundingClientRect().height:0;T="complete";let fe=Q,be=!1,he=Ce=>{fe=Ce,be=!0};ho.set(f,he),pb(f,te,{swap:()=>{C(fe),be=!1,ho.set(f,he)},onSettled:()=>{be?C(fe):ho.set(f,Ce=>{f.replaceChildren(m(Ce))})}});return}(Q.status!=="complete"||Q.id!==b.id)&&(u=null),b=Q,k(Q,se),oe(Q)}),f}var xf=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",i=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:e.config,defaultRenderer:()=>bf(t,e)});if(l)return l}return bf(t,e)};var sc=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},qn=new sc;qn.register("PersonaArtifactCard",ua,{bubbleChrome:!1});qn.register("PersonaArtifactInline",xf,{bubbleChrome:!1});function Ts(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?aa(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var ic=!1;function gb(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Cf(t,e,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(e!=="auto"||!t||typeof r!="function"||ic||s){o();return}ic=!0;let i=gb(n);t.style.setProperty("view-transition-name",i);let l=()=>{ic=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var mb="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",hb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function yb(t){let e=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(t.props??{},null,2),e.appendChild(n),e.appendChild(o),e}function bb(t){if(t===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let e=t&&typeof t=="object"?t:void 0;return{enabled:!0,delayMs:e?.delayMs??200,minVisibleMs:e?.minVisibleMs??300,timeoutMs:e?.timeoutMs??8e3,injectReadySignal:e?.injectReadySignal!==!1,label:e?.label===!1?!1:e?.label??"Starting preview...",labelDelayMs:e?.labelDelayMs??2e3,renderIndicator:e?.renderIndicator}}var vb=220;function xb(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(2);return crypto.getRandomValues(t),t[0].toString(36)+t[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Cb(t){return`
203
- <script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function wb(t,e,n){let o=y("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let i=n.renderIndicator({artifactId:t,config:e});if(i)return o.appendChild(i),{el:o,revealLabel:()=>{}}}catch{}let r=y("div","persona-artifact-frame-loading-indicator");r.appendChild(rf());let s=null;return n.label!==!1&&(s=y("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function Ab(t,e,n,o,r,s){let i=null,l=0,p=!1,c=new Set,d=()=>{c.forEach(T=>clearTimeout(T)),c.clear()},u=(T,k)=>{let $=setTimeout(()=>{c.delete($),T()},k);c.add($)},b=()=>{i&&i.parentElement&&i.remove(),i=null},f=()=>{if(i||p)return;let T=wb(r,s,o);i=T.el,t.appendChild(i),l=Date.now(),o.label!==!1&&u(T.revealLabel,o.labelDelayMs)},m=()=>{i&&(i.classList.add("persona-artifact-frame-loading--out"),u(b,vb))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",H):e.removeEventListener("load",L)},R=()=>{if(p||(p=!0,C(),d(),!i))return;let T=Math.max(0,o.minVisibleMs-(Date.now()-l));T>0?u(m,T):m()};function H(T){if(n===null)return;let k=T.data;!k||k.persona!=="artifact-preview-ready"||k.token!==n||T.source===e.contentWindow&&R()}function L(){let T=k=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>k()):setTimeout(k,0)};T(()=>T(()=>R()))}return u(f,o.delayMs),u(R,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",H):e.addEventListener("load",L),()=>{p=!0,d(),C(),b()}}function fa(t,e){let{config:n}=e,o=e.registry??qn,r=e.bodyLayout,s=n.markdown?Ai(n.markdown):null,i=Si(n.sanitize),l=t,p=!1,c=Z=>{let oe=_n()!==null;s&&!oe&&!p&&(p=!0,wi(()=>ge(l)));let Q=s?s(Z):ao(Z);return s&&oe&&i?i(Q):Q},d=y("div","persona-artifact-preview-body"),u=null,b=null,f=null,m=()=>{f&&(f(),f=null),u=null,b=null},C=null,R=null,H=null,L=!1,T=()=>{C=null,R=null,H=null,L=!1},k=null,$=null,G=()=>{k=null,$=null},w=40,F=0,D=Z=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>Z()):setTimeout(Z,0),B=Z=>Z.scrollHeight-Z.clientHeight-Z.scrollTop<=w,P=Z=>{if(!r)return;let oe=Z.scrollHeight-Z.clientHeight>1,Q=Z.scrollHeight-Z.clientHeight-Z.scrollTop;Z.classList.toggle("persona-artifact-fade-top",r.fadeTop&&oe&&Z.scrollTop>1),Z.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&oe&&Q>1)},I=Z=>{F||(F=D(()=>{F=0,Z.scrollTop=Z.scrollHeight,P(Z)}))},j=(Z,oe,Q,se)=>{let te=!!r,fe=Q.id+"|"+(te?"w":"p");if(!C||H!==fe||C.parentElement!==d){m(),G(),d.replaceChildren();let Ce=y("pre",mb+" persona-code-pre"),$e=y("code","persona-code");if(Ce.appendChild($e),te){let Ee=y("div","persona-artifact-source-window");if(Ee.appendChild(Ce),d.appendChild(Ee),!(r?.overflow==="clip")&&typeof Ee.addEventListener=="function"){let ze=()=>Ee.scrollHeight-Ee.clientHeight>1;Ee.addEventListener("scroll",()=>{B(Ee)&&(L=!1),P(Ee)},{passive:!0}),Ee.addEventListener("wheel",Ke=>{ze()&&Ke.deltaY<0&&(L=!0)},{passive:!0}),Ee.addEventListener("touchmove",()=>{ze()&&(L=!0)},{passive:!0})}C=Ee}else d.appendChild(Ce),C=Ce;R=$e,H=fe}let be=te?C:null;be&&(be.classList.toggle("persona-artifact-source-window--fixed",se),be.classList.toggle("persona-artifact-source-window--clip",se&&r?.overflow==="clip"));let he=be?B(be):!0;if(R.replaceChildren(uf(Z,oe?.language,oe?.path)),be){let Ce=Q.status!=="complete";se&&Ce&&r?.followOutput&&!L&&he?I(be):Ce||(L=!1),P(be)}},pe=Z=>{m(),T(),G(),d.replaceChildren();let oe=y("div",hb);oe.innerHTML=c(Z),d.appendChild(oe)},ue=Z=>{let oe=Z.id,Q=n.features?.artifacts,se=xr(Z,Q,"status-body");if(k&&$===oe&&k.parentElement===d){let be=k.querySelector(".persona-artifact-status-view-text");be&&No(be,se,Q);return}m(),T(),d.replaceChildren();let te=y("div","persona-artifact-status-view"),fe=y("div","persona-artifact-status-view-text");No(fe,se,Q),te.appendChild(fe),d.appendChild(te),k=te,$=oe},ge=Z=>{l=Z;let oe=e.resolveViewMode?.(Z)??r?.viewMode??"rendered",Q=Z.artifactType==="markdown"?Z.file:void 0,se=Z.status!=="complete";se||vr(Z.id);let te=se?r?.streamingHeight:r?.completeHeight,fe=!!r&&typeof te=="number";if(r?.streamingView==="status"&&se){ue(Z);return}if(Q){let he=aa(Z.markdown??""),Ce=As(Q),$e=n.features?.artifacts?.filePreview?.enabled!==!1;if(!se&&oe==="rendered"&&$e&&(Ce==="html"||Ce==="svg")){let ke=Z.id+"\0"+he;if(u&&b===ke&&u.parentElement===d)return;T(),G(),m(),d.replaceChildren();let ze=n.features?.artifacts?.filePreview,Ke=ze?.iframeSandbox??"allow-scripts";!ze?.dangerouslyAllowSameOrigin&&Ke.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Ke=Ke.split(/\s+/).filter(Bt=>Bt&&Bt!=="allow-same-origin").join(" "));let Le=bb(ze?.loading),Re=y("div","persona-artifact-frame"),Je=y("iframe","persona-artifact-iframe");Je.setAttribute("sandbox",Ke),Je.setAttribute("data-artifact-id",Z.id);let Ot=null;Le.enabled&&Le.injectReadySignal?(Ot=xb(),Je.srcdoc=he+Cb(Ot)):Je.srcdoc=he,Re.appendChild(Je),d.appendChild(Re),Le.enabled&&(f=Ab(Re,Je,Ot,Le,Z.id,n)),u=Re,b=ke;return}if(m(),!se&&Ce==="markdown"&&oe==="rendered"){pe(he);return}j(he,{language:Q.language,path:Q.path},Z,fe);return}if(Z.artifactType==="markdown"){if(oe==="source"){m(),j(Z.markdown??"",void 0,Z,fe);return}pe(Z.markdown??"");return}m(),T(),G(),d.replaceChildren();let be=Z.component?o.get(Z.component):void 0;if(be){let Ce={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let $e=be(Z.props??{},Ce);if($e){d.appendChild($e);return}}catch{}}d.appendChild(yb(Z))};return ge(t),{el:d,update(Z){ge(Z)}}}var wf=require("idiomorph"),ga=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;wf.Idiomorph.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var Af=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var ac={index:-1,draft:""};function Sf(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!i)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function Mf(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function Tf(){return new Map}function Ef(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function kf(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function Lf(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function Pf(t){return t.role!=="assistant"||t.variant==="tool"||t.variant==="reasoning"?!1:t.variant==="approval"?!0:!!(t.content?.trim()||t.rawContent?.trim()||t.contentParts?.length)}function ma(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function In(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function yo(t,e){return In(t)-t.scrollTop<=e}function ha(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:c=!1}=t,d=n-o;return i||Math.abs(d)<s?{action:"none",delta:d,nextLastScrollTop:n}:!e&&r&&(!c||d>0)?{action:"resume",delta:d,nextLastScrollTop:n}:e&&l&&d<0?{action:"pause",delta:d,nextLastScrollTop:n}:e&&p&&!r?{action:"pause",delta:d,nextLastScrollTop:n}:{action:"none",delta:d,nextLastScrollTop:n}}function ya(t){let{following:e,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=t;return e&&n<0?"pause":!e&&r&&n>0&&o?"resume":"none"}function If(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Rf(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function Wf(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var Es={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Sb=["pre","code","a","script","style"],ba=t=>({type:t?.type??Es.type,placeholder:t?.placeholder??Es.placeholder,speed:t?.speed??Es.speed,duration:t?.duration??Es.duration,buffer:t?.buffer??Es.buffer}),Mb=[{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"}],Bf=new Map;for(let t of Mb)Bf.set(t.name,t);var Ar=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:Bf.get(t)??null,va=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
204
- `);return s<0?"":t.slice(0,s)}return t},Tb=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=e,r},Eb=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=e,r},lc=/\s/,kb=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(e.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Lb=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(lc.test(s[l])){let p=l;for(;p<s.length&&lc.test(s[p]);)p+=1;i.appendChild(o.createTextNode(s.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let c=l;for(;c<s.length&&!lc.test(s[c]);)p.appendChild(Tb(o,s[c],e,n.value)),n.value+=1,c+=1;i.appendChild(p),l=c}r.replaceChild(i,t)},Pb=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?i.appendChild(o.createTextNode(p)):(i.appendChild(Eb(o,p,e,n.value)),n.value+=1));r.replaceChild(i,t)},ks=(t,e,n,o)=>{if(!t||typeof document>"u")return t;let r=document.createElement("div");r.innerHTML=t;let s=new Set((o?.skipTags??Sb).map(u=>u.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=i.nextNode();for(;p;)kb(p,s)||l.push(p),p=i.nextNode();let c={value:o?.startIndex??0},d=e==="char"?Lb:Pb;for(let u of l)d(u,n,c);return r.innerHTML},xa=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},Ls=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},Hf=new WeakMap,Ib=(t,e)=>{if(!t.styles)return;let n=Hf.get(e);if(n||(n=new Set,Hf.set(e,n)),n.has(t.name)){let s=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(t.name)}n.add(t.name);let r=(e instanceof ShadowRoot?e.ownerDocument:e.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",t.name),r.textContent=t.styles,e.appendChild(r)},cc=new WeakMap,Rb=(t,e)=>{if(!t.onAttach)return;let n=cc.get(e);if(n||(n=new Map,cc.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},Df=t=>{let e=cc.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},Ca=(t,e)=>{Ib(t,e),Rb(t,e)};function dc(t,e=Qt){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),i=s.position==="static"||s.position==="";return i&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{i&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var Ps=0,bo=null;function pc(t=document){if(Ps++,Ps===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;bo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,Ps=Math.max(0,Ps-1),Ps===0&&bo)){let n=t.body,o=t.defaultView??window;n.style.overflow=bo.originalOverflow,n.style.position=bo.originalPosition,n.style.top=bo.originalTop,n.style.width=bo.originalWidth,o.scrollTo(0,bo.scrollY),bo=null}}}var Is={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},_t=t=>(t?.launcher?.mountMode??"floating")==="docked",Rs=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",bn=t=>{let e=t?.launcher?.dock;return{side:e?.side??Is.side,width:e?.width??Is.width,animate:e?.animate??Is.animate,reveal:e?.reveal??Is.reveal,maxHeight:e?.maxHeight??Is.maxHeight}};tt();var Tn={"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"};tt();St();tt();St();var Wb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",wa=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=Wb,buttonSize:r,iconSize:s="28px"}=e,i=t?.launcher??{},l=r??i.closeButtonSize??"32px",p=y("div",o),c=i.closeButtonTooltipText??"Close chat",d=i.closeButtonShowTooltip??!0,u=i.closeButtonIconName??"x",b=i.closeButtonIconText??"\xD7",f=!!(i.closeButtonBorderWidth||i.closeButtonBorderColor),m=we("button",{className:zn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!i.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!i.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:l,width:l,display:n?void 0:"none",color:i.closeButtonColor||Zt.actionIconColor,backgroundColor:i.closeButtonBackgroundColor||void 0,border:f?`${i.closeButtonBorderWidth||"0px"} solid ${i.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:i.closeButtonBorderRadius||void 0,paddingLeft:i.closeButtonPaddingX||void 0,paddingRight:i.closeButtonPaddingX||void 0,paddingTop:i.closeButtonPaddingY||void 0,paddingBottom:i.closeButtonPaddingY||void 0}}),C=ae(u,s,"currentColor",1);return C?(C.style.display="block",m.appendChild(C)):m.textContent=b,p.appendChild(m),jt({anchor:m,trigger:p,text:()=>m.getAttribute("aria-label")??c,enabled:d}),{button:m,wrapper:p}},Hb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Aa=(t,e={})=>{let{wrapperClassName:n=Hb,buttonSize:o,iconSize:r="20px"}=e,i=(t?.launcher??{}).clearChat??{},l=o??i.size??"32px",p=i.iconName??"refresh-cw",c=i.iconColor??"",d=i.backgroundColor??"",u=i.borderWidth??"",b=i.borderColor??"",f=i.borderRadius??"",m=i.paddingX??"",C=i.paddingY??"",R=i.tooltipText??"Clear chat",H=i.showTooltip??!0,L=y("div",n),T=!!(u||b),k=we("button",{className:zn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":R},style:{height:l,width:l,color:c||Zt.actionIconColor,backgroundColor:d||void 0,border:T?`${u||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:m||void 0,paddingRight:m||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),$=ae(p,r,"currentColor",1);return $&&($.style.display="block",k.appendChild($)),L.appendChild(k),jt({anchor:k,trigger:L,text:()=>k.getAttribute("aria-label")??R,enabled:H}),{button:k,wrapper:L}};var Zt={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))"},Fo=t=>{let{config:e,showClose:n=!0}=t,o=we("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=e?.launcher??{},s=r.headerIconSize??"48px",i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,c=we("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(p){let $=parseFloat(s)||24,G=ae(p,$*.6,"currentColor",1);G?c.replaceChildren(G):c.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let $=y("img");$.src=e.launcher.iconUrl,$.alt="",$.className="persona-rounded-xl persona-object-cover",$.style.height=s,$.style.width=s,c.replaceChildren($)}else c.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let d=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=we("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Zt.titleColor}}),b=we("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Zt.subtitleColor}});d.append(u,b),l?o.append(d):o.append(c,d);let f=r.clearChat??{},m=f.enabled??!0,C=f.placement??"inline",R=null,H=null;if(m){let G=Aa(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});R=G.button,H=G.wrapper,C==="top-right"&&(H.style.right="48px"),C==="inline"&&o.appendChild(H)}let L=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":m&&C==="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:T,wrapper:k}=wa(e,{showClose:n,wrapperClassName:L});return i!=="top-right"&&o.appendChild(k),{header:o,iconHolder:c,headerTitle:u,headerSubtitle:b,closeButton:T,closeButtonWrapper:k,clearChatButton:R,clearChatButtonWrapper:H}},Ws=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};tt();St();var Bb=t=>{let e=Fo({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function Db(t,e,n){if(e?.length)for(let o of e){let r=y("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(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ae(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=y("div","persona-relative");s.appendChild(r);let i=Cr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()}),t.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),t.appendChild(r)}}var Nb=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,i=e?.launcher??{},l=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,c,d;if(p)c=ff({label:i.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=Zt.titleColor,d=c.querySelector(".persona-combo-btn-label")??c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=y("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Zt.titleColor,d.textContent=i.title??"Chat Assistant",c.appendChild(d),Db(c,r?.trailingActions,r?.onAction??s),r?.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let T=r.onTitleClick;c.addEventListener("click",k=>{k.target.closest("button")||T()}),c.addEventListener("keydown",k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),T())})}let L=r?.titleRowHover;L&&(c.style.borderRadius=L.borderRadius??"10px",c.style.padding=L.padding??"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=L.background??"",c.style.borderColor=L.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}l.appendChild(c);let u=i.closeButtonSize??"32px",b=y("div",""),f=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=i.closeButtonColor||Zt.actionIconColor;let m=i.closeButtonIconName??"x",C=ae(m,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),b.appendChild(f),l.appendChild(b);let R=y("div");R.style.display="none";let H=y("span");return H.style.display="none",{header:l,iconHolder:R,headerTitle:d,headerSubtitle:H,closeButton:f,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},Nf={default:Bb,minimal:Nb},Ob=t=>Nf[t]??Nf.default,Sa=(t,e,n)=>{if(e?.render){let i=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=y("div");l.style.display="none";let p=y("span"),c=y("span"),d=y("button");d.style.display="none";let u=y("div");return u.style.display="none",{header:i,iconHolder:l,headerTitle:p,headerSubtitle:c,closeButton:d,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=Ob(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};tt();tt();St();var Ma=t=>{let e=y("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=t?.copy?.inputPlaceholder??"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;e.style.maxHeight=`${n*o}px`,e.style.overflowY="auto";let r=()=>{let i=parseFloat(e.style.maxHeight);return Number.isFinite(i)&&i>0?i:n*o},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let i=Math.min(e.scrollHeight,r());e.style.height=`${i}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Ta=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",i=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",p=t?.copy?.sendButtonLabel??"Send",c=t?.copy?.stopButtonLabel??"Stop",d=e.showTooltip??!1,u=e.size??"40px",b=e.backgroundColor,f=e.textColor,m=y("div","persona-send-button-wrapper"),C=we("button",{className:zn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!b&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&b||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),R=null,H=null;if(n){let k=parseFloat(u)||24,$=f?.trim()||"currentColor";r?(R=ae(r,k,$,2),R?C.appendChild(R):C.textContent=o):C.textContent=o,H=ae(s,k,$,2)}else C.textContent=p;C.setAttribute("aria-label",i),m.appendChild(C),jt({anchor:C,trigger:m,text:()=>C.getAttribute("aria-label")??"",enabled:d});let L="send";return{button:C,wrapper:m,setMode:k=>{if(k===L)return;L=k;let $=k==="stop"?l:i;if(C.setAttribute("aria-label",$),n){if(R&&H){let G=k==="stop"?H:R;C.replaceChildren(G)}}else C.textContent=k==="stop"?c:p}}},Ea=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype";if(!(o||r))return null;let i=t?.sendButton?.size??"40px",l=e.iconName??"mic",p=e.iconSize??i,c=parseFloat(p)||24,d=e.backgroundColor??t?.sendButton?.backgroundColor,u=e.iconColor??t?.sendButton?.textColor,b=y("div","persona-send-button-wrapper"),f=we("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":e.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:d||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),C=ae(l,c,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",b.appendChild(f);let R=e.tooltipText??"Start voice recognition",H=e.showTooltip??!1;return jt({anchor:f,trigger:b,text:()=>f.getAttribute("aria-label")??R,enabled:H}),{button:f,wrapper:b}},ka=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=t?.sendButton?.size??"40px",o=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=y("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(e.allowedTypes??Un).join(","),r.multiple=(e.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=e.buttonIconName??"paperclip",i=n,l=parseFloat(i)||40,p=Math.round(l*.6),c=y("div","persona-send-button-wrapper"),d=we("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{width:i,height:i,minWidth:i,minHeight:i,fontSize:"18px",lineHeight:"1"}}),u=ae(s,p,"currentColor",1.5);u?d.appendChild(u):d.textContent="\u{1F4CE}",d.addEventListener("click",f=>{f.preventDefault(),r.click()}),c.appendChild(d);let b=e.buttonTooltipText??"Attach file";return jt({anchor:d,trigger:c,text:()=>d.getAttribute("aria-label")??b}),{button:d,wrapper:c,input:r,previewsContainer:o}},La=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=e.visible??!0;o.style.display=r?"":"none";let s=e.idleText??"Online";if(e.idleLink){let i=y("a");i.href=e.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=s,i.style.color="inherit",i.style.textDecoration="none",o.appendChild(i)}else o.textContent=s;return o},Pa=()=>we("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ia=t=>{let{config:e}=t,n=we("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Pa(),r=we("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:i}=Ma(e);i();let l=Ta(e),p=Ea(e),c=ka(e),d=La(e);c&&(c.previewsContainer.style.gap="8px",r.append(c.previewsContainer,c.input)),r.append(s);let u=we("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&b.append(c.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(b,f),r.append(u),r.addEventListener("click",m=>{m.target!==l.button&&m.target!==l.wrapper&&m.target!==p?.button&&m.target!==p?.wrapper&&m.target!==c?.button&&m.target!==c?.wrapper&&s.focus()}),n.append(o,r,d),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:d,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:u,leftActions:b,rightActions:f,setSendButtonMode:l.setMode}};tt();St();var Of=()=>{let t=we("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=y("span","persona-pill-peek__icon"),n=ae("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let o=y("span","persona-pill-peek__text"),r=y("span","persona-pill-peek__caret"),s=ae("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},Ff=t=>{let{config:e}=t,n=we("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Pa(),r=La(e);r.style.display="none";let{textarea:s,attachAutoResize:i}=Ma(e);s.style.maxHeight="100px",i();let l=Ta(e),p=Ea(e),c=ka(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let d=we("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let b=y("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&b.append(p.wrapper),b.append(l.wrapper),d.addEventListener("click",m=>{m.target!==l.button&&m.target!==l.wrapper&&m.target!==p?.button&&m.target!==p?.wrapper&&m.target!==c?.button&&m.target!==c?.wrapper&&s.focus()}),c&&d.append(c.input),d.append(u,s,b),c&&n.append(c.previewsContainer),n.append(o,d,r);let f=d;return{footer:n,suggestions:o,composerForm:d,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:b,setSendButtonMode:l.setMode}};var _f=t=>{let e=t?.launcher?.enabled??!0,n=_t(t);if(Rs(t)){let d=t?.launcher?.composerBar??{},u=y("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=d.expandedSize??"anchored",u.style.zIndex=String(t?.launcher?.zIndex??Qt);let b=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");b.style.width="100%",u.appendChild(b);let f=y("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=d.expandedSize??"anchored",f.style.zIndex=String(t?.launcher?.zIndex??Qt),{wrapper:u,panel:b,pillRoot:f}}if(n){let d=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return d.appendChild(u),{wrapper:d,panel:u}}if(!e){let d=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),b=t?.launcher?.width??"100%";return d.style.width=b,u.style.width="100%",d.appendChild(u),{wrapper:d,panel:u}}let r=t?.launcher??{},s=r.position&&Tn[r.position]?Tn[r.position]:Tn["bottom-right"],i=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(t?.launcher?.zIndex??Qt);let l=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=t?.launcher?.width??t?.launcherWidth??Vn;return l.style.width=c,l.style.maxWidth=c,i.appendChild(l),{wrapper:i,panel:l}},Fb=(t,e)=>{let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=wa(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=t?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let k=Aa(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});i=k.button,l=k.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=we("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=we("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let d=we("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=we("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),b=we("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},d,u),f=y("div","persona-flex persona-flex-col persona-gap-3"),m=t?.layout?.contentMaxWidth;m&&(f.style.maxWidth=m,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(b.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(b,f);let R=we("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),H=Ff({config:t}),{root:L,textNode:T}=Of();return n.append(p,r,c,R),l&&n.appendChild(l),{container:n,body:c,messagesWrapper:f,composerOverlay:R,suggestions:H.suggestions,textarea:H.textarea,sendButton:H.sendButton,sendButtonWrapper:H.sendButtonWrapper,micButton:H.micButton,micButtonWrapper:H.micButtonWrapper,composerForm:H.composerForm,statusText:H.statusText,introTitle:d,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:p,footer:H.footer,attachmentButton:H.attachmentButton,attachmentButtonWrapper:H.attachmentButtonWrapper,attachmentInput:H.attachmentInput,attachmentPreviewsContainer:H.attachmentPreviewsContainer,actionsRow:H.actionsRow,leftActions:H.leftActions,rightActions:H.rightActions,setSendButtonMode:H.setSendButtonMode,peekBanner:L,peekTextNode:T}},$f=(t,e=!0)=>{if(Rs(t))return Fb(t,e);let n=we("div",{className:"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",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?Sa(t,o,{showClose:e}):Fo({config:t,showClose:e}),i=we("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});i.style.setProperty("scrollbar-gutter","stable");let l=we("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=we("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),c=we("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:_t(t)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),d=y("div","persona-flex persona-flex-col persona-gap-3"),u=t?.layout?.contentMaxWidth;u&&(d.style.maxWidth=u,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(c.style.display="none",i.classList.remove("persona-gap-6"),i.classList.add("persona-gap-3")),i.append(c,d);let f=Ia({config:t}),m=t?.layout?.showFooter!==!1;r?Ws(n,s,t):(s.header.style.display="none",Ws(n,s,t)),n.append(i);let C=we("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return m||(f.footer.style.display="none"),n.append(f.footer),n.append(C),{container:n,body:i,messagesWrapper:d,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:p,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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};tt();St();var uc=(t,e)=>{let n=y("button");n.type="button",n.innerHTML=`
202
+ `)),n=v("span","persona-code-line")),o(r.type,s[i])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function Lg(t,e,n){let o=t.length<=mb?hb(e,n):null,r=o?Sb(t,o):[{type:"plain",value:t}];return Mb(r)}Je();wt();Je();wt();function Mr(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=t,i=v("div","persona-dropdown-menu persona-hidden");i.setAttribute("role","menu"),i.setAttribute("data-persona-theme-zone","dropdown"),s?(i.style.position="fixed",i.style.zIndex=String(Ji)):(i.style.position="absolute",i.style.top="100%",i.style.marginTop="4px",r==="bottom-right"?i.style.right="0":i.style.left="0");for(let g of e){if(g.dividerBefore){let L=document.createElement("hr");i.appendChild(L)}let h=document.createElement("button");if(h.type="button",h.setAttribute("role","menuitem"),h.setAttribute("data-dropdown-item-id",g.id),g.destructive&&h.setAttribute("data-destructive",""),g.icon){let L=ae(g.icon,16,"currentColor",1.5);L&&h.appendChild(L)}let C=document.createElement("span");C.textContent=g.label,h.appendChild(C),h.addEventListener("click",L=>{L.stopPropagation(),d(),n(g.id)}),i.appendChild(h)}let l=null;function p(){if(!s)return;let g=o.getBoundingClientRect();i.style.top=`${g.bottom+4}px`,r==="bottom-right"?(i.style.right=`${window.innerWidth-g.right}px`,i.style.left="auto"):(i.style.left=`${g.left}px`,i.style.right="auto")}function c(){p(),i.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=h=>{!i.contains(h.target)&&!o.contains(h.target)&&d()};document.addEventListener("click",g,!0),l=()=>document.removeEventListener("click",g,!0)})}function d(){i.classList.add("persona-hidden"),l?.(),l=null}function u(){i.classList.contains("persona-hidden")?c():d()}function b(){d(),i.remove()}return s&&s.appendChild(i),{element:i,show:c,hide:d,toggle:u,destroy:b}}function Ht(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,onClick:i,aria:l}=t,p=v("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let c=ae(e,o??16,"currentColor",r??2);if(c&&p.appendChild(c),i&&p.addEventListener("click",i),l)for(let[d,u]of Object.entries(l))p.setAttribute(d,u);return p}function zo(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:p}=t,c="persona-label-btn";o!=="default"&&(c+=" persona-label-btn--"+o),c+=" persona-label-btn--"+r,i&&(c+=" "+i);let d=v("button",c);if(d.type="button",d.setAttribute("aria-label",n),e){let b=ae(e,s??14,"currentColor",2);b&&d.appendChild(b)}let u=v("span");if(u.textContent=n,d.appendChild(u),l&&d.addEventListener("click",l),p)for(let[b,g]of Object.entries(p))d.setAttribute(b,g);return d}function ha(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function p(){for(let d of l)d.btn.setAttribute("aria-pressed",d.id===i?"true":"false")}for(let d of e){let u;d.icon?u=Ht({icon:d.icon,label:d.label,className:d.className,onClick:()=>{i=d.id,p(),o(d.id)}}):(u=v("button","persona-icon-btn"+(d.className?" "+d.className:"")),u.type="button",u.setAttribute("aria-label",d.label),u.title=d.label,u.textContent=d.label,u.addEventListener("click",()=>{i=d.id,p(),o(d.id)})),u.setAttribute("aria-pressed",d.id===i?"true":"false"),l.push({id:d.id,btn:u}),s.appendChild(u)}function c(d){i=d,p()}return{element:s,setSelected:c}}function Pg(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:p}=t,c=v("div","persona-combo-btn"+(l?" "+l:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let d=v("span","persona-combo-btn-label");d.textContent=e,c.appendChild(d);let u=ae(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),p&&(c.style.borderRadius=p.borderRadius??"10px",c.style.padding=p.padding??"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=p.background??"",c.style.borderColor=p.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let b=Mr({items:o,onSelect:g=>{c.setAttribute("aria-expanded","false"),r(g)},anchor:c,position:s,portal:i});return i||c.appendChild(b.element),c.addEventListener("click",g=>{g.stopPropagation();let h=!b.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",h?"false":"true"),b.toggle()}),c.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),c.click())}),{element:c,setLabel:g=>{d.textContent=g,c.setAttribute("aria-label",g)},open:()=>{c.setAttribute("aria-expanded","true"),b.show()},close:()=>{c.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let g=!b.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",g?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),c.remove()}}}Je();var ya="persona-artifact-custom-action-btn";function Tr(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+ya+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+ya+(n?" persona-artifact-doc-icon-btn":"");o=v("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=v("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=zo({icon:t.icon,label:t.label,className:ya+(n?" persona-artifact-doc-copy-btn":"")}):o=Ht({icon:t.icon,label:t.label,className:ya+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function Rs(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}function Ig(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?Wn(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",i=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",p=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0,c=n?bo(n):l==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&d.setAttribute("data-open-artifact",s);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.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 b=document.createElement("div");b.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let h=document.createElement("div");if(h.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",h.style.color="var(--persona-muted, #9ca3af)",i==="streaming"){let C=e?.config?.features?.artifacts,L={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},B=Sr(L,C,"card");$o(h,B,C)}else s&&Ar(s),h.textContent=c;if(b.append(g,h),d.append(u,b),i==="complete"){let C=e?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let B={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let k of C)try{if(k.visible===void 0||k.visible(B)){let S=Tr(k);S.setAttribute("data-artifact-custom-action",k.id),S.className=`${S.className} persona-flex-shrink-0`,d.append(S)}}catch{}}let L=zo({label:"Download",className:"persona-flex-shrink-0"});L.title=`Download ${r}`,L.setAttribute("data-download-artifact",s),d.append(L)}return d}var ba=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",i=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:e.config,defaultRenderer:()=>Ig(t,e)});if(l)return l}return Ig(t,e)};Je();wt();var xo=new WeakMap;function cc(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=xo.get(r);if(!s)return;let i=o.get(r.getAttribute("data-artifact-inline")??"");i&&s(i,n)})}function Dg(t){return xo.has(t)}function Tb(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete",r=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0;if(t.artifactType==="component"){let i=t.componentProps,l=i&&typeof i=="object"&&!Array.isArray(i)?i:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:l,...r?{presentation:r}:{}}}let s=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Rg(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?Wn(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?bo(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Eb(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}var Wg=180,kb=240,Lb=.8,Pb=300,Ib=500,Rb="cubic-bezier(0.2, 0, 0, 1)",Hg=240,Wb=.35;function Hb(t,e,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let i=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&i.push(l.animate([{opacity:1},{opacity:0}],{duration:Wg,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let B of i)B.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let p=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!p||Math.abs(p-e)<1){l(),r();return}let c=Math.abs(e-p),d=Math.round(Math.min(Ib,Math.max(Pb,kb+c*Lb))),u=Math.round(d*Wb),b=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,g=b?b.animate([{opacity:0},{opacity:1}],{duration:Hg,delay:u,easing:"ease-out",fill:"backwards"}):null,h=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:d,easing:Rb});t.style.height=`${p}px`;let C=!1,L=()=>{C||(C=!0,l(),r())};Promise.allSettled([h.finished,g?.finished].filter(Boolean)).then(L),window.setTimeout(L,Math.max(d,u+Hg)+120)},Wg)}function Bb(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Ws="--persona-artifact-inline-body-height";function Db(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,i=e?.height;typeof i=="number"||i==="auto"?(r=i,s=i):i&&typeof i=="object"&&(r=i.streaming??320,s=i.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:e?.followOutput!==!1,c,d,u=e?.fadeMask;u===!0?(c=!0,d=!0):u===!1?(c=!1,d=!1):u&&typeof u=="object"?(c=u.top===!0,d=u.bottom===!0):l==="clip"?(c=!1,d=!0):(c=!0,d=!0);let b=e?.transition==="none"?"none":"auto",g=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:c,fadeBottom:d,transition:b,completeDisplay:g}}function Bg(t,e){let n=Tb(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:i,showViewToggle:l}=Bb(o),p=o?.inlineActions??[],c=Db(o),d=c.completeDisplay==="card",u=null,b=n,g=v("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let h=J=>ba(Eb(J),e),C=J=>{g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Ws),g.replaceChildren(h(J)),xo.set(g,ie=>{g.replaceChildren(h(ie))})};if(d&&n.status==="complete")return C(n),g;let L=va(n,{config:e.config,bodyLayout:c,resolveViewMode:()=>u??c.viewMode}),B=v("div","persona-artifact-inline-body");B.appendChild(L.el);let k=J=>{let ie=J.status!=="complete",ee=ie?c.streamingHeight:c.completeHeight,fe=typeof ee=="number";fe?g.style.setProperty(Ws,`${ee}px`):g.style.removeProperty(Ws);let be=!!L.el.querySelector(".persona-code-pre"),he=!!L.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");B.classList.toggle("persona-artifact-content-flush",be),B.classList.toggle("persona-artifact-inline-body--sized",fe&&he),B.classList.toggle("persona-artifact-inline-body--cap",!ie&&!he&&typeof c.completeHeight=="number")},S=n.status,E=(J,ie)=>{S!=="complete"&&J.status==="complete"?(typeof c.completeHeight=="number"?g.style.setProperty(Ws,`${c.completeHeight}px`):g.style.removeProperty(Ws),Og(B,ie?.suppressTransition?"none":c.transition,J.id,()=>{L.update(J),k(J)})):L.update(J),k(J),S=J.status};k(n);let z=c.overflow==="clip"&&i&&!!n.id;if(z&&(B.setAttribute("data-expand-artifact-inline",n.id),B.setAttribute("role","button"),B.setAttribute("tabindex","0"),B.classList.add("persona-cursor-pointer"),B.setAttribute("aria-label",`Open ${Rg(n).title} in panel`)),!r)return g.appendChild(B),xo.set(g,E),g;let G=v("div","persona-artifact-inline-chrome");G.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let A=v("div","persona-artifact-inline-chrome-lead"),O=v("span","persona-flex persona-items-center persona-flex-shrink-0"),D=ae("file-text",16,"currentColor",2);D&&O.appendChild(D);let W=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),P=v("span","persona-artifact-inline-type");A.append(O,W,P);let I=v("div","persona-artifact-inline-chrome-actions"),j=v("span","persona-flex persona-items-center persona-gap-1"),pe=()=>u??c.viewMode,ge=l?ha({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:pe(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:J=>{let ie=J==="source"?"source":"rendered";ie!==pe()&&(u=ie,L.update(b),k(b))}}):null,se=s?Ht({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;se&&n.id&&se.setAttribute("data-copy-artifact",n.id);let Y=i?Ht({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Y&&n.id&&Y.setAttribute("data-expand-artifact-inline",n.id),I.appendChild(j),ge&&I.appendChild(ge.element),se&&I.appendChild(se),Y&&I.appendChild(Y),G.append(A,I),g.append(G,B);let oe=J=>{let{title:ie,typeLabel:ee}=Rg(J);W.textContent=ie,W.title=ie,z&&B.setAttribute("aria-label",`Open ${ie} in panel`);let fe=J.status!=="complete";if(fe){P.classList.contains("persona-artifact-inline-status")||(P.className="persona-artifact-inline-status",P.removeAttribute("data-preserve-animation"),P.replaceChildren());let be=Sr(J,o,"inline-chrome");$o(P,be,o)}else Ar(J.id),P.className="persona-artifact-inline-type",P.removeAttribute("data-preserve-animation"),P.replaceChildren(),P.textContent=ee;if(se&&se.classList.toggle("persona-hidden",fe),ge){let be=J.artifactType==="markdown"?J.file:void 0,he=!1;if(!fe&&be&&c.viewMode!=="source"){let we=Is(be);we==="markdown"?he=!0:(we==="html"||we==="svg")&&(he=o?.filePreview?.enabled!==!1)}ge.element.classList.toggle("persona-hidden",!he),ge.setSelected(pe())}if(j.replaceChildren(),!fe&&p.length>0){let be=Rs(J);if(be)for(let he of p)try{if(he.visible===void 0||he.visible(be)){let we=Tr(he,{documentChrome:!0});we.setAttribute("data-artifact-custom-action",he.id),we.classList.add("persona-flex-shrink-0"),j.appendChild(we)}}catch{}}};return oe(n),xo.set(g,(J,ie)=>{if(d&&S!=="complete"&&J.status==="complete"){let ee=g.isConnected?g.getBoundingClientRect().height:0;S="complete";let fe=J,be=!1,he=we=>{fe=we,be=!0};xo.set(g,he),Hb(g,ee,{swap:()=>{C(fe),be=!1,xo.set(g,he)},onSettled:()=>{be?C(fe):xo.set(g,we=>{g.replaceChildren(h(we))})}});return}(J.status!=="complete"||J.id!==b.id)&&(u=null),b=J,E(J,ie),oe(J)}),g}var Ng=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",i=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:e.config,defaultRenderer:()=>Bg(t,e)});if(l)return l}return Bg(t,e)};var dc=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},Qn=new dc;Qn.register("PersonaArtifactCard",ba,{bubbleChrome:!1});Qn.register("PersonaArtifactInline",Ng,{bubbleChrome:!1});function Hs(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?ga(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var pc=!1;function Nb(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Og(t,e,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(e!=="auto"||!t||typeof r!="function"||pc||s){o();return}pc=!0;let i=Nb(n);t.style.setProperty("view-transition-name",i);let l=()=>{pc=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Ob="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Fb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function _b(t){let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(t.props??{},null,2),e.appendChild(n),e.appendChild(o),e}function $b(t){if(t===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let e=t&&typeof t=="object"?t:void 0;return{enabled:!0,delayMs:e?.delayMs??200,minVisibleMs:e?.minVisibleMs??300,timeoutMs:e?.timeoutMs??8e3,injectReadySignal:e?.injectReadySignal!==!1,label:e?.label===!1?!1:e?.label??"Starting preview...",labelDelayMs:e?.labelDelayMs??2e3,renderIndicator:e?.renderIndicator}}var zb=220;function Ub(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(2);return crypto.getRandomValues(t),t[0].toString(36)+t[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function jb(t){return`
203
+ <script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function Vb(t,e,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let i=n.renderIndicator({artifactId:t,config:e});if(i)return o.appendChild(i),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(wg());let s=null;return n.label!==!1&&(s=v("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function qb(t,e,n,o,r,s){let i=null,l=0,p=!1,c=new Set,d=()=>{c.forEach(S=>clearTimeout(S)),c.clear()},u=(S,E)=>{let z=setTimeout(()=>{c.delete(z),S()},E);c.add(z)},b=()=>{i&&i.parentElement&&i.remove(),i=null},g=()=>{if(i||p)return;let S=Vb(r,s,o);i=S.el,t.appendChild(i),l=Date.now(),o.label!==!1&&u(S.revealLabel,o.labelDelayMs)},h=()=>{i&&(i.classList.add("persona-artifact-frame-loading--out"),u(b,zb))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",B):e.removeEventListener("load",k)},L=()=>{if(p||(p=!0,C(),d(),!i))return;let S=Math.max(0,o.minVisibleMs-(Date.now()-l));S>0?u(h,S):h()};function B(S){if(n===null)return;let E=S.data;!E||E.persona!=="artifact-preview-ready"||E.token!==n||S.source===e.contentWindow&&L()}function k(){let S=E=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>E()):setTimeout(E,0)};S(()=>S(()=>L()))}return u(g,o.delayMs),u(L,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",B):e.addEventListener("load",k),()=>{p=!0,d(),C(),b()}}function va(t,e){let{config:n}=e,o=e.registry??Qn,r=e.bodyLayout,s=n.markdown?Li(n.markdown):null,i=Pi(n.sanitize),l=t,p=!1,c=Y=>{let oe=Un()!==null;s&&!oe&&!p&&(p=!0,ki(()=>se(l)));let J=s?s(Y):po(Y);return s&&oe&&i?i(J):J},d=v("div","persona-artifact-preview-body"),u=null,b=null,g=null,h=()=>{g&&(g(),g=null),u=null,b=null},C=null,L=null,B=null,k=!1,S=()=>{C=null,L=null,B=null,k=!1},E=null,z=null,G=()=>{E=null,z=null},A=40,O=0,D=Y=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>Y()):setTimeout(Y,0),W=Y=>Y.scrollHeight-Y.clientHeight-Y.scrollTop<=A,P=Y=>{if(!r)return;let oe=Y.scrollHeight-Y.clientHeight>1,J=Y.scrollHeight-Y.clientHeight-Y.scrollTop;Y.classList.toggle("persona-artifact-fade-top",r.fadeTop&&oe&&Y.scrollTop>1),Y.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&oe&&J>1)},I=Y=>{O||(O=D(()=>{O=0,Y.scrollTop=Y.scrollHeight,P(Y)}))},j=(Y,oe,J,ie)=>{let ee=!!r,fe=J.id+"|"+(ee?"w":"p");if(!C||B!==fe||C.parentElement!==d){h(),G(),d.replaceChildren();let we=v("pre",Ob+" persona-code-pre"),ve=v("code","persona-code");if(we.appendChild(ve),ee){let Te=v("div","persona-artifact-source-window");if(Te.appendChild(we),d.appendChild(Te),!(r?.overflow==="clip")&&typeof Te.addEventListener=="function"){let _e=()=>Te.scrollHeight-Te.clientHeight>1;Te.addEventListener("scroll",()=>{W(Te)&&(k=!1),P(Te)},{passive:!0}),Te.addEventListener("wheel",Ve=>{_e()&&Ve.deltaY<0&&(k=!0)},{passive:!0}),Te.addEventListener("touchmove",()=>{_e()&&(k=!0)},{passive:!0})}C=Te}else d.appendChild(we),C=we;L=ve,B=fe}let be=ee?C:null;be&&(be.classList.toggle("persona-artifact-source-window--fixed",ie),be.classList.toggle("persona-artifact-source-window--clip",ie&&r?.overflow==="clip"));let he=be?W(be):!0;if(L.replaceChildren(Lg(Y,oe?.language,oe?.path)),be){let we=J.status!=="complete";ie&&we&&r?.followOutput&&!k&&he?I(be):we||(k=!1),P(be)}},pe=Y=>{h(),S(),G(),d.replaceChildren();let oe=v("div",Fb);oe.innerHTML=c(Y),d.appendChild(oe)},ge=Y=>{let oe=Y.id,J=n.features?.artifacts,ie=Sr(Y,J,"status-body");if(E&&z===oe&&E.parentElement===d){let be=E.querySelector(".persona-artifact-status-view-text");be&&$o(be,ie,J);return}h(),S(),d.replaceChildren();let ee=v("div","persona-artifact-status-view"),fe=v("div","persona-artifact-status-view-text");$o(fe,ie,J),ee.appendChild(fe),d.appendChild(ee),E=ee,z=oe},se=Y=>{l=Y;let oe=e.resolveViewMode?.(Y)??r?.viewMode??"rendered",J=Y.artifactType==="markdown"?Y.file:void 0,ie=Y.status!=="complete";ie||Ar(Y.id);let ee=ie?r?.streamingHeight:r?.completeHeight,fe=!!r&&typeof ee=="number";if(r?.streamingView==="status"&&ie){ge(Y);return}if(J){let he=ga(Y.markdown??""),we=Is(J),ve=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ie&&oe==="rendered"&&ve&&(we==="html"||we==="svg")){let Me=Y.id+"\0"+he;if(u&&b===Me&&u.parentElement===d)return;S(),G(),h(),d.replaceChildren();let _e=n.features?.artifacts?.filePreview,Ve=_e?.iframeSandbox??"allow-scripts";!_e?.dangerouslyAllowSameOrigin&&Ve.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Ve=Ve.split(/\s+/).filter(Bt=>Bt&&Bt!=="allow-same-origin").join(" "));let ke=$b(_e?.loading),Re=v("div","persona-artifact-frame"),Ge=v("iframe","persona-artifact-iframe");Ge.setAttribute("sandbox",Ve),Ge.setAttribute("data-artifact-id",Y.id);let Nt=null;ke.enabled&&ke.injectReadySignal?(Nt=Ub(),Ge.srcdoc=he+jb(Nt)):Ge.srcdoc=he,Re.appendChild(Ge),d.appendChild(Re),ke.enabled&&(g=qb(Re,Ge,Nt,ke,Y.id,n)),u=Re,b=Me;return}if(h(),!ie&&we==="markdown"&&oe==="rendered"){pe(he);return}j(he,{language:J.language,path:J.path},Y,fe);return}if(Y.artifactType==="markdown"){if(oe==="source"){h(),j(Y.markdown??"",void 0,Y,fe);return}pe(Y.markdown??"");return}h(),S(),G(),d.replaceChildren();let be=Y.component?o.get(Y.component):void 0;if(be){let we={message:{id:Y.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let ve=be(Y.props??{},we);if(ve){d.appendChild(ve);return}}catch{}}d.appendChild(_b(Y))};return se(t),{el:d,update(Y){se(Y)}}}var Fg=require("idiomorph"),xa=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;Fg.Idiomorph.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var _g=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var uc={index:-1,draft:""};function $g(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!i)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function zg(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function Ug(){return new Map}function jg(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function Vg(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function qg(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function Kg(t){return t.role!=="assistant"||t.variant==="tool"||t.variant==="reasoning"?!1:t.variant==="approval"?!0:!!(t.content?.trim()||t.rawContent?.trim()||t.contentParts?.length)}function Ca(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Hn(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function Co(t,e){return Hn(t)-t.scrollTop<=e}function wa(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:c=!1}=t,d=n-o;return i||Math.abs(d)<s?{action:"none",delta:d,nextLastScrollTop:n}:!e&&r&&(!c||d>0)?{action:"resume",delta:d,nextLastScrollTop:n}:e&&l&&d<0?{action:"pause",delta:d,nextLastScrollTop:n}:e&&p&&!r?{action:"pause",delta:d,nextLastScrollTop:n}:{action:"none",delta:d,nextLastScrollTop:n}}function Aa(t){let{following:e,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=t;return e&&n<0?"pause":!e&&r&&n>0&&o?"resume":"none"}function Gg(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Qg(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function Xg(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var Bs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Kb=["pre","code","a","script","style"],Sa=t=>({type:t?.type??Bs.type,placeholder:t?.placeholder??Bs.placeholder,speed:t?.speed??Bs.speed,duration:t?.duration??Bs.duration,buffer:t?.buffer??Bs.buffer}),Gb=[{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"}],Yg=new Map;for(let t of Gb)Yg.set(t.name,t);var Er=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:Yg.get(t)??null,Ma=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
204
+ `);return s<0?"":t.slice(0,s)}return t},Qb=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=e,r},Xb=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=e,r},gc=/\s/,Jb=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(e.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Yb=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(gc.test(s[l])){let p=l;for(;p<s.length&&gc.test(s[p]);)p+=1;i.appendChild(o.createTextNode(s.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let c=l;for(;c<s.length&&!gc.test(s[c]);)p.appendChild(Qb(o,s[c],e,n.value)),n.value+=1,c+=1;i.appendChild(p),l=c}r.replaceChild(i,t)},Zb=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?i.appendChild(o.createTextNode(p)):(i.appendChild(Xb(o,p,e,n.value)),n.value+=1));r.replaceChild(i,t)},Ds=(t,e,n,o)=>{if(!t||typeof document>"u")return t;let r=document.createElement("div");r.innerHTML=t;let s=new Set((o?.skipTags??Kb).map(u=>u.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=i.nextNode();for(;p;)Jb(p,s)||l.push(p),p=i.nextNode();let c={value:o?.startIndex??0},d=e==="char"?Yb:Zb;for(let u of l)d(u,n,c);return r.innerHTML},Ta=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},Ns=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},Jg=new WeakMap,ev=(t,e)=>{if(!t.styles)return;let n=Jg.get(e);if(n||(n=new Set,Jg.set(e,n)),n.has(t.name)){let s=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(t.name)}n.add(t.name);let r=(e instanceof ShadowRoot?e.ownerDocument:e.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",t.name),r.textContent=t.styles,e.appendChild(r)},fc=new WeakMap,tv=(t,e)=>{if(!t.onAttach)return;let n=fc.get(e);if(n||(n=new Map,fc.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},Zg=t=>{let e=fc.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},Ea=(t,e)=>{ev(t,e),tv(t,e)};function mc(t,e=Qt){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),i=s.position==="static"||s.position==="";return i&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{i&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var Os=0,wo=null;function hc(t=document){if(Os++,Os===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;wo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,Os=Math.max(0,Os-1),Os===0&&wo)){let n=t.body,o=t.defaultView??window;n.style.overflow=wo.originalOverflow,n.style.position=wo.originalPosition,n.style.top=wo.originalTop,n.style.width=wo.originalWidth,o.scrollTo(0,wo.scrollY),wo=null}}}var Fs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},_t=t=>(t?.launcher?.mountMode??"floating")==="docked",_s=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",xn=t=>{let e=t?.launcher?.dock;return{side:e?.side??Fs.side,width:e?.width??Fs.width,animate:e?.animate??Fs.animate,reveal:e?.reveal??Fs.reveal,maxHeight:e?.maxHeight??Fs.maxHeight}};Je();Je();wt();var yc=t=>t==="followUp"?"follow-up":t,nv=(t,e=0)=>{if(typeof t=="string"){let r=t.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},ov=t=>{switch(t){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'}},ef=new WeakSet,rv=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,sv=t=>{rv()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},ka=t=>{let e=[],n=[],o=null,r=null,s=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},i=()=>{if(r=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){s();return}let d=Math.max(0,t.scrollWidth-t.clientWidth);if(d<=1){s();return}let u=getComputedStyle(t).direction==="rtl",b=Math.min(d,Math.max(0,Math.abs(t.scrollLeft))),g=4,h=b<=g,C=b>=d-g,L=u?!C:!h,B=u?!h:!C;t.toggleAttribute("data-scroll-left",L),t.toggleAttribute("data-scroll-right",B)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};t.addEventListener("scroll",l,{passive:!0});let p=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return p?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",l),p?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(d,u,b,g,h,C)=>{t.replaceChildren(),e.length=0,n.length=0;let L=C?.source??"config",B=C?.surface??(L==="config"?"starter":"followUp"),k=B==="followUp",S=C?.variant??"chip",E=C?.behavior??"send",z=C?.overflow??"wrap",G=C?.config??{},A=C?.plugins??[],O=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,D=k?"followUps":"starters";!ef.has(G)&&G.debug===!0&&S!=="chip"&&G.suggestions?.[D]?.overflow!==void 0&&(ef.add(G),console.info(`[persona] suggestions.${D}.overflow applies to the "chip" variant only; the "${S}" variant manages its own stacking.`));let W=se=>se.map(nv).filter(Y=>Y!==null).map(Y=>({...Y,behavior:Y.behavior??E})),P=W(d??[]);A.forEach(se=>{se.transformSuggestions&&(P=W(se.transformSuggestions({suggestions:P.map(Y=>({...Y})),surface:B,source:L,config:G})))});let I=O===void 0?P:P.slice(0,O);if(!I.length){t.hidden=!0,o=null,s();return}if(!k&&(g??u.getMessages()).some(Y=>Y.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=yc(B),t.dataset.variant=S,t.dataset.overflow=z;let j=document.createDocumentFragment(),pe=u.isStreaming();I.forEach((se,Y)=>{var be,he,we;let oe=se.behavior,J=()=>{if(u.isStreaming())return;let ve={suggestion:{...se},surface:B,source:L,behavior:oe},Te=t.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:ve,bubbles:!0,composed:!0,cancelable:!0}));if(k&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:se.prompt},bubbles:!0,composed:!0})),!!Te){for(let Me of A)if(Me.onSuggestionSelect?.({suggestion:{...se},surface:B,source:L,variant:S,config:G})===!1)return;if(oe==="fill"){b.value=se.prompt,b.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),b.focus();return}b.value="",u.sendMessage(se.prompt)}},ie=()=>{let ve=v("button",`persona-suggestion persona-suggestion--${S}`);if(ve.type="button",ve.disabled=pe,ve.dataset.suggestionId=se.id,ve.dataset.emphasis=se.emphasis,ve.dataset.behavior=oe,S==="chip"&&(h?.fontFamily&&(ve.style.fontFamily=ov(h.fontFamily)),h?.fontWeight&&(ve.style.fontWeight=h.fontWeight),h?.paddingX&&(ve.style.paddingLeft=h.paddingX,ve.style.paddingRight=h.paddingX),h?.paddingY&&(ve.style.paddingTop=h.paddingY,ve.style.paddingBottom=h.paddingY)),se.icon){let Me=ae(se.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);Me&&(Me.classList.add("persona-suggestion__icon"),se.iconColor&&(Me.style.color=se.iconColor),ve.appendChild(Me))}let Te=v("span","persona-suggestion__copy");if(Te.appendChild(Ce("span",{className:"persona-suggestion__label",text:se.label})),se.description&&Te.appendChild(Ce("span",{className:"persona-suggestion__description",text:se.description})),ve.appendChild(Te),S!=="chip"){let Me=ae("arrow-right",16,"currentColor",1.8);Me&&(Me.classList.add("persona-suggestion__arrow"),ve.appendChild(Me))}return ve.addEventListener("click",J),ve},ee=null;for(let ve of A)if(ve.renderSuggestion&&(ee=ve.renderSuggestion({suggestion:{...se},index:Y,surface:B,source:L,variant:S,streaming:pe,config:G,defaultRenderer:ie,select:J}),ee))break;ee??(ee=ie()),(be=ee.dataset).suggestionId||(be.suggestionId=se.id),(he=ee.dataset).behavior||(he.behavior=oe),(we=ee.dataset).emphasis||(we.emphasis=se.emphasis),ee instanceof HTMLButtonElement||ee.setAttribute("aria-disabled",pe?"true":"false"),j.appendChild(ee),n.push(ee),[...ee instanceof HTMLButtonElement?[ee]:[],...Array.from(ee.querySelectorAll("button"))].forEach(ve=>{e.includes(ve)||(ve.disabled=pe,e.push(ve))})}),t.appendChild(j),i(),l();let ge=JSON.stringify({normalized:I,surface:B,variant:S,source:L});ge!==o&&(o=ge,sv(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:I.map(se=>({...se})),surface:B,source:L,variant:S},bubbles:!0,composed:!0})),k&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:I.map(se=>se.prompt)},bubbles:!0,composed:!0})))}}};var kn={"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"};Je();wt();Je();wt();var iv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",La=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=iv,buttonSize:r,iconSize:s="28px"}=e,i=t?.launcher??{},l=r??i.closeButtonSize??"32px",p=v("div",o),c=i.closeButtonTooltipText??"Close chat",d=i.closeButtonShowTooltip??!0,u=i.closeButtonIconName??"x",b=i.closeButtonIconText??"\xD7",g=!!(i.closeButtonBorderWidth||i.closeButtonBorderColor),h=Ce("button",{className:Vn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!i.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!i.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:l,width:l,display:n?void 0:"none",color:i.closeButtonColor||tn.actionIconColor,backgroundColor:i.closeButtonBackgroundColor||void 0,border:g?`${i.closeButtonBorderWidth||"0px"} solid ${i.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:i.closeButtonBorderRadius||void 0,paddingLeft:i.closeButtonPaddingX||void 0,paddingRight:i.closeButtonPaddingX||void 0,paddingTop:i.closeButtonPaddingY||void 0,paddingBottom:i.closeButtonPaddingY||void 0}}),C=ae(u,s,"currentColor",1);return C?(C.style.display="block",h.appendChild(C)):h.textContent=b,p.appendChild(h),Ut({anchor:h,trigger:p,text:()=>h.getAttribute("aria-label")??c,enabled:d}),{button:h,wrapper:p}},av="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pa=(t,e={})=>{let{wrapperClassName:n=av,buttonSize:o,iconSize:r="20px"}=e,i=(t?.launcher??{}).clearChat??{},l=o??i.size??"32px",p=i.iconName??"refresh-cw",c=i.iconColor??"",d=i.backgroundColor??"",u=i.borderWidth??"",b=i.borderColor??"",g=i.borderRadius??"",h=i.paddingX??"",C=i.paddingY??"",L=i.tooltipText??"Clear chat",B=i.showTooltip??!0,k=v("div",n),S=!!(u||b),E=Ce("button",{className:Vn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!S&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":L},style:{height:l,width:l,color:c||tn.actionIconColor,backgroundColor:d||void 0,border:S?`${u||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),z=ae(p,r,"currentColor",1);return z&&(z.style.display="block",E.appendChild(z)),k.appendChild(E),Ut({anchor:E,trigger:k,text:()=>E.getAttribute("aria-label")??L,enabled:B}),{button:E,wrapper:k}};var tn={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))"},Uo=t=>{let{config:e,showClose:n=!0}=t,o=Ce("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=e?.launcher??{},s=r.headerIconSize??"48px",i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,c=Ce("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(p){let z=parseFloat(s)||24,G=ae(p,z*.6,"currentColor",1);G?c.replaceChildren(G):c.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let z=v("img");z.src=e.launcher.iconUrl,z.alt="",z.className="persona-rounded-xl persona-object-cover",z.style.height=s,z.style.width=s,c.replaceChildren(z)}else c.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let d=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Ce("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:tn.titleColor}}),b=Ce("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:tn.subtitleColor}});d.append(u,b),l?o.append(d):o.append(c,d);let g=r.clearChat??{},h=g.enabled??!0,C=g.placement??"inline",L=null,B=null;if(h){let G=Pa(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});L=G.button,B=G.wrapper,C==="top-right"&&(B.style.right="48px"),C==="inline"&&o.appendChild(B)}let k=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&C==="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:S,wrapper:E}=La(e,{showClose:n,wrapperClassName:k});return i!=="top-right"&&o.appendChild(E),{header:o,iconHolder:c,headerTitle:u,headerSubtitle:b,closeButton:S,closeButtonWrapper:E,clearChatButton:L,clearChatButtonWrapper:B}},$s=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};Je();wt();var lv=t=>{let e=Uo({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function cv(t,e,n){if(e?.length)for(let o of e){let r=v("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(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ae(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=v("div","persona-relative");s.appendChild(r);let i=Mr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()}),t.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),t.appendChild(r)}}var dv=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,i=e?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,c,d;if(p)c=Pg({label:i.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=tn.titleColor,d=c.querySelector(".persona-combo-btn-label")??c;else{if(c=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=v("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=tn.titleColor,d.textContent=i.title??"Chat Assistant",c.appendChild(d),cv(c,r?.trailingActions,r?.onAction??s),r?.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let S=r.onTitleClick;c.addEventListener("click",E=>{E.target.closest("button")||S()}),c.addEventListener("keydown",E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),S())})}let k=r?.titleRowHover;k&&(c.style.borderRadius=k.borderRadius??"10px",c.style.padding=k.padding??"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=k.background??"",c.style.borderColor=k.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}l.appendChild(c);let u=i.closeButtonSize??"32px",b=v("div",""),g=v("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=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=i.closeButtonColor||tn.actionIconColor;let h=i.closeButtonIconName??"x",C=ae(h,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),b.appendChild(g),l.appendChild(b);let L=v("div");L.style.display="none";let B=v("span");return B.style.display="none",{header:l,iconHolder:L,headerTitle:d,headerSubtitle:B,closeButton:g,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},tf={default:lv,minimal:dv},pv=t=>tf[t]??tf.default,Ia=(t,e,n)=>{if(e?.render){let i=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=v("div");l.style.display="none";let p=v("span"),c=v("span"),d=v("button");d.style.display="none";let u=v("div");return u.style.display="none",{header:i,iconHolder:l,headerTitle:p,headerSubtitle:c,closeButton:d,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=pv(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};Je();Je();wt();var Ra=t=>{let e=v("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=t?.copy?.inputPlaceholder??"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20,r=()=>{let p=e.ownerDocument?.defaultView;if(!p?.getComputedStyle)return o;let c=p.getComputedStyle(e).lineHeight;if(!c||!c.trim().endsWith("px"))return o;let d=parseFloat(c);return Number.isFinite(d)&&d>0?d:o},s=`${n*o}px`;e.style.maxHeight=s,e.style.overflowY="auto";let i=()=>{let p=e.style.maxHeight;if(p!==s){let d=parseFloat(p);if(Number.isFinite(d)&&d>0)return d}let c=n*r();return s=`${c}px`,e.style.maxHeight=s,c},l=()=>{e.addEventListener("input",()=>{e.style.height="auto";let p=Math.min(e.scrollHeight,i());e.style.height=`${p}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:l}},Wa=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",i=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",p=t?.copy?.sendButtonLabel??"Send",c=t?.copy?.stopButtonLabel??"Stop",d=e.showTooltip??!1,u=e.size??"40px",b=e.backgroundColor,g=e.textColor,h=v("div","persona-send-button-wrapper"),C=Ce("button",{className:Vn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!b&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&b||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),L=null,B=null;if(n){let E=parseFloat(e.iconSize??"")||Math.round((parseFloat(u)||24)*.5),z=e.iconStrokeWidth??2,G=g?.trim()||"currentColor";r?(L=ae(r,E,G,z),L?C.appendChild(L):C.textContent=o):C.textContent=o,B=ae(s,E,G,z)}else C.textContent=p;C.setAttribute("aria-label",i),h.appendChild(C),Ut({anchor:C,trigger:h,text:()=>C.getAttribute("aria-label")??"",enabled:d});let k="send";return{button:C,wrapper:h,setMode:E=>{if(E===k)return;k=E;let z=E==="stop"?l:i;if(C.setAttribute("aria-label",z),n){if(L&&B){let G=E==="stop"?B:L;C.replaceChildren(G)}}else C.textContent=E==="stop"?c:p}}},Ha=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype";if(!(o||r))return null;let i=t?.sendButton?.size??"40px",l=e.iconName??"mic",p=e.iconSize??i,c=parseFloat(p)||24,d=e.backgroundColor??t?.sendButton?.backgroundColor,u=e.iconColor??t?.sendButton?.textColor,b=v("div","persona-send-button-wrapper"),g=Ce("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":e.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:d||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),C=ae(l,c,u||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",b.appendChild(g);let L=e.tooltipText??"Start voice recognition",B=e.showTooltip??!1;return Ut({anchor:g,trigger:b,text:()=>g.getAttribute("aria-label")??L,enabled:B}),{button:g,wrapper:b}},Ba=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=t?.sendButton?.size??"40px",o=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=v("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(e.allowedTypes??Kn).join(","),r.multiple=(e.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=e.buttonIconName??"paperclip",i=n,l=parseFloat(i)||40,p=Math.round(l*.6),c=v("div","persona-send-button-wrapper"),d=Ce("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{width:i,height:i,minWidth:i,minHeight:i,fontSize:"18px",lineHeight:"1"}}),u=ae(s,p,"currentColor",1.5);u?d.appendChild(u):d.textContent="\u{1F4CE}",d.addEventListener("click",g=>{g.preventDefault(),r.click()}),c.appendChild(d);let b=e.buttonTooltipText??"Attach file";return Ut({anchor:d,trigger:c,text:()=>d.getAttribute("aria-label")??b}),{button:d,wrapper:c,input:r,previewsContainer:o}},Da=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=e.visible??!0;o.style.display=r?"":"none";let s=e.idleText??"Online";if(e.idleLink){let i=v("a");i.href=e.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=s,i.style.color="inherit",i.style.textDecoration="none",o.appendChild(i)}else o.textContent=s;return o},Na=()=>Ce("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Oa=t=>{let{config:e}=t,n=Ce("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Na(),r=Ce("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:i}=Ra(e);i();let l=Wa(e),p=Ha(e),c=Ba(e),d=Da(e);c&&(c.previewsContainer.style.gap="8px",r.append(c.previewsContainer,c.input)),r.append(s);let u=Ce("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&b.append(c.wrapper),p&&g.append(p.wrapper),g.append(l.wrapper),u.append(b,g),r.append(u),r.addEventListener("click",h=>{h.target!==l.button&&h.target!==l.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==c?.button&&h.target!==c?.wrapper&&s.focus()}),n.append(o,r,d),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:d,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:u,leftActions:b,rightActions:g,setSendButtonMode:l.setMode}};Je();wt();var nf=()=>{let t=Ce("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),n=ae("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=ae("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},of=t=>{let{config:e}=t,n=Ce("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Na(),r=Da(e);r.style.display="none";let{textarea:s,attachAutoResize:i}=Ra(e);s.style.maxHeight="100px",i();let l=Wa(e),p=Ha(e),c=Ba(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let d=Ce("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=v("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let b=v("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&b.append(p.wrapper),b.append(l.wrapper),d.addEventListener("click",h=>{h.target!==l.button&&h.target!==l.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==c?.button&&h.target!==c?.wrapper&&s.focus()}),c&&d.append(c.input),d.append(u,s,b),c&&n.append(c.previewsContainer),n.append(o,d,r);let g=d;return{footer:n,suggestions:o,composerForm:d,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:g,leftActions:u,rightActions:b,setSendButtonMode:l.setMode}};var rf=t=>{let e=t?.launcher?.enabled??!0,n=_t(t);if(_s(t)){let d=t?.launcher?.composerBar??{},u=v("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=d.expandedSize??"anchored",u.style.zIndex=String(t?.launcher?.zIndex??Qt);let b=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");b.style.width="100%",u.appendChild(b);let g=v("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=d.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??Qt),{wrapper:u,panel:b,pillRoot:g}}if(n){let d=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return d.appendChild(u),{wrapper:d,panel:u}}if(!e){let d=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),b=t?.launcher?.width??"100%";return d.style.width=b,u.style.width="100%",d.appendChild(u),{wrapper:d,panel:u}}let r=t?.launcher??{},s=r.position&&kn[r.position]?kn[r.position]:kn["bottom-right"],i=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(t?.launcher?.zIndex??Qt);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=t?.launcher?.width??t?.launcherWidth??Gn;return l.style.width=c,l.style.maxWidth=c,i.appendChild(l),{wrapper:i,panel:l}},Fa=t=>{let e=Ce("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":yc(t)}});return e.hidden=!0,e},uv=(t,e)=>{let n=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=La(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=t?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let G=Pa(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});i=G.button,l=G.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=Ce("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Ce("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let d=Ce("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Ce("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),b=Fa("starter"),g=Ce("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},d,u,b),h=v("div","persona-flex persona-flex-col persona-gap-3"),C=Fa("followUp"),L=t?.layout?.contentMaxWidth;L&&(h.style.maxWidth=L,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,h,C);let k=Ce("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),S=of({config:t}),{root:E,textNode:z}=nf();return n.append(p,r,c,k),l&&n.appendChild(l),{container:n,body:c,messagesWrapper:h,starterSuggestions:b,transcriptSuggestions:C,composerOverlay:k,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,introTitle:d,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:p,footer:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode,peekBanner:E,peekTextNode:z}},sf=(t,e=!0)=>{if(_s(t))return uv(t,e);let n=Ce("div",{className:"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",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?Ia(t,o,{showClose:e}):Uo({config:t,showClose:e}),i=Ce("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});i.style.setProperty("scrollbar-gutter","stable");let l=Ce("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Ce("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),c=Fa("starter"),d=Ce("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:_t(t)?"none":"var(--persona-intro-card-shadow, none)"}},l,p,c),u=v("div","persona-flex persona-flex-col persona-gap-3"),b=Fa("followUp"),g=t?.layout?.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(d.style.display="none",i.classList.remove("persona-gap-6"),i.classList.add("persona-gap-3")),i.append(d,u,b);let C=Oa({config:t}),L=t?.layout?.showFooter!==!1;r?$s(n,s,t):(s.header.style.display="none",$s(n,s,t)),n.append(i);let B=Ce("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return L||(C.footer.style.display="none"),n.append(C.footer),n.append(B),{container:n,body:i,messagesWrapper:u,starterSuggestions:c,transcriptSuggestions:b,composerOverlay:B,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,introTitle:l,introSubtitle:p,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:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode}};Je();wt();var bc=(t,e)=>{let n=v("button");n.type="button",n.innerHTML=`
205
205
  <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>
206
206
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
207
207
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -209,14 +209,14 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
209
209
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
210
210
  </span>
211
211
  <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>
212
- `,n.addEventListener("click",e);let o=s=>{let i=s.launcher??{},l=_t(s),p=n.querySelector("[data-role='launcher-title']");if(p){let T=i.title??"Chat Assistant";p.textContent=T,p.setAttribute("title",T)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let T=i.subtitle??"Here to help you get answers fast";c.textContent=T,c.setAttribute("title",T)}let d=n.querySelector(".persona-flex-col");d&&(i.textHidden||l?d.style.display="none":d.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(i.agentIconHidden)u.style.display="none";else{let T=i.agentIconSize??"40px";if(u.style.height=T,u.style.width=T,i.agentIconBackgroundColor?(u.style.backgroundColor=i.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",i.agentIconName){let k=parseFloat(T)||24,$=ae(i.agentIconName,k*.6,"var(--persona-text-inverse, #ffffff)",2);$?(u.appendChild($),u.style.display=""):(u.textContent=i.agentIconText??"\u{1F4AC}",u.style.display="")}else i.iconUrl?u.style.display="none":(u.textContent=i.agentIconText??"\u{1F4AC}",u.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let T=i.agentIconSize??"40px";b.style.height=T,b.style.width=T,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(b.src=i.iconUrl,b.style.display="block"):b.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let T=i.callToActionIconSize??"32px";f.style.height=T,f.style.width=T,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(f.style.color=i.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let k=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,k=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",i.callToActionIconName){let $=parseFloat(T)||24,G=Math.max($-k,8),w=ae(i.callToActionIconName,G,"currentColor",2);w?f.appendChild(w):f.textContent=i.callToActionIconText??"\u2197"}else f.textContent=i.callToActionIconText??"\u2197"}let m=i.position&&Tn[i.position]?Tn[i.position]:Tn["bottom-right"],C="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",R="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?R:`${C} ${m}`,l||(n.style.zIndex=String(i.zIndex??Qt));let H="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=i.border??H,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:L,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=i.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:r}};var zf=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=_f(t),s=$f(t,e),i={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:i,panelElements:s,transcript:l,header:p,composer:c,replaceHeader:b=>(p.element.replaceWith(b.header),p.element=b.header,p.iconHolder=b.iconHolder,p.headerTitle=b.headerTitle,p.headerSubtitle=b.headerSubtitle,p.closeButton=b.closeButton,p.closeButtonWrapper=b.closeButtonWrapper,p.clearChatButton=b.clearChatButton,p.clearChatButtonWrapper=b.clearChatButtonWrapper,b),replaceComposer:b=>{c.footer.replaceWith(b),c.footer=b}}},fc=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>uc(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=uc(t,n);return{instance:r,element:r.element}};tt();St();var _b=t=>{switch(t){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}},$b=(t,e)=>{if(!t)return null;let n=_b(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},zb=(t,e)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},jb=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},gc=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},mc=320,qf=320,Ub=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Vb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),qb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Kb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Gb=t=>{if(!t||t.length===0)return null;let e=we("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=we("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=y("span","persona-mention-chip-icon"),s=ae(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(we("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},Qb=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(xs(o.ref,{readonly:!0,render:e}))}return n},jf="\uE000",Uf="\uE001",Xb=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${jf}${r}:${b}${Uf}`,i=e.map((b,f)=>b.kind==="text"?b.text:s(f)).join(""),l=n(i);if(!e.every((b,f)=>b.kind==="text"||l.includes(s(f)))){t.replaceChildren(Qb(e,o));return}t.innerHTML=l;let c=new RegExp(`${jf}${r}:(\\d+)${Uf}`),d=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),u=[];for(let b=d.nextNode();b;b=d.nextNode())u.push(b);for(let b of u){let f=b;for(let m=c.exec(f.data);m;m=c.exec(f.data)){let C=e[Number(m[1])],R=f.splitText(m.index);R.data=R.data.slice(m[0].length),C?.kind==="mention"&&R.parentNode?.insertBefore(xs(C.ref,{readonly:!0,render:o}),R),f=R}}},Jb=(t,e,n)=>{if(t.length===0)return null;try{let o=y("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,i=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,p)=>{let c=y("img");c.alt=l.alt?.trim()||`Attached image ${p+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${mc}px`,c.style.maxHeight=`${qf}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let d=!1;r+=1,c.addEventListener("error",()=>{d||(d=!0,r=Math.max(0,r-1),c.remove(),r===0&&i())}),c.addEventListener("load",()=>{d=!0}),jb(l.image)?(c.src=l.image,o.appendChild(c)):(d=!0,r=Math.max(0,r-1),c.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},Yb=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!gc(o.audio))return;let r=y("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mc}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Zb=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!gc(o.video))return;let r=y("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mc}px`,r.style.maxHeight=`${qf}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},ev=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!gc(o.data))return;let r=y("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Hs=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";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="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},tv=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Hs};if(e){let r=e(o);if(r!==null)return r}return Hs()},nv=(t,e)=>{let n=y("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"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=y("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Vf=(t,e,n="div")=>{let o=y(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},hc=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},ov=(t,e,n)=>{let o=e.showCopy??!0,r=e.showUpvote??!0,s=e.showDownvote??!0,i=e.showReadAloud??!1;if(!o&&!r&&!s&&!i){let m=y("div");return m.style.display="none",m.id=`actions-${t.id}`,m.setAttribute("data-actions-for",t.id),m}let l=e.visibility??"hover",p=e.align??"right",c=e.layout??"pill-inside",d={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],b=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${d} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${t.id}`,b.setAttribute("data-actions-for",t.id);let f=(m,C,R)=>{let H=Ht({icon:m,label:C,size:14,className:"persona-message-action-btn"});return H.setAttribute("data-action",R),H};return o&&b.appendChild(f("copy","Copy message","copy")),i&&b.appendChild(f("volume-2","Read aloud","read-aloud")),r&&b.appendChild(f("thumbs-up","Upvote","upvote")),s&&b.appendChild(f("thumbs-down","Downvote","downvote")),b},yc=(t,e,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",p=i.avatar,c=i.timestamp,d=p?.show??!1,u=c?.show??!1,b=p?.position??"left",f=c?.position??"below",m=hc(t.role,l),C=y("div",m.join(" "));C.id=`bubble-${t.id}`,C.setAttribute("data-message-id",t.id),C.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let R=Ub(t),H=t.content?.trim()??"",T=R.length>0&&H===Di,k=ba(s?.widgetConfig?.features?.streamAnimation),$=s?.widgetConfig?.features?.streamAnimation?.plugins,G=t.role==="assistant"&&k.type!=="none"?Ar(k.type,$):null,w=t.role==="assistant"&&G?.isAnimating?.(t)===!0,F=t.role==="assistant"&&G!==null&&(!!t.streaming||w);F&&G?.bubbleClass&&C.classList.add(G.bubbleClass);let D=document.createElement("div");D.classList.add("persona-message-content"),t.streaming&&D.classList.add("persona-content-streaming"),F&&G&&(G.containerClass&&D.classList.add(G.containerClass),D.style.setProperty("--persona-stream-step",`${k.speed}ms`),D.style.setProperty("--persona-stream-duration",`${k.duration}ms`));let B=F?va(t.content??"",k.buffer,G,t,!!t.streaming):t.content??"",P=()=>{let te=e({text:B,message:t,streaming:!!t.streaming,raw:t.rawContent});return F&&G?.wrap==="char"?ks(te,"char",t.id,{skipTags:G.skipTags}):F&&G?.wrap==="word"?ks(te,"word",t.id,{skipTags:G.skipTags}):te},I=null;if(T?(I=document.createElement("div"),I.innerHTML=P(),I.style.display="none",D.appendChild(I)):t.contentSegments?.length?Xb(D,t.contentSegments,te=>e({text:te,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):D.innerHTML=P(),F&&G?.useCaret&&!T&&H){let te=xa(),fe=D.querySelectorAll(".persona-stream-char, .persona-stream-word"),be=fe[fe.length-1];if(be?.parentNode)be.parentNode.insertBefore(te,be.nextSibling);else{let he=D.lastElementChild;he?he.appendChild(te):D.appendChild(te)}}if(u&&f==="inline"&&t.createdAt){let te=Vf(t,c,"span");te.classList.add("persona-timestamp-inline");let fe=D.lastElementChild;fe?fe.appendChild(te):D.appendChild(te)}if(R.length>0){let te=Jb(R,!T&&!!H,()=>{T&&I&&(I.style.display="")});te?C.appendChild(te):T&&I&&(I.style.display="")}let j=Vb(t);if(j.length>0){let te=Yb(j);te&&C.appendChild(te)}let pe=qb(t);if(pe.length>0){let te=Zb(pe);te&&C.appendChild(te)}let ue=Kb(t);if(ue.length>0){let te=ev(ue);te&&C.appendChild(te)}let ge=t.contentSegments?.length?null:Gb(t.contextMentions);if(ge&&C.appendChild(ge),C.appendChild(D),u&&f==="below"&&t.createdAt){let te=Vf(t,c);te.classList.add("persona-mt-1"),C.appendChild(te)}let Z=t.role==="assistant"?$b(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let te=!!(B&&B.trim()),fe=k.placeholder==="skeleton",be=fe&&k.buffer==="line"&&te;if(te)be&&C.appendChild(Ls());else if(fe)C.appendChild(Ls());else{let he=tv("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);he&&C.appendChild(he)}}if(Z&&t.stopReason&&!t.streaming&&(H||(D.style.display="none"),C.appendChild(zb(t.stopReason,Z))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let te=ov(t,o,r);C.appendChild(te)}if(!d||t.role==="system")return C;let Q=y("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),se=nv(p,t.role);return b==="right"||b==="left"&&t.role==="user"?Q.append(C,se):Q.append(se,C),Q};tt();St();var Sr=new Set,rv=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),sv=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
213
- `):""},Kf=(t,e)=>{let n=Sr.has(t),o=e.querySelector('button[data-expand-header="true"]'),r=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let c=ae(n?"chevron-up":"chevron-down",16,"currentColor",2);c?l.appendChild(c):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},bc=(t,e)=>{let n=t.reasoning,o=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","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-${t.id}`,o.setAttribute("data-message-id",t.id),!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,i=s&&Sr.has(t.id),l=n.status!=="complete",p=sv(t,r.previewMaxLines??3),c=y("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");c.type="button",s&&(c.setAttribute("aria-expanded",i?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let d=y("div","persona-flex persona-flex-col persona-text-left"),u=y("span","persona-text-xs persona-text-persona-primary"),b="Thinking...",f=e?.reasoning??{},m=String(n.startedAt??Date.now()),C=()=>{let pe=y("span","");return pe.setAttribute("data-tool-elapsed",m),pe.textContent=Ri(n),pe},R=f.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:b,previewText:p,isActive:l,config:e??{},elapsed:Ri(n),createElapsedElement:C});typeof R=="string"&&R.trim()?(u.textContent=R,d.appendChild(u)):R instanceof HTMLElement?d.appendChild(R):(u.textContent=b,d.appendChild(u));let H=y("span","persona-text-xs persona-text-persona-primary");H.textContent=Np(n),d.appendChild(H);let L=r.loadingAnimation??"none",T=f.activeTextTemplate,k=f.completeTextTemplate,$=l?T:k,G=R instanceof HTMLElement,w=(pe,ue)=>{u.textContent="";let ge=Wi(pe,""),Z=0;for(let oe of ge){let Q=oe.styles.length>0?(()=>{let se=y("span",oe.styles.map(te=>`persona-tool-text-${te}`).join(" "));return u.appendChild(se),se})():u;if(oe.isDuration&&l)Q.appendChild(C());else{let se=oe.isDuration?Ri(n):oe.text;ue?Z=mo(Q,se,Z):Q.appendChild(document.createTextNode(se))}}};if(!G&&$)if(H.style.display="none",u.style.display="",l&&L!=="none"){let pe=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),L==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),w($,!1)):(u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),L==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),w($,!0))}else w($,!1);else if(!G&&l&&L!=="none"){u.style.display="";let pe=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),L==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`);else{u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),L==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let ue=u.textContent||b;u.textContent="",mo(u,ue,0)}n.status==="complete"&&(u.style.display="none")}else G||(n.status==="complete"?u.style.display="none":u.style.display="");let F=null;if(s){F=y("div","persona-flex persona-items-center");let ue=ae(i?"chevron-up":"chevron-down",16,"currentColor",2);ue?F.appendChild(ue):F.textContent=i?"Hide":"Show";let ge=y("div","persona-flex persona-items-center persona-ml-auto");ge.append(F),c.append(d,ge)}else c.append(d);let D=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","reasoning"),D.style.display="none",D.style.whiteSpace="pre-wrap",!i&&l&&r.activePreview&&p){let pe=e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:p,isActive:l,config:e??{}});rv(D,pe)||(D.textContent=p),D.style.display=""}if(!i&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(c,D),o;let B=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");B.style.display=i?"":"none";let P=n.chunks.join(""),I=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return I.textContent=P||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),B.appendChild(I),(()=>{if(c.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let ue=ae(i?"chevron-up":"chevron-down",16,"currentColor",2);ue?F.appendChild(ue):F.textContent=i?"Hide":"Show"}B.style.display=i?"":"none",D.style.display=i?"none":D.textContent||D.childNodes.length?"":"none"})(),o.append(c,D,B),o};tt();St();var Mr=new Set,iv=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),av=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
214
- `);let r=fo(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
215
- `):""},vc=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},lv=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=av(t,o?.previewMaxLines??3),i=n?Op(n):"";if(!n)return{summary:i,previewText:s,isActive:!1};let l=n.status!=="complete",p=e?.toolCall??{},c=i;return r==="tool-name"?c=n.name?.trim()||i:r==="tool-preview"&&s&&(c=s),l&&p.activeTextTemplate?c=kl(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=kl(n,p.completeTextTemplate,c)),{summary:c,previewText:s,isActive:l}},Gf=(t,e,n)=>{let o=Mr.has(t),r=n?.toolCall??{},s=e.querySelector('button[data-expand-header="true"]'),i=e.querySelector(".persona-border-t"),l=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!i)return;s.setAttribute("aria-expanded",o?"true":"false");let c=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=ae(o?"chevron-up":"chevron-down",16,d,2);u?c.appendChild(u):c.textContent=o?"Hide":"Show"}i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},xc=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","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-${t.id}`,r.setAttribute("data-message-id",t.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=e?.features?.toolCallDisplay??{},i=s.expandable!==!1,l=i&&Mr.has(t.id),{summary:p,previewText:c,isActive:d}=lv(t,e),u=y("button",i?"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");u.type="button",i&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let b=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let m=String(n.startedAt??Date.now()),C=()=>{let P=y("span","");return P.setAttribute("data-tool-elapsed",m),P.textContent=as(n),P},R=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:s.collapsedMode??"tool-call",isActive:d,config:e??{},elapsed:as(n),createElapsedElement:C});typeof R=="string"&&R.trim()?(f.textContent=R,b.appendChild(f)):R instanceof HTMLElement?b.appendChild(R):(f.textContent=p,b.appendChild(f));let H=s.loadingAnimation??"none",L=o.activeTextTemplate,T=o.completeTextTemplate,k=d?L:T,$=R instanceof HTMLElement,G=(P,I)=>{f.textContent="";let j=n.name?.trim()||"tool",pe=Wi(P,j),ue=0;for(let ge of pe){let Z=ge.styles.length>0?(()=>{let oe=y("span",ge.styles.map(Q=>`persona-tool-text-${Q}`).join(" "));return f.appendChild(oe),oe})():f;if(ge.isDuration&&d)Z.appendChild(C());else{let oe=ge.isDuration?as(n):ge.text;I?ue=mo(Z,oe,ue):Z.appendChild(document.createTextNode(oe))}}};if(!$)if(d&&H!=="none"){let P=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),H==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${P}ms`),k&&G(k,!1);else if(f.classList.add(`persona-tool-loading-${H}`),f.style.setProperty("--persona-tool-anim-duration",`${P}ms`),H==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),k)G(k,!0);else{let I=f.textContent||p;f.textContent="",mo(f,I,0)}}else k&&G(k,!1);let w=null;if(i){w=y("div","persona-flex persona-items-center");let P=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",I=ae(l?"chevron-up":"chevron-down",16,P,2);I?w.appendChild(I):w.textContent=l?"Hide":"Show";let j=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");j.append(w),u.append(b,j)}else u.append(b);let F=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","tool"),F.style.display="none",F.style.whiteSpace="pre-wrap",!l&&d&&s.activePreview&&c){let P=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:c,isActive:d,config:e??{}});iv(F,P)||(F.textContent=c),F.style.display=""}if(!l&&d&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!i)return r.append(u,F),r;let D=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(D.style.display=l?"":"none",o.contentBackgroundColor&&(D.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(D.style.color=o.contentTextColor),o.contentPaddingX&&(D.style.paddingLeft=o.contentPaddingX,D.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(D.style.paddingTop=o.contentPaddingY,D.style.paddingBottom=o.contentPaddingY),n.name){let P=y("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?P.style.color=o.contentTextColor:o.headerTextColor&&(P.style.color=o.headerTextColor),P.textContent=n.name,D.appendChild(P)}if(n.args!==void 0){let P=y("div","persona-space-y-1"),I=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(I.style.color=o.labelTextColor),I.textContent="Arguments";let j=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");j.style.fontSize="0.75rem",j.style.lineHeight="1rem",vc(j,o),j.textContent=fo(n.args),P.append(I,j),D.appendChild(P)}if(n.chunks&&n.chunks.length){let P=y("div","persona-space-y-1"),I=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(I.style.color=o.labelTextColor),I.textContent="Activity";let j=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");j.style.fontSize="0.75rem",j.style.lineHeight="1rem",vc(j,o),j.textContent=n.chunks.join(""),P.append(I,j),D.appendChild(P)}if(n.status==="complete"&&n.result!==void 0){let P=y("div","persona-space-y-1"),I=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(I.style.color=o.labelTextColor),I.textContent="Result";let j=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");j.style.fontSize="0.75rem",j.style.lineHeight="1rem",vc(j,o),j.textContent=fo(n.result),P.append(I,j),D.appendChild(P)}if(n.status==="complete"&&typeof n.duration=="number"){let P=y("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(P.style.color=o.contentTextColor),P.textContent=`Duration: ${n.duration}ms`,D.appendChild(P)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),w){w.innerHTML="";let P=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",I=ae(l?"chevron-up":"chevron-down",16,P,2);I?w.appendChild(I):w.textContent=l?"Hide":"Show"}D.style.display=l?"":"none",F.style.display=l?"none":F.textContent||F.childNodes.length?"":"none"})(),r.append(u,F,D),r};tt();St();var _o=new Map,Ra=t=>{let n=(t.startsWith($n)?t.slice($n.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Qf=t=>t?.approval!==!1?t?.approval:void 0,Xf=(t,e)=>{let n=Qf(e)?.detailsDisplay??"collapsed";return _o.get(t)??n==="expanded"},Jf=(t,e,n)=>{let o=Qf(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let i=ae(e?"chevron-up":"chevron-down",14,"currentColor",2);i&&s.appendChild(i)}},Yf=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=Xf(t,n);Jf(o,s,n),r.style.display=s?"":"none"};var Wa=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let i=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=y("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",d=ae(p,20,c,2);d&&l.appendChild(d);let u=y("div","persona-flex-1 persona-min-w-0"),b=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",b.appendChild(f),!r){let w=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");w.setAttribute("data-approval-status",n.status),n.status==="approved"?(w.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",w.style.color="var(--persona-palette-colors-success-700, #15803d)",w.textContent="Approved"):n.status==="denied"?(w.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",w.style.color="var(--persona-palette-colors-error-700, #b91c1c)",w.textContent="Denied"):n.status==="timeout"&&(w.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",w.style.color="var(--persona-palette-colors-warning-700, #b45309)",w.textContent="Timeout"),b.appendChild(w)}u.appendChild(b);let C=n.toolType==="webmcp"||n.toolName.startsWith($n)?ns(n.toolName):void 0,R=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),H=!n.toolName,L=R||(H?n.description:`The assistant wants to use \u201C${C??Ra(n.toolName)}\u201D.`),T=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(T.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=L,u.appendChild(T),n.reason){let w=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");w.setAttribute("data-approval-reason","true"),o?.reasonColor?w.style.color=o.reasonColor:o?.descriptionColor&&(w.style.color=o.descriptionColor);let F=y("span","persona-font-medium");F.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(F),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let k=o?.detailsDisplay??"collapsed",$=!!n.description&&!H,G=$||!!n.parameters;if(k!=="hidden"&&G){let w=Xf(t.id,e),F=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");F.type="button",F.setAttribute("data-expand-header","true"),F.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(F.style.color=o.descriptionColor);let D=y("span");D.setAttribute("data-approval-details-label","true");let B=y("span","persona-inline-flex persona-items-center");B.setAttribute("data-approval-details-chevron","true"),F.append(D,B),Jf(F,w,e),u.appendChild(F);let P=y("div");if(P.setAttribute("data-approval-details","true"),P.style.display=w?"":"none",$){let I=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(I.style.color=o.descriptionColor),I.textContent=n.description,P.appendChild(I)}if(n.parameters){let I=y("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");o?.parameterBackgroundColor&&(I.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(I.style.color=o.parameterTextColor),I.style.fontSize="0.75rem",I.style.lineHeight="1rem",I.textContent=fo(n.parameters),P.appendChild(I)}u.appendChild(P)}if(r){let w=y("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let F=y("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");F.type="button",F.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",F.style.color=o?.approveButtonTextColor??"#ffffff",F.setAttribute("data-approval-action","approve");let D=ae("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);D&&(D.style.marginRight="4px",F.appendChild(D));let B=document.createTextNode(o?.approveLabel??"Approve");F.appendChild(B);let P=y("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");P.type="button",P.style.backgroundColor=o?.denyButtonColor??"transparent",P.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",P.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,P.setAttribute("data-approval-action","deny");let I=ae("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);I&&(I.style.marginRight="4px",P.appendChild(I));let j=document.createTextNode(o?.denyLabel??"Deny");P.appendChild(j),w.append(F,P),u.appendChild(w)}return i.append(l,u),s.appendChild(i),s};tt();St();$l();var cv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Zf=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},$o=(t,e)=>{Zf(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},dv=t=>t?.approval!==!1?t?.approval:void 0,pv=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return _o.get(t)??n==="expanded"},Cc=t=>{let e=y("span","persona-approval-kbd");return e.textContent=t,e},uv=(t,e)=>{let n=y("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith($n)?ns(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let i=r??Ra(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=i,n.appendChild(p),l){n.append(" from ");let c=document.createElement("strong");c.textContent=l,n.appendChild(c)}return n},fv=t=>{let e=y("div","persona-approval-resolved"),n=ae("ban",15,"currentColor",2);n&&e.appendChild(n);let o=y("span","persona-approval-resolved-name");return o.textContent=t.toolName?Ra(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},gv=(t,e,n,o,r,s,i)=>{let l=y("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",c=!!n.description&&p!=="hidden",d=n.parameters!=null&&p!=="hidden",u=c||d,b=u&&pv(e.id,o),f=o?.showDetailsLabel??"Show details",m=o?.hideDetailsLabel??"Hide details",C=y("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",b?"true":"false"),C.setAttribute("aria-label",b?m:f)):C.setAttribute("data-static","true");let R=y("span","persona-approval-logo"),H=ae("shield-check",16,"currentColor",2);H&&R.appendChild(H),C.appendChild(R);let L=uv(n,o);if(u){let F=y("span","persona-approval-toggle");F.setAttribute("aria-hidden","true");let D=ae("chevron-down",14,"currentColor",2);D&&F.appendChild(D),L.append(" "),L.appendChild(F)}C.appendChild(L),l.appendChild(C);let T=y("div","persona-approval-body");if(u){let F=y("div","persona-approval-details");if(F.setAttribute("data-role","params"),F.hidden=!b,c){let D=y("p","persona-approval-desc");o?.descriptionColor&&(D.style.color=o.descriptionColor),D.textContent=n.description,F.appendChild(D)}if(d){let D=y("pre","persona-approval-params");o?.parameterBackgroundColor&&(D.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(D.style.color=o.parameterTextColor),D.textContent=fo(n.parameters),F.appendChild(D)}T.appendChild(F)}if(n.reason){let F=y("p","persona-approval-reason");o?.reasonColor?F.style.color=o.reasonColor:o?.descriptionColor&&(F.style.color=o.descriptionColor);let D=y("span","persona-approval-reason-label");D.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,F.append(D,document.createTextNode(n.reason)),T.appendChild(F)}let k=y("div","persona-approval-actions"),$=null,G=F=>{o?.approveButtonColor&&(F.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(F.style.color=o.approveButtonTextColor)},w=y("button","persona-approval-deny");if(w.type="button",w.setAttribute("data-action","deny"),o?.denyButtonColor&&(w.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(w.style.color=o.denyButtonTextColor),w.append(o?.denyLabel??"Deny"),i){let F=y("div","persona-approval-split"),D=y("button","persona-approval-primary");D.type="button",D.setAttribute("data-action","always"),G(D),D.append(o?.approveLabel??"Always allow",Cc("\u23CE"));let B=y("button","persona-approval-caret");B.type="button",B.setAttribute("data-action","toggle-menu"),B.setAttribute("aria-label","More options"),G(B);let P=ae("chevron-down",15,"currentColor",2);P&&B.appendChild(P),F.append(D,B),k.append(F,w),w.append(Cc("Esc"));let I=y("div","persona-approval-menu"),j=y("button","persona-approval-menu-item");j.type="button",j.append("Allow once",Cc("\u2318\u23CE")),I.appendChild(j),$=Qi({anchor:F,content:I,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,$),j.addEventListener("click",()=>{$o(t,e.id),r()})}else{let F=y("button","persona-approval-primary persona-approval-primary--solo");F.type="button",F.setAttribute("data-action","allow"),G(F),F.append(o?.approveLabel??"Allow"),k.append(F,w)}return T.appendChild(k),l.appendChild(T),l.addEventListener("click",F=>{let D=F.target instanceof Element?F.target.closest("[data-action]"):null;if(!D)return;let B=D.getAttribute("data-action");if(B==="toggle-params"){let P=l.querySelector('[data-role="params"]');if(P){let I=P.hidden;P.hidden=!I,C.setAttribute("aria-expanded",I?"true":"false"),C.setAttribute("aria-label",I?m:f),_o.set(e.id,I)}return}if(B==="toggle-menu"){$?.toggle();return}if(B==="always"){$o(t,e.id),r({remember:!0});return}if(B==="allow"){$o(t,e.id),r();return}if(B==="deny"){$o(t,e.id),s();return}}),l},eg=()=>{let t=cv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:i})=>{let l=o?.approval;if(!l)return null;let p=dv(i);if(l.status!=="pending"){if($o(t,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return fv(l)}Zf(t,o.id);let c=p?.enableAlwaysAllow===!0,d=gv(t,o,l,p,r,s,c);if(c){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let u=b=>{xu(b)||o.id===t.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),$o(t,o.id),b.key==="Escape"?s():b.metaKey||b.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return d}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])$o(t,o);t.latestPendingApprovalId=null}}};tt();var tg=t=>{let e=[],n=null;return{buttons:e,render:(r,s,i,l,p,c)=>{t.innerHTML="",e.length=0;let d=c?.agentPushed===!0;if(d||(n=null),!r||!r.length||!d&&(l??(s?s.getMessages():[])).some(R=>R.role==="user"))return;let u=document.createDocumentFragment(),b=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'}};if(r.forEach(m=>{let C=y("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=m,C.disabled=b,p?.fontFamily&&(C.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(i.value="",d&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:m},bubbles:!0,composed:!0})),s.sendMessage(m))}),u.appendChild(C),e.push(C)}),t.appendChild(u),d){let m=JSON.stringify(r);m!==n&&(n=m,t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var Bs=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),this.store?.put(e)}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 e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ds=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{e(i.result)},i.onerror=()=>{n(i.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}};var mv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),hv=new Set(["step_start","execution_start"]),yv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),bv=new Set(["step_complete","agent_turn_complete"]),vv=new Set(["flow_complete","agent_complete"]),ng=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),rg=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),cn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,zo=(t,e)=>{let n=t[e];return rg(n)?n:void 0};function wc(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function Ha(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function xv(t,e){return typeof e.type=="string"?e.type:t}function Cv(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function wv(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function og(t){let e=zo(t,"result"),n=[zo(t,"tokens"),zo(t,"totalTokens"),e?zo(e,"tokens"):void 0,zo(t,"usage"),e?zo(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=cn(o.output)??cn(o.outputTokens)??cn(o.completionTokens);if(r!==void 0)return r}return cn(t.outputTokens)??cn(t.completionTokens)??(e?cn(e.outputTokens)??cn(e.completionTokens):void 0)}function Av(t){let e=zo(t,"result");return cn(t.executionTime)??cn(t.executionTimeMs)??cn(t.execution_time)??cn(t.duration)??(e?cn(e.executionTime)??cn(e.executionTimeMs):void 0)}function Sv(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ns=class{constructor(e=Sv){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Ha(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){if(!rg(n)){ng.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=xv(e,n),r=this.now();if(mv.has(o)){this.startRun(r);return}if(hv.has(o)){this.run||this.startRun(r);return}if(yv.has(o)){if(!wv(o,n))return;let s=Cv(n);if(!s)return;this.run||this.startRun(r);let i=this.run;i.firstDeltaAt??(i.firstDeltaAt=r),i.visibleCharCount+=s.length;let l=i.exactOutputTokens+wc(i.visibleCharCount),p=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ha(l,p),outputTokens:l,durationMs:p,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(bv.has(o)){if(!this.run)return;let s=this.run,i=og(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+wc(s.visibleCharCount),c=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Ha(p,c),outputTokens:p,durationMs:c,source:l?"usage":"estimate"};return}if(vv.has(o)){if(!this.run)return;let s=this.run,i=og(n),l=i??s.exactOutputTokens+wc(s.visibleCharCount),p=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Ha(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(ng.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Av(n)??o-e.startedAt}};tt();St();function Tr(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var Mv={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)"}},Tv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ev=["flowName","stepName","reasoningText","text","name","tool","toolName"],kv=100;function Lv(t,e){let n={...Mv,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return Tv}function Pv(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function Iv(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Rv(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){let r=o.split("."),s=n;for(let i of r)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Wv(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function Hv(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function Bv(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function Dv(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function Nv(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>i(),parsedPayload:r});if(l)return l}return i();function i(){let l=y("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]"),p=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function Ac(t,e,n,o,r,s,i,l){let p=r.has(t.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Tr(c,o.classNames?.eventRow);let d=i.find(b=>b.renderEventStreamRow);if(d?.renderEventStreamRow&&l){let b=d.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(t.id)});if(b)return c.appendChild(b),c}return c.appendChild(u()),c;function u(){let b=y("div",""),f=y("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");f.setAttribute("data-event-id",t.id);let m=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ae(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&m.appendChild(C);let R=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),H=o.timestampFormat??"relative";R.textContent=H==="relative"?Pv(t.timestamp,n):Iv(t.timestamp);let L=null;o.showSequenceNumbers!==!1&&(L=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),L.textContent=String(e+1));let T=Lv(t.type,o.badgeColors),k=y("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");k.style.backgroundColor=T.bg,k.style.color=T.text,k.style.borderColor=T.text+"50",k.textContent=t.type;let $=o.descriptionFields??Ev,G=Rv(t.payload,$),w=null;G&&(w=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=G);let F=y("div","persona-flex-1 persona-min-w-0"),D=y("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"),B=ae("clipboard","12px","currentColor",1.5);return B&&D.appendChild(B),D.addEventListener("click",async P=>{P.stopPropagation(),await Wv(Hv(t)),D.innerHTML="";let I=ae("check","12px","currentColor",1.5);I&&D.appendChild(I),setTimeout(()=>{D.innerHTML="";let j=ae("clipboard","12px","currentColor",1.5);j&&D.appendChild(j)},1500)}),f.appendChild(m),f.appendChild(R),L&&f.appendChild(L),f.appendChild(k),w&&f.appendChild(w),f.appendChild(F),f.appendChild(D),b.appendChild(f),p&&b.appendChild(Nv(t,i,l)),b}}function sg(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:i}=t,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,c=l?.iconName??"arrow-down",d=l?.label??"",u=r?.features?.eventStream??{},b=s.find(m=>m.renderEventStreamView);if(b?.renderEventStreamView&&r){let m=b.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>f().element,onClose:o});if(m)return{element:m,update:()=>{},destroy:()=>{}}}return f();function f(){let m=u.classNames,C=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Tr(C,m?.panel);let R=[],H="",L="",T=null,k=[],$={},G=0,w=ma(),F=0,D=0,B=!1,P=null,I=!1,j=0,pe=new Set,ue=new Map,ge="",Z="",oe=null,Q,se,te,fe,be=null,he=null,Ce=null;function $e(){let z=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),K=y("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");if(Tr(K,m?.headerBar),i){he=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),he.style.cursor="help",be=y("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 persona-tabular-nums"),be.textContent="-- tok/s",Ce=y("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Ce.style.display="none",Ce.style.pointerEvents="none";let Oe=he,Dt=Ce,Fa=()=>{if(!Dt.textContent)return;let zs=Oe.getBoundingClientRect(),js=z.getBoundingClientRect();Dt.style.left=`${zs.left-js.left}px`,Dt.style.top=`${zs.bottom-js.top+4}px`,Dt.style.display="block"},vo=()=>{Dt.style.display="none"};he.addEventListener("mouseenter",Fa),he.addEventListener("mouseleave",vo),he.appendChild(be)}let ne=y("div","persona-flex-1");Q=y("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 Ge=y("option","");Ge.value="",Ge.textContent="All events (0)",Q.appendChild(Ge),se=y("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"),se.type="button",se.title="Copy All";let Ye=ae("clipboard-copy","12px","currentColor",1.5);Ye&&se.appendChild(Ye);let it=y("span","persona-event-copy-all persona-text-xs");it.textContent="Copy All",se.appendChild(it),he&&K.appendChild(he),K.appendChild(ne),K.appendChild(Q),K.appendChild(se);let X=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Tr(X,m?.searchBar);let je=ae("search","14px","var(--persona-muted, #9ca3af)",1.5),Ae=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");je&&Ae.appendChild(je),te=y("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"),Tr(te,m?.searchInput),te.type="text",te.placeholder="Search event payloads...",fe=y("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"),fe.type="button",fe.style.display="none";let Ue=ae("x","12px","currentColor",2);return Ue&&fe.appendChild(Ue),X.appendChild(Ae),X.appendChild(te),X.appendChild(fe),z.appendChild(K),z.appendChild(X),Ce&&z.appendChild(Ce),z}let Ee,ke=s.find(z=>z.renderEventStreamToolbar);ke?.renderEventStreamToolbar&&r?Ee=ke.renderEventStreamToolbar({config:r,defaultRenderer:()=>$e(),eventCount:e.getSize(),filteredCount:0,onFilterChange:K=>{H=K,nt(),ce()},onSearchChange:K=>{L=K,nt(),ce()}})??$e():Ee=$e();let ze=y("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");ze.style.display="none";function Ke(){if(!i||!be||!he)return;let z=i(),K=Bv(z);be.textContent=K;let ne=Dv(z);Ce&&(Ce.textContent=ne,ne||(Ce.style.display="none")),he.setAttribute("aria-label",ne?`Throughput: ${K}, ${ne}`:`Throughput: ${K}`)}let Le=y("div","persona-flex-1 persona-min-h-0 persona-relative"),Re=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Re.style.height="100%";let Je=y("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");Tr(Je,m?.scrollIndicator),Je.style.display="none",Je.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let Ot=ae(c,"14px","currentColor",2);Ot&&Je.appendChild(Ot);let Bt=y("span","");Bt.textContent=d,Je.appendChild(Bt);let Xt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Xt.style.display="none",Le.appendChild(Re),Le.appendChild(Xt),Le.appendChild(Je),C.setAttribute("tabindex","0"),C.appendChild(Ee),C.appendChild(ze),C.appendChild(Le);function Mt(){let z=e.getAll(),K={};for(let X of z)K[X.type]=(K[X.type]||0)+1;let ne=Object.keys(K).sort(),Ge=ne.length!==k.length||!ne.every((X,je)=>X===k[je]),Be=!Ge&&ne.some(X=>K[X]!==$[X]),Ye=z.length!==Object.values($).reduce((X,je)=>X+je,0);if(!Ge&&!Be&&!Ye||(k=ne,$=K,!Q))return;let it=Q.value;if(Q.options[0].textContent=`All events (${z.length})`,Ge){for(;Q.options.length>1;)Q.remove(1);for(let X of ne){let je=y("option","");je.value=X,je.textContent=`${X} (${K[X]||0})`,Q.appendChild(je)}it&&ne.includes(it)?Q.value=it:it&&(Q.value="",H="")}else for(let X=1;X<Q.options.length;X++){let je=Q.options[X];je.textContent=`${je.value} (${K[je.value]||0})`}}function Ne(){let z=e.getAll();if(H&&(z=z.filter(K=>K.type===H)),L){let K=L.toLowerCase();z=z.filter(ne=>ne.type.toLowerCase().includes(K)||ne.payload.toLowerCase().includes(K))}return z}function me(){return H!==""||L!==""}function nt(){G=0,F=0,w.resume(),Je.style.display="none"}function He(z){pe.has(z)?pe.delete(z):pe.add(z),oe=z;let K=Re.scrollTop,ne=w.isFollowing();I=!0,w.pause(),ce(),Re.scrollTop=K,ne&&w.resume(),I=!1}function ve(){return yo(Re,50)}function ce(){D=Date.now(),B=!1,Ke(),Mt();let z=e.getEvictedCount();z>0?(ze.textContent=`${z.toLocaleString()} older events truncated`,ze.style.display=""):ze.style.display="none",R=Ne();let K=R.length,ne=e.getSize()>0;K===0&&ne&&me()?(Xt.textContent=L?`No events matching '${L}'`:"No events matching filter",Xt.style.display="",Re.style.display="none"):(Xt.style.display="none",Re.style.display=""),se&&(se.title=me()?`Copy Filtered (${K})`:"Copy All"),p&&!w.isFollowing()&&K>G&&(F+=K-G,Bt.textContent=d?`${d}${F>0?` (${F})`:""}`:"",Je.style.display=""),G=K;let Ge=e.getAll(),Be=Ge.length>0?Ge[0].timestamp:0,Ye=new Set(R.map(je=>je.id));for(let je of pe)Ye.has(je)||pe.delete(je);let it=H!==ge||L!==Z,X=ue.size===0&&R.length>0;if(it||X||R.length===0){Re.innerHTML="",ue.clear();let je=document.createDocumentFragment();for(let Ae=0;Ae<R.length;Ae++){let Ue=Ac(R[Ae],Ae,Be,u,pe,He,s,r);ue.set(R[Ae].id,Ue),je.appendChild(Ue)}Re.appendChild(je),ge=H,Z=L,oe=null}else{if(oe!==null){let Ae=ue.get(oe);if(Ae&&Ae.parentNode===Re){let Ue=R.findIndex(Oe=>Oe.id===oe);if(Ue>=0){let Oe=Ac(R[Ue],Ue,Be,u,pe,He,s,r);Re.insertBefore(Oe,Ae),Ae.remove(),ue.set(oe,Oe)}}oe=null}let je=new Set(R.map(Ae=>Ae.id));for(let[Ae,Ue]of ue)je.has(Ae)||(Ue.remove(),ue.delete(Ae));for(let Ae=0;Ae<R.length;Ae++){let Ue=R[Ae];if(!ue.has(Ue.id)){let Oe=Ac(Ue,Ae,Be,u,pe,He,s,r);ue.set(Ue.id,Oe),Re.appendChild(Oe)}}}w.isFollowing()&&(Re.scrollTop=Re.scrollHeight)}function We(){if(Date.now()-D>=kv){P!==null&&(cancelAnimationFrame(P),P=null),ce();return}B||(B=!0,P=requestAnimationFrame(()=>{P=null,ce()}))}let ct=(z,K)=>{if(!se)return;se.innerHTML="";let ne=ae(z,"12px","currentColor",1.5);ne&&se.appendChild(ne);let Ge=y("span","persona-text-xs");Ge.textContent="Copy All",se.appendChild(Ge),setTimeout(()=>{se.innerHTML="";let Be=ae("clipboard-copy","12px","currentColor",1.5);Be&&se.appendChild(Be);let Ye=y("span","persona-text-xs");Ye.textContent="Copy All",se.appendChild(Ye),se.disabled=!1},K)},ye=async()=>{if(se){se.disabled=!0;try{let z;me()?z=R:n?(z=await n(),z.length===0&&(z=e.getAll())):z=e.getAll();let K=z.map(ne=>{try{return JSON.parse(ne.payload)}catch{return ne.payload}});await navigator.clipboard.writeText(JSON.stringify(K,null,2)),ct("check",1500)}catch{ct("x",1500)}}},Me=()=>{Q&&(H=Q.value,nt(),ce())},re=()=>{!te||!fe||(fe.style.display=te.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{L=te.value,nt(),ce()},150))},M=()=>{!te||!fe||(te.value="",L="",fe.style.display="none",T&&clearTimeout(T),nt(),ce())},U=()=>{if(I)return;let z=Re.scrollTop,{action:K,nextLastScrollTop:ne}=ha({following:w.isFollowing(),currentScrollTop:z,lastScrollTop:j,nearBottom:ve(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});j=ne,K==="resume"?(w.resume(),F=0,Je.style.display="none"):K==="pause"&&(w.pause(),p&&(Bt.textContent=d,Je.style.display=""))},v=z=>{let K=ya({following:w.isFollowing(),deltaY:z.deltaY,nearBottom:ve(),resumeWhenNearBottom:!0});K==="pause"?(w.pause(),p&&(Bt.textContent=d,Je.style.display="")):K==="resume"&&(w.resume(),F=0,Je.style.display="none")},N=()=>{p&&(Re.scrollTop=Re.scrollHeight,w.resume(),F=0,Je.style.display="none")},E=z=>{let K=z.target;if(!K||K.closest("button"))return;let ne=K.closest("[data-event-id]");if(!ne)return;let Ge=ne.getAttribute("data-event-id");Ge&&He(Ge)},O=z=>{if((z.metaKey||z.ctrlKey)&&z.key==="f"){z.preventDefault(),te?.focus(),te?.select();return}z.key==="Escape"&&(te&&document.activeElement===te?(M(),te.blur(),C.focus()):o&&o())};se&&se.addEventListener("click",ye),Q&&Q.addEventListener("change",Me),te&&te.addEventListener("input",re),fe&&fe.addEventListener("click",M),Re.addEventListener("scroll",U),Re.addEventListener("wheel",v,{passive:!0}),Re.addEventListener("click",E),Je.addEventListener("click",N),C.addEventListener("keydown",O);function J(){T&&clearTimeout(T),P!==null&&(cancelAnimationFrame(P),P=null),B=!1,ue.clear(),se&&se.removeEventListener("click",ye),Q&&Q.removeEventListener("change",Me),te&&te.removeEventListener("input",re),fe&&fe.removeEventListener("click",M),Re.removeEventListener("scroll",U),Re.removeEventListener("wheel",v),Re.removeEventListener("click",E),Je.removeEventListener("click",N),C.removeEventListener("keydown",O)}return{element:C,update:We,destroy:J}}}tt();St();function ig(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let s=[],i=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let b=u;return s.findIndex(f=>f===b||f.contains(b))},c=u=>{let b=p(u.target);if(b<0)return;let f=b;if(u.key===r)f=Math.min(b+1,s.length-1);else if(u.key===o)f=Math.max(b-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=s.length-1;else return;u.preventDefault(),f!==b&&e.onSelect(f)},d=u=>{let b=p(u.target);b>=0&&l(s[b])};return t.addEventListener("keydown",c),t.addEventListener("focusin",d),{beforeRender(){i=typeof document<"u"&&t.contains(document.activeElement)},render(u,b){if(s=u,u.forEach((f,m)=>{f.setAttribute("role","tab");let C=m===b;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||b<0&&m===0?0:-1}),i){let f=(b>=0?u[b]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){t.removeEventListener("keydown",c),t.removeEventListener("focusin",d)}}}function ag(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",i=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),c=re=>({start:re===!1?!1:typeof re=="object"&&re?re.start!==!1:!0,end:re===!1?!1:typeof re=="object"&&re?re.end!==!1:!0}),{start:d,end:u}=c(n?.tabFade),b=typeof document<"u"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{b?.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),I?.hide()};b&&b.addEventListener("click",()=>{f(),e.onDismiss?.()});let m=y("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");m.setAttribute("data-persona-theme-zone","artifact-pane"),r&&m.classList.add("persona-artifact-pane-document");let C=y("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");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let R=y("span","persona-text-xs persona-font-medium persona-truncate");R.textContent=s;let H=Ht({icon:"x",label:i});H.addEventListener("click",()=>{f(),e.onDismiss?.()});let L="rendered",T=da({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:re=>{L=re==="source"?"source":"rendered",ct()}}),k=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),$=n?.documentToolbarShowCopyLabel===!0,G=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,F=!!(G&&w&&w.length>0),D=null,B,P=null,I=null;if(r&&($||G)&&!F){if(B=$?Oo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ht({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),G){let re=ae("chevron-down",14,"currentColor",2);re&&B.appendChild(re)}}else r&&F?(D=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),B=$?Oo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ht({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P=Ht({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"}}),D.append(B,P)):r?B=Ht({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(B=Ht({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&B.classList.add("persona-hidden"));let j=r?Ht({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Ht({icon:"refresh-cw",label:"Refresh"}),pe=r?Ht({icon:"x",label:i,className:"persona-artifact-doc-icon-btn"}):Ht({icon:"x",label:i}),ue=Ht({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&ue.classList.add("persona-hidden");let ge=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),Z=t.features?.artifacts?.toolbarActions??[],oe=()=>{let re=Le.find(N=>N.id===Re)??Le[Le.length-1],M=re?.id??null,U=re?.artifactType==="markdown"?re.markdown??"":"",v=re?JSON.stringify({component:re.component,props:re.props},null,2):"";return{markdown:U,jsonPayload:v,id:M}},Q=async()=>{let re=Le.find(M=>M.id===Re)??Le[Le.length-1];try{await navigator.clipboard.writeText(Ts(re))}catch{}};if(B.addEventListener("click",async()=>{let re=n?.onDocumentToolbarCopyMenuSelect;if(re&&F){let{markdown:M,jsonPayload:U,id:v}=oe();try{await re({actionId:"primary",artifactId:v,markdown:M,jsonPayload:U})}catch{}return}await Q()}),P&&w?.length){let re=()=>m.closest("[data-persona-root]")??document.body,M=()=>{I=Cr({items:w.map(U=>({id:U.id,label:U.label})),onSelect:async U=>{let{markdown:v,jsonPayload:N,id:E}=oe(),O=n?.onDocumentToolbarCopyMenuSelect;try{O?await O({actionId:U,artifactId:E,markdown:v,jsonPayload:N}):U==="markdown"||U==="md"?await navigator.clipboard.writeText(v):U==="json"||U==="source"?await navigator.clipboard.writeText(N):await navigator.clipboard.writeText(v||N)}catch{}},anchor:D??P,position:"bottom-right",portal:re()})};m.isConnected?M():requestAnimationFrame(M),P.addEventListener("click",U=>{U.stopPropagation(),I?.toggle()})}j.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ct()}),pe.addEventListener("click",()=>{f(),e.onDismiss?.()});let se=y("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");if(r)C.replaceChildren(),D?k.append(D,j,pe):k.append(B,j,pe),k.insertBefore(ge,pe),k.insertBefore(ue,pe),C.append(T.element,se,k);else{let re=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");re.append(B,ge,ue,H),C.appendChild(R),C.appendChild(re)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let te=y("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");p&&te.style.setProperty("--persona-artifact-tab-fade-size",p);let fe=t.features?.artifacts?.renderTabBar,be=y("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),he=ig(te,{onSelect:re=>e.onSelect(Le[re].id)}),Ce=re=>{let M=re.scrollWidth-re.clientWidth,U=M>1,v=Math.abs(re.scrollLeft);re.classList.toggle("persona-artifact-tab-fade-start",d&&U&&v>1),re.classList.toggle("persona-artifact-tab-fade-end",u&&U&&v<M-1)},$e=0,Ee=()=>{if($e)return;let re=()=>{$e=0,Ce(te)};$e=typeof requestAnimationFrame=="function"?requestAnimationFrame(re):setTimeout(re,0)};te.addEventListener("scroll",()=>Ee(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Ce(te)).observe(te);let ke=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),ze=()=>{ke.scrollLeft=0},Ke=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(ze):setTimeout(ze,0)};if(l){for(let re of[te,be])re.style.paddingLeft=l,re.style.paddingRight=l;ke.style.padding=l}m.appendChild(C),m.appendChild(te),m.appendChild(be),m.appendChild(ke);let Le=[],Re=null,Je=!1,Ot=!1,Bt=!0,Xt=!1,Mt=null,Ne="",me=null,nt=!1,He=re=>re.artifactType==="markdown"&&!!re.file||r?L:"rendered",ve=re=>{r||(re&&!nt?(C.insertBefore(T.element,R),nt=!0):!re&&nt&&(T.element.remove(),nt=!1))},ce=()=>Re&&Le.find(re=>re.id===Re)||Le[Le.length-1],We=()=>{let re=Ss(ce());if(!re){ge.replaceChildren();return}let M=Z.filter(U=>U.visible===void 0||U.visible(re)).map(U=>wr(U,{documentChrome:r,onClick:()=>{let v=Ss(ce());if(v)try{Promise.resolve(U.onClick(v)).catch(()=>{})}catch{}}}));ge.replaceChildren(...M)},ct=()=>{We();let re=r&&Le.length<=1,M=!!fe;if(te.classList.toggle("persona-hidden",re||M),be.classList.toggle("persona-hidden",re||!M),M&&fe){let N=Le.map(E=>E.id).join("|")+" "+(Re??"");if(N!==Ne){Ne=N;let E=fe({records:Le,selectedId:Re,onSelect:e.onSelect});be.firstElementChild!==E&&be.replaceChildren(E)}}else{he.beforeRender(),te.replaceChildren();let N=[],E=-1;for(let[O,J]of Le.entries()){let z=y("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");z.type="button";let K=J.artifactType==="markdown"?J.file:void 0,ne=K?Pn(K.path):J.title||J.id.slice(0,8),Ge=K?.path||J.title||ne;z.textContent=ne,z.title=Ge,z.setAttribute("aria-label",Ge),J.id===Re&&(z.classList.add("persona-bg-persona-container","persona-border-persona-border"),E=O),z.addEventListener("click",()=>e.onSelect(J.id)),te.appendChild(z),N.push(z)}if(he.render(N,E),E>=0&&Re!==Mt){Mt=Re;let O=N[E];typeof O.scrollIntoView=="function"&&O.scrollIntoView({block:"nearest",inline:"nearest"})}Ce(te)}let U=Re&&Le.find(N=>N.id===Re)||Le[Le.length-1];if(!U){ke.replaceChildren(),me=null,ve(!1);return}let v=U.artifactType==="markdown"?U.file:void 0;if(ve(!!v),r){let N=v?go(v):U.artifactType==="markdown"?"MD":U.component??"Component",E=(U.title||"Document").trim(),O=v?Pn(v.path):E.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";se.textContent=`${O} \xB7 ${N}`}else R.textContent=v?Pn(v.path):s;me?(me.el.parentElement!==ke&&ke.replaceChildren(me.el),me.update(U)):(me=fa(U,{config:t,resolveViewMode:He}),ke.replaceChildren(me.el)),ke.classList.toggle("persona-artifact-content-flush",!!ke.querySelector(".persona-code-pre"))},ye=()=>{let re=Le.length>0;if(m.classList.toggle("persona-hidden",!re),b){let v=((typeof m.closest=="function"?m.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;re&&v&&Je?(b.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}},Me=()=>{Xt=!1,ct(),ye()};return{element:m,backdrop:b,update(re){let M=re.selectedId??re.artifacts[re.artifacts.length-1]?.id??null,U=M!==Re;Le=re.artifacts,Re=M,Le.length>0&&(Je=!0),Xt=!0,Bt&&Me(),U&&ze()},setMobileOpen(re){Je=re,!re&&b?(b.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):ye()},setExpanded(re){re!==Ot&&(Ot=re,Ke());let M=ae(re?"minimize":"maximize",16,"currentColor",2);M&&ue.replaceChildren(M);let U=re?"Collapse artifacts panel":"Expand artifacts panel";ue.setAttribute("aria-label",U),ue.title=U},setExpandToggleVisible(re){ue.classList.toggle("persona-hidden",!re)},setCopyButtonVisible(re){r||B.classList.toggle("persona-hidden",!re)},setCustomActions(re){Z=re,We()},setTabFade(re){let M=c(re);M.start===d&&M.end===u||(d=M.start,u=M.end,Ce(te))},setRenderTabBar(re){re!==fe&&(fe=re,Ne="",ct())},setVisible(re){re!==Bt&&(Bt=re,re&&Xt&&Me())}}}function en(t){return t?.features?.artifacts?.enabled===!0}function lg(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!en(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function Ov(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var cg=["panel","seamless","detached"];function Sc(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&cg.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Mc(t){return!t||!en(t)?!1:Sc(t)==="detached"}function Os(t,e){if(!en(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),Ov(t),lg(t,e);return}let n=e.features?.artifacts?.layout,o=Sc(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let i=n?.documentToolbarIconColor?.trim();i?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",i):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?t.style.setProperty("--persona-artifact-doc-toggle-active-border",p):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),lg(t,e)}function Fs(t,e){for(let l of cg)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!en(e))return;let n=e.features?.artifacts?.layout,o=Sc(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let i=n?.chatShadow?.trim();i&&t.style.setProperty("--persona-artifact-chat-shadow",i)}function dg(t,e){return!e||!en(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var Fv=new Set(["__proto__","prototype","constructor"]),_v=new Set(["collapsed","card","panel","inline"]),pg=new Set(["markdown","component"]),$v=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,jo=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Da=t=>!Fv.has(t),Tc=t=>typeof t=="string"&&_v.has(t),Uo=t=>Object.keys(t).length>0;function Rn(t,e,n,o){t.push({path:e,code:n,message:o})}var zv="Ignored because this key is not part of the persisted preference schema.",Ba="Ignored an unsupported value.",jv="Expected collapsed, panel, or inline.",Uv='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',ug={kind:"mode",message:Ba},Er={kind:"string",message:"Expected a CSS length string."},Kn={kind:"boolean"},Vv={paneWidth:Er,paneMaxWidth:Er,paneMinWidth:Er,expandedPanelWidth:Er,resizableMinWidth:Er,resizableMaxWidth:Er,expandLauncherPanelWhenOpen:Kn,resizable:Kn},qv={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Kn,showReasoning:Kn,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Ba},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Ba},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Ba},expandable:Kn,grouped:Kn}},reasoningDisplay:{kind:"object",children:{expandable:Kn,activePreview:Kn}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:ug,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:ug,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:pg,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:pg}}},filePreview:{kind:"object",children:{enabled:Kn}},layout:{kind:"object",children:Vv}}}}};function fg(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Rn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Rn(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Rn(o,n,"invalid_value",e.message);case"mode":return Tc(t)?hn(t):Rn(o,n,"invalid_value",e.message);case"modeMap":{if(!jo(t))return Rn(o,n,"invalid_type","Expected an object.");let r=e.keys==="mediaType"?void 0:e.keys,s={};for(let[i,l]of Object.entries(t)){let p=r?i:ir(i);Da(i)&&(r?r.has(i):$v.test(p))?Tc(l)?s[p]=hn(l):Rn(o,`${n}.${i}`,"invalid_value",jv):Rn(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":Uv)}return Uo(s)?s:void 0}case"object":{if(e.bareMode&&Tc(t))return hn(t);if(!jo(t))return Rn(o,n,"invalid_type",e.message??"Expected an object.");let r=Object.keys(e.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(t))(!Da(l)||!r.includes(l))&&Rn(o,s(l),"unknown_key",zv);let i={};for(let l of r){let p=e.children[l],c=fg(t[l],p,s(l),o);if(p.deprecated&&t[l]!==void 0&&Rn(o,s(l),"deprecated_key",p.deprecated),c===void 0)continue;let d=p.alias??l,u=i[d];i[d]=jo(u)&&jo(c)?{...u,...c}:c}return Uo(i)?i:void 0}}}function Kv(t){let e=[];return{preferences:(t===null?void 0:fg(t,qv,"",e))??{},issues:e}}function kr(t){if(Array.isArray(t))return t.map(kr);if(!jo(t))return t;let e={};for(let[n,o]of Object.entries(t))Da(n)&&o!==void 0&&(e[n]=kr(o));return e}function gg(t,e){let n=kr(t);for(let[o,r]of Object.entries(e)){if(!Da(o)||r===void 0)continue;let s=n[o];n[o]=jo(s)&&jo(r)?gg(s,r):kr(r)}return n}function Gv(t){let e={},n;for(let r of t){let s=Kv(r).preferences;n=mg(n,s.artifacts?.display),e=gg(e,s)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Qv(t,e){if(e===void 0)return t===void 0?void 0:kr(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byMediaType,...e.byMediaType},s={...o?{default:o}:{},...Uo(r)?{byMediaType:r}:{}};return Uo(s)?s:void 0}function mg(t,e){if(e===void 0)return t===void 0?void 0:kr(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byType,...n.byKind,...e.byType,...e.byKind},s=Qv(n.files,e.files),i={...o?{default:o}:{},...Uo(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Uo(i)?i:void 0}function Xv(t={},e){let n=Gv(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=t.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let i=mg(r.display,n.artifacts.display);i!==void 0&&(s.display=i)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Ec(t){let e=t.preferences;return!e||!Uo(e)?t:{...t,features:Xv(t.features??{},[e])}}function Jv(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function Yv(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Zv(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function ex(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function kc(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function hg(t,e,n,o,r,s){let i=Jv(r,200),l=ex(e,n,o,200);l=Math.max(i,l);let p=Yv(s);return p!==null&&(l=Math.min(l,p)),Zv(t,i,l)}tt();var yg={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"}},Lc=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let i=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=yg[i]??yg.init;s.classList.add("persona-form-card","persona-space-y-4");let p=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let m=y("p","persona-text-sm persona-text-persona-muted");m.textContent=l.description,p.appendChild(m)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",l.fields.forEach(m=>{let C=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${i}-${m.name}`;let R=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=m.label,C.appendChild(R);let H=m.type??"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=`${e.id}-${i}-${m.name}`,L.name=m.name,L.placeholder=m.placeholder??"",m.required&&(L.required=!0),C.appendChild(L),d.appendChild(C)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("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");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(b),u.appendChild(f),d.appendChild(u),s.replaceChildren(p,d),d.addEventListener("submit",async m=>{m.preventDefault();let C=n.formEndpoint??"/form",R=new FormData(d),H={};R.forEach((L,T)=>{H[T]=L}),H.type=i,f.disabled=!0,b.textContent="Submitting\u2026";try{let L=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!L.ok)throw new Error(`Form submission failed (${L.status})`);let T=await L.json();b.textContent=T.message??"Thanks! We'll be in touch soon.",T.success&&T.nextPrompt&&await o.sendMessage(String(T.nextPrompt))}catch(L){b.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Pc=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,i)=>(i.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},Ic=new Pc;var bg=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),tx=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),vg=(t,e,n)=>{if(!bg(t)||!bg(e)||tx.has(n))return e;let o={...t};for(let r of Object.keys(e)){if(e[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=vg(t[r],e[r],s)}return o};function xg(t,e){let n=vg(t,e,"");return oa(n)}var Cg=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(i=>{try{i(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var nx=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},ox=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},Wc=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=nx(t),n=ox(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Rc=t=>typeof t=="string"?t:t==null?"":String(t),_s={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Rc(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Rc(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Rc(n.text)}}},wg=t=>Array.isArray(t)?t.map(e=>String(e)):[],Hc=t=>{let e=new Set(wg(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(wg(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?t.parsers.reduce((c,d)=>c||d?.({text:i,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let p={action:l,message:s.message};t.emit("action:detected",p);for(let c of t.handlers)if(c)try{let d=()=>{t.emit("action:resubmit",p)},u=c(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:d});if(!u)continue;if(u.handled){let b=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:b,resubmit:u.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var rx=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},sx=t=>t.map(e=>({...e,streaming:!1})),ix=t=>t.map(e=>({...e,status:"complete"})),Ag=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?rx(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?sx(n.messages):void 0,artifacts:n.artifacts?ix(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Bc=require("partial-json");function Sg(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=qn.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let i={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(t.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function Mg(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Dc(t){let e=Mg(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Tg(t){let e=Mg(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var ax=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Eg(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:c=ax}=t,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let u=null,b=document.createElement("div");b.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let m=document.createElement("h3");m.className="persona-feedback-title",m.textContent=o,f.appendChild(m);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),b.appendChild(f);let R=document.createElement("div");R.className="persona-feedback-rating persona-feedback-rating-csat",R.setAttribute("role","radiogroup"),R.setAttribute("aria-label","Satisfaction rating from 1 to 5");let H=[];for(let G=1;G<=5;G++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${G} star${G>1?"s":""}: ${c[G-1]}`),w.title=c[G-1],w.dataset.rating=String(G),w.innerHTML=`
212
+ `,n.addEventListener("click",e);let o=s=>{let i=s.launcher??{},l=_t(s),p=n.querySelector("[data-role='launcher-title']");if(p){let S=i.title??"Chat Assistant";p.textContent=S,p.setAttribute("title",S)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let S=i.subtitle??"Here to help you get answers fast";c.textContent=S,c.setAttribute("title",S)}let d=n.querySelector(".persona-flex-col");d&&(i.textHidden||l?d.style.display="none":d.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(i.agentIconHidden)u.style.display="none";else{let S=i.agentIconSize??"40px";if(u.style.height=S,u.style.width=S,i.agentIconBackgroundColor?(u.style.backgroundColor=i.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",i.agentIconName){let E=parseFloat(S)||24,z=ae(i.agentIconName,E*.6,"var(--persona-text-inverse, #ffffff)",2);z?(u.appendChild(z),u.style.display=""):(u.textContent=i.agentIconText??"\u{1F4AC}",u.style.display="")}else i.iconUrl?u.style.display="none":(u.textContent=i.agentIconText??"\u{1F4AC}",u.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let S=i.agentIconSize??"40px";b.style.height=S,b.style.width=S,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(b.src=i.iconUrl,b.style.display="block"):b.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let S=i.callToActionIconSize??"32px";g.style.height=S,g.style.width=S,i.callToActionIconBackgroundColor?(g.style.backgroundColor=i.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(g.style.color=i.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let E=0;if(i.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=i.callToActionIconPadding,E=(parseFloat(i.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),i.callToActionIconHidden)g.style.display="none";else if(g.style.display=l?"none":"",g.innerHTML="",i.callToActionIconName){let z=parseFloat(S)||24,G=Math.max(z-E,8),A=ae(i.callToActionIconName,G,"currentColor",2);A?g.appendChild(A):g.textContent=i.callToActionIconText??"\u2197"}else g.textContent=i.callToActionIconText??"\u2197"}let h=i.position&&kn[i.position]?kn[i.position]:kn["bottom-right"],C="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",L="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?L:`${C} ${h}`,l||(n.style.zIndex=String(i.zIndex??Qt));let B="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=i.border??B,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:k,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=i.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:r}};var af=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=rf(t),s=sf(t,e),i={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:i,panelElements:s,transcript:l,header:p,composer:c,replaceHeader:b=>(p.element.replaceWith(b.header),p.element=b.header,p.iconHolder=b.iconHolder,p.headerTitle=b.headerTitle,p.headerSubtitle=b.headerSubtitle,p.closeButton=b.closeButton,p.closeButtonWrapper=b.closeButtonWrapper,p.clearChatButton=b.clearChatButton,p.clearChatButtonWrapper=b.clearChatButtonWrapper,b),replaceComposer:b=>{c.footer.replaceWith(b),c.footer=b}}},vc=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>bc(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=bc(t,n);return{instance:r,element:r.element}};Je();wt();var gv=t=>{switch(t){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}},fv=(t,e)=>{if(!t)return null;let n=gv(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},mv=(t,e)=>{let n=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},hv=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},xc=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},Cc=320,pf=320,yv=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),bv=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),vv=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),xv=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Cv=t=>{if(!t||t.length===0)return null;let e=Ce("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=Ce("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=ae(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Ce("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},wv=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ks(o.ref,{readonly:!0,render:e}))}return n},lf="\uE000",cf="\uE001",Av=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${lf}${r}:${b}${cf}`,i=e.map((b,g)=>b.kind==="text"?b.text:s(g)).join(""),l=n(i);if(!e.every((b,g)=>b.kind==="text"||l.includes(s(g)))){t.replaceChildren(wv(e,o));return}t.innerHTML=l;let c=new RegExp(`${lf}${r}:(\\d+)${cf}`),d=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),u=[];for(let b=d.nextNode();b;b=d.nextNode())u.push(b);for(let b of u){let g=b;for(let h=c.exec(g.data);h;h=c.exec(g.data)){let C=e[Number(h[1])],L=g.splitText(h.index);L.data=L.data.slice(h[0].length),C?.kind==="mention"&&L.parentNode?.insertBefore(ks(C.ref,{readonly:!0,render:o}),L),g=L}}},Sv=(t,e,n)=>{if(t.length===0)return null;try{let o=v("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,i=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,p)=>{let c=v("img");c.alt=l.alt?.trim()||`Attached image ${p+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Cc}px`,c.style.maxHeight=`${pf}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let d=!1;r+=1,c.addEventListener("error",()=>{d||(d=!0,r=Math.max(0,r-1),c.remove(),r===0&&i())}),c.addEventListener("load",()=>{d=!0}),hv(l.image)?(c.src=l.image,o.appendChild(c)):(d=!0,r=Math.max(0,r-1),c.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},Mv=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!xc(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Cc}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Tv=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!xc(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Cc}px`,r.style.maxHeight=`${pf}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Ev=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!xc(o.data))return;let r=v("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},zs=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";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="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},kv=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:zs};if(e){let r=e(o);if(r!==null)return r}return zs()},Lv=(t,e)=>{let n=v("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"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=v("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},df=(t,e,n="div")=>{let o=v(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},wc=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},Pv=(t,e,n)=>{let o=e.showCopy??!0,r=e.showUpvote??!0,s=e.showDownvote??!0,i=e.showReadAloud??!1;if(!o&&!r&&!s&&!i){let h=v("div");return h.style.display="none",h.id=`actions-${t.id}`,h.setAttribute("data-actions-for",t.id),h}let l=e.visibility??"hover",p=e.align??"right",c=e.layout??"pill-inside",d={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],b=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${d} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${t.id}`,b.setAttribute("data-actions-for",t.id);let g=(h,C,L)=>{let B=Ht({icon:h,label:C,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",L),B};return o&&b.appendChild(g("copy","Copy message","copy")),i&&b.appendChild(g("volume-2","Read aloud","read-aloud")),r&&b.appendChild(g("thumbs-up","Upvote","upvote")),s&&b.appendChild(g("thumbs-down","Downvote","downvote")),b},Ac=(t,e,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",p=i.avatar,c=i.timestamp,d=p?.show??!1,u=c?.show??!1,b=p?.position??"left",g=c?.position??"below",h=wc(t.role,l),C=v("div",h.join(" "));C.id=`bubble-${t.id}`,C.setAttribute("data-message-id",t.id),C.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=yv(t),B=t.content?.trim()??"",S=L.length>0&&B===zi,E=Sa(s?.widgetConfig?.features?.streamAnimation),z=s?.widgetConfig?.features?.streamAnimation?.plugins,G=t.role==="assistant"&&E.type!=="none"?Er(E.type,z):null,A=t.role==="assistant"&&G?.isAnimating?.(t)===!0,O=t.role==="assistant"&&G!==null&&(!!t.streaming||A);O&&G?.bubbleClass&&C.classList.add(G.bubbleClass);let D=document.createElement("div");D.classList.add("persona-message-content"),t.streaming&&D.classList.add("persona-content-streaming"),O&&G&&(G.containerClass&&D.classList.add(G.containerClass),D.style.setProperty("--persona-stream-step",`${E.speed}ms`),D.style.setProperty("--persona-stream-duration",`${E.duration}ms`));let W=O?Ma(t.content??"",E.buffer,G,t,!!t.streaming):t.content??"",P=()=>{let ee=e({text:W,message:t,streaming:!!t.streaming,raw:t.rawContent});return O&&G?.wrap==="char"?Ds(ee,"char",t.id,{skipTags:G.skipTags}):O&&G?.wrap==="word"?Ds(ee,"word",t.id,{skipTags:G.skipTags}):ee},I=null;if(S?(I=document.createElement("div"),I.innerHTML=P(),I.style.display="none",D.appendChild(I)):t.contentSegments?.length?Av(D,t.contentSegments,ee=>e({text:ee,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):D.innerHTML=P(),O&&G?.useCaret&&!S&&B){let ee=Ta(),fe=D.querySelectorAll(".persona-stream-char, .persona-stream-word"),be=fe[fe.length-1];if(be?.parentNode)be.parentNode.insertBefore(ee,be.nextSibling);else{let he=D.lastElementChild;he?he.appendChild(ee):D.appendChild(ee)}}if(u&&g==="inline"&&t.createdAt){let ee=df(t,c,"span");ee.classList.add("persona-timestamp-inline");let fe=D.lastElementChild;fe?fe.appendChild(ee):D.appendChild(ee)}if(L.length>0){let ee=Sv(L,!S&&!!B,()=>{S&&I&&(I.style.display="")});ee?C.appendChild(ee):S&&I&&(I.style.display="")}let j=bv(t);if(j.length>0){let ee=Mv(j);ee&&C.appendChild(ee)}let pe=vv(t);if(pe.length>0){let ee=Tv(pe);ee&&C.appendChild(ee)}let ge=xv(t);if(ge.length>0){let ee=Ev(ge);ee&&C.appendChild(ee)}let se=t.contentSegments?.length?null:Cv(t.contextMentions);if(se&&C.appendChild(se),C.appendChild(D),u&&g==="below"&&t.createdAt){let ee=df(t,c);ee.classList.add("persona-mt-1"),C.appendChild(ee)}let Y=t.role==="assistant"?fv(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let ee=!!(W&&W.trim()),fe=E.placeholder==="skeleton",be=fe&&E.buffer==="line"&&ee;if(ee)be&&C.appendChild(Ns());else if(fe)C.appendChild(Ns());else{let he=kv("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);he&&C.appendChild(he)}}if(Y&&t.stopReason&&!t.streaming&&(B||(D.style.display="none"),C.appendChild(mv(t.stopReason,Y))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let ee=Pv(t,o,r);C.appendChild(ee)}if(!d||t.role==="system")return C;let J=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ie=Lv(p,t.role);return b==="right"||b==="left"&&t.role==="user"?J.append(C,ie):J.append(ie,C),J};Je();wt();var kr=new Set,Iv=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Rv=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
213
+ `):""},uf=(t,e)=>{let n=kr.has(t),o=e.querySelector('button[data-expand-header="true"]'),r=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let c=ae(n?"chevron-up":"chevron-down",16,"currentColor",2);c?l.appendChild(c):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Sc=(t,e)=>{let n=t.reasoning,o=v("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","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-${t.id}`,o.setAttribute("data-message-id",t.id),!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,i=s&&kr.has(t.id),l=n.status!=="complete",p=Rv(t,r.previewMaxLines??3),c=v("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");c.type="button",s&&(c.setAttribute("aria-expanded",i?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let d=v("div","persona-flex persona-flex-col persona-text-left"),u=v("span","persona-text-xs persona-text-persona-primary"),b="Thinking...",g=e?.reasoning??{},h=String(n.startedAt??Date.now()),C=()=>{let pe=v("span","");return pe.setAttribute("data-tool-elapsed",h),pe.textContent=Oi(n),pe},L=g.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:b,previewText:p,isActive:l,config:e??{},elapsed:Oi(n),createElapsedElement:C});typeof L=="string"&&L.trim()?(u.textContent=L,d.appendChild(u)):L instanceof HTMLElement?d.appendChild(L):(u.textContent=b,d.appendChild(u));let B=v("span","persona-text-xs persona-text-persona-primary");B.textContent=tu(n),d.appendChild(B);let k=r.loadingAnimation??"none",S=g.activeTextTemplate,E=g.completeTextTemplate,z=l?S:E,G=L instanceof HTMLElement,A=(pe,ge)=>{u.textContent="";let se=Fi(pe,""),Y=0;for(let oe of se){let J=oe.styles.length>0?(()=>{let ie=v("span",oe.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return u.appendChild(ie),ie})():u;if(oe.isDuration&&l)J.appendChild(C());else{let ie=oe.isDuration?Oi(n):oe.text;ge?Y=vo(J,ie,Y):J.appendChild(document.createTextNode(ie))}}};if(!G&&z)if(B.style.display="none",u.style.display="",l&&k!=="none"){let pe=g.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),k==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),A(z,!1)):(u.classList.add(`persona-tool-loading-${k}`),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),A(z,!0))}else A(z,!1);else if(!G&&l&&k!=="none"){u.style.display="";let pe=g.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),k==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`);else{u.classList.add(`persona-tool-loading-${k}`),u.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let ge=u.textContent||b;u.textContent="",vo(u,ge,0)}n.status==="complete"&&(u.style.display="none")}else G||(n.status==="complete"?u.style.display="none":u.style.display="");let O=null;if(s){O=v("div","persona-flex persona-items-center");let ge=ae(i?"chevron-up":"chevron-down",16,"currentColor",2);ge?O.appendChild(ge):O.textContent=i?"Hide":"Show";let se=v("div","persona-flex persona-items-center persona-ml-auto");se.append(O),c.append(d,se)}else c.append(d);let D=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","reasoning"),D.style.display="none",D.style.whiteSpace="pre-wrap",!i&&l&&r.activePreview&&p){let pe=e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:p,isActive:l,config:e??{}});Iv(D,pe)||(D.textContent=p),D.style.display=""}if(!i&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(c,D),o;let W=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");W.style.display=i?"":"none";let P=n.chunks.join(""),I=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return I.textContent=P||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),W.appendChild(I),(()=>{if(c.setAttribute("aria-expanded",i?"true":"false"),O){O.innerHTML="";let ge=ae(i?"chevron-up":"chevron-down",16,"currentColor",2);ge?O.appendChild(ge):O.textContent=i?"Hide":"Show"}W.style.display=i?"":"none",D.style.display=i?"none":D.textContent||D.childNodes.length?"":"none"})(),o.append(c,D,W),o};Je();wt();var Lr=new Set,Wv=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Hv=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
214
+ `);let r=yo(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
215
+ `):""},Mc=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},Bv=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Hv(t,o?.previewMaxLines??3),i=n?nu(n):"";if(!n)return{summary:i,previewText:s,isActive:!1};let l=n.status!=="complete",p=e?.toolCall??{},c=i;return r==="tool-name"?c=n.name?.trim()||i:r==="tool-preview"&&s&&(c=s),l&&p.activeTextTemplate?c=Wl(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=Wl(n,p.completeTextTemplate,c)),{summary:c,previewText:s,isActive:l}},gf=(t,e,n)=>{let o=Lr.has(t),r=n?.toolCall??{},s=e.querySelector('button[data-expand-header="true"]'),i=e.querySelector(".persona-border-t"),l=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!i)return;s.setAttribute("aria-expanded",o?"true":"false");let c=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=ae(o?"chevron-up":"chevron-down",16,d,2);u?c.appendChild(u):c.textContent=o?"Hide":"Show"}i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Tc=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=v("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","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-${t.id}`,r.setAttribute("data-message-id",t.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=e?.features?.toolCallDisplay??{},i=s.expandable!==!1,l=i&&Lr.has(t.id),{summary:p,previewText:c,isActive:d}=Bv(t,e),u=v("button",i?"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");u.type="button",i&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let b=v("div","persona-flex persona-flex-col persona-text-left"),g=v("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let h=String(n.startedAt??Date.now()),C=()=>{let P=v("span","");return P.setAttribute("data-tool-elapsed",h),P.textContent=ms(n),P},L=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:s.collapsedMode??"tool-call",isActive:d,config:e??{},elapsed:ms(n),createElapsedElement:C});typeof L=="string"&&L.trim()?(g.textContent=L,b.appendChild(g)):L instanceof HTMLElement?b.appendChild(L):(g.textContent=p,b.appendChild(g));let B=s.loadingAnimation??"none",k=o.activeTextTemplate,S=o.completeTextTemplate,E=d?k:S,z=L instanceof HTMLElement,G=(P,I)=>{g.textContent="";let j=n.name?.trim()||"tool",pe=Fi(P,j),ge=0;for(let se of pe){let Y=se.styles.length>0?(()=>{let oe=v("span",se.styles.map(J=>`persona-tool-text-${J}`).join(" "));return g.appendChild(oe),oe})():g;if(se.isDuration&&d)Y.appendChild(C());else{let oe=se.isDuration?ms(n):se.text;I?ge=vo(Y,oe,ge):Y.appendChild(document.createTextNode(oe))}}};if(!z)if(d&&B!=="none"){let P=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),B==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${P}ms`),E&&G(E,!1);else if(g.classList.add(`persona-tool-loading-${B}`),g.style.setProperty("--persona-tool-anim-duration",`${P}ms`),B==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),E)G(E,!0);else{let I=g.textContent||p;g.textContent="",vo(g,I,0)}}else E&&G(E,!1);let A=null;if(i){A=v("div","persona-flex persona-items-center");let P=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",I=ae(l?"chevron-up":"chevron-down",16,P,2);I?A.appendChild(I):A.textContent=l?"Hide":"Show";let j=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");j.append(A),u.append(b,j)}else u.append(b);let O=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(O.setAttribute("data-persona-collapsed-preview","tool"),O.style.display="none",O.style.whiteSpace="pre-wrap",!l&&d&&s.activePreview&&c){let P=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:c,isActive:d,config:e??{}});Wv(O,P)||(O.textContent=c),O.style.display=""}if(!l&&d&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!i)return r.append(u,O),r;let D=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(D.style.display=l?"":"none",o.contentBackgroundColor&&(D.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(D.style.color=o.contentTextColor),o.contentPaddingX&&(D.style.paddingLeft=o.contentPaddingX,D.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(D.style.paddingTop=o.contentPaddingY,D.style.paddingBottom=o.contentPaddingY),n.name){let P=v("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?P.style.color=o.contentTextColor:o.headerTextColor&&(P.style.color=o.headerTextColor),P.textContent=n.name,D.appendChild(P)}if(n.args!==void 0){let P=v("div","persona-space-y-1"),I=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(I.style.color=o.labelTextColor),I.textContent="Arguments";let j=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");j.style.fontSize="0.75rem",j.style.lineHeight="1rem",Mc(j,o),j.textContent=yo(n.args),P.append(I,j),D.appendChild(P)}if(n.chunks&&n.chunks.length){let P=v("div","persona-space-y-1"),I=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(I.style.color=o.labelTextColor),I.textContent="Activity";let j=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");j.style.fontSize="0.75rem",j.style.lineHeight="1rem",Mc(j,o),j.textContent=n.chunks.join(""),P.append(I,j),D.appendChild(P)}if(n.status==="complete"&&n.result!==void 0){let P=v("div","persona-space-y-1"),I=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(I.style.color=o.labelTextColor),I.textContent="Result";let j=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");j.style.fontSize="0.75rem",j.style.lineHeight="1rem",Mc(j,o),j.textContent=yo(n.result),P.append(I,j),D.appendChild(P)}if(n.status==="complete"&&typeof n.duration=="number"){let P=v("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(P.style.color=o.contentTextColor),P.textContent=`Duration: ${n.duration}ms`,D.appendChild(P)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),A){A.innerHTML="";let P=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",I=ae(l?"chevron-up":"chevron-down",16,P,2);I?A.appendChild(I):A.textContent=l?"Hide":"Show"}D.style.display=l?"":"none",O.style.display=l?"none":O.textContent||O.childNodes.length?"":"none"})(),r.append(u,O,D),r};Je();wt();var jo=new Map,_a=t=>{let n=(t.startsWith(jn)?t.slice(jn.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},ff=t=>t?.approval!==!1?t?.approval:void 0,mf=(t,e)=>{let n=ff(e)?.detailsDisplay??"collapsed";return jo.get(t)??n==="expanded"},hf=(t,e,n)=>{let o=ff(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let i=ae(e?"chevron-up":"chevron-down",14,"currentColor",2);i&&s.appendChild(i)}},yf=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=mf(t,n);hf(o,s,n),r.style.display=s?"":"none"};var $a=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let i=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=v("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",d=ae(p,20,c,2);d&&l.appendChild(d);let u=v("div","persona-flex-1 persona-min-w-0"),b=v("div","persona-flex persona-items-center persona-gap-2"),g=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",b.appendChild(g),!r){let A=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");A.setAttribute("data-approval-status",n.status),n.status==="approved"?(A.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",A.style.color="var(--persona-palette-colors-success-700, #15803d)",A.textContent="Approved"):n.status==="denied"?(A.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",A.style.color="var(--persona-palette-colors-error-700, #b91c1c)",A.textContent="Denied"):n.status==="timeout"&&(A.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",A.style.color="var(--persona-palette-colors-warning-700, #b45309)",A.textContent="Timeout"),b.appendChild(A)}u.appendChild(b);let C=n.toolType==="webmcp"||n.toolName.startsWith(jn)?cs(n.toolName):void 0,L=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),B=!n.toolName,k=L||(B?n.description:`The assistant wants to use \u201C${C??_a(n.toolName)}\u201D.`),S=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(S.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(S.style.color=o.descriptionColor),S.textContent=k,u.appendChild(S),n.reason){let A=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");A.setAttribute("data-approval-reason","true"),o?.reasonColor?A.style.color=o.reasonColor:o?.descriptionColor&&(A.style.color=o.descriptionColor);let O=v("span","persona-font-medium");O.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,A.appendChild(O),A.appendChild(document.createTextNode(n.reason)),u.appendChild(A)}let E=o?.detailsDisplay??"collapsed",z=!!n.description&&!B,G=z||!!n.parameters;if(E!=="hidden"&&G){let A=mf(t.id,e),O=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");O.type="button",O.setAttribute("data-expand-header","true"),O.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(O.style.color=o.descriptionColor);let D=v("span");D.setAttribute("data-approval-details-label","true");let W=v("span","persona-inline-flex persona-items-center");W.setAttribute("data-approval-details-chevron","true"),O.append(D,W),hf(O,A,e),u.appendChild(O);let P=v("div");if(P.setAttribute("data-approval-details","true"),P.style.display=A?"":"none",z){let I=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(I.style.color=o.descriptionColor),I.textContent=n.description,P.appendChild(I)}if(n.parameters){let I=v("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");o?.parameterBackgroundColor&&(I.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(I.style.color=o.parameterTextColor),I.style.fontSize="0.75rem",I.style.lineHeight="1rem",I.textContent=yo(n.parameters),P.appendChild(I)}u.appendChild(P)}if(r){let A=v("div","persona-flex persona-gap-2 persona-mt-2");A.setAttribute("data-approval-buttons","true");let O=v("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");O.type="button",O.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",O.style.color=o?.approveButtonTextColor??"#ffffff",O.setAttribute("data-approval-action","approve");let D=ae("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);D&&(D.style.marginRight="4px",O.appendChild(D));let W=document.createTextNode(o?.approveLabel??"Approve");O.appendChild(W);let P=v("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");P.type="button",P.style.backgroundColor=o?.denyButtonColor??"transparent",P.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",P.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,P.setAttribute("data-approval-action","deny");let I=ae("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);I&&(I.style.marginRight="4px",P.appendChild(I));let j=document.createTextNode(o?.denyLabel??"Deny");P.appendChild(j),A.append(O,P),u.appendChild(A)}return i.append(l,u),s.appendChild(i),s};Je();wt();ql();var Dv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),bf=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},Vo=(t,e)=>{bf(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},Nv=t=>t?.approval!==!1?t?.approval:void 0,Ov=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return jo.get(t)??n==="expanded"},Ec=t=>{let e=v("span","persona-approval-kbd");return e.textContent=t,e},Fv=(t,e)=>{let n=v("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(jn)?cs(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let i=r??_a(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=i,n.appendChild(p),l){n.append(" from ");let c=document.createElement("strong");c.textContent=l,n.appendChild(c)}return n},_v=t=>{let e=v("div","persona-approval-resolved"),n=ae("ban",15,"currentColor",2);n&&e.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=t.toolName?_a(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},$v=(t,e,n,o,r,s,i)=>{let l=v("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",c=!!n.description&&p!=="hidden",d=n.parameters!=null&&p!=="hidden",u=c||d,b=u&&Ov(e.id,o),g=o?.showDetailsLabel??"Show details",h=o?.hideDetailsLabel??"Hide details",C=v("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",b?"true":"false"),C.setAttribute("aria-label",b?h:g)):C.setAttribute("data-static","true");let L=v("span","persona-approval-logo"),B=ae("shield-check",16,"currentColor",2);B&&L.appendChild(B),C.appendChild(L);let k=Fv(n,o);if(u){let O=v("span","persona-approval-toggle");O.setAttribute("aria-hidden","true");let D=ae("chevron-down",14,"currentColor",2);D&&O.appendChild(D),k.append(" "),k.appendChild(O)}C.appendChild(k),l.appendChild(C);let S=v("div","persona-approval-body");if(u){let O=v("div","persona-approval-details");if(O.setAttribute("data-role","params"),O.hidden=!b,c){let D=v("p","persona-approval-desc");o?.descriptionColor&&(D.style.color=o.descriptionColor),D.textContent=n.description,O.appendChild(D)}if(d){let D=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(D.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(D.style.color=o.parameterTextColor),D.textContent=yo(n.parameters),O.appendChild(D)}S.appendChild(O)}if(n.reason){let O=v("p","persona-approval-reason");o?.reasonColor?O.style.color=o.reasonColor:o?.descriptionColor&&(O.style.color=o.descriptionColor);let D=v("span","persona-approval-reason-label");D.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,O.append(D,document.createTextNode(n.reason)),S.appendChild(O)}let E=v("div","persona-approval-actions"),z=null,G=O=>{o?.approveButtonColor&&(O.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(O.style.color=o.approveButtonTextColor)},A=v("button","persona-approval-deny");if(A.type="button",A.setAttribute("data-action","deny"),o?.denyButtonColor&&(A.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(A.style.color=o.denyButtonTextColor),A.append(o?.denyLabel??"Deny"),i){let O=v("div","persona-approval-split"),D=v("button","persona-approval-primary");D.type="button",D.setAttribute("data-action","always"),G(D),D.append(o?.approveLabel??"Always allow",Ec("\u23CE"));let W=v("button","persona-approval-caret");W.type="button",W.setAttribute("data-action","toggle-menu"),W.setAttribute("aria-label","More options"),G(W);let P=ae("chevron-down",15,"currentColor",2);P&&W.appendChild(P),O.append(D,W),E.append(O,A),A.append(Ec("Esc"));let I=v("div","persona-approval-menu"),j=v("button","persona-approval-menu-item");j.type="button",j.append("Allow once",Ec("\u2318\u23CE")),I.appendChild(j),z=ta({anchor:O,content:I,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,z),j.addEventListener("click",()=>{Vo(t,e.id),r()})}else{let O=v("button","persona-approval-primary persona-approval-primary--solo");O.type="button",O.setAttribute("data-action","allow"),G(O),O.append(o?.approveLabel??"Allow"),E.append(O,A)}return S.appendChild(E),l.appendChild(S),l.addEventListener("click",O=>{let D=O.target instanceof Element?O.target.closest("[data-action]"):null;if(!D)return;let W=D.getAttribute("data-action");if(W==="toggle-params"){let P=l.querySelector('[data-role="params"]');if(P){let I=P.hidden;P.hidden=!I,C.setAttribute("aria-expanded",I?"true":"false"),C.setAttribute("aria-label",I?h:g),jo.set(e.id,I)}return}if(W==="toggle-menu"){z?.toggle();return}if(W==="always"){Vo(t,e.id),r({remember:!0});return}if(W==="allow"){Vo(t,e.id),r();return}if(W==="deny"){Vo(t,e.id),s();return}}),l},vf=()=>{let t=Dv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:i})=>{let l=o?.approval;if(!l)return null;let p=Nv(i);if(l.status!=="pending"){if(Vo(t,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return _v(l)}bf(t,o.id);let c=p?.enableAlwaysAllow===!0,d=$v(t,o,l,p,r,s,c);if(c){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let u=b=>{Ou(b)||o.id===t.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),Vo(t,o.id),b.key==="Escape"?s():b.metaKey||b.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return d}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])Vo(t,o);t.latestPendingApprovalId=null}}};var Us=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),this.store?.put(e)}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 e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var js=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{e(i.result)},i.onerror=()=>{n(i.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}};var zv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Uv=new Set(["step_start","execution_start"]),jv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Vv=new Set(["step_complete","agent_turn_complete"]),qv=new Set(["flow_complete","agent_complete"]),xf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),wf=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),pn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,qo=(t,e)=>{let n=t[e];return wf(n)?n:void 0};function kc(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function za(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Kv(t,e){return typeof e.type=="string"?e.type:t}function Gv(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function Qv(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Cf(t){let e=qo(t,"result"),n=[qo(t,"tokens"),qo(t,"totalTokens"),e?qo(e,"tokens"):void 0,qo(t,"usage"),e?qo(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=pn(o.output)??pn(o.outputTokens)??pn(o.completionTokens);if(r!==void 0)return r}return pn(t.outputTokens)??pn(t.completionTokens)??(e?pn(e.outputTokens)??pn(e.completionTokens):void 0)}function Xv(t){let e=qo(t,"result");return pn(t.executionTime)??pn(t.executionTimeMs)??pn(t.execution_time)??pn(t.duration)??(e?pn(e.executionTime)??pn(e.executionTimeMs):void 0)}function Jv(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Vs=class{constructor(e=Jv){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:za(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){if(!wf(n)){xf.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Kv(e,n),r=this.now();if(zv.has(o)){this.startRun(r);return}if(Uv.has(o)){this.run||this.startRun(r);return}if(jv.has(o)){if(!Qv(o,n))return;let s=Gv(n);if(!s)return;this.run||this.startRun(r);let i=this.run;i.firstDeltaAt??(i.firstDeltaAt=r),i.visibleCharCount+=s.length;let l=i.exactOutputTokens+kc(i.visibleCharCount),p=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:za(l,p),outputTokens:l,durationMs:p,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Vv.has(o)){if(!this.run)return;let s=this.run,i=Cf(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+kc(s.visibleCharCount),c=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:za(p,c),outputTokens:p,durationMs:c,source:l?"usage":"estimate"};return}if(qv.has(o)){if(!this.run)return;let s=this.run,i=Cf(n),l=i??s.exactOutputTokens+kc(s.visibleCharCount),p=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:za(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(xf.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Xv(n)??o-e.startedAt}};Je();wt();function Pr(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var Yv={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)"}},Zv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},ex=["flowName","stepName","reasoningText","text","name","tool","toolName"],tx=100;function nx(t,e){let n={...Yv,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return Zv}function ox(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function rx(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function sx(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){let r=o.split("."),s=n;for(let i of r)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function ix(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function ax(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function lx(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function cx(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function dx(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>i(),parsedPayload:r});if(l)return l}return i();function i(){let l=v("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]"),p=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function Lc(t,e,n,o,r,s,i,l){let p=r.has(t.id),c=v("div","persona-border-b persona-border-persona-divider persona-text-xs");Pr(c,o.classNames?.eventRow);let d=i.find(b=>b.renderEventStreamRow);if(d?.renderEventStreamRow&&l){let b=d.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(t.id)});if(b)return c.appendChild(b),c}return c.appendChild(u()),c;function u(){let b=v("div",""),g=v("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");g.setAttribute("data-event-id",t.id);let h=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ae(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&h.appendChild(C);let L=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=o.timestampFormat??"relative";L.textContent=B==="relative"?ox(t.timestamp,n):rx(t.timestamp);let k=null;o.showSequenceNumbers!==!1&&(k=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(e+1));let S=nx(t.type,o.badgeColors),E=v("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");E.style.backgroundColor=S.bg,E.style.color=S.text,E.style.borderColor=S.text+"50",E.textContent=t.type;let z=o.descriptionFields??ex,G=sx(t.payload,z),A=null;G&&(A=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),A.textContent=G);let O=v("div","persona-flex-1 persona-min-w-0"),D=v("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"),W=ae("clipboard","12px","currentColor",1.5);return W&&D.appendChild(W),D.addEventListener("click",async P=>{P.stopPropagation(),await ix(ax(t)),D.innerHTML="";let I=ae("check","12px","currentColor",1.5);I&&D.appendChild(I),setTimeout(()=>{D.innerHTML="";let j=ae("clipboard","12px","currentColor",1.5);j&&D.appendChild(j)},1500)}),g.appendChild(h),g.appendChild(L),k&&g.appendChild(k),g.appendChild(E),A&&g.appendChild(A),g.appendChild(O),g.appendChild(D),b.appendChild(g),p&&b.appendChild(dx(t,i,l)),b}}function Af(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:i}=t,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,c=l?.iconName??"arrow-down",d=l?.label??"",u=r?.features?.eventStream??{},b=s.find(h=>h.renderEventStreamView);if(b?.renderEventStreamView&&r){let h=b.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>g().element,onClose:o});if(h)return{element:h,update:()=>{},destroy:()=>{}}}return g();function g(){let h=u.classNames,C=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Pr(C,h?.panel);let L=[],B="",k="",S=null,E=[],z={},G=0,A=Ca(),O=0,D=0,W=!1,P=null,I=!1,j=0,pe=new Set,ge=new Map,se="",Y="",oe=null,J,ie,ee,fe,be=null,he=null,we=null;function ve(){let F=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),te=v("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");if(Pr(te,h?.headerBar),i){he=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),he.style.cursor="help",be=v("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 persona-tabular-nums"),be.textContent="-- tok/s",we=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),we.style.display="none",we.style.pointerEvents="none";let Ne=he,Ot=we,At=()=>{if(!Ot.textContent)return;let Xs=Ne.getBoundingClientRect(),Jn=F.getBoundingClientRect();Ot.style.left=`${Xs.left-Jn.left}px`,Ot.style.top=`${Xs.bottom-Jn.top+4}px`,Ot.style.display="block"},Yt=()=>{Ot.style.display="none"};he.addEventListener("mouseenter",At),he.addEventListener("mouseleave",Yt),he.appendChild(be)}let de=v("div","persona-flex-1");J=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Le=v("option","");Le.value="",Le.textContent="All events (0)",J.appendChild(Le),ie=v("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"),ie.type="button",ie.title="Copy All";let rt=ae("clipboard-copy","12px","currentColor",1.5);rt&&ie.appendChild(rt);let ot=v("span","persona-event-copy-all persona-text-xs");ot.textContent="Copy All",ie.appendChild(ot),he&&te.appendChild(he),te.appendChild(de),te.appendChild(J),te.appendChild(ie);let ze=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Pr(ze,h?.searchBar);let Ze=ae("search","14px","var(--persona-muted, #9ca3af)",1.5),X=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ze&&X.appendChild(Ze),ee=v("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"),Pr(ee,h?.searchInput),ee.type="text",ee.placeholder="Search event payloads...",fe=v("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"),fe.type="button",fe.style.display="none";let Ue=ae("x","12px","currentColor",2);return Ue&&fe.appendChild(Ue),ze.appendChild(X),ze.appendChild(ee),ze.appendChild(fe),F.appendChild(te),F.appendChild(ze),we&&F.appendChild(we),F}let Te,Me=s.find(F=>F.renderEventStreamToolbar);Me?.renderEventStreamToolbar&&r?Te=Me.renderEventStreamToolbar({config:r,defaultRenderer:()=>ve(),eventCount:e.getSize(),filteredCount:0,onFilterChange:te=>{B=te,Ye(),ue()},onSearchChange:te=>{k=te,Ye(),ue()}})??ve():Te=ve();let _e=v("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");_e.style.display="none";function Ve(){if(!i||!be||!he)return;let F=i(),te=lx(F);be.textContent=te;let de=cx(F);we&&(we.textContent=de,de||(we.style.display="none")),he.setAttribute("aria-label",de?`Throughput: ${te}, ${de}`:`Throughput: ${te}`)}let ke=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Re=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Re.style.height="100%";let Ge=v("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");Pr(Ge,h?.scrollIndicator),Ge.style.display="none",Ge.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let Nt=ae(c,"14px","currentColor",2);Nt&&Ge.appendChild(Nt);let Bt=v("span","");Bt.textContent=d,Ge.appendChild(Bt);let Xt=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Xt.style.display="none",ke.appendChild(Re),ke.appendChild(Xt),ke.appendChild(Ge),C.setAttribute("tabindex","0"),C.appendChild(Te),C.appendChild(_e),C.appendChild(ke);function Mt(){let F=e.getAll(),te={};for(let ze of F)te[ze.type]=(te[ze.type]||0)+1;let de=Object.keys(te).sort(),Le=de.length!==E.length||!de.every((ze,Ze)=>ze===E[Ze]),Se=!Le&&de.some(ze=>te[ze]!==z[ze]),rt=F.length!==Object.values(z).reduce((ze,Ze)=>ze+Ze,0);if(!Le&&!Se&&!rt||(E=de,z=te,!J))return;let ot=J.value;if(J.options[0].textContent=`All events (${F.length})`,Le){for(;J.options.length>1;)J.remove(1);for(let ze of de){let Ze=v("option","");Ze.value=ze,Ze.textContent=`${ze} (${te[ze]||0})`,J.appendChild(Ze)}ot&&de.includes(ot)?J.value=ot:ot&&(J.value="",B="")}else for(let ze=1;ze<J.options.length;ze++){let Ze=J.options[ze];Ze.textContent=`${Ze.value} (${te[Ze.value]||0})`}}function De(){let F=e.getAll();if(B&&(F=F.filter(te=>te.type===B)),k){let te=k.toLowerCase();F=F.filter(de=>de.type.toLowerCase().includes(te)||de.payload.toLowerCase().includes(te))}return F}function ye(){return B!==""||k!==""}function Ye(){G=0,O=0,A.resume(),Ge.style.display="none"}function He(F){pe.has(F)?pe.delete(F):pe.add(F),oe=F;let te=Re.scrollTop,de=A.isFollowing();I=!0,A.pause(),ue(),Re.scrollTop=te,de&&A.resume(),I=!1}function xe(){return Co(Re,50)}function ue(){D=Date.now(),W=!1,Ve(),Mt();let F=e.getEvictedCount();F>0?(_e.textContent=`${F.toLocaleString()} older events truncated`,_e.style.display=""):_e.style.display="none",L=De();let te=L.length,de=e.getSize()>0;te===0&&de&&ye()?(Xt.textContent=k?`No events matching '${k}'`:"No events matching filter",Xt.style.display="",Re.style.display="none"):(Xt.style.display="none",Re.style.display=""),ie&&(ie.title=ye()?`Copy Filtered (${te})`:"Copy All"),p&&!A.isFollowing()&&te>G&&(O+=te-G,Bt.textContent=d?`${d}${O>0?` (${O})`:""}`:"",Ge.style.display=""),G=te;let Le=e.getAll(),Se=Le.length>0?Le[0].timestamp:0,rt=new Set(L.map(Ze=>Ze.id));for(let Ze of pe)rt.has(Ze)||pe.delete(Ze);let ot=B!==se||k!==Y,ze=ge.size===0&&L.length>0;if(ot||ze||L.length===0){Re.innerHTML="",ge.clear();let Ze=document.createDocumentFragment();for(let X=0;X<L.length;X++){let Ue=Lc(L[X],X,Se,u,pe,He,s,r);ge.set(L[X].id,Ue),Ze.appendChild(Ue)}Re.appendChild(Ze),se=B,Y=k,oe=null}else{if(oe!==null){let X=ge.get(oe);if(X&&X.parentNode===Re){let Ue=L.findIndex(Ne=>Ne.id===oe);if(Ue>=0){let Ne=Lc(L[Ue],Ue,Se,u,pe,He,s,r);Re.insertBefore(Ne,X),X.remove(),ge.set(oe,Ne)}}oe=null}let Ze=new Set(L.map(X=>X.id));for(let[X,Ue]of ge)Ze.has(X)||(Ue.remove(),ge.delete(X));for(let X=0;X<L.length;X++){let Ue=L[X];if(!ge.has(Ue.id)){let Ne=Lc(Ue,X,Se,u,pe,He,s,r);ge.set(Ue.id,Ne),Re.appendChild(Ne)}}}A.isFollowing()&&(Re.scrollTop=Re.scrollHeight)}function We(){if(Date.now()-D>=tx){P!==null&&(cancelAnimationFrame(P),P=null),ue();return}W||(W=!0,P=requestAnimationFrame(()=>{P=null,ue()}))}let Jt=(F,te)=>{if(!ie)return;ie.innerHTML="";let de=ae(F,"12px","currentColor",1.5);de&&ie.appendChild(de);let Le=v("span","persona-text-xs");Le.textContent="Copy All",ie.appendChild(Le),setTimeout(()=>{ie.innerHTML="";let Se=ae("clipboard-copy","12px","currentColor",1.5);Se&&ie.appendChild(Se);let rt=v("span","persona-text-xs");rt.textContent="Copy All",ie.appendChild(rt),ie.disabled=!1},te)},gt=async()=>{if(ie){ie.disabled=!0;try{let F;ye()?F=L:n?(F=await n(),F.length===0&&(F=e.getAll())):F=e.getAll();let te=F.map(de=>{try{return JSON.parse(de.payload)}catch{return de.payload}});await navigator.clipboard.writeText(JSON.stringify(te,null,2)),Jt("check",1500)}catch{Jt("x",1500)}}},bt=()=>{J&&(B=J.value,Ye(),ue())},Q=()=>{!ee||!fe||(fe.style.display=ee.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{k=ee.value,Ye(),ue()},150))},w=()=>{!ee||!fe||(ee.value="",k="",fe.style.display="none",S&&clearTimeout(S),Ye(),ue())},K=()=>{if(I)return;let F=Re.scrollTop,{action:te,nextLastScrollTop:de}=wa({following:A.isFollowing(),currentScrollTop:F,lastScrollTop:j,nearBottom:xe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});j=de,te==="resume"?(A.resume(),O=0,Ge.style.display="none"):te==="pause"&&(A.pause(),p&&(Bt.textContent=d,Ge.style.display=""))},y=F=>{let te=Aa({following:A.isFollowing(),deltaY:F.deltaY,nearBottom:xe(),resumeWhenNearBottom:!0});te==="pause"?(A.pause(),p&&(Bt.textContent=d,Ge.style.display="")):te==="resume"&&(A.resume(),O=0,Ge.style.display="none")},H=()=>{p&&(Re.scrollTop=Re.scrollHeight,A.resume(),O=0,Ge.style.display="none")},N=F=>{let te=F.target;if(!te||te.closest("button"))return;let de=te.closest("[data-event-id]");if(!de)return;let Le=de.getAttribute("data-event-id");Le&&He(Le)},$=F=>{if((F.metaKey||F.ctrlKey)&&F.key==="f"){F.preventDefault(),ee?.focus(),ee?.select();return}F.key==="Escape"&&(ee&&document.activeElement===ee?(w(),ee.blur(),C.focus()):o&&o())};ie&&ie.addEventListener("click",gt),J&&J.addEventListener("change",bt),ee&&ee.addEventListener("input",Q),fe&&fe.addEventListener("click",w),Re.addEventListener("scroll",K),Re.addEventListener("wheel",y,{passive:!0}),Re.addEventListener("click",N),Ge.addEventListener("click",H),C.addEventListener("keydown",$);function U(){S&&clearTimeout(S),P!==null&&(cancelAnimationFrame(P),P=null),W=!1,ge.clear(),ie&&ie.removeEventListener("click",gt),J&&J.removeEventListener("change",bt),ee&&ee.removeEventListener("input",Q),fe&&fe.removeEventListener("click",w),Re.removeEventListener("scroll",K),Re.removeEventListener("wheel",y),Re.removeEventListener("click",N),Ge.removeEventListener("click",H),C.removeEventListener("keydown",$)}return{element:C,update:We,destroy:U}}}Je();wt();function Sf(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let s=[],i=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let b=u;return s.findIndex(g=>g===b||g.contains(b))},c=u=>{let b=p(u.target);if(b<0)return;let g=b;if(u.key===r)g=Math.min(b+1,s.length-1);else if(u.key===o)g=Math.max(b-1,0);else if(u.key==="Home")g=0;else if(u.key==="End")g=s.length-1;else return;u.preventDefault(),g!==b&&e.onSelect(g)},d=u=>{let b=p(u.target);b>=0&&l(s[b])};return t.addEventListener("keydown",c),t.addEventListener("focusin",d),{beforeRender(){i=typeof document<"u"&&t.contains(document.activeElement)},render(u,b){if(s=u,u.forEach((g,h)=>{g.setAttribute("role","tab");let C=h===b;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||b<0&&h===0?0:-1}),i){let g=(b>=0?u[b]:void 0)??u[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){t.removeEventListener("keydown",c),t.removeEventListener("focusin",d)}}}function Mf(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",i=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),c=Q=>({start:Q===!1?!1:typeof Q=="object"&&Q?Q.start!==!1:!0,end:Q===!1?!1:typeof Q=="object"&&Q?Q.end!==!1:!0}),{start:d,end:u}=c(n?.tabFade),b=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{b?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),I?.hide()};b&&b.addEventListener("click",()=>{g(),e.onDismiss?.()});let h=v("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");h.setAttribute("data-persona-theme-zone","artifact-pane"),r&&h.classList.add("persona-artifact-pane-document");let C=v("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");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let L=v("span","persona-text-xs persona-font-medium persona-truncate");L.textContent=s;let B=Ht({icon:"x",label:i});B.addEventListener("click",()=>{g(),e.onDismiss?.()});let k="rendered",S=ha({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:Q=>{k=Q==="source"?"source":"rendered",Jt()}}),E=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),z=n?.documentToolbarShowCopyLabel===!0,G=n?.documentToolbarShowCopyChevron===!0,A=n?.documentToolbarCopyMenuItems,O=!!(G&&A&&A.length>0),D=null,W,P=null,I=null;if(r&&(z||G)&&!O){if(W=z?zo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ht({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),G){let Q=ae("chevron-down",14,"currentColor",2);Q&&W.appendChild(Q)}}else r&&O?(D=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),W=z?zo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ht({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P=Ht({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"}}),D.append(W,P)):r?W=Ht({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(W=Ht({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&W.classList.add("persona-hidden"));let j=r?Ht({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Ht({icon:"refresh-cw",label:"Refresh"}),pe=r?Ht({icon:"x",label:i,className:"persona-artifact-doc-icon-btn"}):Ht({icon:"x",label:i}),ge=Ht({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&ge.classList.add("persona-hidden");let se=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),Y=t.features?.artifacts?.toolbarActions??[],oe=()=>{let Q=ke.find(H=>H.id===Re)??ke[ke.length-1],w=Q?.id??null,K=Q?.artifactType==="markdown"?Q.markdown??"":"",y=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:K,jsonPayload:y,id:w}},J=async()=>{let Q=ke.find(w=>w.id===Re)??ke[ke.length-1];try{await navigator.clipboard.writeText(Hs(Q))}catch{}};if(W.addEventListener("click",async()=>{let Q=n?.onDocumentToolbarCopyMenuSelect;if(Q&&O){let{markdown:w,jsonPayload:K,id:y}=oe();try{await Q({actionId:"primary",artifactId:y,markdown:w,jsonPayload:K})}catch{}return}await J()}),P&&A?.length){let Q=()=>h.closest("[data-persona-root]")??document.body,w=()=>{I=Mr({items:A.map(K=>({id:K.id,label:K.label})),onSelect:async K=>{let{markdown:y,jsonPayload:H,id:N}=oe(),$=n?.onDocumentToolbarCopyMenuSelect;try{$?await $({actionId:K,artifactId:N,markdown:y,jsonPayload:H}):K==="markdown"||K==="md"?await navigator.clipboard.writeText(y):K==="json"||K==="source"?await navigator.clipboard.writeText(H):await navigator.clipboard.writeText(y||H)}catch{}},anchor:D??P,position:"bottom-right",portal:Q()})};h.isConnected?w():requestAnimationFrame(w),P.addEventListener("click",K=>{K.stopPropagation(),I?.toggle()})}j.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Jt()}),pe.addEventListener("click",()=>{g(),e.onDismiss?.()});let ie=v("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");if(r)C.replaceChildren(),D?E.append(D,j,pe):E.append(W,j,pe),E.insertBefore(se,pe),E.insertBefore(ge,pe),C.append(S.element,ie,E);else{let Q=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");Q.append(W,se,ge,B),C.appendChild(L),C.appendChild(Q)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let ee=v("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");p&&ee.style.setProperty("--persona-artifact-tab-fade-size",p);let fe=t.features?.artifacts?.renderTabBar,be=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),he=Sf(ee,{onSelect:Q=>e.onSelect(ke[Q].id)}),we=Q=>{let w=Q.scrollWidth-Q.clientWidth,K=w>1,y=Math.abs(Q.scrollLeft);Q.classList.toggle("persona-artifact-tab-fade-start",d&&K&&y>1),Q.classList.toggle("persona-artifact-tab-fade-end",u&&K&&y<w-1)},ve=0,Te=()=>{if(ve)return;let Q=()=>{ve=0,we(ee)};ve=typeof requestAnimationFrame=="function"?requestAnimationFrame(Q):setTimeout(Q,0)};ee.addEventListener("scroll",()=>Te(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>we(ee)).observe(ee);let Me=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),_e=()=>{Me.scrollLeft=0},Ve=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(_e):setTimeout(_e,0)};if(l){for(let Q of[ee,be])Q.style.paddingLeft=l,Q.style.paddingRight=l;Me.style.padding=l}h.appendChild(C),h.appendChild(ee),h.appendChild(be),h.appendChild(Me);let ke=[],Re=null,Ge=!1,Nt=!1,Bt=!0,Xt=!1,Mt=null,De="",ye=null,Ye=!1,He=Q=>Q.artifactType==="markdown"&&!!Q.file||r?k:"rendered",xe=Q=>{r||(Q&&!Ye?(C.insertBefore(S.element,L),Ye=!0):!Q&&Ye&&(S.element.remove(),Ye=!1))},ue=()=>Re&&ke.find(Q=>Q.id===Re)||ke[ke.length-1],We=()=>{let Q=Rs(ue());if(!Q){se.replaceChildren();return}let w=Y.filter(K=>K.visible===void 0||K.visible(Q)).map(K=>Tr(K,{documentChrome:r,onClick:()=>{let y=Rs(ue());if(y)try{Promise.resolve(K.onClick(y)).catch(()=>{})}catch{}}}));se.replaceChildren(...w)},Jt=()=>{We();let Q=r&&ke.length<=1,w=!!fe;if(ee.classList.toggle("persona-hidden",Q||w),be.classList.toggle("persona-hidden",Q||!w),w&&fe){let H=ke.map(N=>N.id).join("|")+" "+(Re??"");if(H!==De){De=H;let N=fe({records:ke,selectedId:Re,onSelect:e.onSelect});be.firstElementChild!==N&&be.replaceChildren(N)}}else{he.beforeRender(),ee.replaceChildren();let H=[],N=-1;for(let[$,U]of ke.entries()){let F=v("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");F.type="button";let te=U.artifactType==="markdown"?U.file:void 0,de=te?Wn(te.path):U.title||U.id.slice(0,8),Le=te?.path||U.title||de;F.textContent=de,F.title=Le,F.setAttribute("aria-label",Le),U.id===Re&&(F.classList.add("persona-bg-persona-container","persona-border-persona-border"),N=$),F.addEventListener("click",()=>e.onSelect(U.id)),ee.appendChild(F),H.push(F)}if(he.render(H,N),N>=0&&Re!==Mt){Mt=Re;let $=H[N];typeof $.scrollIntoView=="function"&&$.scrollIntoView({block:"nearest",inline:"nearest"})}we(ee)}let K=Re&&ke.find(H=>H.id===Re)||ke[ke.length-1];if(!K){Me.replaceChildren(),ye=null,xe(!1);return}let y=K.artifactType==="markdown"?K.file:void 0;if(xe(!!y),r){let H=y?bo(y):K.artifactType==="markdown"?"MD":K.component??"Component",N=(K.title||"Document").trim(),$=y?Wn(y.path):N.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${$} \xB7 ${H}`}else L.textContent=y?Wn(y.path):s;ye?(ye.el.parentElement!==Me&&Me.replaceChildren(ye.el),ye.update(K)):(ye=va(K,{config:t,resolveViewMode:He}),Me.replaceChildren(ye.el)),Me.classList.toggle("persona-artifact-content-flush",!!Me.querySelector(".persona-code-pre"))},gt=()=>{let Q=ke.length>0;if(h.classList.toggle("persona-hidden",!Q),b){let y=((typeof h.closest=="function"?h.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;Q&&y&&Ge?(b.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},bt=()=>{Xt=!1,Jt(),gt()};return{element:h,backdrop:b,update(Q){let w=Q.selectedId??Q.artifacts[Q.artifacts.length-1]?.id??null,K=w!==Re;ke=Q.artifacts,Re=w,ke.length>0&&(Ge=!0),Xt=!0,Bt&&bt(),K&&_e()},setMobileOpen(Q){Ge=Q,!Q&&b?(b.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):gt()},setExpanded(Q){Q!==Nt&&(Nt=Q,Ve());let w=ae(Q?"minimize":"maximize",16,"currentColor",2);w&&ge.replaceChildren(w);let K=Q?"Collapse artifacts panel":"Expand artifacts panel";ge.setAttribute("aria-label",K),ge.title=K},setExpandToggleVisible(Q){ge.classList.toggle("persona-hidden",!Q)},setCopyButtonVisible(Q){r||W.classList.toggle("persona-hidden",!Q)},setCustomActions(Q){Y=Q,We()},setTabFade(Q){let w=c(Q);w.start===d&&w.end===u||(d=w.start,u=w.end,we(ee))},setRenderTabBar(Q){Q!==fe&&(fe=Q,De="",Jt())},setVisible(Q){Q!==Bt&&(Bt=Q,Q&&Xt&&bt())}}}function nn(t){return t?.features?.artifacts?.enabled===!0}function Tf(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!nn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function px(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Ef=["panel","seamless","detached"];function Pc(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&Ef.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Ic(t){return!t||!nn(t)?!1:Pc(t)==="detached"}function qs(t,e){if(!nn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),px(t),Tf(t,e);return}let n=e.features?.artifacts?.layout,o=Pc(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let i=n?.documentToolbarIconColor?.trim();i?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",i):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?t.style.setProperty("--persona-artifact-doc-toggle-active-border",p):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Tf(t,e)}function Ks(t,e){for(let l of Ef)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!nn(e))return;let n=e.features?.artifacts?.layout,o=Pc(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let i=n?.chatShadow?.trim();i&&t.style.setProperty("--persona-artifact-chat-shadow",i)}function kf(t,e){return!e||!nn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var ux=new Set(["__proto__","prototype","constructor"]),gx=new Set(["collapsed","card","panel","inline"]),Lf=new Set(["markdown","component"]),fx=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ko=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ja=t=>!ux.has(t),Rc=t=>typeof t=="string"&&gx.has(t),Go=t=>Object.keys(t).length>0;function Bn(t,e,n,o){t.push({path:e,code:n,message:o})}var mx="Ignored because this key is not part of the persisted preference schema.",Ua="Ignored an unsupported value.",hx="Expected collapsed, panel, or inline.",yx='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Pf={kind:"mode",message:Ua},Ir={kind:"string",message:"Expected a CSS length string."},Xn={kind:"boolean"},bx={paneWidth:Ir,paneMaxWidth:Ir,paneMinWidth:Ir,expandedPanelWidth:Ir,resizableMinWidth:Ir,resizableMaxWidth:Ir,expandLauncherPanelWhenOpen:Xn,resizable:Xn},vx={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Xn,showReasoning:Xn,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Ua},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Ua},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Ua},expandable:Xn,grouped:Xn}},reasoningDisplay:{kind:"object",children:{expandable:Xn,activePreview:Xn}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Pf,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Pf,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Lf,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Lf}}},filePreview:{kind:"object",children:{enabled:Xn}},layout:{kind:"object",children:bx}}}}};function If(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Bn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Bn(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Bn(o,n,"invalid_value",e.message);case"mode":return Rc(t)?bn(t):Bn(o,n,"invalid_value",e.message);case"modeMap":{if(!Ko(t))return Bn(o,n,"invalid_type","Expected an object.");let r=e.keys==="mediaType"?void 0:e.keys,s={};for(let[i,l]of Object.entries(t)){let p=r?i:dr(i);ja(i)&&(r?r.has(i):fx.test(p))?Rc(l)?s[p]=bn(l):Bn(o,`${n}.${i}`,"invalid_value",hx):Bn(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":yx)}return Go(s)?s:void 0}case"object":{if(e.bareMode&&Rc(t))return bn(t);if(!Ko(t))return Bn(o,n,"invalid_type",e.message??"Expected an object.");let r=Object.keys(e.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(t))(!ja(l)||!r.includes(l))&&Bn(o,s(l),"unknown_key",mx);let i={};for(let l of r){let p=e.children[l],c=If(t[l],p,s(l),o);if(p.deprecated&&t[l]!==void 0&&Bn(o,s(l),"deprecated_key",p.deprecated),c===void 0)continue;let d=p.alias??l,u=i[d];i[d]=Ko(u)&&Ko(c)?{...u,...c}:c}return Go(i)?i:void 0}}}function xx(t){let e=[];return{preferences:(t===null?void 0:If(t,vx,"",e))??{},issues:e}}function Rr(t){if(Array.isArray(t))return t.map(Rr);if(!Ko(t))return t;let e={};for(let[n,o]of Object.entries(t))ja(n)&&o!==void 0&&(e[n]=Rr(o));return e}function Rf(t,e){let n=Rr(t);for(let[o,r]of Object.entries(e)){if(!ja(o)||r===void 0)continue;let s=n[o];n[o]=Ko(s)&&Ko(r)?Rf(s,r):Rr(r)}return n}function Cx(t){let e={},n;for(let r of t){let s=xx(r).preferences;n=Wf(n,s.artifacts?.display),e=Rf(e,s)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function wx(t,e){if(e===void 0)return t===void 0?void 0:Rr(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byMediaType,...e.byMediaType},s={...o?{default:o}:{},...Go(r)?{byMediaType:r}:{}};return Go(s)?s:void 0}function Wf(t,e){if(e===void 0)return t===void 0?void 0:Rr(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byType,...n.byKind,...e.byType,...e.byKind},s=wx(n.files,e.files),i={...o?{default:o}:{},...Go(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Go(i)?i:void 0}function Ax(t={},e){let n=Cx(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=t.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let i=Wf(r.display,n.artifacts.display);i!==void 0&&(s.display=i)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Wc(t){let e=t.preferences;return!e||!Go(e)?t:{...t,features:Ax(t.features??{},[e])}}function Sx(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function Mx(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Tx(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function Ex(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function Hc(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Hf(t,e,n,o,r,s){let i=Sx(r,200),l=Ex(e,n,o,200);l=Math.max(i,l);let p=Mx(s);return p!==null&&(l=Math.min(l,p)),Tx(t,i,l)}Je();var Bf={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"}},Bc=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let i=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=Bf[i]??Bf.init;s.classList.add("persona-form-card","persona-space-y-4");let p=v("div","persona-space-y-1"),c=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let h=v("p","persona-text-sm persona-text-persona-muted");h.textContent=l.description,p.appendChild(h)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",l.fields.forEach(h=>{let C=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${i}-${h.name}`;let L=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");L.textContent=h.label,C.appendChild(L);let B=h.type??"text",k;B==="textarea"?(k=document.createElement("textarea"),k.rows=3):(k=document.createElement("input"),k.type=B),k.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",k.id=`${e.id}-${i}-${h.name}`,k.name=h.name,k.placeholder=h.placeholder??"",h.required&&(k.required=!0),C.appendChild(k),d.appendChild(C)});let u=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=v("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=l.submitLabel??"Submit",u.appendChild(b),u.appendChild(g),d.appendChild(u),s.replaceChildren(p,d),d.addEventListener("submit",async h=>{h.preventDefault();let C=n.formEndpoint??"/form",L=new FormData(d),B={};L.forEach((k,S)=>{B[S]=k}),B.type=i,g.disabled=!0,b.textContent="Submitting\u2026";try{let k=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let S=await k.json();b.textContent=S.message??"Thanks! We'll be in touch soon.",S.success&&S.nextPrompt&&await o.sendMessage(String(S.nextPrompt))}catch(k){b.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Dc=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,i)=>(i.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},Nc=new Dc;var Df=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),kx=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),Nf=(t,e,n)=>{if(!Df(t)||!Df(e)||kx.has(n))return e;let o={...t};for(let r of Object.keys(e)){if(e[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=Nf(t[r],e[r],s)}return o};function Of(t,e){let n=Nf(t,e,"");return ca(n)}var Ff=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(i=>{try{i(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var Lx=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},Px=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},Fc=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=Lx(t),n=Px(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Oc=t=>typeof t=="string"?t:t==null?"":String(t),Gs={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Oc(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Oc(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Oc(n.text)}}},_f=t=>Array.isArray(t)?t.map(e=>String(e)):[],_c=t=>{let e=new Set(_f(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(_f(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?t.parsers.reduce((c,d)=>c||d?.({text:i,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let p={action:l,message:s.message};t.emit("action:detected",p);for(let c of t.handlers)if(c)try{let d=()=>{t.emit("action:resubmit",p)},u=c(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:d});if(!u)continue;if(u.handled){let b=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:b,resubmit:u.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var Ix=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},Rx=t=>t.map(e=>({...e,streaming:!1})),Wx=t=>t.map(e=>({...e,status:"complete"})),$f=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Ix(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?Rx(n.messages):void 0,artifacts:n.artifacts?Wx(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var $c=require("partial-json");function zf(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=Qn.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let i={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(t.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function Uf(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function zc(t){let e=Uf(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function jf(t){let e=Uf(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var Hx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Vf(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:c=Hx}=t,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let u=null,b=document.createElement("div");b.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,g.appendChild(h);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),b.appendChild(g);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-csat",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let G=1;G<=5;G++){let A=document.createElement("button");A.type="button",A.className="persona-feedback-rating-btn persona-feedback-star-btn",A.setAttribute("role","radio"),A.setAttribute("aria-checked","false"),A.setAttribute("aria-label",`${G} star${G>1?"s":""}: ${c[G-1]}`),A.title=c[G-1],A.dataset.rating=String(G),A.innerHTML=`
216
216
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
217
217
  <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>
218
218
  </svg>
219
- `,w.addEventListener("click",()=>{u=G,H.forEach((F,D)=>{let B=D<G;F.classList.toggle("selected",B),F.setAttribute("aria-checked",D===G-1?"true":"false")})}),H.push(w),R.appendChild(w)}b.appendChild(R);let L=null;if(p){let G=document.createElement("div");G.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),G.appendChild(L),b.appendChild(G)}let T=document.createElement("div");T.className="persona-feedback-actions";let k=document.createElement("button");k.type="button",k.className="persona-feedback-btn persona-feedback-btn-skip",k.textContent=l,k.addEventListener("click",()=>{n?.(),d.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=i,$.addEventListener("click",async()=>{if(u===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let G=L?.value.trim()||void 0;await e(u,G),d.remove()}catch(G){$.disabled=!1,$.textContent=i,console.error("[CSAT Feedback] Failed to submit:",G)}}),T.appendChild(k),T.appendChild($),b.appendChild(T),d.appendChild(b),d}function kg(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:c="Not likely",highLabel:d="Very likely"}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let b=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,m.appendChild(C);let R=document.createElement("p");R.className="persona-feedback-subtitle",R.textContent=r,m.appendChild(R),f.appendChild(m);let H=document.createElement("div");H.className="persona-feedback-rating persona-feedback-rating-nps",H.setAttribute("role","radiogroup"),H.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let T=document.createElement("span");T.className="persona-feedback-label-low",T.textContent=c;let k=document.createElement("span");k.className="persona-feedback-label-high",k.textContent=d,L.appendChild(T),L.appendChild(k);let $=document.createElement("div");$.className="persona-feedback-numbers";let G=[];for(let P=0;P<=10;P++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-number-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`Rating ${P} out of 10`),I.textContent=String(P),I.dataset.rating=String(P),P<=6?I.classList.add("persona-feedback-detractor"):P<=8?I.classList.add("persona-feedback-passive"):I.classList.add("persona-feedback-promoter"),I.addEventListener("click",()=>{b=P,G.forEach((j,pe)=>{j.classList.toggle("selected",pe===P),j.setAttribute("aria-checked",pe===P?"true":"false")})}),G.push(I),$.appendChild(I)}H.appendChild(L),H.appendChild($),f.appendChild(H);let w=null;if(p){let P=document.createElement("div");P.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=s,w.rows=3,w.setAttribute("aria-label","Additional comments"),P.appendChild(w),f.appendChild(P)}let F=document.createElement("div");F.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=l,D.addEventListener("click",()=>{n?.(),u.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=i,B.addEventListener("click",async()=>{if(b===null){$.classList.add("persona-feedback-shake"),setTimeout(()=>$.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let P=w?.value.trim()||void 0;await e(b,P),u.remove()}catch(P){B.disabled=!1,B.textContent=i,console.error("[NPS Feedback] Failed to submit:",P)}}),F.appendChild(D),F.appendChild(B),f.appendChild(F),u.appendChild(f),u}var Lr="persona-chat-history",lx=30*1e3,cx=641,dx={"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 px(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let s=dx[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function Na(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function ux(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function fx(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Nc=t=>!t||typeof t!="object"?{}:{...t},Lg=t=>t.map(e=>({...e,streaming:!1})),Pg=(t,e,n)=>{let o=t?.markdown?Ai(t.markdown):null,r=Si(t?.sanitize);return t?.postprocessMessage&&r&&t?.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=>{let i=s.text??"",l=s.message.rawContent??null;if(e){let d=e.process({text:i,raw:l??i,message:s.message,streaming:s.streaming});d!==null&&(i=d.text,d.persist||(s.message.__skipPersist=!0),d.resubmit&&!s.streaming&&n&&n())}let p=_n()!==null,c;if(t?.postprocessMessage){let d=t.postprocessMessage({...s,text:i,raw:l??s.text??""});c=r?r(d):d}else if(o){let d=s.streaming?cp(i):i,u=o(d);c=r&&p?r(u):u}else c=ao(i);return c}};function Ig(t){let e=y("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,i=ae(n,o,r,s);if(i&&e.appendChild(i),t?.label){let l=y("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var gx=(t,e)=>{let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];n[o]=s?{...s,...r}:r}return n},mx=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:gx(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Rg=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=oa(e),r=o.features;o=Ec(o);let s=Ic.getForInstance(o.plugins),{plugin:i,teardown:l}=eg();o.components&&qn.registerAll(o.components);let p=Cg(),d=o.persistState===!1?null:o.storageAdapter??Ag(),u={},b=null,f=!1,m=a=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(a);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:x}=g;return x&&(f=!0),h}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return a};if(d?.load)try{let a=d.load();if(a&&typeof a.then=="function")b=a.then(g=>m(g??{messages:[],metadata:{}}));else{let h=m(a??{messages:[],metadata:{}});h.metadata&&(u=Nc(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=m({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}let C=()=>u,R=a=>{u=a({...u})??{},Za()},H=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Wc],L=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[_s.message,_s.messageAndClick],T=Hc({parsers:H,handlers:L,getSessionMetadata:C,updateSessionMetadata:R,emit:p.emit,documentRef:typeof document<"u"?document:null});T.syncFromMetadata();let k=o.launcher?.enabled??!0,$=o.launcher?.autoExpand??!1,G=o.autoFocusInput??!1,w=$,F=k,D=o.layout?.header?.layout,B=!1,P=()=>Rs(o),I=()=>k||P(),j=P()?!1:k?$:!0,pe=!1,ue=null,ge=()=>{pe=!0,ue&&clearTimeout(ue),ue=setTimeout(()=>{pe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),pe=!1)},1e4)},Z=Pg(o,T,ge),oe=o.features?.showReasoning??!0,Q=o.features?.showToolCalls??!0,se=o.features?.showEventStreamToggle??!1,te=o.features?.scrollToBottom??{},fe=o.features?.scrollBehavior??{},he=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Ce=se?new Ds(he):null,$e=o.features?.eventStream?.maxEvents??2e3,Ee=se?new Bs($e,Ce):null,ke=se?new Ns:null,ze=null,Ke=!1,Le=null,Re=0;Ce?.open().then(()=>Ee?.restore()).catch(a=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",a)});let Je={onCopy:a=>{p.emit("message:copy",a),q?.isClientTokenMode()&&q.submitMessageFeedback(a.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{p.emit("message:feedback",a),q?.isClientTokenMode()&&q.submitMessageFeedback(a.messageId,a.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(a)}},Ot=o.statusIndicator??{},Bt=a=>a==="idle"?Ot.idleText??Wt.idle:a==="connecting"?Ot.connectingText??Wt.connecting:a==="connected"?Ot.connectedText??Wt.connected:a==="error"?Ot.errorText??Wt.error:a==="paused"?Ot.pausedText??Wt.paused:a==="resuming"?Ot.resumingText??Wt.resuming:Wt[a];function Xt(a,g,h,x){if(x==="idle"&&h.idleLink){a.textContent="";let A=document.createElement("a");A.href=h.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=g,A.style.color="inherit",A.style.textDecoration="none",a.appendChild(A)}else a.textContent=g}let Mt=zf({config:o,showClose:I()}),{wrapper:Ne,panel:me,pillRoot:nt}=Mt.shell,He=Mt.panelElements,{container:ve,body:ce,messagesWrapper:We,suggestions:ct,textarea:ye,sendButton:Me,sendButtonWrapper:re,composerForm:M,statusText:U,introTitle:v,introSubtitle:N,closeButton:E,iconHolder:O,headerTitle:J,headerSubtitle:z,header:K,footer:ne,actionsRow:Ge,rightActions:Be}=He,Ye=He.leftActions,it=He.setSendButtonMode,X=He.micButton,je=He.micButtonWrapper,Ae=He.attachmentButton,Ue=He.attachmentButtonWrapper,Oe=He.attachmentInput,Dt=He.attachmentPreviewsContainer;ve.classList.add("persona-relative"),ce.classList.add("persona-relative");let Fa=12,vo=()=>te.label??"",zs=()=>te.iconName??"arrow-down",js=()=>te.enabled!==!1,dn=()=>fe.mode??"anchor-top",Gn=()=>dn()==="follow"||dn()==="anchor-top"&&_r,Uc=()=>fe.anchorTopOffset??16,Vg=()=>fe.restorePosition??"bottom",Vc=()=>fe.pauseOnInteraction===!0,qc=()=>fe.showActivityWhilePinned!==!1,Kc=()=>fe.announce===!0,Lt=y("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");Lt.type="button",Lt.style.display="none",Lt.setAttribute("data-persona-scroll-to-bottom","true");let Ir=y("span","persona-flex persona-items-center"),_a=y("span",""),xo=y("span","");xo.setAttribute("data-persona-scroll-to-bottom-count",""),xo.style.display="none",Lt.append(Ir,_a,xo),ve.appendChild(Lt);let Qn=y("div","persona-stream-anchor-spacer");Qn.setAttribute("aria-hidden","true"),Qn.setAttribute("data-persona-anchor-spacer",""),Qn.style.flexShrink="0",Qn.style.pointerEvents="none",Qn.style.height="0px",ce.appendChild(Qn);let Co=y("div","persona-sr-only");Co.setAttribute("aria-live","polite"),Co.setAttribute("aria-atomic","true"),Co.setAttribute("role","status"),Co.setAttribute("data-persona-live-region",""),Object.assign(Co.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),ve.appendChild(Co);let Rr=null,Us=null,Gc=a=>{!Kc()||!a||(Us=a,Rr===null&&(Rr=setTimeout(()=>{Rr=null,Us&&Kc()&&(Co.textContent=Us),Us=null},400)))},Vo=()=>{let g=ne.style.display==="none"?0:ne.offsetHeight;Lt.style.bottom=`${g+Fa}px`};Vo();let Qc=()=>{let a=!!vo();Lt.setAttribute("aria-label",vo()||"Jump to latest"),Lt.title=vo(),Lt.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Ir.innerHTML="";let g=ae(zs(),"14px","currentColor",2);g?(Ir.appendChild(g),Ir.style.display=""):Ir.style.display="none",_a.textContent=vo(),_a.style.display=a?"":"none"};Qc();let Tt=null,on=null,Xc=null,Jc=s.find(a=>a.renderHeader);if(Jc?.renderHeader){let a=Jc.renderHeader({config:o,defaultRenderer:()=>{let g=Fo({config:o,showClose:I()});return Ws(ve,g,o),g.header},onClose:()=>ut(!1,"user")});if(a){let g=ve.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(a),K=a,Mt.header.element=a)}}let $a=()=>{if(!Ee)return;if(Ke=!0,!ze&&Ee&&(ze=sg({buffer:Ee,getFullHistory:()=>Ee.getAllFromStore(),onClose:()=>Wr(),config:o,plugins:s,getThroughput:()=>ke?.getMetric()??{status:"idle"}})),ze&&(ce.style.display="none",ne.parentNode?.insertBefore(ze.element,ne),ze.update()),ot){ot.style.boxShadow=`inset 0 0 0 1.5px ${Zt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(h=>h&&ot.classList.add(h))}let a=()=>{if(!Ke)return;let g=Date.now();g-Re>=200&&(ze?.update(),Re=g),Le=requestAnimationFrame(a)};Re=0,Le=requestAnimationFrame(a),sn(),p.emit("eventStream:opened",{timestamp:Date.now()})},Wr=()=>{if(Ke){if(Ke=!1,ze&&ze.element.remove(),ce.style.display="",ot){ot.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(g=>g&&ot.classList.remove(g))}Le!==null&&(cancelAnimationFrame(Le),Le=null),sn(),p.emit("eventStream:closed",{timestamp:Date.now()})}},ot=null;if(se){let a=o.features?.eventStream?.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"+(a?.toggleButton?" "+a.toggleButton:"");ot=y("button",g),ot.style.width="28px",ot.style.height="28px",ot.style.color=Zt.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let h=ae("activity","18px","currentColor",1.5);h&&ot.appendChild(h);let x=He.clearChatButtonWrapper,A=He.closeButtonWrapper,W=x||A;W&&W.parentNode===K?K.insertBefore(ot,W):K.appendChild(ot),ot.addEventListener("click",()=>{Ke?Wr():$a()})}let qg=a=>{let g=o.attachments;if(!g?.enabled)return;let h=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!h){h=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let A=a.querySelector("[data-persona-composer-form]");A?.parentNode?A.parentNode.insertBefore(h,A):a.insertBefore(h,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let A=y("input");A.type="file",A.setAttribute("data-persona-composer-attachment-input",""),A.accept=(g.allowedTypes??Un).join(","),A.multiple=(g.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),a.appendChild(A)}},Yc=s.find(a=>a.renderComposer);if(Yc?.renderComposer){let a=o.composer,g=Yc.renderComposer({config:o,defaultRenderer:()=>Ia({config:o}).footer,onSubmit:h=>{if(!q||q.isStreaming())return;let x=h.trim(),A=Tt?.hasAttachments()??!1;if(!x&&!A)return;kd();let W;A&&(W=[],W.push(...Tt.getContentParts()),x&&W.push(fr(x))),q.sendMessage(x,{contentParts:W}),A&&Tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Oe?.click()},models:a?.models,selectedModelId:a?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Xc?.()}:void 0});g&&(Mt.replaceComposer(g),ne=Mt.composer.footer)}let Kg=a=>{let g=(...xe)=>{for(let le of xe){let Se=a.querySelector(le);if(Se)return Se}return null},h=a.querySelector("[data-persona-composer-form]"),x=a.querySelector("[data-persona-composer-input]"),A=a.querySelector("[data-persona-composer-submit]"),W=a.querySelector("[data-persona-composer-mic]"),ee=a.querySelector("[data-persona-composer-status]");h&&(M=h),x&&(ye=x),A&&(Me=A),W&&(X=W,je=W.parentElement),ee&&(U=ee);let V=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(ct=V);let Y=g("[data-persona-composer-attachment-button]",".persona-attachment-button");Y&&(Ae=Y,Ue=Y.parentElement),Oe=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Dt=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let de=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");de&&(Ge=de),Ye=g(".persona-widget-composer__left-actions")};qg(ne),Kg(ne);let Xn=o.layout?.contentMaxWidth??(P()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Xn&&(We.style.maxWidth=Xn,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%"),Xn&&M&&!P()&&(M.style.maxWidth=Xn,M.style.marginLeft="auto",M.style.marginRight="auto"),Xn&&ct&&!P()&&(ct.style.maxWidth=Xn,ct.style.marginLeft="auto",ct.style.marginRight="auto"),Xn&&Dt&&!P()&&(Dt.style.maxWidth=Xn,Dt.style.marginLeft="auto",Dt.style.marginRight="auto"),o.attachments?.enabled&&Oe&&Dt){Tt=gs.fromConfig(o.attachments),Tt.setPreviewsContainer(Dt),Oe.addEventListener("change",h=>{let x=h.target;Tt?.handleFileSelect(x.files),x.value=""});let a=o.attachments.dropOverlay,g=Ig(a);ve.appendChild(g)}let Gg=()=>on?.prefetch();if(o.contextMentions?.enabled&&ye&&(on=Ku({config:o,textarea:ye,anchor:M??ye,getMessages:()=>q.getMessages(),liveRegionHost:ve}),on)){let a=ye;a.parentElement?.insertBefore(on.contextRow,a);let g=on.affordanceButtons;for(let h=g.length-1;h>=0;h--){let x=g[h];Ye?Ye.insertBefore(x,Ye.firstChild):M?.appendChild(x)}}(()=>{let a=o.layout?.slots??{},g=x=>{switch(x){case"body-top":return ve.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return We;case"footer-top":return ct;case"composer":return M;case"footer-bottom":return U;default:return null}},h=(x,A)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")K.insertBefore(A,K.firstChild);else if(x==="header-right")K.appendChild(A);else{let W=K.querySelector(".persona-flex-col");W?W.parentNode?.insertBefore(A,W.nextSibling):K.appendChild(A)}break;case"body-top":{let W=ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");W?W.replaceWith(A):ce.insertBefore(A,ce.firstChild);break}case"body-bottom":ce.appendChild(A);break;case"footer-top":ct.replaceWith(A);break;case"footer-bottom":U.replaceWith(A);break;default:break}};for(let[x,A]of Object.entries(a))if(A)try{let W=A({config:o,defaultContent:()=>g(x)});W&&h(x,W)}catch(W){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,W)}})();let Zc=a=>{let h=a.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let W=h.getAttribute("data-bubble-type");if(W==="reasoning")Sr.has(A)?Sr.delete(A):Sr.add(A),Kf(A,x);else if(W==="tool")Mr.has(A)?Mr.delete(A):Mr.add(A),Gf(A,x,o);else if(W==="approval"){let V=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Y=_o.get(A)??V;_o.set(A,!Y),Yf(A,x,o)}Mo.delete(A)};We.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Zc(a))}),We.addEventListener("keydown",a=>{let g=a.target;(a.key==="Enter"||a.key===" ")&&g.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Zc(a))}),We.addEventListener("copy",a=>{let{clipboardData:g}=a;if(!g)return;let h=We.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let A=x.toString(),W=Af(A);!W||W===A||(g.setData("text/plain",W),a.preventDefault())});let za=new Map,ed=null,td="idle",Qg={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Xg=(a,g)=>{let{icon:h,label:x}=Qg[g];a.setAttribute("aria-label",x),a.title=x,a.setAttribute("aria-pressed",g==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",g!=="idle"),a.classList.toggle("persona-message-action-loading",g==="loading");let A=ae(h,14,"currentColor",2);A&&(a.innerHTML="",a.appendChild(A))},nd=()=>{We.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let x=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Xg(g,x&&x===ed?td:"idle")})};We.addEventListener("click",a=>{let h=a.target.closest(".persona-message-action-btn[data-action]");if(!h)return;a.preventDefault(),a.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let A=x.getAttribute("data-actions-for");if(!A)return;let W=h.getAttribute("data-action");if(W==="copy"){let V=q.getMessages().find(Y=>Y.id===A);if(V&&Je.onCopy){let Y=V.content||"";navigator.clipboard.writeText(Y).then(()=>{h.classList.add("persona-message-action-success");let de=ae("check",14,"currentColor",2);de&&(h.innerHTML="",h.appendChild(de)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let xe=ae("copy",14,"currentColor",2);xe&&(h.innerHTML="",h.appendChild(xe))},2e3)}).catch(de=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",de)}),Je.onCopy(V)}}else if(W==="read-aloud")q.toggleReadAloud(A);else if(W==="upvote"||W==="downvote"){let V=(za.get(A)??null)===W,Y=W==="upvote"?"thumbs-up":"thumbs-down";if(V){za.delete(A),h.classList.remove("persona-message-action-active");let de=ae(Y,14,"currentColor",2);de&&(h.innerHTML="",h.appendChild(de))}else{let de=W==="upvote"?"downvote":"upvote",xe=x.querySelector(`[data-action="${de}"]`);if(xe){xe.classList.remove("persona-message-action-active");let rt=ae(de==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);rt&&(xe.innerHTML="",xe.appendChild(rt))}za.set(A,W),h.classList.add("persona-message-action-active");let le=ae(Y,14,"currentColor",2);le&&(le.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(le)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let qe=q.getMessages().find(ft=>ft.id===A);qe&&Je.onFeedback&&Je.onFeedback({type:W,messageId:qe.id,message:qe})}}}),We.addEventListener("click",a=>{let h=a.target.closest("button[data-approval-action]");if(!h)return;a.preventDefault(),a.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let W=h.getAttribute("data-approval-action");if(!W)return;let ee=W==="approve"?"approved":"denied",Y=q.getMessages().find(xe=>xe.id===A);if(!Y?.approval)return;let de=x.querySelector("[data-approval-buttons]");de&&de.querySelectorAll("button").forEach(le=>{le.disabled=!0,le.style.opacity="0.5",le.style.cursor="not-allowed"}),Y.approval.toolType==="webmcp"?q.resolveWebMcpApproval(A,ee):q.resolveApproval(Y.approval,ee)});let Ze=null,Hr=null,Br=()=>{},Dr="none",Vs=null,vn={artifacts:[],selectedId:null},Wn=!1,xn=!1,Nr=!1,qo=!1,od=()=>qo||vn.artifacts.some(a=>lo(o.features?.artifacts,a)==="panel"),qs=()=>vn.artifacts.length>0&&!Wn&&od(),dt={current:null},ja=(a,g)=>{let h=q.getArtifactById(g),x=h?.markdown,A=h?.title||"artifact",W=h?.file,ee=h?.artifactType??"markdown";if(!x){let de=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(de){let le=q.getMessages().find(Se=>Se.id===de);if(le?.rawContent)try{let Se=JSON.parse(le.rawContent);x=Se?.props?.markdown,A=Se?.props?.title||A,Se?.props?.file&&typeof Se.props.file=="object"&&(W=Se.props.file),!h&&typeof Se?.props?.artifactType=="string"&&(ee=Se.props.artifactType)}catch{}}}return{markdown:x,title:A,file:W,artifactType:ee}};We.addEventListener("click",a=>{let h=a.target.closest("[data-download-artifact]");if(!h)return;a.preventDefault(),a.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:W,title:ee,file:V}=ja(h,x);if(!W)return;let{filename:Y,mime:de,content:xe}=of({title:ee,markdown:W,file:V}),le=new Blob([xe],{type:de}),Se=URL.createObjectURL(le),qe=document.createElement("a");qe.href=Se,qe.download=Y,qe.click(),URL.revokeObjectURL(Se)}),We.addEventListener("click",a=>{let h=a.target.closest("[data-artifact-custom-action]");if(!h)return;a.preventDefault(),a.stopPropagation();let x=h.getAttribute("data-artifact-custom-action");if(!x)return;let A=h.closest("[data-artifact-inline]"),W=A?null:h.closest("[data-open-artifact]"),ee=A?A.getAttribute("data-artifact-inline"):W?.getAttribute("data-open-artifact")??null,Y=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ft=>ft.id===x);if(!Y)return;let{markdown:de,title:xe,file:le,artifactType:Se}=ja(h,ee??""),qe={artifactId:ee,title:xe,artifactType:Se,markdown:de,file:le};try{Promise.resolve(Y.onClick(qe)).catch(()=>{})}catch{}}),We.addEventListener("click",a=>{let h=a.target.closest("[data-copy-artifact]");if(!h)return;a.preventDefault(),a.stopPropagation();let x=h.getAttribute("data-copy-artifact");if(!x)return;let A=q.getArtifactById(x),W="";if(A)W=Ts(A);else{let{markdown:ee,file:V,artifactType:Y}=ja(h,x);Y==="markdown"&&(W=Ts({id:x,artifactType:"markdown",status:"complete",markdown:ee??"",...V?{file:V}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let ee=ae("check",16,"currentColor",2);ee&&(h.replaceChildren(ee),setTimeout(()=>{let V=ae("copy",16,"currentColor",2);V&&h.replaceChildren(V)},1500))}).catch(()=>{})}),We.addEventListener("click",a=>{let h=a.target.closest("[data-expand-artifact-inline]");if(!h)return;a.preventDefault(),a.stopPropagation();let x=h.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Wn=!1,qo=!0,xn=!0,Nr=!0,q.selectArtifact(x),Hn())}),We.addEventListener("click",a=>{let g=a.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let h=g.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(a.preventDefault(),a.stopPropagation(),Wn=!1,qo=!0,q.selectArtifact(x),Hn())}),We.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let g=a.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),g.click())});let Ko=He.composerOverlay,Go=(a,g,h)=>{let x=g.trim();if(!x||!dt.current)return;let A=a.getAttribute("data-tool-call-id")??"",W=h.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:x,answers:h.structured,values:h.values??(h.source==="multi"?x.split(", "):[x]),isFreeText:W,source:h.source},bubbles:!0,composed:!0})),dr(Ko,A);let ee=dt.current.getMessages().find(V=>V.toolCall?.id===A);ee?.agentMetadata?.awaitingLocalTool?dt.current.resolveAskUserQuestion(ee,h.structured??x):dt.current.sendMessage(x)},wo=a=>{let g=dt.current;if(!g)return;let h=a.getAttribute("data-tool-call-id")??"",x=g.getMessages().find(A=>A.toolCall?.id===h);x&&g.persistAskUserQuestionProgress(x,{answers:Ei(a,x),currentIndex:yn(a)})},rd=a=>Object.entries(a).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ua=a=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=yn(a),h=cr(a);if(g>=h-1)return;let x=dt.current?.getMessages().find(A=>A.toolCall?.id===a.getAttribute("data-tool-call-id"));x&&(Li(a,x,o,g+1),wo(a))};Ko.addEventListener("click",a=>{let h=a.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let A=h.getAttribute("data-ask-user-action");if(a.preventDefault(),a.stopPropagation(),A==="dismiss"){let W=x.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),dr(Ko,W);let ee=dt.current?.getMessages().find(V=>V.toolCall?.id===W);ee?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(ee),dt.current?.resolveAskUserQuestion(ee,"(dismissed)"));return}if(A==="pick"){let W=h.getAttribute("data-option-label");if(!W)return;let ee=x.getAttribute("data-multi-select")==="true",V=po(x);if(V&&ee){let Y=Bo(x)[yn(x)],de=new Set(Array.isArray(Y)?Y:[]);de.has(W)?de.delete(W):de.add(W),uo(x,Array.from(de)),wo(x);return}if(V){uo(x,W),wo(x),Ua(x);return}if(ee){let Y=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Y?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Y);let de=x.querySelector('[data-ask-user-action="submit-multi"]');de&&(de.disabled=Ml(x).length===0);return}Go(x,W,{source:"pick",values:[W]});return}if(A==="submit-multi"){let W=Ml(x);if(W.length===0)return;Go(x,W.join(", "),{source:"multi",values:W});return}if(A==="open-free-text"){let W=x.querySelector('[data-ask-free-text-row="true"]');W&&(W.classList.remove("persona-hidden"),W.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(A==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(A==="submit-free-text"){let ee=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!ee.trim())return;if(po(x)){uo(x,ee.trim()),wo(x),Ua(x);return}Go(x,ee,{source:"free-text"});return}if(A==="next"||A==="back"){if(!dt.current)return;let W=x.getAttribute("data-tool-call-id")??"",ee=dt.current.getMessages().find(le=>le.toolCall?.id===W);if(!ee)return;let Y=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(Y){let le=Bo(x)[yn(x)];(typeof le!="string"||le!==Y)&&uo(x,Y)}let de=A==="next"?1:-1,xe=yn(x)+de;Li(x,ee,o,xe),wo(x);return}if(A==="submit-all"){if(!dt.current)return;let W=x.getAttribute("data-tool-call-id")??"",ee=dt.current.getMessages().find(le=>le.toolCall?.id===W);if(!ee)return;let Y=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";Y&&uo(x,Y);let de=Ei(x,ee);dt.current.persistAskUserQuestionProgress(ee,{answers:de,currentIndex:yn(x)});let xe=rd(de);Go(x,xe||"(submitted)",{source:"submit-all",structured:de});return}if(A==="skip"){if(!dt.current)return;let W=x.getAttribute("data-tool-call-id")??"",ee=dt.current.getMessages().find(Se=>Se.toolCall?.id===W);if(!ee)return;let V=po(x),Y=yn(x),de=cr(x),xe=Y>=de-1;if(!V){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),dr(Ko,W),ee.agentMetadata?.awaitingLocalTool&&(dt.current.markAskUserQuestionResolved(ee),dt.current.resolveAskUserQuestion(ee,"(dismissed)"));return}uo(x,"");let le=x.querySelector('[data-ask-free-text-input="true"]');if(le&&(le.value=""),xe){let Se=Ei(x,ee),qe=rd(Se);Go(x,qe||"(skipped)",{source:"submit-all",structured:Se});return}Li(x,ee,o,Y+1),wo(x);return}}),Ko.addEventListener("keydown",a=>{if(a.key!=="Enter")return;let h=a.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;a.preventDefault();let A=h.value;if(A.trim()){if(po(x)){uo(x,A.trim()),wo(x),Ua(x);return}Go(x,A,{source:"free-text"})}});let sd=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let g=a.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let h=Ko.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(a.key),W=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];W&&(a.preventDefault(),W.click())};document.addEventListener("keydown",sd);let Jn=null,xt=null,Or=null,Ks=null,Va=()=>{},id=!1,Gs="",Qs="";function qa(){Ks?.(),Ks=null}let ad=()=>{if(!Jn||!xt)return;let a=t.classList.contains("persona-artifact-welded-split"),g=t.ownerDocument.defaultView??window,h=g.innerWidth<=640;if(!a||t.classList.contains("persona-artifact-narrow-host")||h){xt.style.removeProperty("position"),xt.style.removeProperty("left"),xt.style.removeProperty("top"),xt.style.removeProperty("bottom"),xt.style.removeProperty("width"),xt.style.removeProperty("z-index");return}let x=Jn.firstElementChild;if(!x||x===xt)return;let A=10;xt.style.position="absolute",xt.style.top="0",xt.style.bottom="0",xt.style.width=`${A}px`,xt.style.zIndex="5";let W=kc(Jn,g),ee=x.offsetWidth+W/2-A/2;xt.style.left=`${Math.max(0,ee)}px`},Xs=()=>{},Jg=()=>{let a=t.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!g||a.innerWidth>h?!1:k||_t(o)},Js=()=>!en(o)||!qs()||t.classList.contains("persona-artifact-narrow-host")||Jg()||(t.ownerDocument.defaultView??window).innerWidth<cx?"none":Mc(o)?"detached":"welded",Hn=()=>{if(!Ze||!en(o))return;Os(t,o),Fs(t,o),Xs();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=me.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=a);let h=qs();Ze.setVisible(h),Ze.update(vn),Wn?(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),xn=!1,Nr=!1):vn.artifacts.length>0&&od()?(Ze.element.classList.remove("persona-hidden"),Ze.setMobileOpen(!0)):(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),xn=!1,Nr=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ze.setExpandToggleVisible(x),Ze.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ze.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ze.setTabFade(o.features?.artifacts?.layout?.tabFade),Ze.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!Nr&&(xn=!1),xn!==id){let W=Ze.element;xn?(Gs=W.style.width,Qs=W.style.maxWidth,W.style.removeProperty("width"),W.style.removeProperty("max-width")):(Gs&&(W.style.width=Gs),Qs&&(W.style.maxWidth=Qs),Gs="",Qs=""),id=xn}t.classList.toggle("persona-artifact-expanded",xn),Ze.setExpanded(xn);let A=Js();A!==Dr&&(Dr=A,Br()),Va()};if(en(o)){me.style.position="relative";let a=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(ve),Ze=ag(o,{onSelect:h=>dt.current?.selectArtifact(h),onDismiss:()=>{Wn=!0,Hn()},onToggleExpand:()=>{let h=!xn,x=vn.selectedId??vn.artifacts[vn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:h})!==!0&&(xn=h,h||(Nr=!1),Hn())}}),Ze.element.classList.add("persona-hidden"),Jn=g,g.appendChild(a),g.appendChild(Ze.element),Ze.backdrop&&me.appendChild(Ze.backdrop),me.appendChild(g),Va=()=>{if(!Jn||!Ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Or?.(),Or=null,qa(),xt&&(xt.remove(),xt=null),Ze.element.style.removeProperty("width"),Ze.element.style.removeProperty("maxWidth");return}if(!xt){let x=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let A=t.ownerDocument,W=A.defaultView??window,ee=V=>{if(!Ze||V.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||W.innerWidth<=640)return;V.preventDefault(),qa();let Y=V.clientX,de=Ze.element.getBoundingClientRect().width,xe=o.features?.artifacts?.layout,le=qe=>{let ft=Jn.getBoundingClientRect().width,rt=t.classList.contains("persona-artifact-welded-split"),an=kc(Jn,W),Et=rt?0:x.getBoundingClientRect().width||6,It=de-(qe.clientX-Y),_=hg(It,ft,an,Et,xe?.resizableMinWidth,xe?.resizableMaxWidth);Ze.element.style.width=`${_}px`,Ze.element.style.maxWidth="none",ad()},Se=()=>{A.removeEventListener("pointermove",le),A.removeEventListener("pointerup",Se),A.removeEventListener("pointercancel",Se),Ks=null;try{x.releasePointerCapture(V.pointerId)}catch{}};Ks=Se,A.addEventListener("pointermove",le),A.addEventListener("pointerup",Se),A.addEventListener("pointercancel",Se);try{x.setPointerCapture(V.pointerId)}catch{}};x.addEventListener("pointerdown",ee),xt=x,Jn.insertBefore(x,Ze.element),Or=()=>{x.removeEventListener("pointerdown",ee)}}if(xt){let x=qs();xt.classList.toggle("persona-hidden",!x),ad()}},Xs=()=>{if(!k||!Ze||(o.launcher?.sidebarMode??!1)||_t(o)&&bn(o).reveal==="emerge")return;let x=t.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,W=o.launcher?.mobileBreakpoint??640;if(A&&x.innerWidth<=W||!dg(o,k))return;let ee=o.launcher?.width??o.launcherWidth??Vn,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";qs()?(me.style.width=V,me.style.maxWidth=V):(me.style.width=ee,me.style.maxWidth=ee)},typeof ResizeObserver<"u"&&(Hr=new ResizeObserver(()=>{Hn()}),Hr.observe(me))}else me.appendChild(ve);P()&&nt&&(He.peekBanner&&nt.appendChild(He.peekBanner),nt.appendChild(ne)),t.appendChild(Ne),nt&&t.appendChild(nt);let Ys=()=>{if(P()){me.style.width="100%",me.style.maxWidth="100%";let kt=o.launcher?.composerBar??{},nn=Ne.dataset.state==="expanded",hi=kt.expandedSize??"anchored";if(!(nn&&hi!=="fullscreen")){ve.style.background="",ve.style.border="",ve.style.borderRadius="",ve.style.overflow="",ve.style.boxShadow="";return}let es=o.theme?.components?.panel,yi=br(o),nr=(On,Wo)=>On==null||On===""?Wo:Yt(yi,On)??On,bi="1px solid var(--persona-border)",gl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ro="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ve.style.background="var(--persona-surface, #ffffff)",ve.style.border=nr(es?.border,bi),ve.style.borderRadius=nr(es?.borderRadius,Ro),ve.style.boxShadow=nr(es?.shadow,gl),ve.style.overflow="hidden";return}let a=_t(o),g=o.launcher?.sidebarMode??!1,h=a||g||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,W=o.theme?.components?.panel,ee=br(o),V=(kt,nn)=>kt==null||kt===""?nn:Yt(ee,kt)??kt,Y=t.ownerDocument.defaultView??window,de=o.launcher?.mobileFullscreen??!0,xe=o.launcher?.mobileBreakpoint??640,le=Y.innerWidth<=xe,Se=de&&le&&k,qe=a&&de&&le,ft=o.launcher?.position??"bottom-left",rt=ft==="bottom-left"||ft==="top-left",an=o.launcher?.zIndex??Qt,Et="var(--persona-panel-border, 1px solid var(--persona-border))",It="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",_="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Pe=A&&!Se&&!qe;Pe?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let Fe=Pe?Et:g||Se?"none":Et,Te=Pe?It:Se?"none":g?rt?"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))":x?"none":It;a&&!Se&&!Pe&&(Te="none",Fe="none");let At=Pe?_:g||Se?"0":_,gt=V(W?.border,Fe),Ft=V(W?.shadow,Te),mt=V(W?.borderRadius,At),tn=Js(),Rt=tn==="detached",Ie=tn==="welded";t.classList.toggle("persona-artifact-detached-split",Rt),t.classList.toggle("persona-artifact-welded-split",Ie);let _e="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",wt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&en(o)&&Mc(o)&&x&&!a;t.classList.toggle("persona-artifact-chat-flush",wt);let pt=Rt||wt?"none":Ft,ht=Rt?Et:Ie?"none":gt,et=Rt?_:mt;wt&&(ht="none",et="0");let De=W?.borderRadius!=null&&W.borderRadius!=="",vt=wt&&!De?"0":mt,qt=ce.scrollTop;t.style.cssText="",Ne.style.cssText="",me.style.cssText="",ve.style.cssText="",ce.style.cssText="",ne.style.cssText="",Ke&&(ce.style.display="none"),(h||x)&&(t.style.minWidth="0");let mn=()=>{if(qt<=0)return;(ce.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ce.scrollTop===qt)return;let nn=ce.scrollHeight-ce.clientHeight;nn<=0||(ce.scrollTop=Math.min(qt,nn))})};if(Se){Ne.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"),Ne.style.cssText=`
219
+ `,A.addEventListener("click",()=>{u=G,B.forEach((O,D)=>{let W=D<G;O.classList.toggle("selected",W),O.setAttribute("aria-checked",D===G-1?"true":"false")})}),B.push(A),L.appendChild(A)}b.appendChild(L);let k=null;if(p){let G=document.createElement("div");G.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"),G.appendChild(k),b.appendChild(G)}let S=document.createElement("div");S.className="persona-feedback-actions";let E=document.createElement("button");E.type="button",E.className="persona-feedback-btn persona-feedback-btn-skip",E.textContent=l,E.addEventListener("click",()=>{n?.(),d.remove()});let z=document.createElement("button");return z.type="button",z.className="persona-feedback-btn persona-feedback-btn-submit",z.textContent=i,z.addEventListener("click",async()=>{if(u===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}z.disabled=!0,z.textContent="Submitting...";try{let G=k?.value.trim()||void 0;await e(u,G),d.remove()}catch(G){z.disabled=!1,z.textContent=i,console.error("[CSAT Feedback] Failed to submit:",G)}}),S.appendChild(E),S.appendChild(z),b.appendChild(S),d.appendChild(b),d}function qf(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:c="Not likely",highLabel:d="Very likely"}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let b=null,g=document.createElement("div");g.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,h.appendChild(C);let L=document.createElement("p");L.className="persona-feedback-subtitle",L.textContent=r,h.appendChild(L),g.appendChild(h);let B=document.createElement("div");B.className="persona-feedback-rating persona-feedback-rating-nps",B.setAttribute("role","radiogroup"),B.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let S=document.createElement("span");S.className="persona-feedback-label-low",S.textContent=c;let E=document.createElement("span");E.className="persona-feedback-label-high",E.textContent=d,k.appendChild(S),k.appendChild(E);let z=document.createElement("div");z.className="persona-feedback-numbers";let G=[];for(let P=0;P<=10;P++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-number-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`Rating ${P} out of 10`),I.textContent=String(P),I.dataset.rating=String(P),P<=6?I.classList.add("persona-feedback-detractor"):P<=8?I.classList.add("persona-feedback-passive"):I.classList.add("persona-feedback-promoter"),I.addEventListener("click",()=>{b=P,G.forEach((j,pe)=>{j.classList.toggle("selected",pe===P),j.setAttribute("aria-checked",pe===P?"true":"false")})}),G.push(I),z.appendChild(I)}B.appendChild(k),B.appendChild(z),g.appendChild(B);let A=null;if(p){let P=document.createElement("div");P.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=s,A.rows=3,A.setAttribute("aria-label","Additional comments"),P.appendChild(A),g.appendChild(P)}let O=document.createElement("div");O.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=l,D.addEventListener("click",()=>{n?.(),u.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=i,W.addEventListener("click",async()=>{if(b===null){z.classList.add("persona-feedback-shake"),setTimeout(()=>z.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let P=A?.value.trim()||void 0;await e(b,P),u.remove()}catch(P){W.disabled=!1,W.textContent=i,console.error("[NPS Feedback] Failed to submit:",P)}}),O.appendChild(D),O.appendChild(W),g.appendChild(O),u.appendChild(g),u}var Wr="persona-chat-history",Bx=30*1e3,Dx=641,Nx={"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 Ox(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let s=Nx[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function Va(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function Fx(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function _x(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Uc=t=>!t||typeof t!="object"?{}:{...t},Kf=t=>t.map(e=>({...e,streaming:!1})),Gf=(t,e,n)=>{let o=t?.markdown?Li(t.markdown):null,r=Pi(t?.sanitize);return t?.postprocessMessage&&r&&t?.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=>{let i=s.text??"",l=s.message.rawContent??null;if(e){let d=e.process({text:i,raw:l??i,message:s.message,streaming:s.streaming});d!==null&&(i=d.text,d.persist||(s.message.__skipPersist=!0),d.resubmit&&!s.streaming&&n&&n())}let p=Un()!==null,c;if(t?.postprocessMessage){let d=t.postprocessMessage({...s,text:i,raw:l??s.text??""});c=r?r(d):d}else if(o){let d=s.streaming?Ep(i):i,u=o(d);c=r&&p?r(u):u}else c=po(i);return c}};function Qf(t){let e=v("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,i=ae(n,o,r,s);if(i&&e.appendChild(i),t?.label){let l=v("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var $x=(t,e)=>{let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];n[o]=s?{...s,...r}:r}return n},zx=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:$x(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Xf=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=ca(e),r=o.features;o=Wc(o);let s=Nc.getForInstance(o.plugins),{plugin:i,teardown:l}=vf();o.components&&Qn.registerAll(o.components);let p=Ff(),d=o.persistState===!1?null:o.storageAdapter??$f(),u={},b=null,g=!1,h=a=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(a);if(f&&typeof f=="object"&&"state"in f){let{state:m,open:x}=f;return x&&(g=!0),m}return f}catch(f){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return a};if(d?.load)try{let a=d.load();if(a&&typeof a.then=="function")b=a.then(f=>h(f??{messages:[],metadata:{}}));else{let m=h(a??{messages:[],metadata:{}});m.metadata&&(u=Uc(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=h({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}let C=()=>u,L=a=>{u=a({...u})??{},sl()},B=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Fc],k=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Gs.message,Gs.messageAndClick],S=_c({parsers:B,handlers:k,getSessionMetadata:C,updateSessionMetadata:L,emit:p.emit,documentRef:typeof document<"u"?document:null});S.syncFromMetadata();let E=o.launcher?.enabled??!0,z=o.launcher?.autoExpand??!1,G=o.autoFocusInput??!1,A=z,O=E,D=o.layout?.header?.layout,W=!1,P=()=>_s(o),I=()=>E||P(),j=P()?!1:E?z:!0,pe=!1,ge=null,se=()=>{pe=!0,ge&&clearTimeout(ge),ge=setTimeout(()=>{pe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),pe=!1)},1e4)},Y=Gf(o,S,se),oe=o.features?.showReasoning??!0,J=o.features?.showToolCalls??!0,ie=o.features?.showEventStreamToggle??!1,ee=o.features?.scrollToBottom??{},fe=o.features?.scrollBehavior??{},he=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,we=ie?new js(he):null,ve=o.features?.eventStream?.maxEvents??2e3,Te=ie?new Us(ve,we):null,Me=ie?new Vs:null,_e=null,Ve=!1,ke=null,Re=0;we?.open().then(()=>Te?.restore()).catch(a=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",a)});let Ge={onCopy:a=>{p.emit("message:copy",a),V?.isClientTokenMode()&&V.submitMessageFeedback(a.id,"copy").catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",f)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{p.emit("message:feedback",a),V?.isClientTokenMode()&&V.submitMessageFeedback(a.messageId,a.type).catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",f)}),o.messageActions?.onFeedback?.(a)}},Nt=o.statusIndicator??{},Bt=a=>a==="idle"?Nt.idleText??Wt.idle:a==="connecting"?Nt.connectingText??Wt.connecting:a==="connected"?Nt.connectedText??Wt.connected:a==="error"?Nt.errorText??Wt.error:a==="paused"?Nt.pausedText??Wt.paused:a==="resuming"?Nt.resumingText??Wt.resuming:Wt[a];function Xt(a,f,m,x){if(x==="idle"&&m.idleLink){a.textContent="";let T=document.createElement("a");T.href=m.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=f,T.style.color="inherit",T.style.textDecoration="none",a.appendChild(T)}else a.textContent=f}let Mt=af({config:o,showClose:I()}),{wrapper:De,panel:ye,pillRoot:Ye}=Mt.shell,He=Mt.panelElements,{container:xe,body:ue,messagesWrapper:We,starterSuggestions:Jt,transcriptSuggestions:gt,suggestions:bt,textarea:Q,sendButton:w,sendButtonWrapper:K,composerForm:y,statusText:H,introTitle:N,introSubtitle:$,closeButton:U,iconHolder:F,headerTitle:te,headerSubtitle:de,header:Le,footer:Se,actionsRow:rt,rightActions:ot}=He,ze=He.leftActions,Ze=He.setSendButtonMode,X=He.micButton,Ue=He.micButtonWrapper,Ne=He.attachmentButton,Ot=He.attachmentButtonWrapper,At=He.attachmentInput,Yt=He.attachmentPreviewsContainer;xe.classList.add("persona-relative"),ue.classList.add("persona-relative");let Xs=12,Jn=()=>ee.label??"",cm=()=>ee.iconName??"arrow-down",dm=()=>ee.enabled!==!1,un=()=>fe.mode??"anchor-top",Yn=()=>un()==="follow"||un()==="anchor-top"&&Kr,Xc=()=>fe.anchorTopOffset??16,pm=()=>fe.restorePosition??"bottom",Jc=()=>fe.pauseOnInteraction===!0,Yc=()=>fe.showActivityWhilePinned!==!1,Zc=()=>fe.announce===!0,Lt=v("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");Lt.type="button",Lt.style.display="none",Lt.setAttribute("data-persona-scroll-to-bottom","true");let Br=v("span","persona-flex persona-items-center"),Ka=v("span",""),Ao=v("span","");Ao.setAttribute("data-persona-scroll-to-bottom-count",""),Ao.style.display="none",Lt.append(Br,Ka,Ao),xe.appendChild(Lt);let Zn=v("div","persona-stream-anchor-spacer");Zn.setAttribute("aria-hidden","true"),Zn.setAttribute("data-persona-anchor-spacer",""),Zn.style.flexShrink="0",Zn.style.pointerEvents="none",Zn.style.height="0px",ue.appendChild(Zn);let So=v("div","persona-sr-only");So.setAttribute("aria-live","polite"),So.setAttribute("aria-atomic","true"),So.setAttribute("role","status"),So.setAttribute("data-persona-live-region",""),Object.assign(So.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),xe.appendChild(So);let Dr=null,Js=null,ed=a=>{!Zc()||!a||(Js=a,Dr===null&&(Dr=setTimeout(()=>{Dr=null,Js&&Zc()&&(So.textContent=Js),Js=null},400)))},Qo=()=>{let f=Se.style.display==="none"?0:Se.offsetHeight;Lt.style.bottom=`${f+Xs}px`};Qo();let td=()=>{let a=!!Jn();Lt.setAttribute("aria-label",Jn()||"Jump to latest"),Lt.title=Jn(),Lt.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Br.innerHTML="";let f=ae(cm(),"14px","currentColor",2);f?(Br.appendChild(f),Br.style.display=""):Br.style.display="none",Ka.textContent=Jn(),Ka.style.display=a?"":"none"};td();let Tt=null,sn=null,nd=null,od=s.find(a=>a.renderHeader);if(od?.renderHeader){let a=od.renderHeader({config:o,defaultRenderer:()=>{let f=Uo({config:o,showClose:I()});return $s(xe,f,o),f.header},onClose:()=>ct(!1,"user")});if(a){let f=xe.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(a),Le=a,Mt.header.element=a)}}let Ga=()=>{if(!Te)return;if(Ve=!0,!_e&&Te&&(_e=Af({buffer:Te,getFullHistory:()=>Te.getAllFromStore(),onClose:()=>Nr(),config:o,plugins:s,getThroughput:()=>Me?.getMetric()??{status:"idle"}})),_e&&(ue.style.display="none",Se.parentNode?.insertBefore(_e.element,Se),_e.update()),et){et.style.boxShadow=`inset 0 0 0 1.5px ${tn.actionIconColor}`;let f=o.features?.eventStream?.classNames?.toggleButtonActive;f&&f.split(/\s+/).forEach(m=>m&&et.classList.add(m))}let a=()=>{if(!Ve)return;let f=Date.now();f-Re>=200&&(_e?.update(),Re=f),ke=requestAnimationFrame(a)};Re=0,ke=requestAnimationFrame(a),ln(),p.emit("eventStream:opened",{timestamp:Date.now()})},Nr=()=>{if(Ve){if(Ve=!1,_e&&_e.element.remove(),ue.style.display="",et){et.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(f=>f&&et.classList.remove(f))}ke!==null&&(cancelAnimationFrame(ke),ke=null),ln(),p.emit("eventStream:closed",{timestamp:Date.now()})}},et=null;if(ie){let a=o.features?.eventStream?.classNames,f="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"+(a?.toggleButton?" "+a.toggleButton:"");et=v("button",f),et.style.width="28px",et.style.height="28px",et.style.color=tn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let m=ae("activity","18px","currentColor",1.5);m&&et.appendChild(m);let x=He.clearChatButtonWrapper,T=He.closeButtonWrapper,R=x||T;R&&R.parentNode===Le?Le.insertBefore(et,R):Le.appendChild(et),et.addEventListener("click",()=>{Ve?Nr():Ga()})}let um=a=>{let f=o.attachments;if(!f?.enabled)return;let m=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!m){m=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let T=a.querySelector("[data-persona-composer-form]");T?.parentNode?T.parentNode.insertBefore(m,T):a.insertBefore(m,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let T=v("input");T.type="file",T.setAttribute("data-persona-composer-attachment-input",""),T.accept=(f.allowedTypes??Kn).join(","),T.multiple=(f.maxFiles??4)>1,T.style.display="none",T.setAttribute("aria-label",f.buttonTooltipText??"Attach files"),a.appendChild(T)}},rd=s.find(a=>a.renderComposer);if(rd?.renderComposer){let a=o.composer,f=rd.renderComposer({config:o,defaultRenderer:()=>Oa({config:o}).footer,onSubmit:m=>{if(!V||V.isStreaming())return;let x=m.trim(),T=Tt?.hasAttachments()??!1;if(!x&&!T)return;qd();let R;T&&(R=[],R.push(...Tt.getContentParts()),x&&R.push(yr(x))),V.sendMessage(x,{contentParts:R}),T&&Tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{At?.click()},models:a?.models,selectedModelId:a?.selectedModelId,onModelChange:m=>{o.composer={...o.composer,selectedModelId:m},o.agent&&(o.agent={...o.agent,model:m})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{nd?.()}:void 0});f&&(Mt.replaceComposer(f),Se=Mt.composer.footer)}let gm=a=>{let f=(...me)=>{for(let ce of me){let Ae=a.querySelector(ce);if(Ae)return Ae}return null},m=a.querySelector("[data-persona-composer-form]"),x=a.querySelector("[data-persona-composer-input]"),T=a.querySelector("[data-persona-composer-submit]"),R=a.querySelector("[data-persona-composer-mic]"),ne=a.querySelector("[data-persona-composer-status]");m&&(y=m),x&&(Q=x),T&&(w=T),R&&(X=R,Ue=R.parentElement),ne&&(H=ne);let q=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");q&&(bt=q);let Z=f("[data-persona-composer-attachment-button]",".persona-attachment-button");Z&&(Ne=Z,Ot=Z.parentElement),At=f("[data-persona-composer-attachment-input]",'input[type="file"]'),Yt=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let re=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");re&&(rt=re),ze=f(".persona-widget-composer__left-actions")};um(Se),gm(Se);let Ln=o.layout?.contentMaxWidth??(P()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Ln&&(We.style.maxWidth=Ln,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",Jt.style.maxWidth=Ln,gt.style.maxWidth=Ln,gt.style.marginLeft="auto",gt.style.marginRight="auto",gt.style.width="100%"),Ln&&y&&!P()&&(y.style.maxWidth=Ln,y.style.marginLeft="auto",y.style.marginRight="auto"),Ln&&bt&&!P()&&(bt.style.maxWidth=Ln,bt.style.marginLeft="auto",bt.style.marginRight="auto"),Ln&&Yt&&!P()&&(Yt.style.maxWidth=Ln,Yt.style.marginLeft="auto",Yt.style.marginRight="auto"),o.attachments?.enabled&&At&&Yt){Tt=ws.fromConfig(o.attachments),Tt.setPreviewsContainer(Yt),At.addEventListener("change",m=>{let x=m.target;Tt?.handleFileSelect(x.files),x.value=""});let a=o.attachments.dropOverlay,f=Qf(a);xe.appendChild(f)}let fm=()=>sn?.prefetch();if(o.contextMentions?.enabled&&Q&&(sn=pg({config:o,textarea:Q,anchor:y??Q,getMessages:()=>V.getMessages(),liveRegionHost:xe}),sn)){let a=Q;a.parentElement?.insertBefore(sn.contextRow,a);let f=sn.affordanceButtons;for(let m=f.length-1;m>=0;m--){let x=f[m];ze?ze.insertBefore(x,ze.firstChild):y?.appendChild(x)}}(()=>{let a=o.layout?.slots??{},f=x=>{switch(x){case"body-top":return xe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return We;case"footer-top":return bt;case"composer":return y;case"footer-bottom":return H;default:return null}},m=(x,T)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")Le.insertBefore(T,Le.firstChild);else if(x==="header-right")Le.appendChild(T);else{let R=Le.querySelector(".persona-flex-col");R?R.parentNode?.insertBefore(T,R.nextSibling):Le.appendChild(T)}break;case"body-top":{let R=ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");R?R.replaceWith(T):ue.insertBefore(T,ue.firstChild);break}case"body-bottom":ue.appendChild(T);break;case"footer-top":bt.replaceWith(T);break;case"footer-bottom":H.replaceWith(T);break;default:break}};for(let[x,T]of Object.entries(a))if(T)try{let R=T({config:o,defaultContent:()=>f(x)});R&&m(x,R)}catch(R){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,R)}})();let sd=a=>{let m=a.target.closest('button[data-expand-header="true"]');if(!m)return;let x=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let T=x.getAttribute("data-message-id");if(!T)return;let R=m.getAttribute("data-bubble-type");if(R==="reasoning")kr.has(T)?kr.delete(T):kr.add(T),uf(T,x);else if(R==="tool")Lr.has(T)?Lr.delete(T):Lr.add(T),gf(T,x,o);else if(R==="approval"){let q=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Z=jo.get(T)??q;jo.set(T,!Z),yf(T,x,o)}Lo.delete(T)};We.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),sd(a))}),We.addEventListener("keydown",a=>{let f=a.target;(a.key==="Enter"||a.key===" ")&&f.closest('button[data-expand-header="true"]')&&(a.preventDefault(),sd(a))}),We.addEventListener("copy",a=>{let{clipboardData:f}=a;if(!f)return;let m=We.getRootNode(),x=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let T=x.toString(),R=_g(T);!R||R===T||(f.setData("text/plain",R),a.preventDefault())});let Qa=new Map,id=null,ad="idle",mm={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},hm=(a,f)=>{let{icon:m,label:x}=mm[f];a.setAttribute("aria-label",x),a.title=x,a.setAttribute("aria-pressed",f==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",f!=="idle"),a.classList.toggle("persona-message-action-loading",f==="loading");let T=ae(m,14,"currentColor",2);T&&(a.innerHTML="",a.appendChild(T))},ld=()=>{We.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{let x=f.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;hm(f,x&&x===id?ad:"idle")})};We.addEventListener("click",a=>{let m=a.target.closest(".persona-message-action-btn[data-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let x=m.closest("[data-actions-for]");if(!x)return;let T=x.getAttribute("data-actions-for");if(!T)return;let R=m.getAttribute("data-action");if(R==="copy"){let q=V.getMessages().find(Z=>Z.id===T);if(q&&Ge.onCopy){let Z=q.content||"";navigator.clipboard.writeText(Z).then(()=>{m.classList.add("persona-message-action-success");let re=ae("check",14,"currentColor",2);re&&(m.innerHTML="",m.appendChild(re)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let me=ae("copy",14,"currentColor",2);me&&(m.innerHTML="",m.appendChild(me))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),Ge.onCopy(q)}}else if(R==="read-aloud")V.toggleReadAloud(T);else if(R==="upvote"||R==="downvote"){let q=(Qa.get(T)??null)===R,Z=R==="upvote"?"thumbs-up":"thumbs-down";if(q){Qa.delete(T),m.classList.remove("persona-message-action-active");let re=ae(Z,14,"currentColor",2);re&&(m.innerHTML="",m.appendChild(re))}else{let re=R==="upvote"?"downvote":"upvote",me=x.querySelector(`[data-action="${re}"]`);if(me){me.classList.remove("persona-message-action-active");let tt=ae(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);tt&&(me.innerHTML="",me.appendChild(tt))}Qa.set(T,R),m.classList.add("persona-message-action-active");let ce=ae(Z,14,"currentColor",2);ce&&(ce.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(ce)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let je=V.getMessages().find(dt=>dt.id===T);je&&Ge.onFeedback&&Ge.onFeedback({type:R,messageId:je.id,message:je})}}}),We.addEventListener("click",a=>{let m=a.target.closest("button[data-approval-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let x=m.closest(".persona-approval-bubble");if(!x)return;let T=x.getAttribute("data-message-id");if(!T)return;let R=m.getAttribute("data-approval-action");if(!R)return;let ne=R==="approve"?"approved":"denied",Z=V.getMessages().find(me=>me.id===T);if(!Z?.approval)return;let re=x.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(ce=>{ce.disabled=!0,ce.style.opacity="0.5",ce.style.cursor="not-allowed"}),Z.approval.toolType==="webmcp"?V.resolveWebMcpApproval(T,ne):V.resolveApproval(Z.approval,ne)});let Qe=null,Or=null,Fr=()=>{},_r="none",Ys=null,Cn={artifacts:[],selectedId:null},Dn=!1,wn=!1,$r=!1,Xo=!1,cd=()=>Xo||Cn.artifacts.some(a=>uo(o.features?.artifacts,a)==="panel"),Zs=()=>Cn.artifacts.length>0&&!Dn&&cd(),at={current:null},Xa=(a,f)=>{let m=V.getArtifactById(f),x=m?.markdown,T=m?.title||"artifact",R=m?.file,ne=m?.artifactType??"markdown";if(!x){let re=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let ce=V.getMessages().find(Ae=>Ae.id===re);if(ce?.rawContent)try{let Ae=JSON.parse(ce.rawContent);x=Ae?.props?.markdown,T=Ae?.props?.title||T,Ae?.props?.file&&typeof Ae.props.file=="object"&&(R=Ae.props.file),!m&&typeof Ae?.props?.artifactType=="string"&&(ne=Ae.props.artifactType)}catch{}}}return{markdown:x,title:T,file:R,artifactType:ne}};We.addEventListener("click",a=>{let m=a.target.closest("[data-download-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let x=m.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:R,title:ne,file:q}=Xa(m,x);if(!R)return;let{filename:Z,mime:re,content:me}=Cg({title:ne,markdown:R,file:q}),ce=new Blob([me],{type:re}),Ae=URL.createObjectURL(ce),je=document.createElement("a");je.href=Ae,je.download=Z,je.click(),URL.revokeObjectURL(Ae)}),We.addEventListener("click",a=>{let m=a.target.closest("[data-artifact-custom-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let x=m.getAttribute("data-artifact-custom-action");if(!x)return;let T=m.closest("[data-artifact-inline]"),R=T?null:m.closest("[data-open-artifact]"),ne=T?T.getAttribute("data-artifact-inline"):R?.getAttribute("data-open-artifact")??null,Z=(T?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(dt=>dt.id===x);if(!Z)return;let{markdown:re,title:me,file:ce,artifactType:Ae}=Xa(m,ne??""),je={artifactId:ne,title:me,artifactType:Ae,markdown:re,file:ce};try{Promise.resolve(Z.onClick(je)).catch(()=>{})}catch{}}),We.addEventListener("click",a=>{let m=a.target.closest("[data-copy-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let x=m.getAttribute("data-copy-artifact");if(!x)return;let T=V.getArtifactById(x),R="";if(T)R=Hs(T);else{let{markdown:ne,file:q,artifactType:Z}=Xa(m,x);Z==="markdown"&&(R=Hs({id:x,artifactType:"markdown",status:"complete",markdown:ne??"",...q?{file:q}:{}}))}R&&navigator.clipboard.writeText(R).then(()=>{let ne=ae("check",16,"currentColor",2);ne&&(m.replaceChildren(ne),setTimeout(()=>{let q=ae("copy",16,"currentColor",2);q&&m.replaceChildren(q)},1500))}).catch(()=>{})}),We.addEventListener("click",a=>{let m=a.target.closest("[data-expand-artifact-inline]");if(!m)return;a.preventDefault(),a.stopPropagation();let x=m.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Dn=!1,Xo=!0,wn=!0,$r=!0,V.selectArtifact(x),Nn())}),We.addEventListener("click",a=>{let f=a.target;if(f.closest("[data-download-artifact]")||f.closest("[data-artifact-custom-action]"))return;let m=f.closest("[data-open-artifact]");if(!m)return;let x=m.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(a.preventDefault(),a.stopPropagation(),Dn=!1,Xo=!0,V.selectArtifact(x),Nn())}),We.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let f=a.target;!f.hasAttribute("data-open-artifact")&&!f.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),f.click())});let Jo=He.composerOverlay,Yo=(a,f,m)=>{let x=f.trim();if(!x||!at.current)return;let T=a.getAttribute("data-tool-call-id")??"",R=m.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:x,answers:m.structured,values:m.values??(m.source==="multi"?x.split(", "):[x]),isFreeText:R,source:m.source},bubbles:!0,composed:!0})),fr(Jo,T);let ne=at.current.getMessages().find(q=>q.toolCall?.id===T);ne?.agentMetadata?.awaitingLocalTool?at.current.resolveAskUserQuestion(ne,m.structured??x):at.current.sendMessage(x)},Mo=a=>{let f=at.current;if(!f)return;let m=a.getAttribute("data-tool-call-id")??"",x=f.getMessages().find(T=>T.toolCall?.id===m);x&&f.persistAskUserQuestionProgress(x,{answers:Wi(a,x),currentIndex:vn(a)})},dd=a=>Object.entries(a).map(([f,m])=>`${f}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),Ja=a=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=vn(a),m=gr(a);if(f>=m-1)return;let x=at.current?.getMessages().find(T=>T.toolCall?.id===a.getAttribute("data-tool-call-id"));x&&(Bi(a,x,o,f+1),Mo(a))};Jo.addEventListener("click",a=>{let m=a.target.closest("[data-ask-user-action]");if(!m)return;let x=m.closest("[data-persona-ask-sheet-for]");if(!x)return;let T=m.getAttribute("data-ask-user-action");if(a.preventDefault(),a.stopPropagation(),T==="dismiss"){let R=x.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),fr(Jo,R);let ne=at.current?.getMessages().find(q=>q.toolCall?.id===R);ne?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(ne),at.current?.resolveAskUserQuestion(ne,"(dismissed)"));return}if(T==="pick"){let R=m.getAttribute("data-option-label");if(!R)return;let ne=x.getAttribute("data-multi-select")==="true",q=fo(x);if(q&&ne){let Z=Fo(x)[vn(x)],re=new Set(Array.isArray(Z)?Z:[]);re.has(R)?re.delete(R):re.add(R),mo(x,Array.from(re)),Mo(x);return}if(q){mo(x,R),Mo(x),Ja(x);return}if(ne){let Z=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",Z?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!Z);let re=x.querySelector('[data-ask-user-action="submit-multi"]');re&&(re.disabled=Il(x).length===0);return}Yo(x,R,{source:"pick",values:[R]});return}if(T==="submit-multi"){let R=Il(x);if(R.length===0)return;Yo(x,R.join(", "),{source:"multi",values:R});return}if(T==="open-free-text"){let R=x.querySelector('[data-ask-free-text-row="true"]');R&&(R.classList.remove("persona-hidden"),R.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(T==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(T==="submit-free-text"){let ne=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!ne.trim())return;if(fo(x)){mo(x,ne.trim()),Mo(x),Ja(x);return}Yo(x,ne,{source:"free-text"});return}if(T==="next"||T==="back"){if(!at.current)return;let R=x.getAttribute("data-tool-call-id")??"",ne=at.current.getMessages().find(ce=>ce.toolCall?.id===R);if(!ne)return;let Z=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(Z){let ce=Fo(x)[vn(x)];(typeof ce!="string"||ce!==Z)&&mo(x,Z)}let re=T==="next"?1:-1,me=vn(x)+re;Bi(x,ne,o,me),Mo(x);return}if(T==="submit-all"){if(!at.current)return;let R=x.getAttribute("data-tool-call-id")??"",ne=at.current.getMessages().find(ce=>ce.toolCall?.id===R);if(!ne)return;let Z=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";Z&&mo(x,Z);let re=Wi(x,ne);at.current.persistAskUserQuestionProgress(ne,{answers:re,currentIndex:vn(x)});let me=dd(re);Yo(x,me||"(submitted)",{source:"submit-all",structured:re});return}if(T==="skip"){if(!at.current)return;let R=x.getAttribute("data-tool-call-id")??"",ne=at.current.getMessages().find(Ae=>Ae.toolCall?.id===R);if(!ne)return;let q=fo(x),Z=vn(x),re=gr(x),me=Z>=re-1;if(!q){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:R},bubbles:!0,composed:!0})),fr(Jo,R),ne.agentMetadata?.awaitingLocalTool&&(at.current.markAskUserQuestionResolved(ne),at.current.resolveAskUserQuestion(ne,"(dismissed)"));return}mo(x,"");let ce=x.querySelector('[data-ask-free-text-input="true"]');if(ce&&(ce.value=""),me){let Ae=Wi(x,ne),je=dd(Ae);Yo(x,je||"(skipped)",{source:"submit-all",structured:Ae});return}Bi(x,ne,o,Z+1),Mo(x);return}}),Jo.addEventListener("keydown",a=>{if(a.key!=="Enter")return;let m=a.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let x=m.closest("[data-persona-ask-sheet-for]");if(!x)return;a.preventDefault();let T=m.value;if(T.trim()){if(fo(x)){mo(x,T.trim()),Mo(x),Ja(x);return}Yo(x,T,{source:"free-text"})}});let pd=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let f=a.target;if(f?.tagName==="INPUT"||f?.tagName==="TEXTAREA"||f?.isContentEditable)return;let m=Jo.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let x=Number(a.key),R=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];R&&(a.preventDefault(),R.click())};document.addEventListener("keydown",pd);let eo=null,vt=null,zr=null,ei=null,Ya=()=>{},ud=!1,ti="",ni="";function Za(){ei?.(),ei=null}let gd=()=>{if(!eo||!vt)return;let a=t.classList.contains("persona-artifact-welded-split"),f=t.ownerDocument.defaultView??window,m=f.innerWidth<=640;if(!a||t.classList.contains("persona-artifact-narrow-host")||m){vt.style.removeProperty("position"),vt.style.removeProperty("left"),vt.style.removeProperty("top"),vt.style.removeProperty("bottom"),vt.style.removeProperty("width"),vt.style.removeProperty("z-index");return}let x=eo.firstElementChild;if(!x||x===vt)return;let T=10;vt.style.position="absolute",vt.style.top="0",vt.style.bottom="0",vt.style.width=`${T}px`,vt.style.zIndex="5";let R=Hc(eo,f),ne=x.offsetWidth+R/2-T/2;vt.style.left=`${Math.max(0,ne)}px`},oi=()=>{},ym=()=>{let a=t.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!f||a.innerWidth>m?!1:E||_t(o)},ri=()=>!nn(o)||!Zs()||t.classList.contains("persona-artifact-narrow-host")||ym()||(t.ownerDocument.defaultView??window).innerWidth<Dx?"none":Ic(o)?"detached":"welded",Nn=()=>{if(!Qe||!nn(o))return;qs(t,o),Ks(t,o),oi();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,f=ye.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",f>0&&f<=a);let m=Zs();Qe.setVisible(m),Qe.update(Cn),Dn?(Qe.setMobileOpen(!1),Qe.element.classList.add("persona-hidden"),Qe.backdrop?.classList.add("persona-hidden"),wn=!1,$r=!1):Cn.artifacts.length>0&&cd()?(Qe.element.classList.remove("persona-hidden"),Qe.setMobileOpen(!0)):(Qe.setMobileOpen(!1),Qe.element.classList.add("persona-hidden"),Qe.backdrop?.classList.add("persona-hidden"),wn=!1,$r=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Qe.setExpandToggleVisible(x),Qe.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Qe.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Qe.setTabFade(o.features?.artifacts?.layout?.tabFade),Qe.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!$r&&(wn=!1),wn!==ud){let R=Qe.element;wn?(ti=R.style.width,ni=R.style.maxWidth,R.style.removeProperty("width"),R.style.removeProperty("max-width")):(ti&&(R.style.width=ti),ni&&(R.style.maxWidth=ni),ti="",ni=""),ud=wn}t.classList.toggle("persona-artifact-expanded",wn),Qe.setExpanded(wn);let T=ri();T!==_r&&(_r=T,Fr()),Ya()};if(nn(o)){ye.style.position="relative";let a=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(xe),Qe=Mf(o,{onSelect:m=>at.current?.selectArtifact(m),onDismiss:()=>{Dn=!0,Nn()},onToggleExpand:()=>{let m=!wn,x=Cn.selectedId??Cn.artifacts[Cn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:m})!==!0&&(wn=m,m||($r=!1),Nn())}}),Qe.element.classList.add("persona-hidden"),eo=f,f.appendChild(a),f.appendChild(Qe.element),Qe.backdrop&&ye.appendChild(Qe.backdrop),ye.appendChild(f),Ya=()=>{if(!eo||!Qe)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){zr?.(),zr=null,Za(),vt&&(vt.remove(),vt=null),Qe.element.style.removeProperty("width"),Qe.element.style.removeProperty("maxWidth");return}if(!vt){let x=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let T=t.ownerDocument,R=T.defaultView??window,ne=q=>{if(!Qe||q.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||R.innerWidth<=640)return;q.preventDefault(),Za();let Z=q.clientX,re=Qe.element.getBoundingClientRect().width,me=o.features?.artifacts?.layout,ce=je=>{let dt=eo.getBoundingClientRect().width,tt=t.classList.contains("persona-artifact-welded-split"),cn=Hc(eo,R),Et=tt?0:x.getBoundingClientRect().width||6,It=re-(je.clientX-Z),_=Hf(It,dt,cn,Et,me?.resizableMinWidth,me?.resizableMaxWidth);Qe.element.style.width=`${_}px`,Qe.element.style.maxWidth="none",gd()},Ae=()=>{T.removeEventListener("pointermove",ce),T.removeEventListener("pointerup",Ae),T.removeEventListener("pointercancel",Ae),ei=null;try{x.releasePointerCapture(q.pointerId)}catch{}};ei=Ae,T.addEventListener("pointermove",ce),T.addEventListener("pointerup",Ae),T.addEventListener("pointercancel",Ae);try{x.setPointerCapture(q.pointerId)}catch{}};x.addEventListener("pointerdown",ne),vt=x,eo.insertBefore(x,Qe.element),zr=()=>{x.removeEventListener("pointerdown",ne)}}if(vt){let x=Zs();vt.classList.toggle("persona-hidden",!x),gd()}},oi=()=>{if(!E||!Qe||(o.launcher?.sidebarMode??!1)||_t(o)&&xn(o).reveal==="emerge")return;let x=t.ownerDocument.defaultView??window,T=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640;if(T&&x.innerWidth<=R||!kf(o,E))return;let ne=o.launcher?.width??o.launcherWidth??Gn,q=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Zs()?(ye.style.width=q,ye.style.maxWidth=q):(ye.style.width=ne,ye.style.maxWidth=ne)},typeof ResizeObserver<"u"&&(Or=new ResizeObserver(()=>{Nn()}),Or.observe(ye))}else ye.appendChild(xe);P()&&Ye&&(He.peekBanner&&Ye.appendChild(He.peekBanner),Ye.appendChild(Se)),t.appendChild(De),Ye&&t.appendChild(Ye);let si=()=>{if(P()){ye.style.width="100%",ye.style.maxWidth="100%";let kt=o.launcher?.composerBar??{},rn=De.dataset.state==="expanded",wi=kt.expandedSize??"anchored";if(!(rn&&wi!=="fullscreen")){xe.style.background="",xe.style.border="",xe.style.borderRadius="",xe.style.overflow="",xe.style.boxShadow="";return}let as=o.theme?.components?.panel,Ai=wr(o),ir=($n,No)=>$n==null||$n===""?No:en(Ai,$n)??$n,Si="1px solid var(--persona-border)",xl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Do="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";xe.style.background="var(--persona-surface, #ffffff)",xe.style.border=ir(as?.border,Si),xe.style.borderRadius=ir(as?.borderRadius,Do),xe.style.boxShadow=ir(as?.shadow,xl),xe.style.overflow="hidden";return}let a=_t(o),f=o.launcher?.sidebarMode??!1,m=a||f||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,T=o.launcher?.detachedPanel===!0,R=o.theme?.components?.panel,ne=wr(o),q=(kt,rn)=>kt==null||kt===""?rn:en(ne,kt)??kt,Z=t.ownerDocument.defaultView??window,re=o.launcher?.mobileFullscreen??!0,me=o.launcher?.mobileBreakpoint??640,ce=Z.innerWidth<=me,Ae=re&&ce&&E,je=a&&re&&ce,dt=o.launcher?.position??"bottom-left",tt=dt==="bottom-left"||dt==="top-left",cn=o.launcher?.zIndex??Qt,Et="var(--persona-panel-border, 1px solid var(--persona-border))",It="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",_="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Pe=T&&!Ae&&!je;Pe?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let Oe=Pe?Et:f||Ae?"none":Et,Ee=Pe?It:Ae?"none":f?tt?"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))":x?"none":It;a&&!Ae&&!Pe&&(Ee="none",Oe="none");let St=Pe?_:f||Ae?"0":_,pt=q(R?.border,Oe),Ft=q(R?.shadow,Ee),ut=q(R?.borderRadius,St),on=ri(),Rt=on==="detached",Ie=on==="welded";t.classList.toggle("persona-artifact-detached-split",Rt),t.classList.toggle("persona-artifact-welded-split",Ie);let Fe="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",Ct=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&nn(o)&&Ic(o)&&x&&!a;t.classList.toggle("persona-artifact-chat-flush",Ct);let lt=Rt||Ct?"none":Ft,ft=Rt?Et:Ie?"none":pt,Xe=Rt?_:ut;Ct&&(ft="none",Xe="0");let Be=R?.borderRadius!=null&&R.borderRadius!=="",yt=Ct&&!Be?"0":ut,qt=ue.scrollTop;t.style.cssText="",De.style.cssText="",ye.style.cssText="",xe.style.cssText="",ue.style.cssText="",Se.style.cssText="",Ve&&(ue.style.display="none"),(m||x)&&(t.style.minWidth="0");let yn=()=>{if(qt<=0)return;(ue.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ue.scrollTop===qt)return;let rn=ue.scrollHeight-ue.clientHeight;rn<=0||(ue.scrollTop=Math.min(qt,rn))})};if(Ae){De.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),De.style.cssText=`
220
220
  position: fixed !important;
221
221
  inset: 0 !important;
222
222
  width: 100% !important;
@@ -226,9 +226,9 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
226
226
  padding: 0 !important;
227
227
  display: flex !important;
228
228
  flex-direction: column !important;
229
- z-index: ${an} !important;
229
+ z-index: ${cn} !important;
230
230
  background-color: var(--persona-surface, #ffffff) !important;
231
- `,me.style.cssText=`
231
+ `,ye.style.cssText=`
232
232
  position: relative !important;
233
233
  display: flex !important;
234
234
  flex-direction: column !important;
@@ -241,7 +241,7 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
241
241
  padding: 0 !important;
242
242
  box-shadow: none !important;
243
243
  border-radius: 0 !important;
244
- `,ve.style.cssText=`
244
+ `,xe.style.cssText=`
245
245
  display: flex !important;
246
246
  flex-direction: column !important;
247
247
  flex: 1 1 0% !important;
@@ -252,7 +252,7 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
252
252
  overflow: hidden !important;
253
253
  border-radius: 0 !important;
254
254
  border: none !important;
255
- `,ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.overflowY="auto",ne.style.flexShrink="0",B=!0,mn();return}let mi=o?.launcher?.width??o?.launcherWidth??Vn;if(!g&&!a)x&&h?(me.style.width="100%",me.style.maxWidth="100%"):(me.style.width=mi,me.style.maxWidth=mi);else if(a)if(bn(o).reveal==="emerge"&&!A){let nn=bn(o).width;me.style.width=nn,me.style.maxWidth=nn}else me.style.width="100%",me.style.maxWidth="100%";if(Xs(),me.style.boxShadow=pt,me.style.borderRadius=vt,Rt?me.style.border="none":Ie&&(me.style.border=gt),ve.style.border=ht,ve.style.borderRadius=et,ve.style.boxShadow=Rt&&!wt?_e:"",wt&&(ve.style.background="transparent",ce.style.background="transparent",ne.style.background="transparent",ne.style.borderTop="none"),Ie){let kt=o.features?.artifacts?.layout;Vs=kt?.unifiedSplitOuterRadius?.trim()||kt?.paneBorderRadius?.trim()||mt}else Vs=null;if(a&&!Se&&!Pe&&!Rt&&!Ie&&W?.border===void 0&&(ve.style.border="none",bn(o).side==="right"?ve.style.borderLeft="1px solid var(--persona-border)":ve.style.borderRight="1px solid var(--persona-border)"),a&&!Se&&Ie&&W?.border===void 0&&(bn(o).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),h&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",x&&(t.style.width="100%"),Ne.style.display="flex",Ne.style.flexDirection="column",Ne.style.flex="1 1 0%",Ne.style.minHeight="0",Ne.style.maxHeight="100%",Ne.style.height="100%",x&&(Ne.style.overflow="hidden"),me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.height="100%",Rt||(me.style.overflow="hidden"),ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.maxHeight="100%",ve.style.overflow="hidden",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.overflowY="auto",ne.style.flexShrink="0"),x&&(Pe||Rt||wt)&&!a&&(wt||(Ne.style.padding="var(--persona-panel-inset)"),Ne.style.background="var(--persona-panel-canvas-bg)"),Ne.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&&!x&&!a&&(Tn[ft]??Tn["bottom-right"]).split(" ").forEach(nn=>Ne.classList.add(nn)),g){let kt=o.launcher?.sidebarWidth??"420px";A?Ne.style.cssText=`
255
+ `,ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.overflowY="auto",Se.style.flexShrink="0",W=!0,yn();return}let Ci=o?.launcher?.width??o?.launcherWidth??Gn;if(!f&&!a)x&&m?(ye.style.width="100%",ye.style.maxWidth="100%"):(ye.style.width=Ci,ye.style.maxWidth=Ci);else if(a)if(xn(o).reveal==="emerge"&&!T){let rn=xn(o).width;ye.style.width=rn,ye.style.maxWidth=rn}else ye.style.width="100%",ye.style.maxWidth="100%";if(oi(),ye.style.boxShadow=lt,ye.style.borderRadius=yt,Rt?ye.style.border="none":Ie&&(ye.style.border=pt),xe.style.border=ft,xe.style.borderRadius=Xe,xe.style.boxShadow=Rt&&!Ct?Fe:"",Ct&&(xe.style.background="transparent",ue.style.background="transparent",Se.style.background="transparent",Se.style.borderTop="none"),Ie){let kt=o.features?.artifacts?.layout;Ys=kt?.unifiedSplitOuterRadius?.trim()||kt?.paneBorderRadius?.trim()||ut}else Ys=null;if(a&&!Ae&&!Pe&&!Rt&&!Ie&&R?.border===void 0&&(xe.style.border="none",xn(o).side==="right"?xe.style.borderLeft="1px solid var(--persona-border)":xe.style.borderRight="1px solid var(--persona-border)"),a&&!Ae&&Ie&&R?.border===void 0&&(xn(o).side==="right"?ye.style.borderLeft="1px solid var(--persona-border)":ye.style.borderRight="1px solid var(--persona-border)"),m&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",x&&(t.style.width="100%"),De.style.display="flex",De.style.flexDirection="column",De.style.flex="1 1 0%",De.style.minHeight="0",De.style.maxHeight="100%",De.style.height="100%",x&&(De.style.overflow="hidden"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",Rt||(ye.style.overflow="hidden"),xe.style.display="flex",xe.style.flexDirection="column",xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.maxHeight="100%",xe.style.overflow="hidden",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.overflowY="auto",Se.style.flexShrink="0"),x&&(Pe||Rt||Ct)&&!a&&(Ct||(De.style.padding="var(--persona-panel-inset)"),De.style.background="var(--persona-panel-canvas-bg)"),De.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!f&&!x&&!a&&(kn[dt]??kn["bottom-right"]).split(" ").forEach(rn=>De.classList.add(rn)),f){let kt=o.launcher?.sidebarWidth??"420px";T?De.style.cssText=`
256
256
  position: fixed !important;
257
257
  top: var(--persona-panel-inset) !important;
258
258
  bottom: var(--persona-panel-inset) !important;
@@ -263,9 +263,9 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
263
263
  padding: 0 !important;
264
264
  display: flex !important;
265
265
  flex-direction: column !important;
266
- z-index: ${an} !important;
267
- ${rt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
268
- `:Ne.style.cssText=`
266
+ z-index: ${cn} !important;
267
+ ${tt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
268
+ `:De.style.cssText=`
269
269
  position: fixed !important;
270
270
  top: 0 !important;
271
271
  bottom: 0 !important;
@@ -276,9 +276,9 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
276
276
  padding: 0 !important;
277
277
  display: flex !important;
278
278
  flex-direction: column !important;
279
- z-index: ${an} !important;
280
- ${rt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
281
- `,me.style.cssText=`
279
+ z-index: ${cn} !important;
280
+ ${tt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
281
+ `,ye.style.cssText=`
282
282
  position: relative !important;
283
283
  display: flex !important;
284
284
  flex-direction: column !important;
@@ -289,10 +289,10 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
289
289
  min-height: 0 !important;
290
290
  margin: 0 !important;
291
291
  padding: 0 !important;
292
- box-shadow: ${pt} !important;
293
- border-radius: ${vt} !important;
294
- ${Rt?"border: none !important;":Ie?`border: ${gt} !important;`:""}
295
- `,me.style.setProperty("width","100%","important"),me.style.setProperty("max-width","100%","important"),ve.style.cssText=`
292
+ box-shadow: ${lt} !important;
293
+ border-radius: ${yt} !important;
294
+ ${Rt?"border: none !important;":Ie?`border: ${pt} !important;`:""}
295
+ `,ye.style.setProperty("width","100%","important"),ye.style.setProperty("max-width","100%","important"),xe.style.cssText=`
296
296
  display: flex !important;
297
297
  flex-direction: column !important;
298
298
  flex: 1 1 0% !important;
@@ -301,16 +301,16 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
301
301
  min-height: 0 !important;
302
302
  max-height: 100% !important;
303
303
  overflow: hidden !important;
304
- border-radius: ${et} !important;
305
- border: ${ht} !important;
306
- ${Rt&&!wt?`box-shadow: ${_e} !important;`:""}
307
- ${wt?"background: transparent !important;":""}
308
- `,ne.style.cssText=`
304
+ border-radius: ${Xe} !important;
305
+ border: ${ft} !important;
306
+ ${Rt&&!Ct?`box-shadow: ${Fe} !important;`:""}
307
+ ${Ct?"background: transparent !important;":""}
308
+ `,Se.style.cssText=`
309
309
  flex-shrink: 0 !important;
310
310
  border-top: none !important;
311
311
  padding: 8px 16px 12px 16px !important;
312
- ${wt?"background: transparent !important;":""}
313
- `}if(!x&&!a){let kt="max-height: -moz-available !important; max-height: stretch !important;",nn=g?"":"padding-top: 1.25em !important;",hi=g?"":`z-index: ${o.launcher?.zIndex??Qt} !important;`;Ne.style.cssText+=kt+nn+hi}mn()};Ys(),ws(t,o),Os(t,o),Fs(t,o),Br=()=>{Ys(),ws(t,o),Os(t,o),Fs(t,o),Vs?t.style.setProperty("--persona-artifact-welded-outer-radius",Vs):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ve=[];Ve.push(()=>{document.removeEventListener("keydown",sd)}),Ve.push(()=>{Rr!==null&&clearTimeout(Rr)});let En=null,kn=null;Ve.push(()=>{En?.(),En=null,kn?.(),kn=null}),Hr&&Ve.push(()=>{Hr?.disconnect(),Hr=null}),Ve.push(()=>{Or?.(),Or=null,qa(),xt&&(xt.remove(),xt=null),Ze?.element.style.removeProperty("width"),Ze?.element.style.removeProperty("maxWidth")}),se&&Ve.push(()=>{Le!==null&&(cancelAnimationFrame(Le),Le=null),ze?.destroy(),ze=null,Ee?.destroy(),Ee=null,Ce=null});let Ao=null,ld=()=>{Ao&&(Ao(),Ao=null),o.colorScheme==="auto"&&(Ao=ia(()=>{ws(t,o)}))};ld(),Ve.push(()=>{Ao&&(Ao(),Ao=null)}),Ve.push(l);let Zs=o.features?.streamAnimation;if(Zs?.type&&Zs.type!=="none"){let a=Ar(Zs.type,Zs.plugins);a&&(Ca(a,t),Ve.push(()=>Df(t)))}let ei=tg(ct),So=null,q,Ka=a=>{if(!q)return;let g=a??q.getMessages(),h=o.features?.suggestReplies?.enabled!==!1?Hp(g):null;h?ei.render(h,q,ye,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(x=>x.role==="user")?ei.render([],q,ye,g):ei.render(o.suggestionChips,q,ye,g,o.suggestionChipsConfig)},Cn=!1,Mo=Tf(),Qo=new Map,To=new Map,Yn=new Map,Ga=0,Yg=_n()!==null,rn=ma(),pn=0,Zn=null,un=!1,ti=!1,eo=0,wn=null,Eo=null,Qa=!1,ni=!1,Fr=null,_r=!0,oi=!1,ri=null,si=!1,ko=()=>{si=!0},Xa=null,Zg=4,ii=24,em=80,Ja=new Map,Xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},cd=o.voiceRecognition?.autoResume??!1,Bn=a=>{p.emit("voice:state",{active:Xe.active,source:a,timestamp:Date.now()})},An=()=>{R(a=>({...a,voiceState:{active:Xe.active,timestamp:Date.now(),manuallyDeactivated:Xe.manuallyDeactivated}}))},tm=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=Nc(u.voiceState),g=!!a.active,h=Number(a.timestamp??0);Xe.manuallyDeactivated=!!a.manuallyDeactivated,g&&Date.now()-h<lx&&setTimeout(()=>{Xe.active||(Xe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?q.toggleVoice().then(()=>{Xe.active=q.isVoiceActive(),Bn("restore"),q.isVoiceActive()&&er()}):pi("restore"))},1e3)},nm=()=>q?Lg(q.getMessages()).filter(a=>!a.__skipPersist):[],ai=null,dd=(a,g)=>{typeof console<"u"&&console.error(a,g)},Ya=(a,g)=>{let h=()=>{try{let ee=a();return!ee||typeof ee.then!="function"?null:Promise.resolve(ee).catch(V=>{dd(g,V)})}catch(ee){return dd(g,ee),null}},x=ai,A=x?x.then(()=>h()??void 0):h();if(!A)return;let W=A.finally(()=>{ai===W&&(ai=null)});ai=W};function Za(a){if(!d?.save)return;let h={messages:a?Lg(a):q?nm():[],metadata:u,artifacts:vn.artifacts,selectedArtifactId:vn.selectedId};Ya(()=>d.save(h),"[AgentWidget] Failed to persist state:")}let Xo=null,pd=()=>Ne.querySelector("#persona-scroll-container")||ce,$r=()=>{Xo!==null&&(cancelAnimationFrame(Xo),Xo=null),un=!1},ud=()=>{Zn!==null&&(cancelAnimationFrame(Zn),Zn=null),ti=!1,$r()},om=()=>Cn&&tl()&&(dn()!=="anchor-top"||qc()),el=()=>{let a=vo()||"Jump to latest",g=om();Lt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),eo>0?(xo.textContent=String(eo),xo.style.display="",Lt.setAttribute("aria-label",`${a} (${eo} new)`)):(xo.textContent="",xo.style.display="none",Lt.setAttribute("aria-label",g?`${a} (response streaming below)`:a))},fd=()=>{eo!==0&&(eo=0,el())},tl=()=>Gn()?!rn.isFollowing():!yo(ce,ii),sn=()=>{if(!js()||Ke){Lt.parentNode&&Lt.remove(),Lt.style.display="none";return}Lt.parentNode!==ve&&ve.appendChild(Lt),Vo();let g=In(ce)>0&&tl();g?el():fd(),Lt.style.display=g?"":"none"},zr=()=>{rn.pause()&&(ud(),sn())},to=()=>{rn.resume(),fd(),sn()},no=(a=!1)=>{Gn()&&rn.isFollowing()&&(!a&&!Cn||(Zn!==null&&(cancelAnimationFrame(Zn),Zn=null),ti=!0,Zn=requestAnimationFrame(()=>{Zn=null,ti=!1,rn.isFollowing()&&rm(pd(),a?220:140)})))},gd=(a,g,h,x=()=>!0)=>{let A=a.scrollTop,W=g(),ee=W-A;if($r(),Math.abs(ee)<1){un=!0,a.scrollTop=W,pn=a.scrollTop,un=!1;return}let V=performance.now();un=!0;let Y=xe=>1-Math.pow(1-xe,3),de=xe=>{if(!x()){$r();return}let le=g();le!==W&&(W=le,ee=W-A);let Se=xe-V,qe=Math.min(Se/h,1),ft=Y(qe),rt=A+ee*ft;a.scrollTop=rt,pn=a.scrollTop,qe<1?Xo=requestAnimationFrame(de):(a.scrollTop=W,pn=a.scrollTop,Xo=null,un=!1)};Xo=requestAnimationFrame(de)},rm=(a,g=500)=>{let h=In(a)-a.scrollTop;if(Math.abs(h)<1){pn=a.scrollTop;return}if(Math.abs(h)>=em){$r(),un=!0,a.scrollTop=In(a),pn=a.scrollTop,un=!1;return}gd(a,()=>In(a),g,()=>rn.isFollowing())},md=()=>{let a=pd();un=!0,a.scrollTop=In(a),pn=a.scrollTop,un=!1,sn()},hd=a=>{let g=0,h=a;for(;h&&h!==ce;)g+=h.offsetTop,h=h.offsetParent;return g},sm=()=>{let a=ce.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??ce.ownerDocument.getSelection()},li=()=>If(sm(),ce),yd=()=>{if(Vg()!=="last-user-turn")return!1;let a=q?.getMessages()??[];if(a.length<2)return!1;let g=[...a].reverse().find(W=>W.role==="user");if(!g)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=ce.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let A=Math.min(Math.max(0,hd(x)-Uc()),In(ce));return un=!0,ce.scrollTop=A,pn=ce.scrollTop,un=!1,dn()==="follow"&&!yo(ce,ii)&&rn.pause(),sn(),!0},bd=a=>{Qn.style.height=`${Math.max(0,Math.round(a))}px`,wn&&(wn.spacerHeight=Math.max(0,a))},jr=()=>{Eo!==null&&(cancelAnimationFrame(Eo),Eo=null),$r(),wn=null,Qn.style.height="0px"},vd=a=>{Eo!==null&&cancelAnimationFrame(Eo),Eo=requestAnimationFrame(()=>{Eo=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=ce.querySelector(`[data-message-id="${g}"]`);if(!h)return;let x=hd(h),A=wn?.spacerHeight??0,W=ce.scrollHeight-A,{targetScrollTop:ee,spacerHeight:V}=Rf({anchorOffsetTop:x,topOffset:Uc(),viewportHeight:ce.clientHeight,contentHeight:W});wn={initialSpacerHeight:V,contentHeightAtAnchor:W,spacerHeight:V},bd(V),gd(ce,()=>ee,220)})},im=()=>{if(Gn()){if(!rn.isFollowing()||yo(ce,1))return;no(!Cn);return}if(wn&&wn.initialSpacerHeight>0){let a=ce.scrollHeight-wn.spacerHeight,g=Wf({initialSpacerHeight:wn.initialSpacerHeight,contentHeightAtAnchor:wn.contentHeightAtAnchor,currentContentHeight:a});g!==wn.spacerHeight&&bd(g)}sn()},am=a=>{let g=dn();g==="follow"?(to(),no(!0)):g==="anchor-top"&&(_r=!1,oi=!0,si=!1,ri=a,vd(a))},lm=()=>{if(dn()==="anchor-top"){if(oi){_r=!1;return}_r=!0,jr(),to(),no(!0)}},cm=a=>{if(dn()!=="anchor-top"||!oi||si||li())return;let g=Fr===null;for(let h of a){if(!g){h.id===Fr&&(g=!0);continue}if(Pf(h)){if(h.id===ri)return;ri=h.id,vd(h.id);return}}},dm=a=>{let g=new Map;a.forEach(h=>{let x=Ja.get(h.id);g.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(p.emit("assistant:message",h),!ni&&(dn()!=="anchor-top"||qc())&&tl()&&(eo+=1,el(),sn(),Gc(eo===1?"1 new message below.":`${eo} new messages below.`))),h.role==="assistant"&&x?.streaming&&h.streaming===!1&&p.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&p.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):p.emit("approval:requested",{approval:h.approval,message:h}))}),Ja.clear(),g.forEach((h,x)=>{Ja.set(x,h)})},ci=(a,g)=>{let h=g==="user"?"user":"assistant",x=o.layout?.messages?.[h],A=x?.width??"content",W=x?.maxWidth??(A==="full"?"100%":"85%");a.classList.add("persona-message-row"),a.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),a.classList.add(`persona-message-row-${g}`,`persona-message-width-${A}`),a.classList.toggle("persona-justify-end",g==="user"),a.setAttribute("data-message-role",g),a.setAttribute("data-message-width",A),a.style.setProperty("--persona-message-row-max-width",W)},Lo=(a,g)=>{let h=document.createElement("div");return h.className="persona-flex",h.id=`wrapper-${a}`,h.setAttribute("data-wrapper-id",a),ci(h,g),h},pm=(a,g,h)=>{let x=document.createElement("div"),W=(()=>{let _=s.find(Pe=>Pe.renderLoadingIndicator);if(_?.renderLoadingIndicator)return _.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),ee=(_,Pe)=>Pe==null?!1:typeof Pe=="string"?(_.textContent=Pe,!0):(_.appendChild(Pe),!0),V=new Set,Y=new Map,de=new Set,xe=s.some(_=>_.renderAskUserQuestion),le=[],Se=[],qe=o.enableComponentStreaming!==!1,ft=o.approval!==!1,rt=[];if(g.forEach(_=>{V.add(_.id),Y.set(_.id,_.role);let Pe=xe&&Ho(_),Fe=ft&&_.variant==="approval"&&!!_.approval,Te=!Pe&&_.role==="assistant"&&!_.variant&&qe&&Dc(_);!Fe&&Yn.has(_.id)&&(a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Yn.delete(_.id)),!Te&&To.has(_.id)&&(a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),To.delete(_.id));let At=Ho(_)?`:${_.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${_.agentMetadata?.askUserQuestionAnswers?Object.keys(_.agentMetadata.askUserQuestionAnswers).length:0}`:"",gt=Mf(_,Ga)+At,Ft=Pe||Fe||Te?null:Ef(Mo,_.id,gt);if(Ft){x.appendChild(Ft.cloneNode(!0)),Ho(_)&&_.toolCall?.id&&_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(de.add(_.toolCall.id),ki(_,o,He.composerOverlay));return}let mt=null,tn=s.find(_e=>!!(_.variant==="reasoning"&&_e.renderReasoning||_.variant==="tool"&&_e.renderToolCall||!_.variant&&_e.renderMessage)),Rt=o.layout?.messages;if(Ho(_)&&_.agentMetadata?.askUserQuestionAnswered===!0){Qo.delete(_.id),a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime");return}if(El(_)&&o.features?.suggestReplies?.enabled!==!1)return;if(Ho(_)&&o.features?.askUserQuestion?.enabled!==!1){let _e=s.find(Ut=>typeof Ut.renderAskUserQuestion=="function");if(_e&&dt.current){let Ut=Qo.get(_.id),Vt=Ut!==gt,wt=null;if(Vt){let{payload:et,complete:De}=lr(_),vt=_.id,qt=()=>dt.current?.getMessages().find(mn=>mn.id===vt);wt=_e.renderAskUserQuestion({message:_,payload:et,complete:De,resolve:mn=>{let Zr=qt();Zr&&dt.current?.resolveAskUserQuestion(Zr,mn)},dismiss:()=>{let mn=qt();mn?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(mn),dt.current?.resolveAskUserQuestion(mn,"(dismissed)"))},config:o})}let pt=Ut!=null;if(Vt&&wt===null&&!pt){_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(de.add(_.toolCall.id),ki(_,o,He.composerOverlay));return}let ht=Lo(_.id,_.role);ht.setAttribute("data-ask-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),x.appendChild(ht),le.push({messageId:_.id,fingerprint:gt,bubble:wt});return}else{_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(de.add(_.toolCall.id),ki(_,o,He.composerOverlay));return}}else if(Fe){let _e=s.find(pt=>typeof pt.renderApproval=="function")??i,Vt=Yn.get(_.id)!==gt,wt=null;if(Vt&&_e?.renderApproval){let pt=_.id,ht=(et,De)=>{let vt=dt.current?.getMessages().find(qt=>qt.id===pt);vt?.approval&&(vt.approval.toolType==="webmcp"?dt.current?.resolveWebMcpApproval(vt.id,et):dt.current?.resolveApproval(vt.approval,et,De))};wt=_e.renderApproval({message:_,defaultRenderer:()=>Wa(_,o),config:o,approve:et=>ht("approved",et),deny:et=>ht("denied",et)})}if(Vt&&wt===null)a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Yn.delete(_.id),mt=Wa(_,o);else{let pt=Lo(_.id,_.role);pt.setAttribute("data-approval-plugin-stub","true"),pt.setAttribute("data-preserve-runtime","true"),x.appendChild(pt),rt.push({messageId:_.id,fingerprint:gt,bubble:wt});return}}else if(tn)if(_.variant==="reasoning"&&_.reasoning&&tn.renderReasoning){if(!oe)return;mt=tn.renderReasoning({message:_,defaultRenderer:()=>bc(_,o),config:o})}else if(_.variant==="tool"&&_.toolCall&&tn.renderToolCall){if(!Q)return;mt=tn.renderToolCall({message:_,defaultRenderer:()=>xc(_,o),config:o})}else tn.renderMessage&&(mt=tn.renderMessage({message:_,defaultRenderer:()=>{let _e=yc(_,h,Rt,o.messageActions,Je,{loadingIndicatorRenderer:W,widgetConfig:o});return _.role!=="user"&&Lc(_e,_,o,q),_e},config:o}));if(!mt&&Te){let _e=Tg(_);if(_e){let Ut=To.get(_.id),Vt=Ut!==gt,wt=o.wrapComponentDirectiveInBubble!==!1&&qn.getOptions(_e.component)?.bubbleChrome!==!1,pt=null;if(Vt){let ht=Sg(_e,{config:o,message:_,transform:h});if(ht&&_e.component==="PersonaArtifactInline"){let et=ht.hasAttribute("data-artifact-inline")?ht:ht.querySelector("[data-artifact-inline]"),De=et?.getAttribute("data-artifact-inline")??"",vt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(De):De,qt=De?a.querySelector(`#wrapper-${_.id}`)?.querySelector(`[data-artifact-inline="${vt}"]`)??null:null;et&&qt&&qt!==et&&vf(qt)&&(et===ht?ht=qt:et.replaceWith(qt))}if(ht)if(wt){let et=document.createElement("div");if(et.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),et.id=`bubble-${_.id}`,et.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let De=document.createElement("div");De.className="persona-mb-3 persona-text-sm persona-leading-relaxed",De.innerHTML=h({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),et.appendChild(De)}et.appendChild(ht),pt=et}else{let et=document.createElement("div");if(et.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",et.id=`bubble-${_.id}`,et.setAttribute("data-message-id",_.id),et.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let De=document.createElement("div");De.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",De.innerHTML=h({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),et.appendChild(De)}et.appendChild(ht),pt=et}}if(pt||Ut!=null){let ht=Lo(_.id,_.role);ht.setAttribute("data-component-directive-stub","true"),ht.setAttribute("data-preserve-runtime","true"),x.appendChild(ht),Se.push({messageId:_.id,fingerprint:gt,bubble:pt});return}}}if(!mt)if(_.variant==="reasoning"&&_.reasoning){if(!oe)return;mt=bc(_,o)}else if(_.variant==="tool"&&_.toolCall){if(!Q)return;mt=xc(_,o)}else if(_.variant==="approval"&&_.approval){if(o.approval===!1)return;mt=Wa(_,o)}else{let _e=o.layout?.messages;_e?.renderUserMessage&&_.role==="user"?mt=_e.renderUserMessage({message:_,config:o,streaming:!!_.streaming}):_e?.renderAssistantMessage&&_.role==="assistant"?mt=_e.renderAssistantMessage({message:_,config:o,streaming:!!_.streaming}):mt=yc(_,h,_e,o.messageActions,Je,{loadingIndicatorRenderer:W,widgetConfig:o}),_.role!=="user"&&mt&&Lc(mt,_,o,q)}let Ie=Lo(_.id,_.role);Ie.appendChild(mt),kf(Mo,_.id,gt,Ie),x.appendChild(Ie)}),He.composerOverlay&&He.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Pe=>{let Fe=Pe.getAttribute("data-persona-ask-sheet-for");Fe&&!de.has(Fe)&&dr(He.composerOverlay,Fe)}),o.features?.toolCallDisplay?.grouped){let _=[],Pe=[],Fe=o.features.toolCallDisplay.groupedMode==="summary";g.forEach(Te=>{if(Te.variant==="tool"&&Te.toolCall&&Q){Pe.push(Te);return}Te.variant==="reasoning"&&!oe||((Pe.length>1||Fe&&Pe.length>0)&&_.push(Pe),Pe=[])}),(Pe.length>1||Fe&&Pe.length>0)&&_.push(Pe),_.forEach(Te=>{let At=Te.map(_e=>Array.from(x.children).find(Ut=>Ut instanceof HTMLElement&&Ut.getAttribute("data-wrapper-id")===_e.id)).filter(_e=>!!_e);if(At.length<(Fe?1:2))return;let gt=Lo(`tool-group-${Te[0].id}`,"assistant");gt.setAttribute("data-persona-tool-group-row","true");let Ft=document.createElement("div");Ft.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ft.setAttribute("data-persona-tool-group","true");let mt=document.createElement("div");mt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",mt.id=`tool-group-summary-${Te[0].id}`;let tn=`Called ${Te.length} ${Te.length===1?"tool":"tools"}`,Rt=o.toolCall?.renderGroupedSummary?.({messages:Te,toolCalls:Te.map(_e=>_e.toolCall).filter(_e=>!!_e),defaultSummary:tn,config:o});ee(mt,Rt)||(mt.textContent=tn);let Ie=document.createElement("div");Ie.className="persona-tool-group-stack persona-flex persona-flex-col",Ie.id=`tool-group-stack-${Te[0].id}`,Ie.setAttribute("data-persona-tool-group-stack","true"),Ft.appendChild(mt),Fe||Ft.appendChild(Ie),gt.appendChild(Ft),At[0].before(gt),At.forEach((_e,Ut)=>{if(Fe){_e.remove();return}_e.style.setProperty("--persona-message-row-max-width","100%");let Vt=document.createElement("div");Vt.className="persona-tool-group-item persona-relative",Vt.setAttribute("data-persona-tool-group-item","true"),Ut<At.length-1&&Vt.setAttribute("data-persona-tool-group-connector","true"),Vt.appendChild(_e),Ie.appendChild(Vt)})})}Lf(Mo,V);let an=g.some(_=>_.role==="assistant"&&_.streaming),Et=g[g.length-1],It=Et?.role==="assistant"&&!Et.streaming&&Et.variant!=="approval";if(Cn&&g.some(_=>_.role==="user")&&!an&&!It){let _={config:o,streaming:!0,location:"standalone",defaultRenderer:Hs},Pe=s.find(Te=>Te.renderLoadingIndicator),Fe=null;if(Pe?.renderLoadingIndicator&&(Fe=Pe.renderLoadingIndicator(_)),Fe===null&&o.loadingIndicator?.render&&(Fe=o.loadingIndicator.render(_)),Fe===null&&(Fe=Hs()),Fe){let Te=document.createElement("div"),At=o.loadingIndicator?.showBubble!==!1,gt=o.layout?.messages?.layout??"bubble";Te.className=At?hc("assistant",gt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Te.setAttribute("data-typing-indicator","true"),At&&(Te.style.color="var(--persona-message-assistant-text, var(--persona-text))",gt!=="flat"&&(Te.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Te.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Te.appendChild(Fe);let Ft=Lo("typing-indicator","assistant");Ft.appendChild(Te),x.appendChild(Ft)}}if(!Cn&&g.length>0){let _=g[g.length-1],Pe={config:o,lastMessage:_,messageCount:g.length},Fe=s.find(At=>At.renderIdleIndicator),Te=null;if(Fe?.renderIdleIndicator&&(Te=Fe.renderIdleIndicator(Pe)),Te===null&&o.loadingIndicator?.renderIdle&&(Te=o.loadingIndicator.renderIdle(Pe)),Te){let At=document.createElement("div"),gt=o.loadingIndicator?.showBubble!==!1;At.className=gt?["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-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),At.setAttribute("data-idle-indicator","true"),At.appendChild(Te);let Ft=Lo("idle-indicator","assistant");Ft.appendChild(At),x.appendChild(Ft)}}if(fp(x),ga(a,x),yl(a),le.length>0)for(let{messageId:_,fingerprint:Pe,bubble:Fe}of le){let Te=a.querySelector(`#wrapper-${_}`);Te&&(ci(Te,Y.get(_)??"assistant"),Fe!==null&&(Te.replaceChildren(Fe),Te.setAttribute("data-bubble-fp",Pe),Qo.set(_,Pe)))}if(Qo.size>0)for(let _ of Qo.keys())V.has(_)||Qo.delete(_);if(Se.length>0)for(let{messageId:_,fingerprint:Pe,bubble:Fe}of Se){let Te=a.querySelector(`#wrapper-${_}`);Te&&(ci(Te,Y.get(_)??"assistant"),Fe!==null&&(Te.replaceChildren(Fe),Te.setAttribute("data-bubble-fp",Pe),To.set(_,Pe)))}if(To.size>0)for(let _ of To.keys())V.has(_)||To.delete(_);if(rt.length>0)for(let{messageId:_,fingerprint:Pe,bubble:Fe}of rt){let Te=a.querySelector(`#wrapper-${_}`);Te&&(ci(Te,Y.get(_)??"assistant"),Fe!==null&&(Te.replaceChildren(Fe),Te.setAttribute("data-bubble-fp",Pe),Yn.set(_,Pe)))}if(Yn.size>0)for(let _ of Yn.keys())V.has(_)||Yn.delete(_)},Ur=(a,g,h)=>{pm(a,g,h),nd()},Vr=null,um=()=>{if(Vr)return;let a=h=>{let x=h.composedPath();x.includes(Ne)||nt&&x.includes(nt)||ut(!1,"user")};Vr=a,(t.ownerDocument??document).addEventListener("pointerdown",a,!0)},xd=()=>{if(!Vr)return;(t.ownerDocument??document).removeEventListener("pointerdown",Vr,!0),Vr=null};Ve.push(()=>xd());let qr=null,fm=()=>{if(qr)return;let a=h=>{h.key==="Escape"&&(h.isComposing||ut(!1,"user"))};qr=a,(t.ownerDocument??document).addEventListener("keydown",a,!0)},Cd=()=>{if(!qr)return;(t.ownerDocument??document).removeEventListener("keydown",qr,!0),qr=null};Ve.push(()=>Cd());let Kr=!1,wd=new Set,gm=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},Jo=()=>{if(!P())return;let a=He.peekBanner,g=He.peekTextNode;if(!a||!g)return;if(j){a.classList.remove("persona-pill-peek--visible");return}let h=q?.getMessages()??[],x;for(let Et=h.length-1;Et>=0;Et--){let It=h[Et];if(It.role==="assistant"&&It.content){x=It;break}}if(!x){a.classList.remove("persona-pill-peek--visible");return}let A=x.content,W=!!x.streaming,ee=gm(),V=ba(ee),Y=V.type!=="none"?Ar(V.type,ee?.plugins):null,de=Y?.isAnimating?.(x)===!0,xe=Y!==null&&(W||de);xe&&Y&&!wd.has(Y.name)&&(Ca(Y,t),wd.add(Y.name));let le=xe&&Y?.containerClass?Y.containerClass:null,Se=g.dataset.personaPeekStreamClass??null;Se&&Se!==le&&(g.classList.remove(Se),delete g.dataset.personaPeekStreamClass),le&&Se!==le&&(g.classList.add(le),g.dataset.personaPeekStreamClass=le),xe?(g.style.setProperty("--persona-stream-step",`${V.speed}ms`),g.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let qe=xe?va(A,V.buffer,Y,x,W):A;if(xe&&V.placeholder==="skeleton"&&W&&(!qe||!qe.trim())){let Et=document.createElement("div"),It=Ls();It.classList.add("persona-pill-peek__skeleton"),Et.appendChild(It),ga(g,Et)}else{let Et=Math.max(0,qe.length-100),It=qe.length>100?qe.slice(-100):qe,_=ao(It);if(!xe||!Y){let Pe=qe.length>100?`\u2026${It}`:It;g.textContent!==Pe&&(g.textContent=Pe)}else{let Pe=_;(Y.wrap==="char"||Y.wrap==="word")&&(Pe=ks(_,Y.wrap,`peek-${x.id}`,{skipTags:Y.skipTags,startIndex:Et}));let Fe=document.createElement("div");if(Fe.innerHTML=Pe,Y.useCaret&&It.length>0){let Te=xa(),At=Fe.querySelectorAll(".persona-stream-char, .persona-stream-word"),gt=At[At.length-1];gt?.parentNode?gt.parentNode.insertBefore(Te,gt.nextSibling):Fe.appendChild(Te)}ga(g,Fe),Y.onAfterRender?.({container:g,bubble:a,messageId:x.id,message:x,speed:V.speed,duration:V.duration})}}let an=Cn||Kr;a.classList.toggle("persona-pill-peek--visible",an)};if(P()){let a=He.peekBanner;if(a){let x=A=>{A.preventDefault(),A.stopPropagation(),ut(!0,"user")};a.addEventListener("pointerdown",x),Ve.push(()=>{a.removeEventListener("pointerdown",x)})}let g=()=>{Kr||(Kr=!0,Jo())},h=()=>{Kr&&(Kr=!1,Jo())};me.addEventListener("pointerenter",g),me.addEventListener("pointerleave",h),Ve.push(()=>{me.removeEventListener("pointerenter",g),me.removeEventListener("pointerleave",h)}),nt&&(nt.addEventListener("pointerenter",g),nt.addEventListener("pointerleave",h),Ve.push(()=>{nt.removeEventListener("pointerenter",g),nt.removeEventListener("pointerleave",h)}))}let mm=a=>{let g=o.launcher?.composerBar??{},h=g.expandedSize??"anchored",x=g.bottomOffset??"16px",A=g.collapsedMaxWidth,W=g.expandedMaxWidth??"880px",ee=g.expandedTopOffset??"5vh",V=g.modalMaxWidth??"880px",Y=g.modalMaxHeight??"min(90vh, 800px)",de="calc(100vw - 32px)",xe="var(--persona-pill-area-height, 80px)",le=Ne.style;if(le.left="",le.right="",le.top="",le.bottom="",le.transform="",le.width="",le.maxWidth="",le.height="",le.maxHeight="",nt){let Se=nt.style;Se.bottom=x,Se.width=A??""}if(a&&h!=="fullscreen"){if(h==="modal"){le.top="50%",le.left="50%",le.transform="translate(-50%, -50%)",le.bottom="auto",le.right="auto",le.width=V,le.maxWidth=de,le.maxHeight=Y,le.height=Y;return}le.left="50%",le.transform="translateX(-50%)",le.bottom=`calc(${x} + ${xe})`,le.top=ee,le.width=W,le.maxWidth=de}},Gr=()=>{if(!I())return;if(P()){let de=(o.launcher?.composerBar??{}).expandedSize??"anchored",xe=j?"expanded":"collapsed";Ne.dataset.state=xe,Ne.dataset.expandedSize=de,nt&&(nt.dataset.state=xe,nt.dataset.expandedSize=de),Ne.style.removeProperty("display"),Ne.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),mm(j),ve.style.display=j?"flex":"none",Ys(),j?(um(),fm()):(xd(),Cd()),Jo();return}let a=_t(o),g=t.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,A=g.innerWidth<=h,W=x&&A&&k,ee=bn(o).reveal;j?(Ne.style.removeProperty("display"),Ne.style.display=a?"flex":"",Ne.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0"),me.classList.add("persona-scale-100","persona-opacity-100"),$t?$t.element.style.display="none":Jt&&(Jt.style.display="none")):(a?a&&(ee==="overlay"||ee==="push")&&!W?(Ne.style.removeProperty("display"),Ne.style.display="flex",Ne.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ne.style.setProperty("display","none","important"),Ne.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ne.style.display="",Ne.classList.add("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100"),me.classList.add("persona-scale-95","persona-opacity-0")),$t?$t.element.style.display=a?"none":"":Jt&&(Jt.style.display=a?"none":""))},ut=(a,g="user")=>{if(!I()||j===a)return;let h=j;j=a,Gr();let x=(()=>{let W=o.launcher?.sidebarMode??!1,ee=t.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,Y=o.launcher?.mobileBreakpoint??640,de=ee.innerWidth<=Y,xe=_t(o)&&V&&de,le=P()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return W||V&&de&&k||xe||le})();if(j&&x){if(!En){let W=t.getRootNode(),ee=W instanceof ShadowRoot?W.host:t.closest(".persona-host");ee&&(En=dc(ee,o.launcher?.zIndex??Qt))}kn||(kn=pc(t.ownerDocument))}else j||(En?.(),En=null,kn?.(),kn=null);j&&(Jr(),yd()||(dn()==="follow"?no(!0):md()));let A={open:j,source:g,timestamp:Date.now()};j&&!h?p.emit("widget:opened",A):!j&&h&&p.emit("widget:closed",A),p.emit("widget:state",{open:j,launcherEnabled:k,voiceActive:Xe.active,streaming:q.isStreaming()})},nl=a=>{it(a?"stop":"send"),X&&(X.disabled=a),ei.buttons.forEach(g=>{g.disabled=a}),ne.dataset.personaComposerStreaming=a?"true":"false",ne.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=a)})},ol=()=>{Xe.active||ye&&ye.focus()};p.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ol(),200)});let Ad=()=>{v.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",N.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",ye.placeholder=o.copy?.inputPlaceholder??"How can I help...";let a=ce.querySelector("[data-persona-intro-card]");if(a){let h=o.copy?.showWelcomeCard!==!1;a.style.display=h?"":"none",h?(ce.classList.remove("persona-gap-3"),ce.classList.add("persona-gap-6")):(ce.classList.remove("persona-gap-6"),ce.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!q?.isStreaming()&&(Me.textContent=o.copy?.sendButtonLabel??"Send"),ye.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ye.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let a=u.sessionId;return typeof a=="string"?a:null},setStoredSessionId:a=>{R(g=>({...g,sessionId:a}))}});let Po=null,hm=()=>{Po==null&&(Po=setInterval(()=>{let a=We.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(Po),Po=null;return}let g=Date.now();a.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=Ii(g-x))})},100))},rl=(a,g)=>{if(Object.is(a,g))return!0;if(a===null||g===null||typeof a!="object"||typeof g!="object")return!1;if(Array.isArray(a)||Array.isArray(g))return!Array.isArray(a)||!Array.isArray(g)||a.length!==g.length?!1:a.every((ee,V)=>rl(ee,g[V]));let h=a,x=g,A=Object.keys(h),W=Object.keys(x);return A.length===W.length&&A.every(ee=>Object.prototype.hasOwnProperty.call(x,ee)&&rl(h[ee],x[ee]))},Sd=a=>{let{content:g,rawContent:h,llmContent:x,...A}=a;return A},sl=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!Dc(a),ym=(a,g,h)=>{if(a.length!==g.length)return!1;let x=a[h.index],A=g[h.index];return!x||!A||x.id!==h.id||A.id!==h.id?!1:(!Object.is(x.content,A.content)||!Object.is(x.rawContent,A.rawContent)||!Object.is(x.llmContent,A.llmContent))&&sl(x)&&sl(A)&&rl(Sd(x),Sd(A))},Md=null,Yo=null,Io=null,Dn=null,di=a=>{Md=a;let g,h;Yo=null;for(let A=a.length-1;A>=0;A-=1){let W=a[A];if(!g&&W.role==="user"&&(g=W),!h&&W.role==="assistant"&&(h=W),!Yo&&sl(W)&&(Yo={index:A,id:W.id}),g&&h&&Yo)break}Ur(We,a,Z),rc(We,vn.artifacts,{suppressTransition:Cn}),hm(),Ka(a),no(!Cn),dm(a),a.length===0&&(jr(),_r=!0,oi=!1,ri=null,si=!1),!Qa||ni?(Qa=!0,Fr=g?.id??null,Xa=h?.id??null):g&&g.id!==Fr?(Fr=g.id,am(g.id)):h&&h.id!==Xa&&lm(),h&&(Xa=h.id),cm(a);let x=Xe.lastUserMessageId;g&&g.id!==x&&(Xe.lastUserMessageId=g.id,p.emit("user:message",g)),Xe.lastUserMessageWasVoice=!!g?.viaVoice,Za(a),Jo()},il=()=>{Dn!==null&&(cancelAnimationFrame(Dn),Dn=null);let a=Io;Io=null,a&&di(a)},Td=()=>{Dn!==null&&cancelAnimationFrame(Dn),Dn=null,Io=null},bm=a=>{let g=Io??Md;if(Cn&&g&&Yo&&ym(g,a,Yo)){Io=a,Dn===null&&(Dn=requestAnimationFrame(()=>{Dn=null;let h=Io;Io=null,h&&di(h)}));return}if(a.length===0){Td(),di(a);return}il(),di(a)};q=new $i(o,{onMessagesChanged(a){bm(a)},onStatusChanged(a){let g=o.statusIndicator??{};Xt(U,(x=>x==="idle"?g.idleText??Wt.idle:x==="connecting"?g.connectingText??Wt.connecting:x==="connected"?g.connectedText??Wt.connected:x==="error"?g.errorText??Wt.error:x==="paused"?g.pausedText??Wt.paused:x==="resuming"?g.resumingText??Wt.resuming:Wt[x])(a),g,a)},onStreamingChanged(a){a||(q?.getMessages().length===0?Td():il()),Cn=a,nl(a),q&&Ur(We,q.getMessages(),Z),a||no(!0),sn(),Gc(a?"Responding\u2026":"Response complete."),Jo()},onVoiceStatusChanged(a){if(p.emit("voice:status",{status:a,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(a){case"listening":Nn(),er();break;case"processing":Nn(),Lm();break;case"speaking":Nn(),Pm();break;default:a==="idle"&&q.isBargeInActive()?(Nn(),er(),X?.setAttribute("aria-label","End voice session")):(Xe.active=!1,Nn(),Bn("system"),An());break}},onArtifactsState(a){vn=a,a.artifacts.length===0&&(qo=!1),rc(We,a.artifacts,{suppressTransition:Cn}),Hn(),Za()},onReconnect(a){let{executionId:g,lastEventId:h}=a.handle;a.phase==="paused"?p.emit("stream:paused",{executionId:g,after:h}):a.phase==="resuming"?p.emit("stream:resuming",{executionId:g,after:h,attempt:a.attempt??1}):p.emit("stream:resumed",{executionId:g,after:h})}}),dt.current=q,Ve.push(()=>q.cancel());let al=null;if(q.onReadAloudChange((a,g)=>{ed=a,td=g,nd();let h=a??al;a&&(al=a);let x=h?q.getMessages().find(A=>A.id===h)??null:null;p.emit("message:read-aloud",{messageId:h,message:x,state:g,timestamp:Date.now()}),g==="idle"&&(al=null)}),Qa=!0,o.voiceRecognition?.provider?.type==="runtype")try{q.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}o.clientToken&&q.initClientSession().catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)}),(Ee||o.onSSEEvent)&&q.setSSEEventCallback((a,g)=>{o.onSSEEvent?.(a,g),ke?.processEvent(a,g),Ee?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(g)})});let Ed=()=>{o.resume&&typeof o.reconnectStream=="function"&&q.resumeFromHandle(o.resume)};b?b.then(a=>{if(a){if(a.metadata&&(u=Nc(a.metadata),T.syncFromMetadata()),a.messages?.length){ni=!0;try{q.hydrateMessages(a.messages)}finally{ni=!1}}a.artifacts?.length&&q.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>Ed()):Ed();let kd=()=>{!P()||j||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ut(!0,"auto")},vm=(a,g)=>a?g?{refs:[...a.refs,...g.refs],finalize:async()=>{let[h,x]=await Promise.allSettled([a.finalize(),g.finalize()]),A=[];return h.status==="fulfilled"?A.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),x.status==="fulfilled"?A.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),mx(A)}}:a:g,xm=()=>{let g=ye.getInlineMessageFields?.();return g&&g.contentSegments.some(x=>x.kind==="mention")?g.contentSegments:void 0},Qr=!1,Cm=async a=>{let g=ye.value.trim(),h=Tt?.hasAttachments()??!1,x=g?await(on?.takeInlineCommand(g)??Promise.resolve(null)):null;if(x?.kind==="action"){ye.value="",ye.style.height="auto",Xr(),on?.clear();return}let A=on?.collectForSubmit()??null,W=x?.kind==="server"?x.mentions:null,ee=vm(A,W),V=x?.kind==="prompt"?x.sendText:g,Y=!!A&&A.refs.length>0;if(!V&&!h&&!Y&&!W)return;kd();let de;h&&(de=[],de.push(...Tt.getContentParts()),V&&de.push(fr(V)));let xe=x?.kind==="prompt"?void 0:xm();ye.value="",ye.style.height="auto",Xr(),q.sendMessage(V,{contentParts:de,mentions:ee??void 0,contentSegments:xe,viaVoice:a?.viaVoice}),h&&Tt.clearAttachments(),A&&on?.clear()},ll=async a=>{if(!Qr){Qr=!0;try{await Cm(a)}finally{Qr=!1}}},Ld=a=>{if(a.preventDefault(),q.isStreaming()){q.cancel(),ke?.reset(),ze?.update();return}Qr||ll()},wm=()=>o.features?.composerHistory!==!1,cl={...ac},dl=!1,Xr=()=>{cl={...ac}},Am=()=>q.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),Sm=a=>{if(!ye)return;dl=!0,ye.value=a,ye.dispatchEvent(new Event("input",{bubbles:!0})),dl=!1;let g=ye.value.length;ye.setSelectionRange(g,g)},Mm=a=>{dl||(a.isComposing||on?.handleInput(a.inputType??void 0),Xr())},Tm=a=>{if(ye&&!(!a.isComposing&&on?.handleKeydown(a))){if(wm()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let g=ye.selectionStart===0&&ye.selectionEnd===0,h=Sf({direction:a.key==="ArrowUp"?"up":"down",history:Am(),currentValue:ye.value,atStart:g,state:cl});if(cl=h.state,h.handled){a.preventDefault(),h.value!==void 0&&Sm(h.value);return}}if(a.key==="Enter"&&!a.shiftKey){if(q.isStreaming()){a.preventDefault();return}if(Qr){a.preventDefault();return}Xr(),a.preventDefault(),Me.click()}}},Pd=a=>{a.key!=="Escape"||a.isComposing||q.isStreaming()&&a.composedPath().includes(ve)&&(q.cancel(),ke?.reset(),ze?.update(),Xr(),a.preventDefault(),a.stopImmediatePropagation())},Em=async a=>{if(o.attachments?.enabled!==!0||!Tt)return;let g=px(a.clipboardData);g.length!==0&&(a.preventDefault(),await Tt.handleFiles(g))},fn=null,Ln=!1,Zo=null,Ct=null,Id=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,pi=(a="user")=>{if(Ln||q.isStreaming())return;let g=Id();if(!g)return;fn=new g;let x=(o.voiceRecognition??{}).pauseDuration??2e3;fn.continuous=!0,fn.interimResults=!0,fn.lang="en-US";let A=ye.value;fn.onresult=W=>{let ee="",V="";for(let de=0;de<W.results.length;de++){let xe=W.results[de],le=xe[0].transcript;xe.isFinal?ee+=le+" ":V=le}let Y=A+ee+V;ye.value=Y,Zo&&clearTimeout(Zo),(ee||V)&&(Zo=window.setTimeout(()=>{ye.value.trim()&&fn&&Ln&&(oo(),ll({viaVoice:!0}))},x))},fn.onerror=W=>{W.error!=="no-speech"&&oo()},fn.onend=()=>{if(Ln){let W=ye.value.trim();W&&W!==A.trim()&&ll({viaVoice:!0}),oo()}};try{if(fn.start(),Ln=!0,Xe.active=!0,a!=="system"&&(Xe.manuallyDeactivated=!1),Bn(a),An(),X){let W=o.voiceRecognition??{};Ct={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:W.iconName??"mic",iconSize:parseFloat(W.iconSize??o.sendButton?.size??"40")||24};let ee=W.recordingBackgroundColor,V=W.recordingIconColor,Y=W.recordingBorderColor;if(X.classList.add("persona-voice-recording"),X.style.backgroundColor=ee??"var(--persona-voice-recording-bg, #ef4444)",X.style.color=V??"var(--persona-voice-recording-indicator, #ffffff)",V){let de=X.querySelector("svg");de&&de.setAttribute("stroke",V)}Y&&(X.style.borderColor=Y),X.setAttribute("aria-label","Stop voice recognition")}}catch{oo("system")}},oo=(a="user")=>{if(Ln){if(Ln=!1,Zo&&(clearTimeout(Zo),Zo=null),fn){try{fn.stop()}catch{}fn=null}if(Xe.active=!1,Bn(a),An(),X){if(X.classList.remove("persona-voice-recording"),Ct){X.style.backgroundColor=Ct.backgroundColor,X.style.color=Ct.color,X.style.borderColor=Ct.borderColor;let g=X.querySelector("svg");g&&g.setAttribute("stroke",Ct.color||"currentColor"),Ct=null}X.setAttribute("aria-label","Start voice recognition")}}},km=(a,g)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=a?.provider?.type==="runtype",A=a?.provider?.type==="custom";if(!(h||x||A))return null;let ee=y("div","persona-send-button-wrapper"),V=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button";let Y=a?.tooltipText??"Start voice recognition";V.setAttribute("aria-label",Y);let de=a?.iconName??"mic",xe=g?.size??"40px",le=a?.iconSize??xe,Se=parseFloat(le)||24,qe=a?.backgroundColor??g?.backgroundColor,ft=a?.iconColor??g?.textColor;V.style.width=le,V.style.height=le,V.style.minWidth=le,V.style.minHeight=le,V.style.fontSize="18px",V.style.lineHeight="1",ft?V.style.color=ft:V.style.color="var(--persona-text, #111827)";let an=ae(de,Se,ft||"currentColor",1.5);an?V.appendChild(an):V.textContent="\u{1F3A4}",qe?V.style.backgroundColor=qe:V.style.backgroundColor="",a?.borderWidth&&(V.style.borderWidth=a.borderWidth,V.style.borderStyle="solid"),a?.borderColor&&(V.style.borderColor=a.borderColor),a?.paddingX&&(V.style.paddingLeft=a.paddingX,V.style.paddingRight=a.paddingX),a?.paddingY&&(V.style.paddingTop=a.paddingY,V.style.paddingBottom=a.paddingY),ee.appendChild(V);let Et=a?.showTooltip??!1;return jt({anchor:V,trigger:ee,text:()=>V.getAttribute("aria-label")??Y,enabled:Et}),{micButton:V,micButtonWrapper:ee}},pl=()=>{if(!X||Ct)return;let a=o.voiceRecognition??{};Ct={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:a.iconName??"mic",iconSize:parseFloat(a.iconSize??o.sendButton?.size??"40")||24}},ul=(a,g)=>{if(!X)return;let h=X.querySelector("svg");h&&h.remove();let x=Ct?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=ae(a,x,g,1.5);A&&X.appendChild(A)},ui=()=>{X&&X.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},er=()=>{if(!X)return;pl();let a=o.voiceRecognition??{},g=a.recordingBackgroundColor,h=a.recordingIconColor,x=a.recordingBorderColor;if(ui(),X.classList.add("persona-voice-recording"),X.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",X.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let A=X.querySelector("svg");A&&A.setAttribute("stroke",h)}x&&(X.style.borderColor=x),X.setAttribute("aria-label","Stop voice recognition")},Lm=()=>{if(!X)return;pl();let a=o.voiceRecognition??{},g=q.getVoiceInterruptionMode(),h=a.processingIconName??"loader",x=a.processingIconColor??Ct?.color??"",A=a.processingBackgroundColor??Ct?.backgroundColor??"",W=a.processingBorderColor??Ct?.borderColor??"";ui(),X.classList.add("persona-voice-processing"),X.style.backgroundColor=A,X.style.borderColor=W;let ee=x||"currentColor";X.style.color=ee,ul(h,ee),X.setAttribute("aria-label","Processing voice input"),g==="none"&&(X.style.cursor="default")},Pm=()=>{if(!X)return;pl();let a=o.voiceRecognition??{},g=q.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",x=a.speakingIconName??h,A=a.speakingIconColor??(g==="barge-in"?a.recordingIconColor??Ct?.color??"":Ct?.color??""),W=a.speakingBackgroundColor??(g==="barge-in"?a.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Ct?.backgroundColor??""),ee=a.speakingBorderColor??(g==="barge-in"?a.recordingBorderColor??"":Ct?.borderColor??"");ui(),X.classList.add("persona-voice-speaking"),X.style.backgroundColor=W,X.style.borderColor=ee;let V=A||"currentColor";X.style.color=V,ul(x,V);let Y=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";X.setAttribute("aria-label",Y),g==="none"&&(X.style.cursor="default"),g==="barge-in"&&X.classList.add("persona-voice-recording")},Nn=()=>{X&&(ui(),Ct&&(X.style.backgroundColor=Ct.backgroundColor??"",X.style.color=Ct.color??"",X.style.borderColor=Ct.borderColor??"",ul(Ct.iconName,Ct.color||"currentColor"),Ct=null),X.style.cursor="",X.setAttribute("aria-label","Start voice recognition"))},fi=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let a=q.getVoiceStatus(),g=q.getVoiceInterruptionMode();if(g==="none"&&(a==="processing"||a==="speaking"))return;if(g==="cancel"&&(a==="processing"||a==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,An(),Bn("user"),Nn()});return}q.toggleVoice().then(()=>{Xe.active=q.isVoiceActive(),Xe.manuallyDeactivated=!q.isVoiceActive(),An(),Bn("user"),q.isVoiceActive()?er():Nn()});return}if(Ln){let a=ye.value.trim();Xe.manuallyDeactivated=!0,An(),oo("user"),a&&(ye.value="",ye.style.height="auto",q.sendMessage(a))}else Xe.manuallyDeactivated=!1,An(),pi("user")};Xc=fi,X&&(X.addEventListener("click",fi),Ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),Nn()):oo("system"),X&&X.removeEventListener("click",fi)}));let Im=p.on("assistant:complete",()=>{cd&&(Xe.active||Xe.manuallyDeactivated||cd==="assistant"&&!Xe.lastUserMessageWasVoice||setTimeout(()=>{!Xe.active&&!Xe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?q.toggleVoice().then(()=>{Xe.active=q.isVoiceActive(),Bn("auto"),q.isVoiceActive()&&er()}):pi("auto"))},600))});Ve.push(Im);let Rm=p.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});Ve.push(Rm);let Rd=()=>{ut(!j,"user")},$t=null,Jt=null;if(k&&!P()){let{instance:a,element:g}=fc({config:o,plugins:s,onToggle:Rd});$t=a,a||(Jt=g)}$t?t.appendChild($t.element):Jt&&t.appendChild(Jt),Gr(),Ka(),Ad(),nl(q.isStreaming()),yd()||(dn()==="follow"?no(!0):md()),tm(),G&&(!k||P()?setTimeout(()=>ol(),0):j&&setTimeout(()=>ol(),200));let Jr=()=>{if(P()){Vo(),Gr();return}let a=_t(o),g=o.launcher?.sidebarMode??!1,h=a||g||(o.launcher?.fullHeight??!1),x=t.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,W=o.launcher?.mobileBreakpoint??640,ee=x.innerWidth<=W,V=A&&ee&&k;try{if(V){Br(),Dr=Js();return}let Y=!1;B&&(B=!1,Br(),Y=!0);let de=Js();if(!Y&&de!==Dr&&(Br(),Y=!0),Dr=de,Y&&Va(),!k&&!a){me.style.height="",me.style.width="";return}if(!g&&!a){let le=o?.launcher?.width??o?.launcherWidth??Vn;me.style.width=le,me.style.maxWidth=le}if(Xs(),!h){let xe=x.innerHeight,le=64,Se=o.launcher?.heightOffset??0,qe=Math.max(200,xe-le),ft=Math.min(640,qe),rt=Math.max(200,ft-Se);me.style.height=`${rt}px`}}finally{if(Vo(),Gr(),j&&k){let de=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),xe=o.launcher?.sidebarMode??!1,le=o.launcher?.mobileFullscreen??!0,Se=_t(o)&&le&&de,qe=xe||le&&de&&k||Se;if(qe&&!kn){let ft=t.getRootNode(),rt=ft instanceof ShadowRoot?ft.host:t.closest(".persona-host");rt&&!En&&(En=dc(rt,o.launcher?.zIndex??Qt)),kn=pc(t.ownerDocument)}else qe||(En?.(),En=null,kn?.(),kn=null)}}};Jr();let Wd=t.ownerDocument.defaultView??window;if(Wd.addEventListener("resize",Jr),Ve.push(()=>Wd.removeEventListener("resize",Jr)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{Vo()});a.observe(ne),Ve.push(()=>a.disconnect())}pn=ce.scrollTop;let Hd=In(ce),Bd=()=>{let a=ce.scrollTop,g=In(ce),h=g<Hd;if(Hd=g,!Gn()){pn=a,sn();return}let{action:x,nextLastScrollTop:A}=ha({following:rn.isFollowing(),currentScrollTop:a,lastScrollTop:pn,nearBottom:yo(ce,ii),userScrollThreshold:Zg,isAutoScrolling:un||ti||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(pn=A,x==="resume"){li()||to();return}x==="pause"&&zr()};if(ce.addEventListener("scroll",Bd,{passive:!0}),Ve.push(()=>ce.removeEventListener("scroll",Bd)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{im(),yl(We)});a.observe(We),a.observe(ce),Ve.push(()=>a.disconnect())}let Dd=()=>{Gn()&&rn.isFollowing()&&li()&&zr()},Nd=ce.ownerDocument;Nd.addEventListener("selectionchange",Dd),Ve.push(()=>{Nd.removeEventListener("selectionchange",Dd)});let Wm=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Od=a=>{Wm.has(a.key)&&(ko(),Vc()&&Gn()&&rn.isFollowing()&&zr())},Fd=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(ko(),Vc()&&Gn()&&rn.isFollowing()&&zr())};ce.addEventListener("keydown",Od),ce.addEventListener("focusin",Fd),Ve.push(()=>{ce.removeEventListener("keydown",Od),ce.removeEventListener("focusin",Fd)});let _d=a=>{if(a.deltaY!==0&&ko(),!Gn())return;let g=ya({following:rn.isFollowing(),deltaY:a.deltaY,nearBottom:yo(ce,ii),resumeWhenNearBottom:!0});g==="pause"?zr():g==="resume"&&!li()&&to()};ce.addEventListener("wheel",_d,{passive:!0}),ce.addEventListener("touchmove",ko,{passive:!0}),ce.addEventListener("pointerdown",ko,{passive:!0}),Ve.push(()=>{ce.removeEventListener("touchmove",ko),ce.removeEventListener("pointerdown",ko)}),Ve.push(()=>ce.removeEventListener("wheel",_d)),Lt.addEventListener("click",()=>{jr(),ce.scrollTop=ce.scrollHeight,pn=ce.scrollTop,to(),no(!0),sn()}),Ve.push(()=>Lt.remove()),Ve.push(()=>{ud(),jr()});let $d=()=>{E&&(So&&(E.removeEventListener("click",So),So=null),I()?(E.style.display="",So=()=>{ut(!1,"user")},E.addEventListener("click",So)):E.style.display="none")};$d(),(()=>{let{clearChatButton:a}=He;a&&a.addEventListener("click",()=>{q.clearMessages(),Mo.clear(),to(),dr(He.composerOverlay);try{localStorage.removeItem(Lr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Lr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Lr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),d?.clear&&Ya(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},T.syncFromMetadata(),Ee?.clear(),ke?.reset(),ze?.update()})})(),M&&M.addEventListener("submit",Ld);let zd=[["keydown",Tm],["input",Mm],["paste",Em],["focus",Gg]],jd=a=>{if(a)for(let[g,h]of zd)a.addEventListener(g,h)},Ud=a=>{if(a)for(let[g,h]of zd)a.removeEventListener(g,h)};jd(ye),on?.onComposerSwap((a,g)=>{Ud(g),ye=a,jd(a)});let Vd=t.ownerDocument??document;Vd.addEventListener("keydown",Pd,!0);let qd="persona-attachment-drop-active",Yr=0,fl=()=>{Yr=0,ve.classList.remove(qd)},tr=()=>o.attachments?.enabled===!0&&Tt!==null,Kd=a=>{!Na(a.dataTransfer)||!tr()||(Yr++,Yr===1&&ve.classList.add(qd))},Gd=a=>{!Na(a.dataTransfer)||!tr()||(Yr--,Yr<=0&&fl())},Qd=a=>{!Na(a.dataTransfer)||!tr()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},Xd=a=>{if(!Na(a.dataTransfer)||!tr())return;a.preventDefault(),a.stopPropagation(),fl();let g=Array.from(a.dataTransfer.files??[]);g.length!==0&&Tt.handleFiles(g)},ro=!0;ve.addEventListener("dragenter",Kd,ro),ve.addEventListener("dragleave",Gd,ro),t.addEventListener("dragover",Qd,ro),t.addEventListener("drop",Xd,ro);let gi=t.ownerDocument,Jd=a=>{tr()&&a.preventDefault()},Yd=a=>{tr()&&a.preventDefault()};gi.addEventListener("dragover",Jd),gi.addEventListener("drop",Yd),Ve.push(()=>{M&&M.removeEventListener("submit",Ld),Ud(ye),Vd.removeEventListener("keydown",Pd,!0),on?.destroy()}),Ve.push(()=>{ve.removeEventListener("dragenter",Kd,ro),ve.removeEventListener("dragleave",Gd,ro),t.removeEventListener("dragover",Qd,ro),t.removeEventListener("drop",Xd,ro),gi.removeEventListener("dragover",Jd),gi.removeEventListener("drop",Yd),fl()}),Ve.push(()=>{q.cancel()}),$t?Ve.push(()=>{$t?.destroy()}):Jt&&Ve.push(()=>{Jt?.remove()});let Pt={update(a){let g=o.toolCall,h=o.messageActions,x=o.layout?.messages,A=o.colorScheme,W=o.loadingIndicator,ee=o.iterationDisplay,V=o.features?.showReasoning,Y=o.features?.showToolCalls,de=o.features?.toolCallDisplay,xe=o.features?.reasoningDisplay,le=o.features?.streamAnimation?.type;o=xg({...o,features:r},a),r=o.features,o=Ec(o),Ys(),ws(t,o),Os(t,o),Fs(t,o),Hn(),o.colorScheme!==A&&ld();let Se=Ic.getForInstance(o.plugins);s.length=0,s.push(...Se),k=o.launcher?.enabled??!0,$=o.launcher?.autoExpand??!1,oe=o.features?.showReasoning??!0,Q=o.features?.showToolCalls??!0,te=o.features?.scrollToBottom??{};let qe=dn();fe=o.features?.scrollBehavior??{},qe!==dn()&&(jr(),to()),Qc(),sn();let ft=se;if(se=o.features?.showEventStreamToggle??!1,se&&!ft){if(Ee||(Ce=new Ds(he),Ee=new Bs($e,Ce),ke=ke??new Ns,Ce.open().then(()=>Ee?.restore()).catch(()=>{}),q.setSSEEventCallback((ie,Qe)=>{o.onSSEEvent?.(ie,Qe),ke?.processEvent(ie,Qe),Ee.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ie,timestamp:Date.now(),payload:JSON.stringify(Qe)})})),!ot&&K){let ie=o.features?.eventStream?.classNames,Qe="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"+(ie?.toggleButton?" "+ie.toggleButton:"");ot=y("button",Qe),ot.style.width="28px",ot.style.height="28px",ot.style.color=Zt.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let yt=ae("activity","18px","currentColor",1.5);yt&&ot.appendChild(yt);let st=He.clearChatButtonWrapper,at=He.closeButtonWrapper,Kt=st||at;Kt&&Kt.parentNode===K?K.insertBefore(ot,Kt):K.appendChild(ot),ot.addEventListener("click",()=>{Ke?Wr():$a()})}}else!se&&ft&&(Wr(),ot&&(ot.remove(),ot=null),Ee?.clear(),Ce?.destroy(),Ee=null,Ce=null,ke?.reset(),ke=null);if(o.launcher?.enabled===!1&&$t&&($t.destroy(),$t=null),o.launcher?.enabled===!1&&Jt&&(Jt.remove(),Jt=null),o.launcher?.enabled!==!1&&!$t&&!Jt){let{instance:ie,element:Qe}=fc({config:o,plugins:s,onToggle:Rd});$t=ie,ie||(Jt=Qe),t.appendChild(Qe)}$t&&$t.update(o),J&&o.launcher?.title!==void 0&&(J.textContent=o.launcher.title),z&&o.launcher?.subtitle!==void 0&&(z.textContent=o.launcher.subtitle);let rt=o.layout?.header;if(rt?.layout!==D&&K){let ie=rt?Sa(o,rt,{showClose:I(),onClose:()=>ut(!1,"user")}):Fo({config:o,showClose:I(),onClose:()=>ut(!1,"user")});Mt.replaceHeader(ie),K=Mt.header.element,O=Mt.header.iconHolder,J=Mt.header.headerTitle,z=Mt.header.headerSubtitle,E=Mt.header.closeButton,D=rt?.layout}else if(rt){if(O&&(O.style.display=rt.showIcon===!1?"none":""),J&&(J.style.display=rt.showTitle===!1?"none":""),z&&(z.style.display=rt.showSubtitle===!1?"none":""),E){let ie=I()&&rt.showCloseButton!==!1;E.style.display=ie?"":"none"}if(He.clearChatButtonWrapper){let ie=rt.showClearChat;if(ie!==void 0){He.clearChatButtonWrapper.style.display=ie?"":"none";let{closeButtonWrapper:Qe}=He;Qe&&!Qe.classList.contains("persona-absolute")&&(ie?Qe.classList.remove("persona-ml-auto"):Qe.classList.add("persona-ml-auto"))}}}let Et=o.layout?.showHeader!==!1;K&&(K.style.display=Et?"":"none");let It=o.layout?.showFooter!==!1;ne&&(ne.style.display=It?"":"none"),Vo(),sn(),k!==F?k?ut($,"auto"):(j=!0,Gr()):$!==w&&ut($,"auto"),w=$,F=k,Jr(),$d();let Fe=JSON.stringify(o.toolCall)!==JSON.stringify(g),Te=JSON.stringify(o.messageActions)!==JSON.stringify(h),At=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),gt=o.loadingIndicator?.render!==W?.render||o.loadingIndicator?.renderIdle!==W?.renderIdle||o.loadingIndicator?.showBubble!==W?.showBubble,Ft=o.iterationDisplay!==ee,mt=(o.features?.showReasoning??!0)!==(V??!0)||(o.features?.showToolCalls??!0)!==(Y??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(de)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(xe);(Fe||Te||At||gt||Ft||mt)&&q&&(Ga++,Ur(We,q.getMessages(),Z));let Rt=o.features?.streamAnimation?.type;if(Rt!==le&&Rt&&Rt!=="none"){let ie=Ar(Rt,o.features?.streamAnimation?.plugins);ie&&Ca(ie,t)}let Ie=o.launcher??{},_e=Ie.headerIconHidden??!1,Ut=o.layout?.header?.showIcon,Vt=_e||Ut===!1,wt=Ie.headerIconName,pt=Ie.headerIconSize??"48px";if(O){let ie=ve.querySelector(".persona-border-b-persona-divider"),Qe=ie?.querySelector(".persona-flex-col");if(Vt)O.style.display="none",ie&&Qe&&!ie.contains(Qe)&&ie.insertBefore(Qe,ie.firstChild);else{if(O.style.display="",O.style.height=pt,O.style.width=pt,ie&&Qe&&(ie.contains(O)?O.nextSibling!==Qe&&(O.remove(),ie.insertBefore(O,Qe)):ie.insertBefore(O,Qe)),wt){let st=parseFloat(pt)||24,at=ae(wt,st*.6,"currentColor",1);at?O.replaceChildren(at):O.textContent=Ie.agentIconText??"\u{1F4AC}"}else if(Ie.iconUrl){let st=O.querySelector("img");if(st)st.src=Ie.iconUrl,st.style.height=pt,st.style.width=pt;else{let at=document.createElement("img");at.src=Ie.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=pt,at.style.width=pt,O.replaceChildren(at)}}else{let st=O.querySelector("svg"),at=O.querySelector("img");(st||at)&&O.replaceChildren(),O.textContent=Ie.agentIconText??"\u{1F4AC}"}let yt=O.querySelector("img");yt&&(yt.style.height=pt,yt.style.width=pt)}}let ht=o.layout?.header?.showTitle,et=o.layout?.header?.showSubtitle;if(J&&(J.style.display=ht===!1?"none":""),z&&(z.style.display=et===!1?"none":""),E){let ie=I()&&o.layout?.header?.showCloseButton!==!1;E.style.display=ie?"":"none";let Qe=Ie.closeButtonSize??"32px",yt=Ie.closeButtonPlacement??"inline";E.style.height=Qe,E.style.width=Qe;let{closeButtonWrapper:st}=He,at=yt==="top-right",Kt=st?.classList.contains("persona-absolute");if(st&&at!==Kt)if(st.remove(),at)st.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ve.style.position="relative",ve.appendChild(st);else{let io=Ie.clearChat?.placement??"inline",ts=Ie.clearChat?.enabled??!0;st.className=ts&&io==="inline"?"":"persona-ml-auto";let Zd=ve.querySelector(".persona-border-b-persona-divider");Zd&&Zd.appendChild(st)}if(E.style.color=Ie.closeButtonColor||Zt.actionIconColor,Ie.closeButtonBackgroundColor?(E.style.backgroundColor=Ie.closeButtonBackgroundColor,E.classList.remove("hover:persona-bg-gray-100")):(E.style.backgroundColor="",E.classList.add("hover:persona-bg-gray-100")),Ie.closeButtonBorderWidth||Ie.closeButtonBorderColor){let io=Ie.closeButtonBorderWidth||"0px",ts=Ie.closeButtonBorderColor||"transparent";E.style.border=`${io} solid ${ts}`,E.classList.remove("persona-border-none")}else E.style.border="",E.classList.add("persona-border-none");Ie.closeButtonBorderRadius?(E.style.borderRadius=Ie.closeButtonBorderRadius,E.classList.remove("persona-rounded-full")):(E.style.borderRadius="",E.classList.add("persona-rounded-full")),Ie.closeButtonPaddingX?(E.style.paddingLeft=Ie.closeButtonPaddingX,E.style.paddingRight=Ie.closeButtonPaddingX):(E.style.paddingLeft="",E.style.paddingRight=""),Ie.closeButtonPaddingY?(E.style.paddingTop=Ie.closeButtonPaddingY,E.style.paddingBottom=Ie.closeButtonPaddingY):(E.style.paddingTop="",E.style.paddingBottom="");let ln=Ie.closeButtonIconName??"x",Sn=Ie.closeButtonIconText??"\xD7";E.innerHTML="";let zt=ae(ln,"28px","currentColor",1);zt?(zt.style.display="block",E.appendChild(zt)):E.textContent=Sn;let Gt=Ie.closeButtonTooltipText??"Close chat",Fn=Ie.closeButtonShowTooltip??!0;E.setAttribute("aria-label",Gt),st&&jt({anchor:E,trigger:st,text:()=>E?.getAttribute("aria-label")??Gt,enabled:Fn})}let{clearChatButton:De,clearChatButtonWrapper:vt}=He;if(De){let ie=Ie.clearChat??{},Qe=ie.enabled??!0,yt=o.layout?.header?.showClearChat,st=yt!==void 0?yt:Qe,at=ie.placement??"inline";if(vt){vt.style.display=st?"":"none";let{closeButtonWrapper:Kt}=He;!P()&&Kt&&!Kt.classList.contains("persona-absolute")&&(st?Kt.classList.remove("persona-ml-auto"):Kt.classList.add("persona-ml-auto"));let ln=at==="top-right",Sn=vt.classList.contains("persona-absolute");if(!P()&&ln!==Sn&&st){if(vt.remove(),ln)vt.className="persona-absolute persona-top-4 persona-z-50",vt.style.right="48px",ve.style.position="relative",ve.appendChild(vt);else{vt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vt.style.right="";let Gt=ve.querySelector(".persona-border-b-persona-divider"),Fn=He.closeButtonWrapper;Gt&&Fn&&Fn.parentElement===Gt?Gt.insertBefore(vt,Fn):Gt&&Gt.appendChild(vt)}let zt=He.closeButtonWrapper;zt&&!zt.classList.contains("persona-absolute")&&(ln?zt.classList.add("persona-ml-auto"):zt.classList.remove("persona-ml-auto"))}}if(st){if(!P()){let io=ie.size??"32px";De.style.height=io,De.style.width=io}let Kt=ie.iconName??"refresh-cw",ln=ie.iconColor??"";De.style.color=ln||Zt.actionIconColor,De.innerHTML="";let Sn=P()?"14px":"20px",zt=ae(Kt,Sn,"currentColor",1);if(zt&&(zt.style.display="block",De.appendChild(zt)),ie.backgroundColor?(De.style.backgroundColor=ie.backgroundColor,De.classList.remove("hover:persona-bg-gray-100")):(De.style.backgroundColor="",De.classList.add("hover:persona-bg-gray-100")),ie.borderWidth||ie.borderColor){let io=ie.borderWidth||"0px",ts=ie.borderColor||"transparent";De.style.border=`${io} solid ${ts}`,De.classList.remove("persona-border-none")}else De.style.border="",De.classList.add("persona-border-none");ie.borderRadius?(De.style.borderRadius=ie.borderRadius,De.classList.remove("persona-rounded-full")):(De.style.borderRadius="",De.classList.add("persona-rounded-full")),ie.paddingX?(De.style.paddingLeft=ie.paddingX,De.style.paddingRight=ie.paddingX):(De.style.paddingLeft="",De.style.paddingRight=""),ie.paddingY?(De.style.paddingTop=ie.paddingY,De.style.paddingBottom=ie.paddingY):(De.style.paddingTop="",De.style.paddingBottom="");let Gt=ie.tooltipText??"Clear chat",Fn=ie.showTooltip??!0;De.setAttribute("aria-label",Gt),vt&&jt({anchor:De,trigger:vt,text:()=>De?.getAttribute("aria-label")??Gt,enabled:Fn})}}let qt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Wc],mn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[_s.message,_s.messageAndClick];T=Hc({parsers:qt,handlers:mn,getSessionMetadata:C,updateSessionMetadata:R,emit:p.emit,documentRef:typeof document<"u"?document:null}),Z=Pg(o,T,ge),q.updateConfig(o),Ur(We,q.getMessages(),Z),Ka(),Ad(),nl(q.isStreaming());let Zr=o.voiceRecognition?.enabled===!0,mi=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),kt=o.voiceRecognition?.provider?.type==="runtype";if(Zr&&(mi||kt))if(!X||!je){let ie=km(o.voiceRecognition,o.sendButton);ie&&(X=ie.micButton,je=ie.micButtonWrapper,Be.insertBefore(je,re),X.addEventListener("click",fi),X.disabled=q.isStreaming())}else{let ie=o.voiceRecognition??{},Qe=o.sendButton??{},yt=ie.iconName??"mic",st=Qe.size??"40px",at=ie.iconSize??st,Kt=parseFloat(at)||24;X.style.width=at,X.style.height=at,X.style.minWidth=at,X.style.minHeight=at;let ln=ie.iconColor??Qe.textColor;X.innerHTML="";let Sn=ae(yt,Kt,ln||"currentColor",1.5);Sn?X.appendChild(Sn):X.textContent="\u{1F3A4}";let zt=ie.backgroundColor??Qe.backgroundColor;zt?X.style.backgroundColor=zt:X.style.backgroundColor="",ln?X.style.color=ln:X.style.color="var(--persona-text, #111827)",ie.borderWidth?(X.style.borderWidth=ie.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),ie.borderColor?X.style.borderColor=ie.borderColor:X.style.borderColor="",ie.paddingX?(X.style.paddingLeft=ie.paddingX,X.style.paddingRight=ie.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),ie.paddingY?(X.style.paddingTop=ie.paddingY,X.style.paddingBottom=ie.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let Gt=ie.tooltipText??"Start voice recognition",Fn=ie.showTooltip??!1;X.setAttribute("aria-label",Gt),je&&jt({anchor:X,trigger:je,text:()=>X?.getAttribute("aria-label")??Gt,enabled:Fn}),je.style.display="",X.disabled=q.isStreaming()}else X&&je&&(je.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?q.isVoiceActive()&&q.toggleVoice():Ln&&oo());if(o.attachments?.enabled===!0){if(!Ue||!Ae){let ie=o.attachments??{},yt=(o.sendButton??{}).size??"40px";Dt||(Dt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Dt.style.display="none",M.insertBefore(Dt,ye)),Oe||(Oe=document.createElement("input"),Oe.type="file",Oe.accept=(ie.allowedTypes??Un).join(","),Oe.multiple=(ie.maxFiles??4)>1,Oe.style.display="none",Oe.setAttribute("aria-label","Attach files"),M.insertBefore(Oe,ye)),Ue=y("div","persona-send-button-wrapper"),Ae=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ae.type="button",Ae.setAttribute("aria-label",ie.buttonTooltipText??"Attach file");let st=ie.buttonIconName??"paperclip",at=yt,Kt=parseFloat(at)||40,ln=Math.round(Kt*.6);Ae.style.width=at,Ae.style.height=at,Ae.style.minWidth=at,Ae.style.minHeight=at,Ae.style.fontSize="18px",Ae.style.lineHeight="1";let Sn=ae(st,ln,"currentColor",1.5);Sn?Ae.appendChild(Sn):Ae.textContent="\u{1F4CE}",Ae.addEventListener("click",Gt=>{Gt.preventDefault(),Oe?.click()}),Ue.appendChild(Ae);let zt=ie.buttonTooltipText??"Attach file";jt({anchor:Ae,trigger:Ue,text:()=>Ae?.getAttribute("aria-label")??zt}),Ye?Ye.append(Ue):M.appendChild(Ue),!Tt&&Oe&&Dt&&(Tt=gs.fromConfig(ie),Tt.setPreviewsContainer(Dt),Oe.addEventListener("change",async()=>{Tt&&Oe?.files&&(await Tt.handleFileSelect(Oe.files),Oe.value="")}))}else{Ue.style.display="";let ie=o.attachments??{};Oe&&(Oe.accept=(ie.allowedTypes??Un).join(","),Oe.multiple=(ie.maxFiles??4)>1),Tt&&Tt.updateConfig({allowedTypes:ie.allowedTypes,maxFileSize:ie.maxFileSize,maxFiles:ie.maxFiles})}if(ve.querySelector(".persona-attachment-drop-overlay")?.remove(),ve.appendChild(Ig(o.attachments?.dropOverlay)),Ae){let ie=o.attachments??{},Qe=ie.buttonTooltipText??"Attach file";Ae.setAttribute("aria-label",Qe),Ae.textContent="";let yt=parseFloat(o.sendButton?.size??"40px")||40,st=ae(ie.buttonIconName??"paperclip",Math.round(yt*.6),"currentColor",1.5);st?Ae.appendChild(st):Ae.textContent="\u{1F4CE}",Ue&&jt({anchor:Ae,trigger:Ue,text:()=>Ae?.getAttribute("aria-label")??Qe})}}else Ue&&(Ue.style.display="none"),Tt&&Tt.clearAttachments(),ve.querySelector(".persona-attachment-drop-overlay")?.remove();let Nt=o.sendButton??{},es=Nt.useIcon??!1,yi=Nt.iconText??"\u2191",nr=Nt.iconName,bi=Nt.tooltipText??"Send message",gl=Nt.showTooltip??!1,Ro=Nt.size??"40px",On=Nt.backgroundColor,Wo=Nt.textColor;if(es){if(Me.style.width=Ro,Me.style.height=Ro,Me.style.minWidth=Ro,Me.style.minHeight=Ro,Me.style.fontSize="18px",Me.style.lineHeight="1",Wo?Me.style.color=Wo:Me.style.color="var(--persona-button-primary-fg, #ffffff)",!q.isStreaming())if(Me.innerHTML="",nr){let ie=parseFloat(Ro)||24,Qe=Wo?.trim()||"currentColor",yt=ae(nr,ie,Qe,2);yt?Me.appendChild(yt):Me.textContent=yi}else Me.textContent=yi;Me.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",On?(Me.style.backgroundColor=On,Me.classList.remove("persona-bg-persona-primary")):(Me.style.backgroundColor="",Me.classList.add("persona-bg-persona-primary"))}else Me.textContent=o.copy?.sendButtonLabel??"Send",Me.style.width="",Me.style.height="",Me.style.minWidth="",Me.style.minHeight="",Me.style.fontSize="",Me.style.lineHeight="",Me.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",On?(Me.style.backgroundColor=On,Me.classList.remove("persona-bg-persona-accent")):Me.classList.add("persona-bg-persona-accent"),Wo?Me.style.color=Wo:Me.classList.add("persona-text-white");Nt.borderWidth?(Me.style.borderWidth=Nt.borderWidth,Me.style.borderStyle="solid"):(Me.style.borderWidth="",Me.style.borderStyle=""),Nt.borderColor?Me.style.borderColor=Nt.borderColor:Me.style.borderColor="",Nt.paddingX?(Me.style.paddingLeft=Nt.paddingX,Me.style.paddingRight=Nt.paddingX):(Me.style.paddingLeft="",Me.style.paddingRight=""),Nt.paddingY?(Me.style.paddingTop=Nt.paddingY,Me.style.paddingBottom=Nt.paddingY):(Me.style.paddingTop="",Me.style.paddingBottom=""),q.isStreaming()||Me.setAttribute("aria-label",bi),re&&jt({anchor:Me,trigger:re,text:()=>Me.getAttribute("aria-label")??bi,enabled:gl});let vi=o.layout?.contentMaxWidth??(P()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);vi?(We.style.maxWidth=vi,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",M&&(M.style.maxWidth=vi,M.style.marginLeft="auto",M.style.marginRight="auto"),ct&&(ct.style.maxWidth=vi,ct.style.marginLeft="auto",ct.style.marginRight="auto")):(We.style.maxWidth="",We.style.marginLeft="",We.style.marginRight="",We.style.width="",M&&(M.style.maxWidth="",M.style.marginLeft="",M.style.marginRight=""),ct&&(ct.style.maxWidth="",ct.style.marginLeft="",ct.style.marginRight=""));let so=o.statusIndicator??{},Hm=so.visible??!0;if(U.style.display=Hm?"":"none",q){let ie=q.getStatus();Xt(U,(yt=>yt==="idle"?so.idleText??Wt.idle:yt==="connecting"?so.connectingText??Wt.connecting:yt==="connected"?so.connectedText??Wt.connected:yt==="error"?so.errorText??Wt.error:Wt[yt])(ie),so,ie)}U.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Bm=so.align==="left"?"persona-text-left":so.align==="center"?"persona-text-center":"persona-text-right";U.classList.add(Bm)},open(){I()&&ut(!0,"api")},close(){I()&&ut(!1,"api")},toggle(){I()&&ut(!j,"api")},reconnect(){q.reconnectNow()},clearChat(){Wn=!1,q.clearMessages(),Mo.clear(),to();try{localStorage.removeItem(Lr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Lr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Lr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),d?.clear&&Ya(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},T.syncFromMetadata(),Ee?.clear(),ke?.reset(),ze?.update()},setMessage(a){return!ye||q.isStreaming()?!1:(!j&&I()&&ut(!0,"system"),ye.value=a,ye.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(q.isStreaming())return!1;let g=a?.trim()||ye.value.trim();return g?(!j&&I()&&ut(!0,"system"),ye.value="",ye.style.height="auto",q.sendMessage(g),!0):!1},startVoiceRecognition(){return q.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(q.isVoiceActive()||(!j&&I()&&ut(!0,"system"),Xe.manuallyDeactivated=!1,An(),q.toggleVoice().then(()=>{Xe.active=q.isVoiceActive(),Bn("user"),q.isVoiceActive()&&er()})),!0):Ln?!0:Id()?(!j&&I()&&ut(!0,"system"),Xe.manuallyDeactivated=!1,An(),pi("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,An(),Bn("user"),Nn()}),!0):!1:Ln?(Xe.manuallyDeactivated=!0,An(),oo("user"),!0):!1},injectMessage(a){return!j&&I()&&ut(!0,"system"),q.injectMessage(a)},injectAssistantMessage(a){!j&&I()&&ut(!0,"system");let g=q.injectAssistantMessage(a);return pe&&(pe=!1,ue&&(clearTimeout(ue),ue=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),g},injectUserMessage(a){return!j&&I()&&ut(!0,"system"),q.injectUserMessage(a)},injectSystemMessage(a){return!j&&I()&&ut(!0,"system"),q.injectSystemMessage(a)},injectMessageBatch(a){return!j&&I()&&ut(!0,"system"),q.injectMessageBatch(a)},injectComponentDirective(a){return!j&&I()&&ut(!0,"system"),q.injectComponentDirective(a)},injectTestMessage(a){!j&&I()&&ut(!0,"system"),q.injectTestEvent(a)},async connectStream(a,g){return q.connectStream(a,g)},__pushEventStreamEvent(a){Ee&&(ke?.processEvent(a.type,a.payload),Ee.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a.type,timestamp:Date.now(),payload:JSON.stringify(a.payload)}))},showEventStream(){!se||!Ee||$a()},hideEventStream(){Ke&&Wr()},isEventStreamVisible(){return Ke},showArtifacts(){en(o)&&(Wn=!1,qo=!0,Hn(),Ze?.setMobileOpen(!0))},hideArtifacts(){en(o)&&(Wn=!0,Hn())},upsertArtifact(a){return en(o)?(lo(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(Wn=!1,qo=!0),q.upsertArtifact(a)):null},selectArtifact(a){en(o)&&q.selectArtifact(a)},clearArtifacts(){en(o)&&q.clearArtifacts()},getArtifacts(){return q?.getArtifacts()??[]},getSelectedArtifactId(){return q?.getSelectedArtifactId()??null},focusInput(){return k&&!j&&!P()||!ye?!1:(ye.focus(),!0)},async resolveApproval(a,g,h){let A=q.getMessages().find(W=>W.variant==="approval"&&W.approval?.id===a);if(!A?.approval)throw new Error(`Approval not found: ${a}`);if(A.approval.toolType==="webmcp"){q.resolveWebMcpApproval(A.id,g);return}return q.resolveApproval(A.approval,g,h)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(a){R(a)},on(a,g){return p.on(a,g)},off(a,g){p.off(a,g)},isOpen(){return I()&&j},isVoiceActive(){return Xe.active},toggleReadAloud(a){q.toggleReadAloud(a)},stopReadAloud(){q.stopSpeaking()},getReadAloudState(a){return q.getReadAloudState(a)},onReadAloudChange(a){return q.onReadAloudChange(a)},getState(){return{open:I()&&j,launcherEnabled:k,voiceActive:Xe.active,streaming:q.isStreaming()}},showCSATFeedback(a){!j&&I()&&ut(!0,"system");let g=We.querySelector(".persona-feedback-container");g&&g.remove();let h=Eg({onSubmit:async(x,A)=>{q.isClientTokenMode()&&await q.submitCSATFeedback(x,A),a?.onSubmit?.(x,A)},onDismiss:a?.onDismiss,...a});We.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!j&&I()&&ut(!0,"system");let g=We.querySelector(".persona-feedback-container");g&&g.remove();let h=kg({onSubmit:async(x,A)=>{q.isClientTokenMode()&&await q.submitNPSFeedback(x,A),a?.onSubmit?.(x,A)},onDismiss:a?.onDismiss,...a});We.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,g){return q.submitCSATFeedback(a,g)},async submitNPSFeedback(a,g){return q.submitNPSFeedback(a,g)},destroy(){il(),Po!=null&&(clearInterval(Po),Po=null),Ve.forEach(a=>a()),Ne.remove(),nt?.remove(),$t?.destroy(),Jt?.remove(),So&&E.removeEventListener("click",So)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,g={controller:Pt,getMessages:Pt.getMessages,getStatus:Pt.getStatus,getMetadata:Pt.getPersistentMetadata,updateMetadata:Pt.updatePersistentMetadata,clearHistory:()=>Pt.clearChat(),setVoiceActive:h=>h?Pt.startVoiceRecognition():Pt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Ve.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=V=>{let Y=V.detail;(!Y?.instanceId||Y.instanceId===a)&&Pt.focusInput()};if(window.addEventListener("persona:focusInput",g),Ve.push(()=>{window.removeEventListener("persona:focusInput",g)}),se){let V=de=>{let xe=de.detail;(!xe?.instanceId||xe.instanceId===a)&&Pt.showEventStream()},Y=de=>{let xe=de.detail;(!xe?.instanceId||xe.instanceId===a)&&Pt.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",Y),Ve.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",Y)})}let h=V=>{let Y=V.detail;(!Y?.instanceId||Y.instanceId===a)&&Pt.showArtifacts()},x=V=>{let Y=V.detail;(!Y?.instanceId||Y.instanceId===a)&&Pt.hideArtifacts()},A=V=>{let Y=V.detail;Y?.instanceId&&Y.instanceId!==a||Y?.artifact&&Pt.upsertArtifact(Y.artifact)},W=V=>{let Y=V.detail;Y?.instanceId&&Y.instanceId!==a||typeof Y?.id=="string"&&Pt.selectArtifact(Y.id)},ee=V=>{let Y=V.detail;(!Y?.instanceId||Y.instanceId===a)&&Pt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",ee),Ve.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",ee)})}let gn=ux(o.persistState);if(gn&&I()){let a=fx(gn.storage),g=`${gn.keyPrefix}widget-open`,h=`${gn.keyPrefix}widget-voice`,x=`${gn.keyPrefix}widget-voice-mode`;if(a){let A=gn.persist?.openState&&a.getItem(g)==="true",W=gn.persist?.voiceState&&a.getItem(h)==="true",ee=gn.persist?.voiceState&&a.getItem(x)==="true";if(A&&setTimeout(()=>{Pt.open(),setTimeout(()=>{if(W||ee)Pt.startVoiceRecognition();else if(gn.persist?.focusInput){let V=t.querySelector("textarea");V&&V.focus()}},100)},0),gn.persist?.openState&&(p.on("widget:opened",()=>{a.setItem(g,"true")}),p.on("widget:closed",()=>{a.setItem(g,"false")})),gn.persist?.voiceState&&(p.on("voice:state",V=>{a.setItem(h,V.active?"true":"false")}),p.on("user:message",V=>{a.setItem(x,V.viaVoice?"true":"false")})),gn.clearOnChatClear){let V=()=>{a.removeItem(g),a.removeItem(h),a.removeItem(x)},Y=()=>V();window.addEventListener("persona:clear-chat",Y),Ve.push(()=>{window.removeEventListener("persona:clear-chat",Y)})}}}if(f&&I()&&setTimeout(()=>{Pt.open()},0),Jo(),!Yg){let a=wi(()=>{q&&(Ga++,Mo.clear(),Ur(We,q.getMessages(),Z))});Ve.push(a)}return Pt};var Wg=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},hx=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},yx=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},bx=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Hg=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},$c=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},Bg=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",$c(t)},Oc=t=>{t.style.transition=""},Fc=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},_c=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Oa=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},vx=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},xx=(t,e,n,o,r,s)=>{let i=s?e:t;r==="left"?i.firstElementChild!==o&&i.replaceChildren(o,n):i.lastElementChild!==o&&i.replaceChildren(n,o)},Cx=t=>{let e=br(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Yt(e,r)??r;return{inset:o(n?.inset,ra),canvasBackground:o(n?.canvasBackground,sa)}},Dg=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},wx=(t,e,n,o,r,s,i,l)=>{let p=bn(s),c=p.reveal==="push",d=l!=null,u=l?.inset??"",b=l?.canvasBackground??"";vx(t,e,n,o,c),xx(t,e,n,o,p.side,c),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=p.side,t.dataset.personaDockOpen=i?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=t.ownerDocument.defaultView,m=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,R=f!=null?f.innerWidth<=C:!1;if(m&&R&&i){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Fc(e),Oc(o),Bg(o),_c(n),Oa(r,o),Dg(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Qt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",c&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),Bg(o),hx(o,p.maxHeight),Dg(o,d&&i,u,b),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Fc(e),Oc(o),_c(n),Oa(r,o);let L=p.animate?"transform 180ms ease":"none",T=p.side==="right"?"translateX(100%)":"translateX(-100%)",k=i?"translateX(0)":T;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=L,o.style.transform=k,o.style.pointerEvents=i?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Oc(o),$c(o),Oa(r,o);let L=Wg(p.width,t.clientWidth),T=Math.max(0,t.clientWidth),k=p.animate?"margin-left 180ms ease":"none",$=p.side==="right"?i?-L:0:i?0:-L;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${T+L}px`,e.style.transition=k,e.style.marginLeft=`${$}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${T}px`,n.style.maxWidth=`${T}px`,n.style.minWidth=`${T}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=i?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",Fc(e),$c(o),_c(n),Oa(r,o);let L=p.reveal==="emerge";L?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let T=i?p.width:"0px",k=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${d?", padding 180ms ease":""}`:"none",$=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${T}`,o.style.width=T,o.style.maxWidth=T,o.style.minWidth=T,o.style.minHeight="0",yx(o,p.maxHeight),o.style.overflow=L||$?"hidden":"visible",o.style.transition=k,L){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let G=d?`calc(${Wg(p.width,t.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=G,r.style.minWidth=G,r.style.maxWidth=G,r.style.boxSizing="border-box"}}},Ax=(t,e)=>{let n=t.ownerDocument.createElement("div");return Hg(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Hg(n,o)},destroy(){n.remove()}}},Sx=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,i=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),c=n.createElement("aside"),d=n.createElement("div"),u=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",c.appendChild(d),o.insertBefore(i,t),p.appendChild(t);let b=null,f=()=>{b?.disconnect(),b=null},m=null,C=()=>{m=e?.launcher?.detachedPanel===!0?Cx(e):null};C();let R=()=>{wx(i,l,p,c,d,e,u,m)},H=null,L=()=>{H?.(),H=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(H=ia(()=>{C(),R()}))},T=()=>{f(),bn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{R()}),b.observe(i)))},k=!1,$=()=>{R(),T(),u&&!k&&i.dataset.personaDockMobileFullscreen!=="true"&&(k=!0,bx(i,bn(e)))},G=i.ownerDocument.defaultView,w=()=>{$()};return G?.addEventListener("resize",w),bn(e).reveal==="push"?(l.appendChild(p),l.appendChild(c),i.appendChild(l)):(i.appendChild(p),i.appendChild(c)),$(),L(),{mode:"docked",host:d,shell:i,syncWidgetState(F){let D=F.launcherEnabled?F.open:!0;u!==D&&(u=D,$())},updateConfig(F){e=F,(e?.launcher?.enabled??!0)===!1&&(u=!0),C(),$(),L()},destroy(){G?.removeEventListener("resize",w),H?.(),H=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),i.remove()}}},Ng=(t,e)=>_t(e)?Sx(t,e):Ax(t,e);var $s={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Og=.15,Fg=1.5,zc="persona-preview-shell-theme",Mx={load:()=>null,save:()=>{},clear:()=>{}},Tx=["How do I get started?","Pricing & plans","Talk to support"];function jc(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ex(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function _g(t){let e=Ex(t);return`* { box-sizing: border-box; }
312
+ ${Ct?"background: transparent !important;":""}
313
+ `}if(!x&&!a){let kt="max-height: -moz-available !important; max-height: stretch !important;",rn=f?"":"padding-top: 1.25em !important;",wi=f?"":`z-index: ${o.launcher?.zIndex??Qt} !important;`;De.style.cssText+=kt+rn+wi}yn()};si(),Ps(t,o),qs(t,o),Ks(t,o),Fr=()=>{si(),Ps(t,o),qs(t,o),Ks(t,o),Ys?t.style.setProperty("--persona-artifact-welded-outer-radius",Ys):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let $e=[];$e.push(()=>{document.removeEventListener("keydown",pd)}),$e.push(()=>{Dr!==null&&clearTimeout(Dr)});let Pn=null,In=null;$e.push(()=>{Pn?.(),Pn=null,In?.(),In=null}),Or&&$e.push(()=>{Or?.disconnect(),Or=null}),$e.push(()=>{zr?.(),zr=null,Za(),vt&&(vt.remove(),vt=null),Qe?.element.style.removeProperty("width"),Qe?.element.style.removeProperty("maxWidth")}),ie&&$e.push(()=>{ke!==null&&(cancelAnimationFrame(ke),ke=null),_e?.destroy(),_e=null,Te?.destroy(),Te=null,we=null});let To=null,fd=()=>{To&&(To(),To=null),o.colorScheme==="auto"&&(To=ua(()=>{Ps(t,o)}))};fd(),$e.push(()=>{To&&(To(),To=null)}),$e.push(l);let ii=o.features?.streamAnimation;if(ii?.type&&ii.type!=="none"){let a=Er(ii.type,ii.plugins);a&&(Ea(a,t),$e.push(()=>Zg(t)))}let Ur=ka(bt),md=ka(Jt),hd=ka(gt),jr=[Ur,md,hd];$e.push(()=>{jr.forEach(a=>a.destroy())});let Eo=null,V,ko=null,yd=!1,bd=0,vd=null,xd=a=>a.reduce((f,m)=>m.role==="user"?f+1:f,0),Cd=a=>{for(let f=a.length-1;f>=0;f--)if(gs(a[f]))return a[f].id??null;return null},wd=!1,bm=()=>{wd||o.debug!==!0||(wd=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but copy.showWelcomeCard is false, so no starters render. Use "auto" or "composer".'))},Ad=!1,Sd=!1,Md=(a,f)=>{Ad||o.debug!==!0||!f.enabled||f.expose||yd||Sd&&(V.isStreaming()||a.some(gs)||(Ad=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},Vr=a=>{if(!V)return;let f=a??V.getMessages(),m=re=>{re.render([],V,Q,f)},x=re=>{jr.forEach(me=>{me!==re&&m(me)})};ko&&(xd(f)>bd||Cd(f)!==vd)&&(ko=null);let T=ho(o);Md(f,T);let R=T.enabled?Zp(f):null,ne=ko??R,q=ko?"host":"agent";if(ne){let re=o.suggestions?.followUps,me=re?.placement??(re?"auto":"composer"),Ae=(me==="auto"?P()?"composer":"after-message":me)==="after-message"?hd:Ur;x(Ae),Ae.render(ne,V,Q,f,o.suggestionChipsConfig,{source:q,surface:"followUp",variant:re?.variant??"chip",behavior:re?.behavior??"send",overflow:re?.overflow??"scroll",maxItems:re?.maxItems??4,config:o,plugins:s});return}if(f.some(re=>re.role==="user")){jr.forEach(m);return}let Z=o.suggestions?.starters;if(Z){let re=o.copy?.showWelcomeCard!==!1,me=Z.placement??"auto",ce=me==="auto"?re?"welcome":"composer":me;if(ce==="welcome"&&!re){bm(),jr.forEach(m);return}let Ae=ce==="welcome"?md:Ur;x(Ae),Ae.render(Z.items??o.suggestionChips,V,Q,f,o.suggestionChipsConfig,{surface:"starter",variant:Z.variant??"card",behavior:Z.behavior??"send",overflow:Z.overflow??"wrap",maxItems:Z.maxItems??4,config:o,plugins:s});return}x(Ur),Ur.render(o.suggestionChips,V,Q,f,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:s})},Td=()=>{ko&&(ko=null,Vr())},vm=a=>{let f=Array.isArray(a)?[...a]:[];if(!f.length){Td();return}let m=V?V.getMessages():[];ko=f,yd=!0,bd=xd(m),vd=Cd(m),Vr(m)},An=!1,Lo=Ug(),Zo=new Map,Po=new Map,to=new Map,el=0,xm=Un()!==null,an=Ca(),gn=0,no=null,fn=!1,ai=!1,oo=0,Sn=null,Io=null,tl=!1,li=!1,qr=null,Kr=!0,ci=!1,di=null,pi=!1,Ro=()=>{pi=!0},nl=null,Cm=4,ui=24,wm=80,ol=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ed=o.voiceRecognition?.autoResume??!1,On=a=>{p.emit("voice:state",{active:Ke.active,source:a,timestamp:Date.now()})},Mn=()=>{L(a=>({...a,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Am=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=Uc(u.voiceState),f=!!a.active,m=Number(a.timestamp??0);Ke.manuallyDeactivated=!!a.manuallyDeactivated,f&&Date.now()-m<Bx&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?V.toggleVoice().then(()=>{Ke.active=V.isVoiceActive(),On("restore"),V.isVoiceActive()&&rr()}):yi("restore"))},1e3)},Sm=()=>V?Kf(V.getMessages()).filter(a=>!a.__skipPersist):[],gi=null,kd=(a,f)=>{typeof console<"u"&&console.error(a,f)},rl=(a,f)=>{let m=()=>{try{let ne=a();return!ne||typeof ne.then!="function"?null:Promise.resolve(ne).catch(q=>{kd(f,q)})}catch(ne){return kd(f,ne),null}},x=gi,T=x?x.then(()=>m()??void 0):m();if(!T)return;let R=T.finally(()=>{gi===R&&(gi=null)});gi=R};function sl(a){if(!d?.save)return;let m={messages:a?Kf(a):V?Sm():[],metadata:u,artifacts:Cn.artifacts,selectedArtifactId:Cn.selectedId};rl(()=>d.save(m),"[AgentWidget] Failed to persist state:")}let er=null,Ld=()=>De.querySelector("#persona-scroll-container")||ue,Gr=()=>{er!==null&&(cancelAnimationFrame(er),er=null),fn=!1},Pd=()=>{no!==null&&(cancelAnimationFrame(no),no=null),ai=!1,Gr()},Mm=()=>An&&al()&&(un()!=="anchor-top"||Yc()),il=()=>{let a=Jn()||"Jump to latest",f=Mm();Lt.toggleAttribute("data-persona-scroll-to-bottom-streaming",f),oo>0?(Ao.textContent=String(oo),Ao.style.display="",Lt.setAttribute("aria-label",`${a} (${oo} new)`)):(Ao.textContent="",Ao.style.display="none",Lt.setAttribute("aria-label",f?`${a} (response streaming below)`:a))},Id=()=>{oo!==0&&(oo=0,il())},al=()=>Yn()?!an.isFollowing():!Co(ue,ui),ln=()=>{if(!dm()||Ve){Lt.parentNode&&Lt.remove(),Lt.style.display="none";return}Lt.parentNode!==xe&&xe.appendChild(Lt),Qo();let f=Hn(ue)>0&&al();f?il():Id(),Lt.style.display=f?"":"none"},Qr=()=>{an.pause()&&(Pd(),ln())},ro=()=>{an.resume(),Id(),ln()},so=(a=!1)=>{Yn()&&an.isFollowing()&&(!a&&!An||(no!==null&&(cancelAnimationFrame(no),no=null),ai=!0,no=requestAnimationFrame(()=>{no=null,ai=!1,an.isFollowing()&&Tm(Ld(),a?220:140)})))},Rd=(a,f,m,x=()=>!0)=>{let T=a.scrollTop,R=f(),ne=R-T;if(Gr(),Math.abs(ne)<1){fn=!0,a.scrollTop=R,gn=a.scrollTop,fn=!1;return}let q=performance.now();fn=!0;let Z=me=>1-Math.pow(1-me,3),re=me=>{if(!x()){Gr();return}let ce=f();ce!==R&&(R=ce,ne=R-T);let Ae=me-q,je=Math.min(Ae/m,1),dt=Z(je),tt=T+ne*dt;a.scrollTop=tt,gn=a.scrollTop,je<1?er=requestAnimationFrame(re):(a.scrollTop=R,gn=a.scrollTop,er=null,fn=!1)};er=requestAnimationFrame(re)},Tm=(a,f=500)=>{let m=Hn(a)-a.scrollTop;if(Math.abs(m)<1){gn=a.scrollTop;return}if(Math.abs(m)>=wm){Gr(),fn=!0,a.scrollTop=Hn(a),gn=a.scrollTop,fn=!1;return}Rd(a,()=>Hn(a),f,()=>an.isFollowing())},Wd=()=>{let a=Ld();fn=!0,a.scrollTop=Hn(a),gn=a.scrollTop,fn=!1,ln()},Hd=a=>{let f=0,m=a;for(;m&&m!==ue;)f+=m.offsetTop,m=m.offsetParent;return f},Em=()=>{let a=ue.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??ue.ownerDocument.getSelection()},fi=()=>Gg(Em(),ue),Bd=()=>{if(pm()!=="last-user-turn")return!1;let a=V?.getMessages()??[];if(a.length<2)return!1;let f=[...a].reverse().find(R=>R.role==="user");if(!f)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(f.id):f.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=ue.querySelector(`[data-message-id="${m}"]`);if(!x)return!1;let T=Math.min(Math.max(0,Hd(x)-Xc()),Hn(ue));return fn=!0,ue.scrollTop=T,gn=ue.scrollTop,fn=!1,un()==="follow"&&!Co(ue,ui)&&an.pause(),ln(),!0},Dd=a=>{Zn.style.height=`${Math.max(0,Math.round(a))}px`,Sn&&(Sn.spacerHeight=Math.max(0,a))},Xr=()=>{Io!==null&&(cancelAnimationFrame(Io),Io=null),Gr(),Sn=null,Zn.style.height="0px"},Nd=a=>{Io!==null&&cancelAnimationFrame(Io),Io=requestAnimationFrame(()=>{Io=null;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),m=ue.querySelector(`[data-message-id="${f}"]`);if(!m)return;let x=Hd(m),T=Sn?.spacerHeight??0,R=ue.scrollHeight-T,{targetScrollTop:ne,spacerHeight:q}=Qg({anchorOffsetTop:x,topOffset:Xc(),viewportHeight:ue.clientHeight,contentHeight:R});Sn={initialSpacerHeight:q,contentHeightAtAnchor:R,spacerHeight:q},Dd(q),Rd(ue,()=>ne,220)})},km=()=>{if(Yn()){if(!an.isFollowing()||Co(ue,1))return;so(!An);return}if(Sn&&Sn.initialSpacerHeight>0){let a=ue.scrollHeight-Sn.spacerHeight,f=Xg({initialSpacerHeight:Sn.initialSpacerHeight,contentHeightAtAnchor:Sn.contentHeightAtAnchor,currentContentHeight:a});f!==Sn.spacerHeight&&Dd(f)}ln()},Lm=a=>{let f=un();f==="follow"?(ro(),so(!0)):f==="anchor-top"&&(Kr=!1,ci=!0,pi=!1,di=a,Nd(a))},Pm=()=>{if(un()==="anchor-top"){if(ci){Kr=!1;return}Kr=!0,Xr(),ro(),so(!0)}},Im=a=>{if(un()!=="anchor-top"||!ci||pi||fi())return;let f=qr===null;for(let m of a){if(!f){m.id===qr&&(f=!0);continue}if(Kg(m)){if(m.id===di)return;di=m.id,Nd(m.id);return}}},Rm=a=>{let f=new Map;a.forEach(m=>{let x=ol.get(m.id);f.set(m.id,{streaming:m.streaming,role:m.role}),!x&&m.role==="assistant"&&(p.emit("assistant:message",m),!li&&(un()!=="anchor-top"||Yc())&&al()&&(oo+=1,il(),ln(),ed(oo===1?"1 new message below.":`${oo} new messages below.`))),m.role==="assistant"&&x?.streaming&&m.streaming===!1&&p.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(x?m.approval.status!=="pending"&&p.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):p.emit("approval:requested",{approval:m.approval,message:m}))}),ol.clear(),f.forEach((m,x)=>{ol.set(x,m)})},mi=(a,f)=>{let m=f==="user"?"user":"assistant",x=o.layout?.messages?.[m],T=x?.width??"content",R=x?.maxWidth??(T==="full"?"100%":"85%");a.classList.add("persona-message-row"),a.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),a.classList.add(`persona-message-row-${f}`,`persona-message-width-${T}`),a.classList.toggle("persona-justify-end",f==="user"),a.setAttribute("data-message-role",f),a.setAttribute("data-message-width",T),a.style.setProperty("--persona-message-row-max-width",R)},Wo=(a,f)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${a}`,m.setAttribute("data-wrapper-id",a),mi(m,f),m},Wm=(a,f,m)=>{let x=document.createElement("div"),R=(()=>{let _=s.find(Pe=>Pe.renderLoadingIndicator);if(_?.renderLoadingIndicator)return _.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),ne=(_,Pe)=>Pe==null?!1:typeof Pe=="string"?(_.textContent=Pe,!0):(_.appendChild(Pe),!0),q=new Set,Z=new Map,re=new Set,me=s.some(_=>_.renderAskUserQuestion),ce=[],Ae=[],je=o.enableComponentStreaming!==!1,dt=o.approval!==!1,tt=[];if(f.forEach(_=>{q.add(_.id),Z.set(_.id,_.role);let Pe=me&&Oo(_),Oe=dt&&_.variant==="approval"&&!!_.approval,Ee=!Pe&&_.role==="assistant"&&!_.variant&&je&&zc(_);!Oe&&to.has(_.id)&&(a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),to.delete(_.id)),!Ee&&Po.has(_.id)&&(a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Po.delete(_.id));let St=Oo(_)?`:${_.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${_.agentMetadata?.askUserQuestionAnswers?Object.keys(_.agentMetadata.askUserQuestionAnswers).length:0}`:"",pt=zg(_,el)+St,Ft=Pe||Oe||Ee?null:jg(Lo,_.id,pt);if(Ft){x.appendChild(Ft.cloneNode(!0)),Oo(_)&&_.toolCall?.id&&_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(re.add(_.toolCall.id),Hi(_,o,He.composerOverlay));return}let ut=null,on=s.find(Fe=>!!(_.variant==="reasoning"&&Fe.renderReasoning||_.variant==="tool"&&Fe.renderToolCall||!_.variant&&Fe.renderMessage)),Rt=o.layout?.messages;if(Oo(_)&&_.agentMetadata?.askUserQuestionAnswered===!0){Zo.delete(_.id),a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime");return}if(gs(_)&&ho(o).enabled)return;if(Oo(_)&&o.features?.askUserQuestion?.enabled!==!1){let Fe=s.find(jt=>typeof jt.renderAskUserQuestion=="function");if(Fe&&at.current){let jt=Zo.get(_.id),Vt=jt!==pt,Ct=null;if(Vt){let{payload:Xe,complete:Be}=ur(_),yt=_.id,qt=()=>at.current?.getMessages().find(yn=>yn.id===yt);Ct=Fe.renderAskUserQuestion({message:_,payload:Xe,complete:Be,resolve:yn=>{let is=qt();is&&at.current?.resolveAskUserQuestion(is,yn)},dismiss:()=>{let yn=qt();yn?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(yn),at.current?.resolveAskUserQuestion(yn,"(dismissed)"))},config:o})}let lt=jt!=null;if(Vt&&Ct===null&&!lt){_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(re.add(_.toolCall.id),Hi(_,o,He.composerOverlay));return}let ft=Wo(_.id,_.role);ft.setAttribute("data-ask-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),x.appendChild(ft),ce.push({messageId:_.id,fingerprint:pt,bubble:Ct});return}else{_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(re.add(_.toolCall.id),Hi(_,o,He.composerOverlay));return}}else if(Oe){let Fe=s.find(lt=>typeof lt.renderApproval=="function")??i,Vt=to.get(_.id)!==pt,Ct=null;if(Vt&&Fe?.renderApproval){let lt=_.id,ft=(Xe,Be)=>{let yt=at.current?.getMessages().find(qt=>qt.id===lt);yt?.approval&&(yt.approval.toolType==="webmcp"?at.current?.resolveWebMcpApproval(yt.id,Xe):at.current?.resolveApproval(yt.approval,Xe,Be))};Ct=Fe.renderApproval({message:_,defaultRenderer:()=>$a(_,o),config:o,approve:Xe=>ft("approved",Xe),deny:Xe=>ft("denied",Xe)})}if(Vt&&Ct===null)a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),to.delete(_.id),ut=$a(_,o);else{let lt=Wo(_.id,_.role);lt.setAttribute("data-approval-plugin-stub","true"),lt.setAttribute("data-preserve-runtime","true"),x.appendChild(lt),tt.push({messageId:_.id,fingerprint:pt,bubble:Ct});return}}else if(on)if(_.variant==="reasoning"&&_.reasoning&&on.renderReasoning){if(!oe)return;ut=on.renderReasoning({message:_,defaultRenderer:()=>Sc(_,o),config:o})}else if(_.variant==="tool"&&_.toolCall&&on.renderToolCall){if(!J)return;ut=on.renderToolCall({message:_,defaultRenderer:()=>Tc(_,o),config:o})}else on.renderMessage&&(ut=on.renderMessage({message:_,defaultRenderer:()=>{let Fe=Ac(_,m,Rt,o.messageActions,Ge,{loadingIndicatorRenderer:R,widgetConfig:o});return _.role!=="user"&&Bc(Fe,_,o,V),Fe},config:o}));if(!ut&&Ee){let Fe=jf(_);if(Fe){let jt=Po.get(_.id),Vt=jt!==pt,Ct=o.wrapComponentDirectiveInBubble!==!1&&Qn.getOptions(Fe.component)?.bubbleChrome!==!1,lt=null;if(Vt){let ft=zf(Fe,{config:o,message:_,transform:m});if(ft&&Fe.component==="PersonaArtifactInline"){let Xe=ft.hasAttribute("data-artifact-inline")?ft:ft.querySelector("[data-artifact-inline]"),Be=Xe?.getAttribute("data-artifact-inline")??"",yt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Be):Be,qt=Be?a.querySelector(`#wrapper-${_.id}`)?.querySelector(`[data-artifact-inline="${yt}"]`)??null:null;Xe&&qt&&qt!==Xe&&Dg(qt)&&(Xe===ft?ft=qt:Xe.replaceWith(qt))}if(ft)if(Ct){let Xe=document.createElement("div");if(Xe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Xe.id=`bubble-${_.id}`,Xe.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let Be=document.createElement("div");Be.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Be.innerHTML=m({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),Xe.appendChild(Be)}Xe.appendChild(ft),lt=Xe}else{let Xe=document.createElement("div");if(Xe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Xe.id=`bubble-${_.id}`,Xe.setAttribute("data-message-id",_.id),Xe.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let Be=document.createElement("div");Be.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Be.innerHTML=m({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),Xe.appendChild(Be)}Xe.appendChild(ft),lt=Xe}}if(lt||jt!=null){let ft=Wo(_.id,_.role);ft.setAttribute("data-component-directive-stub","true"),ft.setAttribute("data-preserve-runtime","true"),x.appendChild(ft),Ae.push({messageId:_.id,fingerprint:pt,bubble:lt});return}}}if(!ut)if(_.variant==="reasoning"&&_.reasoning){if(!oe)return;ut=Sc(_,o)}else if(_.variant==="tool"&&_.toolCall){if(!J)return;ut=Tc(_,o)}else if(_.variant==="approval"&&_.approval){if(o.approval===!1)return;ut=$a(_,o)}else{let Fe=o.layout?.messages;Fe?.renderUserMessage&&_.role==="user"?ut=Fe.renderUserMessage({message:_,config:o,streaming:!!_.streaming}):Fe?.renderAssistantMessage&&_.role==="assistant"?ut=Fe.renderAssistantMessage({message:_,config:o,streaming:!!_.streaming}):ut=Ac(_,m,Fe,o.messageActions,Ge,{loadingIndicatorRenderer:R,widgetConfig:o}),_.role!=="user"&&ut&&Bc(ut,_,o,V)}let Ie=Wo(_.id,_.role);Ie.appendChild(ut),Vg(Lo,_.id,pt,Ie),x.appendChild(Ie)}),He.composerOverlay&&He.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Pe=>{let Oe=Pe.getAttribute("data-persona-ask-sheet-for");Oe&&!re.has(Oe)&&fr(He.composerOverlay,Oe)}),o.features?.toolCallDisplay?.grouped){let _=[],Pe=[],Oe=o.features.toolCallDisplay.groupedMode==="summary";f.forEach(Ee=>{if(Ee.variant==="tool"&&Ee.toolCall&&J){Pe.push(Ee);return}Ee.variant==="reasoning"&&!oe||((Pe.length>1||Oe&&Pe.length>0)&&_.push(Pe),Pe=[])}),(Pe.length>1||Oe&&Pe.length>0)&&_.push(Pe),_.forEach(Ee=>{let St=Ee.map(Fe=>Array.from(x.children).find(jt=>jt instanceof HTMLElement&&jt.getAttribute("data-wrapper-id")===Fe.id)).filter(Fe=>!!Fe);if(St.length<(Oe?1:2))return;let pt=Wo(`tool-group-${Ee[0].id}`,"assistant");pt.setAttribute("data-persona-tool-group-row","true");let Ft=document.createElement("div");Ft.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ft.setAttribute("data-persona-tool-group","true");let ut=document.createElement("div");ut.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ut.id=`tool-group-summary-${Ee[0].id}`;let on=`Called ${Ee.length} ${Ee.length===1?"tool":"tools"}`,Rt=o.toolCall?.renderGroupedSummary?.({messages:Ee,toolCalls:Ee.map(Fe=>Fe.toolCall).filter(Fe=>!!Fe),defaultSummary:on,config:o});ne(ut,Rt)||(ut.textContent=on);let Ie=document.createElement("div");Ie.className="persona-tool-group-stack persona-flex persona-flex-col",Ie.id=`tool-group-stack-${Ee[0].id}`,Ie.setAttribute("data-persona-tool-group-stack","true"),Ft.appendChild(ut),Oe||Ft.appendChild(Ie),pt.appendChild(Ft),St[0].before(pt),St.forEach((Fe,jt)=>{if(Oe){Fe.remove();return}Fe.style.setProperty("--persona-message-row-max-width","100%");let Vt=document.createElement("div");Vt.className="persona-tool-group-item persona-relative",Vt.setAttribute("data-persona-tool-group-item","true"),jt<St.length-1&&Vt.setAttribute("data-persona-tool-group-connector","true"),Vt.appendChild(Fe),Ie.appendChild(Vt)})})}qg(Lo,q);let cn=f.some(_=>_.role==="assistant"&&_.streaming),Et=f[f.length-1],It=Et?.role==="assistant"&&!Et.streaming&&Et.variant!=="approval";if(An&&f.some(_=>_.role==="user")&&!cn&&!It){let _={config:o,streaming:!0,location:"standalone",defaultRenderer:zs},Pe=s.find(Ee=>Ee.renderLoadingIndicator),Oe=null;if(Pe?.renderLoadingIndicator&&(Oe=Pe.renderLoadingIndicator(_)),Oe===null&&o.loadingIndicator?.render&&(Oe=o.loadingIndicator.render(_)),Oe===null&&(Oe=zs()),Oe){let Ee=document.createElement("div"),St=o.loadingIndicator?.showBubble!==!1,pt=o.layout?.messages?.layout??"bubble";Ee.className=St?wc("assistant",pt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ee.setAttribute("data-typing-indicator","true"),St&&(Ee.style.color="var(--persona-message-assistant-text, var(--persona-text))",pt!=="flat"&&(Ee.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ee.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ee.appendChild(Oe);let Ft=Wo("typing-indicator","assistant");Ft.appendChild(Ee),x.appendChild(Ft)}}if(!An&&f.length>0){let _=f[f.length-1],Pe={config:o,lastMessage:_,messageCount:f.length},Oe=s.find(St=>St.renderIdleIndicator),Ee=null;if(Oe?.renderIdleIndicator&&(Ee=Oe.renderIdleIndicator(Pe)),Ee===null&&o.loadingIndicator?.renderIdle&&(Ee=o.loadingIndicator.renderIdle(Pe)),Ee){let St=document.createElement("div"),pt=o.loadingIndicator?.showBubble!==!1;St.className=pt?["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-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),St.setAttribute("data-idle-indicator","true"),St.appendChild(Ee);let Ft=Wo("idle-indicator","assistant");Ft.appendChild(St),x.appendChild(Ft)}}if(Ip(x),xa(a,x),Al(a),ce.length>0)for(let{messageId:_,fingerprint:Pe,bubble:Oe}of ce){let Ee=a.querySelector(`#wrapper-${_}`);Ee&&(mi(Ee,Z.get(_)??"assistant"),Oe!==null&&(Ee.replaceChildren(Oe),Ee.setAttribute("data-bubble-fp",Pe),Zo.set(_,Pe)))}if(Zo.size>0)for(let _ of Zo.keys())q.has(_)||Zo.delete(_);if(Ae.length>0)for(let{messageId:_,fingerprint:Pe,bubble:Oe}of Ae){let Ee=a.querySelector(`#wrapper-${_}`);Ee&&(mi(Ee,Z.get(_)??"assistant"),Oe!==null&&(Ee.replaceChildren(Oe),Ee.setAttribute("data-bubble-fp",Pe),Po.set(_,Pe)))}if(Po.size>0)for(let _ of Po.keys())q.has(_)||Po.delete(_);if(tt.length>0)for(let{messageId:_,fingerprint:Pe,bubble:Oe}of tt){let Ee=a.querySelector(`#wrapper-${_}`);Ee&&(mi(Ee,Z.get(_)??"assistant"),Oe!==null&&(Ee.replaceChildren(Oe),Ee.setAttribute("data-bubble-fp",Pe),to.set(_,Pe)))}if(to.size>0)for(let _ of to.keys())q.has(_)||to.delete(_)},Jr=(a,f,m)=>{Wm(a,f,m),ld()},Yr=null,Hm=()=>{if(Yr)return;let a=m=>{let x=m.composedPath();x.includes(De)||Ye&&x.includes(Ye)||ct(!1,"user")};Yr=a,(t.ownerDocument??document).addEventListener("pointerdown",a,!0)},Od=()=>{if(!Yr)return;(t.ownerDocument??document).removeEventListener("pointerdown",Yr,!0),Yr=null};$e.push(()=>Od());let Zr=null,Bm=()=>{if(Zr)return;let a=m=>{m.key==="Escape"&&(m.isComposing||ct(!1,"user"))};Zr=a,(t.ownerDocument??document).addEventListener("keydown",a,!0)},Fd=()=>{if(!Zr)return;(t.ownerDocument??document).removeEventListener("keydown",Zr,!0),Zr=null};$e.push(()=>Fd());let es=!1,_d=new Set,Dm=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},tr=()=>{if(!P())return;let a=He.peekBanner,f=He.peekTextNode;if(!a||!f)return;if(j){a.classList.remove("persona-pill-peek--visible");return}let m=V?.getMessages()??[],x;for(let Et=m.length-1;Et>=0;Et--){let It=m[Et];if(It.role==="assistant"&&It.content){x=It;break}}if(!x){a.classList.remove("persona-pill-peek--visible");return}let T=x.content,R=!!x.streaming,ne=Dm(),q=Sa(ne),Z=q.type!=="none"?Er(q.type,ne?.plugins):null,re=Z?.isAnimating?.(x)===!0,me=Z!==null&&(R||re);me&&Z&&!_d.has(Z.name)&&(Ea(Z,t),_d.add(Z.name));let ce=me&&Z?.containerClass?Z.containerClass:null,Ae=f.dataset.personaPeekStreamClass??null;Ae&&Ae!==ce&&(f.classList.remove(Ae),delete f.dataset.personaPeekStreamClass),ce&&Ae!==ce&&(f.classList.add(ce),f.dataset.personaPeekStreamClass=ce),me?(f.style.setProperty("--persona-stream-step",`${q.speed}ms`),f.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let je=me?Ma(T,q.buffer,Z,x,R):T;if(me&&q.placeholder==="skeleton"&&R&&(!je||!je.trim())){let Et=document.createElement("div"),It=Ns();It.classList.add("persona-pill-peek__skeleton"),Et.appendChild(It),xa(f,Et)}else{let Et=Math.max(0,je.length-100),It=je.length>100?je.slice(-100):je,_=po(It);if(!me||!Z){let Pe=je.length>100?`\u2026${It}`:It;f.textContent!==Pe&&(f.textContent=Pe)}else{let Pe=_;(Z.wrap==="char"||Z.wrap==="word")&&(Pe=Ds(_,Z.wrap,`peek-${x.id}`,{skipTags:Z.skipTags,startIndex:Et}));let Oe=document.createElement("div");if(Oe.innerHTML=Pe,Z.useCaret&&It.length>0){let Ee=Ta(),St=Oe.querySelectorAll(".persona-stream-char, .persona-stream-word"),pt=St[St.length-1];pt?.parentNode?pt.parentNode.insertBefore(Ee,pt.nextSibling):Oe.appendChild(Ee)}xa(f,Oe),Z.onAfterRender?.({container:f,bubble:a,messageId:x.id,message:x,speed:q.speed,duration:q.duration})}}let cn=An||es;a.classList.toggle("persona-pill-peek--visible",cn)};if(P()){let a=He.peekBanner;if(a){let x=T=>{T.preventDefault(),T.stopPropagation(),ct(!0,"user")};a.addEventListener("pointerdown",x),$e.push(()=>{a.removeEventListener("pointerdown",x)})}let f=()=>{es||(es=!0,tr())},m=()=>{es&&(es=!1,tr())};ye.addEventListener("pointerenter",f),ye.addEventListener("pointerleave",m),$e.push(()=>{ye.removeEventListener("pointerenter",f),ye.removeEventListener("pointerleave",m)}),Ye&&(Ye.addEventListener("pointerenter",f),Ye.addEventListener("pointerleave",m),$e.push(()=>{Ye.removeEventListener("pointerenter",f),Ye.removeEventListener("pointerleave",m)}))}let Nm=a=>{let f=o.launcher?.composerBar??{},m=f.expandedSize??"anchored",x=f.bottomOffset??"16px",T=f.collapsedMaxWidth,R=f.expandedMaxWidth??"880px",ne=f.expandedTopOffset??"5vh",q=f.modalMaxWidth??"880px",Z=f.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",ce=De.style;if(ce.left="",ce.right="",ce.top="",ce.bottom="",ce.transform="",ce.width="",ce.maxWidth="",ce.height="",ce.maxHeight="",Ye){let Ae=Ye.style;Ae.bottom=x,Ae.width=T??""}if(a&&m!=="fullscreen"){if(m==="modal"){ce.top="50%",ce.left="50%",ce.transform="translate(-50%, -50%)",ce.bottom="auto",ce.right="auto",ce.width=q,ce.maxWidth=re,ce.maxHeight=Z,ce.height=Z;return}ce.left="50%",ce.transform="translateX(-50%)",ce.bottom=`calc(${x} + ${me})`,ce.top=ne,ce.width=R,ce.maxWidth=re}},ts=()=>{if(!I())return;if(P()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",me=j?"expanded":"collapsed";De.dataset.state=me,De.dataset.expandedSize=re,Ye&&(Ye.dataset.state=me,Ye.dataset.expandedSize=re),De.style.removeProperty("display"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Nm(j),xe.style.display=j?"flex":"none",si(),j?(Hm(),Bm()):(Od(),Fd()),tr();return}let a=_t(o),f=t.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,T=f.innerWidth<=m,R=x&&T&&E,ne=xn(o).reveal;j?(De.style.removeProperty("display"),De.style.display=a?"flex":"",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0"),ye.classList.add("persona-scale-100","persona-opacity-100"),$t?$t.element.style.display="none":Zt&&(Zt.style.display="none")):(a?a&&(ne==="overlay"||ne==="push")&&!R?(De.style.removeProperty("display"),De.style.display="flex",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.setProperty("display","none","important"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.display="",De.classList.add("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100"),ye.classList.add("persona-scale-95","persona-opacity-0")),$t?$t.element.style.display=a?"none":"":Zt&&(Zt.style.display=a?"none":""))},ct=(a,f="user")=>{if(!I()||j===a)return;let m=j;j=a,ts();let x=(()=>{let R=o.launcher?.sidebarMode??!1,ne=t.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,Z=o.launcher?.mobileBreakpoint??640,re=ne.innerWidth<=Z,me=_t(o)&&q&&re,ce=P()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return R||q&&re&&E||me||ce})();if(j&&x){if(!Pn){let R=t.getRootNode(),ne=R instanceof ShadowRoot?R.host:t.closest(".persona-host");ne&&(Pn=mc(ne,o.launcher?.zIndex??Qt))}In||(In=hc(t.ownerDocument))}else j||(Pn?.(),Pn=null,In?.(),In=null);j&&(rs(),Bd()||(un()==="follow"?so(!0):Wd()));let T={open:j,source:f,timestamp:Date.now()};j&&!m?p.emit("widget:opened",T):!j&&m&&p.emit("widget:closed",T),p.emit("widget:state",{open:j,launcherEnabled:E,voiceActive:Ke.active,streaming:V.isStreaming()})},ll=a=>{Ze(a?"stop":"send"),X&&(X.disabled=a),jr.forEach(f=>{f.elements.forEach(m=>{m.toggleAttribute("data-disabled",a),m instanceof HTMLButtonElement||m.setAttribute("aria-disabled",a?"true":"false")}),f.buttons.forEach(m=>{m.disabled=a})}),Se.dataset.personaComposerStreaming=a?"true":"false",Se.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=a)})},cl=()=>{Ke.active||Q&&Q.focus()};p.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>cl(),200)});let $d=()=>{N.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",$.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",Q.placeholder=o.copy?.inputPlaceholder??"How can I help...";let a=ue.querySelector("[data-persona-intro-card]");if(a){let m=o.copy?.showWelcomeCard!==!1;a.style.display=m?"":"none",m?(ue.classList.remove("persona-gap-3"),ue.classList.add("persona-gap-6")):(ue.classList.remove("persona-gap-6"),ue.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!V?.isStreaming()&&(w.textContent=o.copy?.sendButtonLabel??"Send"),Q.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Q.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let a=u.sessionId;return typeof a=="string"?a:null},setStoredSessionId:a=>{L(f=>({...f,sessionId:a}))}});let Ho=null,Om=()=>{Ho==null&&(Ho=setInterval(()=>{let a=We.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(Ho),Ho=null;return}let f=Date.now();a.forEach(m=>{let x=Number(m.getAttribute("data-tool-elapsed"));x&&(m.textContent=Ni(f-x))})},100))},dl=(a,f)=>{if(Object.is(a,f))return!0;if(a===null||f===null||typeof a!="object"||typeof f!="object")return!1;if(Array.isArray(a)||Array.isArray(f))return!Array.isArray(a)||!Array.isArray(f)||a.length!==f.length?!1:a.every((ne,q)=>dl(ne,f[q]));let m=a,x=f,T=Object.keys(m),R=Object.keys(x);return T.length===R.length&&T.every(ne=>Object.prototype.hasOwnProperty.call(x,ne)&&dl(m[ne],x[ne]))},zd=a=>{let{content:f,rawContent:m,llmContent:x,...T}=a;return T},pl=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!zc(a),Fm=(a,f,m)=>{if(a.length!==f.length)return!1;let x=a[m.index],T=f[m.index];return!x||!T||x.id!==m.id||T.id!==m.id?!1:(!Object.is(x.content,T.content)||!Object.is(x.rawContent,T.rawContent)||!Object.is(x.llmContent,T.llmContent))&&pl(x)&&pl(T)&&dl(zd(x),zd(T))},Ud=null,nr=null,Bo=null,Fn=null,hi=a=>{Ud=a;let f,m;nr=null;for(let T=a.length-1;T>=0;T-=1){let R=a[T];if(!f&&R.role==="user"&&(f=R),!m&&R.role==="assistant"&&(m=R),!nr&&pl(R)&&(nr={index:T,id:R.id}),f&&m&&nr)break}Jr(We,a,Y),cc(We,Cn.artifacts,{suppressTransition:An}),Om(),Vr(a),so(!An),Rm(a),a.length===0&&(Xr(),Kr=!0,ci=!1,di=null,pi=!1),!tl||li?(tl=!0,qr=f?.id??null,nl=m?.id??null):f&&f.id!==qr?(qr=f.id,Lm(f.id)):m&&m.id!==nl&&Pm(),m&&(nl=m.id),Im(a);let x=Ke.lastUserMessageId;f&&f.id!==x&&(Ke.lastUserMessageId=f.id,p.emit("user:message",f)),Ke.lastUserMessageWasVoice=!!f?.viaVoice,sl(a),tr()},ul=()=>{Fn!==null&&(cancelAnimationFrame(Fn),Fn=null);let a=Bo;Bo=null,a&&hi(a)},jd=()=>{Fn!==null&&cancelAnimationFrame(Fn),Fn=null,Bo=null},_m=a=>{let f=Bo??Ud;if(An&&f&&nr&&Fm(f,a,nr)){Bo=a,Fn===null&&(Fn=requestAnimationFrame(()=>{Fn=null;let m=Bo;Bo=null,m&&hi(m)}));return}if(a.length===0){jd(),hi(a);return}ul(),hi(a)};V=new Ki(o,{onMessagesChanged(a){_m(a)},onStatusChanged(a){let f=o.statusIndicator??{};Xt(H,(x=>x==="idle"?f.idleText??Wt.idle:x==="connecting"?f.connectingText??Wt.connecting:x==="connected"?f.connectedText??Wt.connected:x==="error"?f.errorText??Wt.error:x==="paused"?f.pausedText??Wt.paused:x==="resuming"?f.resumingText??Wt.resuming:Wt[x])(a),f,a)},onStreamingChanged(a){a||(V?.getMessages().length===0?jd():ul()),An=a,ll(a),V&&Jr(We,V.getMessages(),Y),a||(so(!0),Sd=!0,V&&Md(V.getMessages(),ho(o))),ln(),ed(a?"Responding\u2026":"Response complete."),tr()},onVoiceStatusChanged(a){if(p.emit("voice:status",{status:a,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(a){case"listening":_n(),rr();break;case"processing":_n(),Jm();break;case"speaking":_n(),Ym();break;default:a==="idle"&&V.isBargeInActive()?(_n(),rr(),X?.setAttribute("aria-label","End voice session")):(Ke.active=!1,_n(),On("system"),Mn());break}},onArtifactsState(a){Cn=a,a.artifacts.length===0&&(Xo=!1),cc(We,a.artifacts,{suppressTransition:An}),Nn(),sl()},onReconnect(a){let{executionId:f,lastEventId:m}=a.handle;a.phase==="paused"?p.emit("stream:paused",{executionId:f,after:m}):a.phase==="resuming"?p.emit("stream:resuming",{executionId:f,after:m,attempt:a.attempt??1}):p.emit("stream:resumed",{executionId:f,after:m})}}),at.current=V,$e.push(()=>V.cancel());let gl=null;if(V.onReadAloudChange((a,f)=>{id=a,ad=f,ld();let m=a??gl;a&&(gl=a);let x=m?V.getMessages().find(T=>T.id===m)??null:null;p.emit("message:read-aloud",{messageId:m,message:x,state:f,timestamp:Date.now()}),f==="idle"&&(gl=null)}),tl=!0,o.voiceRecognition?.provider?.type==="runtype")try{V.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}o.clientToken&&V.initClientSession().catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)}),(Te||o.onSSEEvent)&&V.setSSEEventCallback((a,f)=>{o.onSSEEvent?.(a,f),Me?.processEvent(a,f),Te?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(f)})});let Vd=()=>{o.resume&&typeof o.reconnectStream=="function"&&V.resumeFromHandle(o.resume)};b?b.then(a=>{if(a){if(a.metadata&&(u=Uc(a.metadata),S.syncFromMetadata()),a.messages?.length){li=!0;try{V.hydrateMessages(a.messages)}finally{li=!1}}a.artifacts?.length&&V.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>Vd()):Vd();let qd=()=>{!P()||j||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ct(!0,"auto")},$m=(a,f)=>a?f?{refs:[...a.refs,...f.refs],finalize:async()=>{let[m,x]=await Promise.allSettled([a.finalize(),f.finalize()]),T=[];return m.status==="fulfilled"?T.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),x.status==="fulfilled"?T.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),zx(T)}}:a:f,zm=()=>{let f=Q.getInlineMessageFields?.();return f&&f.contentSegments.some(x=>x.kind==="mention")?f.contentSegments:void 0},ns=!1,Um=async a=>{let f=Q.value.trim(),m=Tt?.hasAttachments()??!1,x=f?await(sn?.takeInlineCommand(f)??Promise.resolve(null)):null;if(x?.kind==="action"){Q.value="",Q.style.height="auto",os(),sn?.clear();return}let T=sn?.collectForSubmit()??null,R=x?.kind==="server"?x.mentions:null,ne=$m(T,R),q=x?.kind==="prompt"?x.sendText:f,Z=!!T&&T.refs.length>0;if(!q&&!m&&!Z&&!R)return;qd();let re;m&&(re=[],re.push(...Tt.getContentParts()),q&&re.push(yr(q)));let me=x?.kind==="prompt"?void 0:zm();Q.value="",Q.style.height="auto",os(),V.sendMessage(q,{contentParts:re,mentions:ne??void 0,contentSegments:me,viaVoice:a?.viaVoice}),m&&Tt.clearAttachments(),T&&sn?.clear()},fl=async a=>{if(!ns){ns=!0;try{await Um(a)}finally{ns=!1}}},Kd=a=>{if(a.preventDefault(),V.isStreaming()){V.cancel(),Me?.reset(),_e?.update();return}ns||fl()},jm=()=>o.features?.composerHistory!==!1,ml={...uc},hl=!1,os=()=>{ml={...uc}},Vm=()=>V.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),qm=a=>{if(!Q)return;hl=!0,Q.value=a,Q.dispatchEvent(new Event("input",{bubbles:!0})),hl=!1;let f=Q.value.length;Q.setSelectionRange(f,f)},Km=a=>{hl||(a.isComposing||sn?.handleInput(a.inputType??void 0),os())},Gm=a=>{if(Q&&!(!a.isComposing&&sn?.handleKeydown(a))){if(jm()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let f=Q.selectionStart===0&&Q.selectionEnd===0,m=$g({direction:a.key==="ArrowUp"?"up":"down",history:Vm(),currentValue:Q.value,atStart:f,state:ml});if(ml=m.state,m.handled){a.preventDefault(),m.value!==void 0&&qm(m.value);return}}if(a.key==="Enter"&&!a.shiftKey){if(V.isStreaming()){a.preventDefault();return}if(ns){a.preventDefault();return}os(),a.preventDefault(),w.click()}}},Gd=a=>{a.key!=="Escape"||a.isComposing||V.isStreaming()&&a.composedPath().includes(xe)&&(V.cancel(),Me?.reset(),_e?.update(),os(),a.preventDefault(),a.stopImmediatePropagation())},Qm=async a=>{if(o.attachments?.enabled!==!0||!Tt)return;let f=Ox(a.clipboardData);f.length!==0&&(a.preventDefault(),await Tt.handleFiles(f))},mn=null,Rn=!1,or=null,xt=null,Qd=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,yi=(a="user")=>{if(Rn||V.isStreaming())return;let f=Qd();if(!f)return;mn=new f;let x=(o.voiceRecognition??{}).pauseDuration??2e3;mn.continuous=!0,mn.interimResults=!0,mn.lang="en-US";let T=Q.value;mn.onresult=R=>{let ne="",q="";for(let re=0;re<R.results.length;re++){let me=R.results[re],ce=me[0].transcript;me.isFinal?ne+=ce+" ":q=ce}let Z=T+ne+q;Q.value=Z,or&&clearTimeout(or),(ne||q)&&(or=window.setTimeout(()=>{Q.value.trim()&&mn&&Rn&&(io(),fl({viaVoice:!0}))},x))},mn.onerror=R=>{R.error!=="no-speech"&&io()},mn.onend=()=>{if(Rn){let R=Q.value.trim();R&&R!==T.trim()&&fl({viaVoice:!0}),io()}};try{if(mn.start(),Rn=!0,Ke.active=!0,a!=="system"&&(Ke.manuallyDeactivated=!1),On(a),Mn(),X){let R=o.voiceRecognition??{};xt={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:R.iconName??"mic",iconSize:parseFloat(R.iconSize??o.sendButton?.size??"40")||24};let ne=R.recordingBackgroundColor,q=R.recordingIconColor,Z=R.recordingBorderColor;if(X.classList.add("persona-voice-recording"),X.style.backgroundColor=ne??"var(--persona-voice-recording-bg, #ef4444)",X.style.color=q??"var(--persona-voice-recording-indicator, #ffffff)",q){let re=X.querySelector("svg");re&&re.setAttribute("stroke",q)}Z&&(X.style.borderColor=Z),X.setAttribute("aria-label","Stop voice recognition")}}catch{io("system")}},io=(a="user")=>{if(Rn){if(Rn=!1,or&&(clearTimeout(or),or=null),mn){try{mn.stop()}catch{}mn=null}if(Ke.active=!1,On(a),Mn(),X){if(X.classList.remove("persona-voice-recording"),xt){X.style.backgroundColor=xt.backgroundColor,X.style.color=xt.color,X.style.borderColor=xt.borderColor;let f=X.querySelector("svg");f&&f.setAttribute("stroke",xt.color||"currentColor"),xt=null}X.setAttribute("aria-label","Start voice recognition")}}},Xm=(a,f)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=a?.provider?.type==="runtype",T=a?.provider?.type==="custom";if(!(m||x||T))return null;let ne=v("div","persona-send-button-wrapper"),q=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");q.type="button";let Z=a?.tooltipText??"Start voice recognition";q.setAttribute("aria-label",Z);let re=a?.iconName??"mic",me=f?.size??"40px",ce=a?.iconSize??me,Ae=parseFloat(ce)||24,je=a?.backgroundColor??f?.backgroundColor,dt=a?.iconColor??f?.textColor;q.style.width=ce,q.style.height=ce,q.style.minWidth=ce,q.style.minHeight=ce,q.style.fontSize="18px",q.style.lineHeight="1",dt?q.style.color=dt:q.style.color="var(--persona-text, #111827)";let cn=ae(re,Ae,dt||"currentColor",1.5);cn?q.appendChild(cn):q.textContent="\u{1F3A4}",je?q.style.backgroundColor=je:q.style.backgroundColor="",a?.borderWidth&&(q.style.borderWidth=a.borderWidth,q.style.borderStyle="solid"),a?.borderColor&&(q.style.borderColor=a.borderColor),a?.paddingX&&(q.style.paddingLeft=a.paddingX,q.style.paddingRight=a.paddingX),a?.paddingY&&(q.style.paddingTop=a.paddingY,q.style.paddingBottom=a.paddingY),ne.appendChild(q);let Et=a?.showTooltip??!1;return Ut({anchor:q,trigger:ne,text:()=>q.getAttribute("aria-label")??Z,enabled:Et}),{micButton:q,micButtonWrapper:ne}},yl=()=>{if(!X||xt)return;let a=o.voiceRecognition??{};xt={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:a.iconName??"mic",iconSize:parseFloat(a.iconSize??o.sendButton?.size??"40")||24}},bl=(a,f)=>{if(!X)return;let m=X.querySelector("svg");m&&m.remove();let x=xt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),T=ae(a,x,f,1.5);T&&X.appendChild(T)},bi=()=>{X&&X.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},rr=()=>{if(!X)return;yl();let a=o.voiceRecognition??{},f=a.recordingBackgroundColor,m=a.recordingIconColor,x=a.recordingBorderColor;if(bi(),X.classList.add("persona-voice-recording"),X.style.backgroundColor=f??"var(--persona-voice-recording-bg, #ef4444)",X.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let T=X.querySelector("svg");T&&T.setAttribute("stroke",m)}x&&(X.style.borderColor=x),X.setAttribute("aria-label","Stop voice recognition")},Jm=()=>{if(!X)return;yl();let a=o.voiceRecognition??{},f=V.getVoiceInterruptionMode(),m=a.processingIconName??"loader",x=a.processingIconColor??xt?.color??"",T=a.processingBackgroundColor??xt?.backgroundColor??"",R=a.processingBorderColor??xt?.borderColor??"";bi(),X.classList.add("persona-voice-processing"),X.style.backgroundColor=T,X.style.borderColor=R;let ne=x||"currentColor";X.style.color=ne,bl(m,ne),X.setAttribute("aria-label","Processing voice input"),f==="none"&&(X.style.cursor="default")},Ym=()=>{if(!X)return;yl();let a=o.voiceRecognition??{},f=V.getVoiceInterruptionMode(),m=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",x=a.speakingIconName??m,T=a.speakingIconColor??(f==="barge-in"?a.recordingIconColor??xt?.color??"":xt?.color??""),R=a.speakingBackgroundColor??(f==="barge-in"?a.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":xt?.backgroundColor??""),ne=a.speakingBorderColor??(f==="barge-in"?a.recordingBorderColor??"":xt?.borderColor??"");bi(),X.classList.add("persona-voice-speaking"),X.style.backgroundColor=R,X.style.borderColor=ne;let q=T||"currentColor";X.style.color=q,bl(x,q);let Z=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";X.setAttribute("aria-label",Z),f==="none"&&(X.style.cursor="default"),f==="barge-in"&&X.classList.add("persona-voice-recording")},_n=()=>{X&&(bi(),xt&&(X.style.backgroundColor=xt.backgroundColor??"",X.style.color=xt.color??"",X.style.borderColor=xt.borderColor??"",bl(xt.iconName,xt.color||"currentColor"),xt=null),X.style.cursor="",X.setAttribute("aria-label","Start voice recognition"))},vi=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let a=V.getVoiceStatus(),f=V.getVoiceInterruptionMode();if(f==="none"&&(a==="processing"||a==="speaking"))return;if(f==="cancel"&&(a==="processing"||a==="speaking")){V.stopVoicePlayback();return}if(V.isBargeInActive()){V.stopVoicePlayback(),V.deactivateBargeIn().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,Mn(),On("user"),_n()});return}V.toggleVoice().then(()=>{Ke.active=V.isVoiceActive(),Ke.manuallyDeactivated=!V.isVoiceActive(),Mn(),On("user"),V.isVoiceActive()?rr():_n()});return}if(Rn){let a=Q.value.trim();Ke.manuallyDeactivated=!0,Mn(),io("user"),a&&(Q.value="",Q.style.height="auto",V.sendMessage(a))}else Ke.manuallyDeactivated=!1,Mn(),yi("user")};nd=vi,X&&(X.addEventListener("click",vi),$e.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(V.isVoiceActive()&&V.toggleVoice(),_n()):io("system"),X&&X.removeEventListener("click",vi)}));let Zm=p.on("assistant:complete",()=>{Ed&&(Ke.active||Ke.manuallyDeactivated||Ed==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?V.toggleVoice().then(()=>{Ke.active=V.isVoiceActive(),On("auto"),V.isVoiceActive()&&rr()}):yi("auto"))},600))});$e.push(Zm);let eh=p.on("action:resubmit",()=>{setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)});$e.push(eh);let Xd=()=>{ct(!j,"user")},$t=null,Zt=null;if(E&&!P()){let{instance:a,element:f}=vc({config:o,plugins:s,onToggle:Xd});$t=a,a||(Zt=f)}$t?t.appendChild($t.element):Zt&&t.appendChild(Zt),ts(),Vr(),$d(),ll(V.isStreaming()),Bd()||(un()==="follow"?so(!0):Wd()),Am(),G&&(!E||P()?setTimeout(()=>cl(),0):j&&setTimeout(()=>cl(),200));let rs=()=>{if(P()){Qo(),ts();return}let a=_t(o),f=o.launcher?.sidebarMode??!1,m=a||f||(o.launcher?.fullHeight??!1),x=t.ownerDocument.defaultView??window,T=o.launcher?.mobileFullscreen??!0,R=o.launcher?.mobileBreakpoint??640,ne=x.innerWidth<=R,q=T&&ne&&E;try{if(q){Fr(),_r=ri();return}let Z=!1;W&&(W=!1,Fr(),Z=!0);let re=ri();if(!Z&&re!==_r&&(Fr(),Z=!0),_r=re,Z&&Ya(),!E&&!a){ye.style.height="",ye.style.width="";return}if(!f&&!a){let ce=o?.launcher?.width??o?.launcherWidth??Gn;ye.style.width=ce,ye.style.maxWidth=ce}if(oi(),!m){let me=x.innerHeight,ce=64,Ae=o.launcher?.heightOffset??0,je=Math.max(200,me-ce),dt=Math.min(640,je),tt=Math.max(200,dt-Ae);ye.style.height=`${tt}px`}}finally{if(Qo(),ts(),j&&E){let re=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),me=o.launcher?.sidebarMode??!1,ce=o.launcher?.mobileFullscreen??!0,Ae=_t(o)&&ce&&re,je=me||ce&&re&&E||Ae;if(je&&!In){let dt=t.getRootNode(),tt=dt instanceof ShadowRoot?dt.host:t.closest(".persona-host");tt&&!Pn&&(Pn=mc(tt,o.launcher?.zIndex??Qt)),In=hc(t.ownerDocument)}else je||(Pn?.(),Pn=null,In?.(),In=null)}}};rs();let Jd=t.ownerDocument.defaultView??window;if(Jd.addEventListener("resize",rs),$e.push(()=>Jd.removeEventListener("resize",rs)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{Qo()});a.observe(Se),$e.push(()=>a.disconnect())}gn=ue.scrollTop;let Yd=Hn(ue),Zd=()=>{let a=ue.scrollTop,f=Hn(ue),m=f<Yd;if(Yd=f,!Yn()){gn=a,ln();return}let{action:x,nextLastScrollTop:T}=wa({following:an.isFollowing(),currentScrollTop:a,lastScrollTop:gn,nearBottom:Co(ue,ui),userScrollThreshold:Cm,isAutoScrolling:fn||ai||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(gn=T,x==="resume"){fi()||ro();return}x==="pause"&&Qr()};if(ue.addEventListener("scroll",Zd,{passive:!0}),$e.push(()=>ue.removeEventListener("scroll",Zd)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{km(),Al(We)});a.observe(We),a.observe(ue),$e.push(()=>a.disconnect())}let ep=()=>{Yn()&&an.isFollowing()&&fi()&&Qr()},tp=ue.ownerDocument;tp.addEventListener("selectionchange",ep),$e.push(()=>{tp.removeEventListener("selectionchange",ep)});let th=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),np=a=>{th.has(a.key)&&(Ro(),Jc()&&Yn()&&an.isFollowing()&&Qr())},op=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(Ro(),Jc()&&Yn()&&an.isFollowing()&&Qr())};ue.addEventListener("keydown",np),ue.addEventListener("focusin",op),$e.push(()=>{ue.removeEventListener("keydown",np),ue.removeEventListener("focusin",op)});let rp=a=>{if(a.deltaY!==0&&Ro(),!Yn())return;let f=Aa({following:an.isFollowing(),deltaY:a.deltaY,nearBottom:Co(ue,ui),resumeWhenNearBottom:!0});f==="pause"?Qr():f==="resume"&&!fi()&&ro()};ue.addEventListener("wheel",rp,{passive:!0}),ue.addEventListener("touchmove",Ro,{passive:!0}),ue.addEventListener("pointerdown",Ro,{passive:!0}),$e.push(()=>{ue.removeEventListener("touchmove",Ro),ue.removeEventListener("pointerdown",Ro)}),$e.push(()=>ue.removeEventListener("wheel",rp)),Lt.addEventListener("click",()=>{Xr(),ue.scrollTop=ue.scrollHeight,gn=ue.scrollTop,ro(),so(!0),ln()}),$e.push(()=>Lt.remove()),$e.push(()=>{Pd(),Xr()});let sp=()=>{U&&(Eo&&(U.removeEventListener("click",Eo),Eo=null),I()?(U.style.display="",Eo=()=>{ct(!1,"user")},U.addEventListener("click",Eo)):U.style.display="none")};sp(),(()=>{let{clearChatButton:a}=He;a&&a.addEventListener("click",()=>{V.clearMessages(),Lo.clear(),ro(),fr(He.composerOverlay);try{localStorage.removeItem(Wr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Wr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(f),d?.clear&&rl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},S.syncFromMetadata(),Te?.clear(),Me?.reset(),_e?.update()})})(),y&&y.addEventListener("submit",Kd);let ip=[["keydown",Gm],["input",Km],["paste",Qm],["focus",fm]],ap=a=>{if(a)for(let[f,m]of ip)a.addEventListener(f,m)},lp=a=>{if(a)for(let[f,m]of ip)a.removeEventListener(f,m)};ap(Q),sn?.onComposerSwap((a,f)=>{lp(f),Q=a,ap(a)});let cp=t.ownerDocument??document;cp.addEventListener("keydown",Gd,!0);let dp="persona-attachment-drop-active",ss=0,vl=()=>{ss=0,xe.classList.remove(dp)},sr=()=>o.attachments?.enabled===!0&&Tt!==null,pp=a=>{!Va(a.dataTransfer)||!sr()||(ss++,ss===1&&xe.classList.add(dp))},up=a=>{!Va(a.dataTransfer)||!sr()||(ss--,ss<=0&&vl())},gp=a=>{!Va(a.dataTransfer)||!sr()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},fp=a=>{if(!Va(a.dataTransfer)||!sr())return;a.preventDefault(),a.stopPropagation(),vl();let f=Array.from(a.dataTransfer.files??[]);f.length!==0&&Tt.handleFiles(f)},ao=!0;xe.addEventListener("dragenter",pp,ao),xe.addEventListener("dragleave",up,ao),t.addEventListener("dragover",gp,ao),t.addEventListener("drop",fp,ao);let xi=t.ownerDocument,mp=a=>{sr()&&a.preventDefault()},hp=a=>{sr()&&a.preventDefault()};xi.addEventListener("dragover",mp),xi.addEventListener("drop",hp),$e.push(()=>{y&&y.removeEventListener("submit",Kd),lp(Q),cp.removeEventListener("keydown",Gd,!0),sn?.destroy()}),$e.push(()=>{xe.removeEventListener("dragenter",pp,ao),xe.removeEventListener("dragleave",up,ao),t.removeEventListener("dragover",gp,ao),t.removeEventListener("drop",fp,ao),xi.removeEventListener("dragover",mp),xi.removeEventListener("drop",hp),vl()}),$e.push(()=>{V.cancel()}),$t?$e.push(()=>{$t?.destroy()}):Zt&&$e.push(()=>{Zt?.remove()});let Pt={update(a){let f=o.toolCall,m=o.messageActions,x=o.layout?.messages,T=o.colorScheme,R=o.loadingIndicator,ne=o.iterationDisplay,q=o.features?.showReasoning,Z=o.features?.showToolCalls,re=o.features?.toolCallDisplay,me=o.features?.reasoningDisplay,ce=o.features?.streamAnimation?.type;o=Of({...o,features:r},a),r=o.features,o=Wc(o),si(),Ps(t,o),qs(t,o),Ks(t,o),Nn(),o.colorScheme!==T&&fd();let Ae=Nc.getForInstance(o.plugins);s.length=0,s.push(...Ae),E=o.launcher?.enabled??!0,z=o.launcher?.autoExpand??!1,oe=o.features?.showReasoning??!0,J=o.features?.showToolCalls??!0,ee=o.features?.scrollToBottom??{};let je=un();fe=o.features?.scrollBehavior??{},je!==un()&&(Xr(),ro()),td(),ln();let dt=ie;if(ie=o.features?.showEventStreamToggle??!1,ie&&!dt){if(Te||(we=new js(he),Te=new Us(ve,we),Me=Me??new Vs,we.open().then(()=>Te?.restore()).catch(()=>{}),V.setSSEEventCallback((le,qe)=>{o.onSSEEvent?.(le,qe),Me?.processEvent(le,qe),Te.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:le,timestamp:Date.now(),payload:JSON.stringify(qe)})})),!et&&Le){let le=o.features?.eventStream?.classNames,qe="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"+(le?.toggleButton?" "+le.toggleButton:"");et=v("button",qe),et.style.width="28px",et.style.height="28px",et.style.color=tn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let mt=ae("activity","18px","currentColor",1.5);mt&&et.appendChild(mt);let nt=He.clearChatButtonWrapper,st=He.closeButtonWrapper,Kt=nt||st;Kt&&Kt.parentNode===Le?Le.insertBefore(et,Kt):Le.appendChild(et),et.addEventListener("click",()=>{Ve?Nr():Ga()})}}else!ie&&dt&&(Nr(),et&&(et.remove(),et=null),Te?.clear(),we?.destroy(),Te=null,we=null,Me?.reset(),Me=null);if(o.launcher?.enabled===!1&&$t&&($t.destroy(),$t=null),o.launcher?.enabled===!1&&Zt&&(Zt.remove(),Zt=null),o.launcher?.enabled!==!1&&!$t&&!Zt){let{instance:le,element:qe}=vc({config:o,plugins:s,onToggle:Xd});$t=le,le||(Zt=qe),t.appendChild(qe)}$t&&$t.update(o),te&&o.launcher?.title!==void 0&&(te.textContent=o.launcher.title),de&&o.launcher?.subtitle!==void 0&&(de.textContent=o.launcher.subtitle);let tt=o.layout?.header;if(tt?.layout!==D&&Le){let le=tt?Ia(o,tt,{showClose:I(),onClose:()=>ct(!1,"user")}):Uo({config:o,showClose:I(),onClose:()=>ct(!1,"user")});Mt.replaceHeader(le),Le=Mt.header.element,F=Mt.header.iconHolder,te=Mt.header.headerTitle,de=Mt.header.headerSubtitle,U=Mt.header.closeButton,D=tt?.layout}else if(tt){if(F&&(F.style.display=tt.showIcon===!1?"none":""),te&&(te.style.display=tt.showTitle===!1?"none":""),de&&(de.style.display=tt.showSubtitle===!1?"none":""),U){let le=I()&&tt.showCloseButton!==!1;U.style.display=le?"":"none"}if(He.clearChatButtonWrapper){let le=tt.showClearChat;if(le!==void 0){He.clearChatButtonWrapper.style.display=le?"":"none";let{closeButtonWrapper:qe}=He;qe&&!qe.classList.contains("persona-absolute")&&(le?qe.classList.remove("persona-ml-auto"):qe.classList.add("persona-ml-auto"))}}}let Et=o.layout?.showHeader!==!1;Le&&(Le.style.display=Et?"":"none");let It=o.layout?.showFooter!==!1;Se&&(Se.style.display=It?"":"none"),Qo(),ln(),E!==O?E?ct(z,"auto"):(j=!0,ts()):z!==A&&ct(z,"auto"),A=z,O=E,rs(),sp();let Oe=JSON.stringify(o.toolCall)!==JSON.stringify(f),Ee=JSON.stringify(o.messageActions)!==JSON.stringify(m),St=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),pt=o.loadingIndicator?.render!==R?.render||o.loadingIndicator?.renderIdle!==R?.renderIdle||o.loadingIndicator?.showBubble!==R?.showBubble,Ft=o.iterationDisplay!==ne,ut=(o.features?.showReasoning??!0)!==(q??!0)||(o.features?.showToolCalls??!0)!==(Z??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(re)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(me);(Oe||Ee||St||pt||Ft||ut)&&V&&(el++,Jr(We,V.getMessages(),Y));let Rt=o.features?.streamAnimation?.type;if(Rt!==ce&&Rt&&Rt!=="none"){let le=Er(Rt,o.features?.streamAnimation?.plugins);le&&Ea(le,t)}let Ie=o.launcher??{},Fe=Ie.headerIconHidden??!1,jt=o.layout?.header?.showIcon,Vt=Fe||jt===!1,Ct=Ie.headerIconName,lt=Ie.headerIconSize??"48px";if(F){let le=xe.querySelector(".persona-border-b-persona-divider"),qe=le?.querySelector(".persona-flex-col");if(Vt)F.style.display="none",le&&qe&&!le.contains(qe)&&le.insertBefore(qe,le.firstChild);else{if(F.style.display="",F.style.height=lt,F.style.width=lt,le&&qe&&(le.contains(F)?F.nextSibling!==qe&&(F.remove(),le.insertBefore(F,qe)):le.insertBefore(F,qe)),Ct){let nt=parseFloat(lt)||24,st=ae(Ct,nt*.6,"currentColor",1);st?F.replaceChildren(st):F.textContent=Ie.agentIconText??"\u{1F4AC}"}else if(Ie.iconUrl){let nt=F.querySelector("img");if(nt)nt.src=Ie.iconUrl,nt.style.height=lt,nt.style.width=lt;else{let st=document.createElement("img");st.src=Ie.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=lt,st.style.width=lt,F.replaceChildren(st)}}else{let nt=F.querySelector("svg"),st=F.querySelector("img");(nt||st)&&F.replaceChildren(),F.textContent=Ie.agentIconText??"\u{1F4AC}"}let mt=F.querySelector("img");mt&&(mt.style.height=lt,mt.style.width=lt)}}let ft=o.layout?.header?.showTitle,Xe=o.layout?.header?.showSubtitle;if(te&&(te.style.display=ft===!1?"none":""),de&&(de.style.display=Xe===!1?"none":""),U){let le=I()&&o.layout?.header?.showCloseButton!==!1;U.style.display=le?"":"none";let qe=Ie.closeButtonSize??"32px",mt=Ie.closeButtonPlacement??"inline";U.style.height=qe,U.style.width=qe;let{closeButtonWrapper:nt}=He,st=mt==="top-right",Kt=nt?.classList.contains("persona-absolute");if(nt&&st!==Kt)if(nt.remove(),st)nt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",xe.style.position="relative",xe.appendChild(nt);else{let co=Ie.clearChat?.placement??"inline",ls=Ie.clearChat?.enabled??!0;nt.className=ls&&co==="inline"?"":"persona-ml-auto";let yp=xe.querySelector(".persona-border-b-persona-divider");yp&&yp.appendChild(nt)}if(U.style.color=Ie.closeButtonColor||tn.actionIconColor,Ie.closeButtonBackgroundColor?(U.style.backgroundColor=Ie.closeButtonBackgroundColor,U.classList.remove("hover:persona-bg-gray-100")):(U.style.backgroundColor="",U.classList.add("hover:persona-bg-gray-100")),Ie.closeButtonBorderWidth||Ie.closeButtonBorderColor){let co=Ie.closeButtonBorderWidth||"0px",ls=Ie.closeButtonBorderColor||"transparent";U.style.border=`${co} solid ${ls}`,U.classList.remove("persona-border-none")}else U.style.border="",U.classList.add("persona-border-none");Ie.closeButtonBorderRadius?(U.style.borderRadius=Ie.closeButtonBorderRadius,U.classList.remove("persona-rounded-full")):(U.style.borderRadius="",U.classList.add("persona-rounded-full")),Ie.closeButtonPaddingX?(U.style.paddingLeft=Ie.closeButtonPaddingX,U.style.paddingRight=Ie.closeButtonPaddingX):(U.style.paddingLeft="",U.style.paddingRight=""),Ie.closeButtonPaddingY?(U.style.paddingTop=Ie.closeButtonPaddingY,U.style.paddingBottom=Ie.closeButtonPaddingY):(U.style.paddingTop="",U.style.paddingBottom="");let dn=Ie.closeButtonIconName??"x",Tn=Ie.closeButtonIconText??"\xD7";U.innerHTML="";let zt=ae(dn,"28px","currentColor",1);zt?(zt.style.display="block",U.appendChild(zt)):U.textContent=Tn;let Gt=Ie.closeButtonTooltipText??"Close chat",zn=Ie.closeButtonShowTooltip??!0;U.setAttribute("aria-label",Gt),nt&&Ut({anchor:U,trigger:nt,text:()=>U?.getAttribute("aria-label")??Gt,enabled:zn})}let{clearChatButton:Be,clearChatButtonWrapper:yt}=He;if(Be){let le=Ie.clearChat??{},qe=le.enabled??!0,mt=o.layout?.header?.showClearChat,nt=mt!==void 0?mt:qe,st=le.placement??"inline";if(yt){yt.style.display=nt?"":"none";let{closeButtonWrapper:Kt}=He;!P()&&Kt&&!Kt.classList.contains("persona-absolute")&&(nt?Kt.classList.remove("persona-ml-auto"):Kt.classList.add("persona-ml-auto"));let dn=st==="top-right",Tn=yt.classList.contains("persona-absolute");if(!P()&&dn!==Tn&&nt){if(yt.remove(),dn)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",xe.style.position="relative",xe.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let Gt=xe.querySelector(".persona-border-b-persona-divider"),zn=He.closeButtonWrapper;Gt&&zn&&zn.parentElement===Gt?Gt.insertBefore(yt,zn):Gt&&Gt.appendChild(yt)}let zt=He.closeButtonWrapper;zt&&!zt.classList.contains("persona-absolute")&&(dn?zt.classList.add("persona-ml-auto"):zt.classList.remove("persona-ml-auto"))}}if(nt){if(!P()){let co=le.size??"32px";Be.style.height=co,Be.style.width=co}let Kt=le.iconName??"refresh-cw",dn=le.iconColor??"";Be.style.color=dn||tn.actionIconColor,Be.innerHTML="";let Tn=P()?"14px":"20px",zt=ae(Kt,Tn,"currentColor",1);if(zt&&(zt.style.display="block",Be.appendChild(zt)),le.backgroundColor?(Be.style.backgroundColor=le.backgroundColor,Be.classList.remove("hover:persona-bg-gray-100")):(Be.style.backgroundColor="",Be.classList.add("hover:persona-bg-gray-100")),le.borderWidth||le.borderColor){let co=le.borderWidth||"0px",ls=le.borderColor||"transparent";Be.style.border=`${co} solid ${ls}`,Be.classList.remove("persona-border-none")}else Be.style.border="",Be.classList.add("persona-border-none");le.borderRadius?(Be.style.borderRadius=le.borderRadius,Be.classList.remove("persona-rounded-full")):(Be.style.borderRadius="",Be.classList.add("persona-rounded-full")),le.paddingX?(Be.style.paddingLeft=le.paddingX,Be.style.paddingRight=le.paddingX):(Be.style.paddingLeft="",Be.style.paddingRight=""),le.paddingY?(Be.style.paddingTop=le.paddingY,Be.style.paddingBottom=le.paddingY):(Be.style.paddingTop="",Be.style.paddingBottom="");let Gt=le.tooltipText??"Clear chat",zn=le.showTooltip??!0;Be.setAttribute("aria-label",Gt),yt&&Ut({anchor:Be,trigger:yt,text:()=>Be?.getAttribute("aria-label")??Gt,enabled:zn})}}let qt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Fc],yn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Gs.message,Gs.messageAndClick];S=_c({parsers:qt,handlers:yn,getSessionMetadata:C,updateSessionMetadata:L,emit:p.emit,documentRef:typeof document<"u"?document:null}),Y=Gf(o,S,se),V.updateConfig(o),Jr(We,V.getMessages(),Y),Vr(),$d(),ll(V.isStreaming());let is=o.voiceRecognition?.enabled===!0,Ci=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),kt=o.voiceRecognition?.provider?.type==="runtype";if(is&&(Ci||kt))if(!X||!Ue){let le=Xm(o.voiceRecognition,o.sendButton);le&&(X=le.micButton,Ue=le.micButtonWrapper,ot.insertBefore(Ue,K),X.addEventListener("click",vi),X.disabled=V.isStreaming())}else{let le=o.voiceRecognition??{},qe=o.sendButton??{},mt=le.iconName??"mic",nt=qe.size??"40px",st=le.iconSize??nt,Kt=parseFloat(st)||24;X.style.width=st,X.style.height=st,X.style.minWidth=st,X.style.minHeight=st;let dn=le.iconColor??qe.textColor;X.innerHTML="";let Tn=ae(mt,Kt,dn||"currentColor",1.5);Tn?X.appendChild(Tn):X.textContent="\u{1F3A4}";let zt=le.backgroundColor??qe.backgroundColor;zt?X.style.backgroundColor=zt:X.style.backgroundColor="",dn?X.style.color=dn:X.style.color="var(--persona-text, #111827)",le.borderWidth?(X.style.borderWidth=le.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),le.borderColor?X.style.borderColor=le.borderColor:X.style.borderColor="",le.paddingX?(X.style.paddingLeft=le.paddingX,X.style.paddingRight=le.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),le.paddingY?(X.style.paddingTop=le.paddingY,X.style.paddingBottom=le.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let Gt=le.tooltipText??"Start voice recognition",zn=le.showTooltip??!1;X.setAttribute("aria-label",Gt),Ue&&Ut({anchor:X,trigger:Ue,text:()=>X?.getAttribute("aria-label")??Gt,enabled:zn}),Ue.style.display="",X.disabled=V.isStreaming()}else X&&Ue&&(Ue.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?V.isVoiceActive()&&V.toggleVoice():Rn&&io());if(o.attachments?.enabled===!0){if(!Ot||!Ne){let le=o.attachments??{},mt=(o.sendButton??{}).size??"40px";Yt||(Yt=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Yt.style.display="none",y.insertBefore(Yt,Q)),At||(At=document.createElement("input"),At.type="file",At.accept=(le.allowedTypes??Kn).join(","),At.multiple=(le.maxFiles??4)>1,At.style.display="none",At.setAttribute("aria-label","Attach files"),y.insertBefore(At,Q)),Ot=v("div","persona-send-button-wrapper"),Ne=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ne.type="button",Ne.setAttribute("aria-label",le.buttonTooltipText??"Attach file");let nt=le.buttonIconName??"paperclip",st=mt,Kt=parseFloat(st)||40,dn=Math.round(Kt*.6);Ne.style.width=st,Ne.style.height=st,Ne.style.minWidth=st,Ne.style.minHeight=st,Ne.style.fontSize="18px",Ne.style.lineHeight="1";let Tn=ae(nt,dn,"currentColor",1.5);Tn?Ne.appendChild(Tn):Ne.textContent="\u{1F4CE}",Ne.addEventListener("click",Gt=>{Gt.preventDefault(),At?.click()}),Ot.appendChild(Ne);let zt=le.buttonTooltipText??"Attach file";Ut({anchor:Ne,trigger:Ot,text:()=>Ne?.getAttribute("aria-label")??zt}),ze?ze.append(Ot):y.appendChild(Ot),!Tt&&At&&Yt&&(Tt=ws.fromConfig(le),Tt.setPreviewsContainer(Yt),At.addEventListener("change",async()=>{Tt&&At?.files&&(await Tt.handleFileSelect(At.files),At.value="")}))}else{Ot.style.display="";let le=o.attachments??{};At&&(At.accept=(le.allowedTypes??Kn).join(","),At.multiple=(le.maxFiles??4)>1),Tt&&Tt.updateConfig({allowedTypes:le.allowedTypes,maxFileSize:le.maxFileSize,maxFiles:le.maxFiles})}if(xe.querySelector(".persona-attachment-drop-overlay")?.remove(),xe.appendChild(Qf(o.attachments?.dropOverlay)),Ne){let le=o.attachments??{},qe=le.buttonTooltipText??"Attach file";Ne.setAttribute("aria-label",qe),Ne.textContent="";let mt=parseFloat(o.sendButton?.size??"40px")||40,nt=ae(le.buttonIconName??"paperclip",Math.round(mt*.6),"currentColor",1.5);nt?Ne.appendChild(nt):Ne.textContent="\u{1F4CE}",Ot&&Ut({anchor:Ne,trigger:Ot,text:()=>Ne?.getAttribute("aria-label")??qe})}}else Ot&&(Ot.style.display="none"),Tt&&Tt.clearAttachments(),xe.querySelector(".persona-attachment-drop-overlay")?.remove();let Dt=o.sendButton??{},as=Dt.useIcon??!1,Ai=Dt.iconText??"\u2191",ir=Dt.iconName,Si=Dt.tooltipText??"Send message",xl=Dt.showTooltip??!1,Do=Dt.size??"40px",$n=Dt.backgroundColor,No=Dt.textColor;if(as){if(w.style.width=Do,w.style.height=Do,w.style.minWidth=Do,w.style.minHeight=Do,w.style.fontSize="18px",w.style.lineHeight="1",No?w.style.color=No:w.style.color="var(--persona-button-primary-fg, #ffffff)",!V.isStreaming())if(w.innerHTML="",ir){let le=parseFloat(Do)||24,qe=No?.trim()||"currentColor",mt=ae(ir,le,qe,2);mt?w.appendChild(mt):w.textContent=Ai}else w.textContent=Ai;w.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",$n?(w.style.backgroundColor=$n,w.classList.remove("persona-bg-persona-primary")):(w.style.backgroundColor="",w.classList.add("persona-bg-persona-primary"))}else w.textContent=o.copy?.sendButtonLabel??"Send",w.style.width="",w.style.height="",w.style.minWidth="",w.style.minHeight="",w.style.fontSize="",w.style.lineHeight="",w.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",$n?(w.style.backgroundColor=$n,w.classList.remove("persona-bg-persona-accent")):w.classList.add("persona-bg-persona-accent"),No?w.style.color=No:w.classList.add("persona-text-white");Dt.borderWidth?(w.style.borderWidth=Dt.borderWidth,w.style.borderStyle="solid"):(w.style.borderWidth="",w.style.borderStyle=""),Dt.borderColor?w.style.borderColor=Dt.borderColor:w.style.borderColor="",Dt.paddingX?(w.style.paddingLeft=Dt.paddingX,w.style.paddingRight=Dt.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),Dt.paddingY?(w.style.paddingTop=Dt.paddingY,w.style.paddingBottom=Dt.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),V.isStreaming()||w.setAttribute("aria-label",Si),K&&Ut({anchor:w,trigger:K,text:()=>w.getAttribute("aria-label")??Si,enabled:xl});let Mi=o.layout?.contentMaxWidth??(P()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Mi?(We.style.maxWidth=Mi,We.style.marginLeft="auto",We.style.marginRight="auto",We.style.width="100%",y&&(y.style.maxWidth=Mi,y.style.marginLeft="auto",y.style.marginRight="auto"),bt&&(bt.style.maxWidth=Mi,bt.style.marginLeft="auto",bt.style.marginRight="auto")):(We.style.maxWidth="",We.style.marginLeft="",We.style.marginRight="",We.style.width="",y&&(y.style.maxWidth="",y.style.marginLeft="",y.style.marginRight=""),bt&&(bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight=""));let lo=o.statusIndicator??{},nh=lo.visible??!0;if(H.style.display=nh?"":"none",V){let le=V.getStatus();Xt(H,(mt=>mt==="idle"?lo.idleText??Wt.idle:mt==="connecting"?lo.connectingText??Wt.connecting:mt==="connected"?lo.connectedText??Wt.connected:mt==="error"?lo.errorText??Wt.error:Wt[mt])(le),lo,le)}H.classList.remove("persona-text-left","persona-text-center","persona-text-right");let oh=lo.align==="left"?"persona-text-left":lo.align==="center"?"persona-text-center":"persona-text-right";H.classList.add(oh)},open(){I()&&ct(!0,"api")},close(){I()&&ct(!1,"api")},toggle(){I()&&ct(!j,"api")},reconnect(){V.reconnectNow()},clearChat(){Dn=!1,V.clearMessages(),Lo.clear(),ro();try{localStorage.removeItem(Wr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wr}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Wr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),d?.clear&&rl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},S.syncFromMetadata(),Te?.clear(),Me?.reset(),_e?.update()},setMessage(a){return!Q||V.isStreaming()?!1:(!j&&I()&&ct(!0,"system"),Q.value=a,Q.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(V.isStreaming())return!1;let f=a?.trim()||Q.value.trim();return f?(!j&&I()&&ct(!0,"system"),Q.value="",Q.style.height="auto",V.sendMessage(f),!0):!1},startVoiceRecognition(){return V.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(V.isVoiceActive()||(!j&&I()&&ct(!0,"system"),Ke.manuallyDeactivated=!1,Mn(),V.toggleVoice().then(()=>{Ke.active=V.isVoiceActive(),On("user"),V.isVoiceActive()&&rr()})),!0):Rn?!0:Qd()?(!j&&I()&&ct(!0,"system"),Ke.manuallyDeactivated=!1,Mn(),yi("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?V.isVoiceActive()?(V.toggleVoice().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,Mn(),On("user"),_n()}),!0):!1:Rn?(Ke.manuallyDeactivated=!0,Mn(),io("user"),!0):!1},injectMessage(a){return!j&&I()&&ct(!0,"system"),V.injectMessage(a)},injectAssistantMessage(a){!j&&I()&&ct(!0,"system");let f=V.injectAssistantMessage(a);return pe&&(pe=!1,ge&&(clearTimeout(ge),ge=null),setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)),f},injectUserMessage(a){return!j&&I()&&ct(!0,"system"),V.injectUserMessage(a)},injectSystemMessage(a){return!j&&I()&&ct(!0,"system"),V.injectSystemMessage(a)},injectMessageBatch(a){return!j&&I()&&ct(!0,"system"),V.injectMessageBatch(a)},injectComponentDirective(a){return!j&&I()&&ct(!0,"system"),V.injectComponentDirective(a)},injectTestMessage(a){!j&&I()&&ct(!0,"system"),V.injectTestEvent(a)},async connectStream(a,f){return V.connectStream(a,f)},__pushEventStreamEvent(a){Te&&(Me?.processEvent(a.type,a.payload),Te.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a.type,timestamp:Date.now(),payload:JSON.stringify(a.payload)}))},showEventStream(){!ie||!Te||Ga()},hideEventStream(){Ve&&Nr()},isEventStreamVisible(){return Ve},showArtifacts(){nn(o)&&(Dn=!1,Xo=!0,Nn(),Qe?.setMobileOpen(!0))},hideArtifacts(){nn(o)&&(Dn=!0,Nn())},upsertArtifact(a){return nn(o)?(uo(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(Dn=!1,Xo=!0),V.upsertArtifact(a)):null},selectArtifact(a){nn(o)&&V.selectArtifact(a)},clearArtifacts(){nn(o)&&V.clearArtifacts()},getArtifacts(){return V?.getArtifacts()??[]},getSelectedArtifactId(){return V?.getSelectedArtifactId()??null},focusInput(){return E&&!j&&!P()||!Q?!1:(Q.focus(),!0)},async resolveApproval(a,f,m){let T=V.getMessages().find(R=>R.variant==="approval"&&R.approval?.id===a);if(!T?.approval)throw new Error(`Approval not found: ${a}`);if(T.approval.toolType==="webmcp"){V.resolveWebMcpApproval(T.id,f);return}return V.resolveApproval(T.approval,f,m)},setFollowUpSuggestions(a){vm(a)},clearFollowUpSuggestions(){Td()},getMessages(){return V.getMessages()},getStatus(){return V.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(a){L(a)},on(a,f){return p.on(a,f)},off(a,f){p.off(a,f)},isOpen(){return I()&&j},isVoiceActive(){return Ke.active},toggleReadAloud(a){V.toggleReadAloud(a)},stopReadAloud(){V.stopSpeaking()},getReadAloudState(a){return V.getReadAloudState(a)},onReadAloudChange(a){return V.onReadAloudChange(a)},getState(){return{open:I()&&j,launcherEnabled:E,voiceActive:Ke.active,streaming:V.isStreaming()}},showCSATFeedback(a){!j&&I()&&ct(!0,"system");let f=We.querySelector(".persona-feedback-container");f&&f.remove();let m=Vf({onSubmit:async(x,T)=>{V.isClientTokenMode()&&await V.submitCSATFeedback(x,T),a?.onSubmit?.(x,T)},onDismiss:a?.onDismiss,...a});We.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!j&&I()&&ct(!0,"system");let f=We.querySelector(".persona-feedback-container");f&&f.remove();let m=qf({onSubmit:async(x,T)=>{V.isClientTokenMode()&&await V.submitNPSFeedback(x,T),a?.onSubmit?.(x,T)},onDismiss:a?.onDismiss,...a});We.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,f){return V.submitCSATFeedback(a,f)},async submitNPSFeedback(a,f){return V.submitNPSFeedback(a,f)},destroy(){ul(),Ho!=null&&(clearInterval(Ho),Ho=null),$e.forEach(a=>a()),De.remove(),Ye?.remove(),$t?.destroy(),Zt?.remove(),Eo&&U.removeEventListener("click",Eo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,f={controller:Pt,getMessages:Pt.getMessages,getStatus:Pt.getStatus,getMetadata:Pt.getPersistentMetadata,updateMetadata:Pt.updatePersistentMetadata,clearHistory:()=>Pt.clearChat(),setVoiceActive:m=>m?Pt.startVoiceRecognition():Pt.stopVoiceRecognition()};window.AgentWidgetBrowser=f,$e.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),f=q=>{let Z=q.detail;(!Z?.instanceId||Z.instanceId===a)&&Pt.focusInput()};if(window.addEventListener("persona:focusInput",f),$e.push(()=>{window.removeEventListener("persona:focusInput",f)}),ie){let q=re=>{let me=re.detail;(!me?.instanceId||me.instanceId===a)&&Pt.showEventStream()},Z=re=>{let me=re.detail;(!me?.instanceId||me.instanceId===a)&&Pt.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",Z),$e.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",Z)})}let m=q=>{let Z=q.detail;(!Z?.instanceId||Z.instanceId===a)&&Pt.showArtifacts()},x=q=>{let Z=q.detail;(!Z?.instanceId||Z.instanceId===a)&&Pt.hideArtifacts()},T=q=>{let Z=q.detail;Z?.instanceId&&Z.instanceId!==a||Z?.artifact&&Pt.upsertArtifact(Z.artifact)},R=q=>{let Z=q.detail;Z?.instanceId&&Z.instanceId!==a||typeof Z?.id=="string"&&Pt.selectArtifact(Z.id)},ne=q=>{let Z=q.detail;(!Z?.instanceId||Z.instanceId===a)&&Pt.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",ne),$e.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",ne)})}let hn=Fx(o.persistState);if(hn&&I()){let a=_x(hn.storage),f=`${hn.keyPrefix}widget-open`,m=`${hn.keyPrefix}widget-voice`,x=`${hn.keyPrefix}widget-voice-mode`;if(a){let T=hn.persist?.openState&&a.getItem(f)==="true",R=hn.persist?.voiceState&&a.getItem(m)==="true",ne=hn.persist?.voiceState&&a.getItem(x)==="true";if(T&&setTimeout(()=>{Pt.open(),setTimeout(()=>{if(R||ne)Pt.startVoiceRecognition();else if(hn.persist?.focusInput){let q=t.querySelector("textarea");q&&q.focus()}},100)},0),hn.persist?.openState&&(p.on("widget:opened",()=>{a.setItem(f,"true")}),p.on("widget:closed",()=>{a.setItem(f,"false")})),hn.persist?.voiceState&&(p.on("voice:state",q=>{a.setItem(m,q.active?"true":"false")}),p.on("user:message",q=>{a.setItem(x,q.viaVoice?"true":"false")})),hn.clearOnChatClear){let q=()=>{a.removeItem(f),a.removeItem(m),a.removeItem(x)},Z=()=>q();window.addEventListener("persona:clear-chat",Z),$e.push(()=>{window.removeEventListener("persona:clear-chat",Z)})}}}if(g&&I()&&setTimeout(()=>{Pt.open()},0),tr(),!xm){let a=ki(()=>{V&&(el++,Lo.clear(),Jr(We,V.getMessages(),Y))});$e.push(a)}return Pt};var Jf=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},Ux=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},jx=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},Vx=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Yf=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},Kc=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},Zf=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Kc(t)},jc=t=>{t.style.transition=""},Vc=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},qc=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},qa=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},qx=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},Kx=(t,e,n,o,r,s)=>{let i=s?e:t;r==="left"?i.firstElementChild!==o&&i.replaceChildren(o,n):i.lastElementChild!==o&&i.replaceChildren(n,o)},Gx=t=>{let e=wr(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:en(e,r)??r;return{inset:o(n?.inset,da),canvasBackground:o(n?.canvasBackground,pa)}},em=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},Qx=(t,e,n,o,r,s,i,l)=>{let p=xn(s),c=p.reveal==="push",d=l!=null,u=l?.inset??"",b=l?.canvasBackground??"";qx(t,e,n,o,c),Kx(t,e,n,o,p.side,c),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=p.side,t.dataset.personaDockOpen=i?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let g=t.ownerDocument.defaultView,h=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,L=g!=null?g.innerWidth<=C:!1;if(h&&L&&i){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Vc(e),jc(o),Zf(o),qc(n),qa(r,o),em(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Qt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",c&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),Zf(o),Ux(o,p.maxHeight),em(o,d&&i,u,b),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Vc(e),jc(o),qc(n),qa(r,o);let k=p.animate?"transform 180ms ease":"none",S=p.side==="right"?"translateX(100%)":"translateX(-100%)",E=i?"translateX(0)":S;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=k,o.style.transform=E,o.style.pointerEvents=i?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",jc(o),Kc(o),qa(r,o);let k=Jf(p.width,t.clientWidth),S=Math.max(0,t.clientWidth),E=p.animate?"margin-left 180ms ease":"none",z=p.side==="right"?i?-k:0:i?0:-k;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${S+k}px`,e.style.transition=E,e.style.marginLeft=`${z}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${S}px`,n.style.maxWidth=`${S}px`,n.style.minWidth=`${S}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=i?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",Vc(e),Kc(o),qc(n),qa(r,o);let k=p.reveal==="emerge";k?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let S=i?p.width:"0px",E=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${d?", padding 180ms ease":""}`:"none",z=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",jx(o,p.maxHeight),o.style.overflow=k||z?"hidden":"visible",o.style.transition=E,k){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let G=d?`calc(${Jf(p.width,t.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=G,r.style.minWidth=G,r.style.maxWidth=G,r.style.boxSizing="border-box"}}},Xx=(t,e)=>{let n=t.ownerDocument.createElement("div");return Yf(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Yf(n,o)},destroy(){n.remove()}}},Jx=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,i=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),c=n.createElement("aside"),d=n.createElement("div"),u=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",c.appendChild(d),o.insertBefore(i,t),p.appendChild(t);let b=null,g=()=>{b?.disconnect(),b=null},h=null,C=()=>{h=e?.launcher?.detachedPanel===!0?Gx(e):null};C();let L=()=>{Qx(i,l,p,c,d,e,u,h)},B=null,k=()=>{B?.(),B=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(B=ua(()=>{C(),L()}))},S=()=>{g(),xn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{L()}),b.observe(i)))},E=!1,z=()=>{L(),S(),u&&!E&&i.dataset.personaDockMobileFullscreen!=="true"&&(E=!0,Vx(i,xn(e)))},G=i.ownerDocument.defaultView,A=()=>{z()};return G?.addEventListener("resize",A),xn(e).reveal==="push"?(l.appendChild(p),l.appendChild(c),i.appendChild(l)):(i.appendChild(p),i.appendChild(c)),z(),k(),{mode:"docked",host:d,shell:i,syncWidgetState(O){let D=O.launcherEnabled?O.open:!0;u!==D&&(u=D,z())},updateConfig(O){e=O,(e?.launcher?.enabled??!0)===!1&&(u=!0),C(),z(),k()},destroy(){G?.removeEventListener("resize",A),B?.(),B=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),i.remove()}}},tm=(t,e)=>_t(e)?Jx(t,e):Xx(t,e);var Qs={desktop:{w:1280,h:800},mobile:{w:390,h:844}},nm=.15,om=1.5,Gc="persona-preview-shell-theme",Yx={load:()=>null,save:()=>{},clear:()=>{}},Zx=["How do I get started?","Pricing & plans","Talk to support"];function Qc(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function eC(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function rm(t){let e=eC(t);return`* { box-sizing: border-box; }
314
314
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
315
315
  html { color-scheme: ${t}; }
316
316
  body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
@@ -334,7 +334,7 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
334
334
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
335
335
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
336
336
  .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
337
- .preview-workspace-card.short { height: 96px; }`}function $g(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(zc);o||(o=n.createElement("style"),o.id=zc,n.head.appendChild(o)),o.textContent=_g(e)}var kx=`
337
+ .preview-workspace-card.short { height: 96px; }`}function sm(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Gc);o||(o=n.createElement("style"),o.id=Gc,n.head.appendChild(o)),o.textContent=rm(e)}var tC=`
338
338
  <div class="preview-iframe-mock" aria-hidden="true">
339
339
  <div class="preview-iframe-chrome">
340
340
  <span class="preview-iframe-dot"></span>
@@ -353,7 +353,7 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
353
353
  <div class="preview-iframe-line body"></div>
354
354
  <div class="preview-iframe-line body"></div>
355
355
  </div>
356
- </div>`,Lx=`
356
+ </div>`,nC=`
357
357
  <div class="preview-workspace-content-shell" aria-hidden="true">
358
358
  <div class="preview-iframe-line hero"></div>
359
359
  <div class="preview-iframe-line body"></div>
@@ -366,8 +366,8 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
366
366
  <div class="preview-workspace-card short"></div>
367
367
  <div class="preview-workspace-card short"></div>
368
368
  </div>
369
- </div>`;function zg(t,e,n,o){let r=`
370
- ${kx}
369
+ </div>`;function im(t,e,n,o){let r=`
370
+ ${tC}
371
371
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
372
372
  <div class="preview-workspace-shell">
373
373
  <div class="preview-workspace-topbar">
@@ -379,7 +379,7 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
379
379
  </div>
380
380
  <div class="preview-workspace-body">
381
381
  <div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
382
- ${Lx}
382
+ ${nC}
383
383
  </div>
384
384
  </div>
385
385
  </div>`;return`<!DOCTYPE html>
@@ -387,16 +387,16 @@ _Details: ${n.message}_`:o}var fs=t=>({isError:!0,content:[{type:"text",text:t}]
387
387
  <head>
388
388
  <meta charset="UTF-8">
389
389
  <meta name="viewport" content="width=device-width, initial-scale=1">
390
- <link rel="stylesheet" href="${jc(o)}">
391
- <style id="${zc}">${_g(e)}</style>
390
+ <link rel="stylesheet" href="${Qc(o)}">
391
+ <style id="${Gc}">${rm(e)}</style>
392
392
  </head>
393
393
  <body>
394
394
  ${n?s:r}
395
395
  </body>
396
- </html>`}var Px=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],Ix=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function Rx(t,e,n=[]){return t==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&Ix(e)?[...Px(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function Wx(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:Tx:t.suggestionChips,initialMessages:Rx(e,t,n),storageAdapter:Mx};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function Hx(t,e){let n=t.theme?yr(t.theme,{validate:!1}):yr();return{...lt,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function Pr(t,e){let n=t.scene??"conversation";return Wx(Hx(t,e),n,t.appendedMessages??[])}function jg(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Pr(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Pr(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Pr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Pr(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Pr(t,n),shellMode:n}]}function Ug(t,e){let n={...e},o=[],r=[],s=null,i=!1,l=1,p=1,c=0;function d(){return n.device??"desktop"}function u(){return n.zoom??l}function b(){let L=getComputedStyle(t),T=parseFloat(L.paddingLeft)+parseFloat(L.paddingRight),k=parseFloat(L.paddingTop)+parseFloat(L.paddingBottom),$=40,G=(n.compareMode??"off")!=="off",w=(t.clientWidth-T-$)/(G?2:1),F=t.clientHeight-k-$;if(w<=0||F<=0)return 1;let D=$s[d()]??$s.desktop;return Math.min(w/D.w,F/D.h,1)}function f(){l=b();let L=Math.max(Og,Math.min(Fg,u()));p=L;let T=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let k of T){let $=k.dataset.device??"desktop",G=$s[$]??$s.desktop;k.style.width=`${G.w*L}px`,k.style.height=`${G.h*L}px`,$==="mobile"&&(k.style.borderRadius=`${32*L}px`);let w=k.querySelector("iframe");w&&(w.style.width=`${G.w}px`,w.style.height=`${G.h}px`,w.style.transformOrigin="top left",w.style.transition="none",w.style.transform=`scale(${L})`)}n.onScaleChange?.(L)}function m(){n.onBeforeDestroy?.();for(let L of o)L.destroy();for(let L of r)L();o=[],r=[]}function C(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function R(){if(i)return;m();let L=++c,T=jg(n),k=d(),$=(n.compareMode??"off")!=="off",G=(n.scene??"conversation")==="minimized",w=n.widgetCssPath??"/widget-dist/widget.css",F=n.buildSrcdoc??zg,D=k==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",B=ge=>`<div class="${D}" data-mount-id="${ge.mountId}" data-device="${k}" data-shell-mode="${ge.shellMode}">
397
- ${$?`<div class="preview-frame-meta"><span class="preview-frame-label">${jc(ge.label)}</span></div>`:""}
398
- <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ge.mountId}"></iframe>
399
- </div>`,P=$?`<div class="preview-compare-grid">${T.map(ge=>`<div class="preview-compare-cell">${B(ge)}</div>`).join("")}</div>`:`<div class="preview-single">${B(T[0])}</div>`;n.morphContainer?n.morphContainer(t,P):t.innerHTML=P,f();let I=C(),j=0,pe=I.length,ue=()=>{if(i||L!==c)return;for(let Z of I){let oe=Z.dataset.mountId;if(!oe||!Z.contentDocument)continue;let Q=T.find(he=>he.mountId===oe);if(!Q)continue;let se=()=>{},te=_t(Q.config),fe=te?(()=>{let he=Z.contentDocument?.getElementById(`preview-content-${oe}`);if(!he)return null;let Ce=Ng(he,Q.config),$e=Z.contentDocument.createElement("div");$e.id=oe,$e.style.height="100%",$e.style.display="flex",$e.style.flexDirection="column",$e.style.flex="1",$e.style.minHeight="0",Ce.host.appendChild($e);let Ee=()=>Ce.syncWidgetState(be.getState()),ke=se;return se=()=>{Ce.destroy(),ke()},$e.__syncDock=Ee,$e.__hostLayout=Ce,$e})():Z.contentDocument.getElementById(oe);if(!fe)continue;let be=Rg(fe,Q.config);if(o.push(be),te&&fe.__syncDock){let he=fe.__syncDock,Ce=be.on("widget:opened",he),$e=be.on("widget:closed",he),Ee=se;se=()=>{Ce(),$e(),Ee()},he()}r.push(se),G&&be.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let Z of o)Z.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
396
+ </html>`}var oC=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],rC=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function sC(t,e,n=[]){if(t==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return t==="home"?[]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&rC(e)?[...oC(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function iC(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:Zx:t.suggestionChips,initialMessages:sC(e,t,n),storageAdapter:Yx};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function aC(t,e){let n=t.theme?Cr(t.theme,{validate:!1}):Cr();return{...it,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function Hr(t,e){let n=t.scene??"conversation";return iC(aC(t,e),n,t.appendedMessages??[])}function am(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Hr(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Hr(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Hr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Hr(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Hr(t,n),shellMode:n}]}function lm(t,e){let n={...e},o=[],r=[],s=null,i=!1,l=1,p=1,c=0;function d(){return n.device??"desktop"}function u(){return n.zoom??l}function b(){let k=getComputedStyle(t),S=parseFloat(k.paddingLeft)+parseFloat(k.paddingRight),E=parseFloat(k.paddingTop)+parseFloat(k.paddingBottom),z=40,G=(n.compareMode??"off")!=="off",A=(t.clientWidth-S-z)/(G?2:1),O=t.clientHeight-E-z;if(A<=0||O<=0)return 1;let D=Qs[d()]??Qs.desktop;return Math.min(A/D.w,O/D.h,1)}function g(){l=b();let k=Math.max(nm,Math.min(om,u()));p=k;let S=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let E of S){let z=E.dataset.device??"desktop",G=Qs[z]??Qs.desktop;E.style.width=`${G.w*k}px`,E.style.height=`${G.h*k}px`,z==="mobile"&&(E.style.borderRadius=`${32*k}px`);let A=E.querySelector("iframe");A&&(A.style.width=`${G.w}px`,A.style.height=`${G.h}px`,A.style.transformOrigin="top left",A.style.transition="none",A.style.transform=`scale(${k})`)}n.onScaleChange?.(k)}function h(){n.onBeforeDestroy?.();for(let k of o)k.destroy();for(let k of r)k();o=[],r=[]}function C(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function L(){if(i)return;h();let k=++c,S=am(n),E=d(),z=(n.compareMode??"off")!=="off",G=(n.scene??"conversation")==="minimized",A=n.widgetCssPath??"/widget-dist/widget.css",O=n.buildSrcdoc??im,D=E==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",W=se=>`<div class="${D}" data-mount-id="${se.mountId}" data-device="${E}" data-shell-mode="${se.shellMode}">
397
+ ${z?`<div class="preview-frame-meta"><span class="preview-frame-label">${Qc(se.label)}</span></div>`:""}
398
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${se.mountId}"></iframe>
399
+ </div>`,P=z?`<div class="preview-compare-grid">${S.map(se=>`<div class="preview-compare-cell">${W(se)}</div>`).join("")}</div>`:`<div class="preview-single">${W(S[0])}</div>`;n.morphContainer?n.morphContainer(t,P):t.innerHTML=P,g();let I=C(),j=0,pe=I.length,ge=()=>{if(i||k!==c)return;for(let Y of I){let oe=Y.dataset.mountId;if(!oe||!Y.contentDocument)continue;let J=S.find(he=>he.mountId===oe);if(!J)continue;let ie=()=>{},ee=_t(J.config),fe=ee?(()=>{let he=Y.contentDocument?.getElementById(`preview-content-${oe}`);if(!he)return null;let we=tm(he,J.config),ve=Y.contentDocument.createElement("div");ve.id=oe,ve.style.height="100%",ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1",ve.style.minHeight="0",we.host.appendChild(ve);let Te=()=>we.syncWidgetState(be.getState()),Me=ie;return ie=()=>{we.destroy(),Me()},ve.__syncDock=Te,ve.__hostLayout=we,ve})():Y.contentDocument.getElementById(oe);if(!fe)continue;let be=Xf(fe,J.config);if(o.push(be),ee&&fe.__syncDock){let he=fe.__syncDock,we=be.on("widget:opened",he),ve=be.on("widget:closed",he),Te=ie;ie=()=>{we(),ve(),Te()},he()}r.push(ie),G&&be.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let Y of o)Y.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
400
400
 
401
401
  This is a preview of the artifact sidebar.
402
402
 
@@ -404,4 +404,4 @@ This is a preview of the artifact sidebar.
404
404
 
405
405
  - Markdown rendering
406
406
  - Document toolbar
407
- - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:I,controllers:[...o]})};for(let ge of I){let Z=ge.dataset.mountId;if(!Z)continue;let oe=T.find(Q=>Q.mountId===Z);oe&&(ge.addEventListener("load",()=>{j++,j>=pe&&ue()},{once:!0}),ge.srcdoc=F(Z,oe.shellMode,_t(oe.config),w))}pe===0&&ue()}function H(){if(i)return;let L=jg(n);if(o.length!==L.length){R();return}if(L.some(k=>{let $=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${k.mountId}"]`);return!$||$.dataset.shellMode!==k.shellMode})){R();return}o.forEach((k,$)=>{k.update(L[$].config),(n.scene??"conversation")==="minimized"&&k.close()});for(let k of L){let $=t.querySelector(`iframe[data-mount-id="${k.mountId}"]`);$&&$g($,k.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{i||f()}),s.observe(t)),R(),{update(L){if(i)return;let T=L.device!==void 0&&L.device!==n.device||L.scene!==void 0&&L.scene!==n.scene||L.compareMode!==void 0&&L.compareMode!==n.compareMode||L.widgetCssPath!==void 0&&L.widgetCssPath!==n.widgetCssPath;n={...n,...L},T?R():H()},destroy(){i||(i=!0,m(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){i||(n={...n,zoom:void 0},f())},getIframes(){return C()},getScale(){return p},setZoom(L){i||(n={...n,zoom:L},f())}}}0&&(module.exports={createThemePreview});
407
+ - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:I,controllers:[...o]})};for(let se of I){let Y=se.dataset.mountId;if(!Y)continue;let oe=S.find(J=>J.mountId===Y);oe&&(se.addEventListener("load",()=>{j++,j>=pe&&ge()},{once:!0}),se.srcdoc=O(Y,oe.shellMode,_t(oe.config),A))}pe===0&&ge()}function B(){if(i)return;let k=am(n);if(o.length!==k.length){L();return}if(k.some(E=>{let z=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${E.mountId}"]`);return!z||z.dataset.shellMode!==E.shellMode})){L();return}o.forEach((E,z)=>{E.update(k[z].config),(n.scene??"conversation")==="minimized"&&E.close()});for(let E of k){let z=t.querySelector(`iframe[data-mount-id="${E.mountId}"]`);z&&sm(z,E.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{i||g()}),s.observe(t)),L(),{update(k){if(i)return;let S=k.device!==void 0&&k.device!==n.device||k.scene!==void 0&&k.scene!==n.scene||k.compareMode!==void 0&&k.compareMode!==n.compareMode||k.widgetCssPath!==void 0&&k.widgetCssPath!==n.widgetCssPath;n={...n,...k},S?L():B()},destroy(){i||(i=!0,h(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){i||(n={...n,zoom:void 0},g())},getIframes(){return C()},getScale(){return p},setZoom(k){i||(n={...n,zoom:k},g())}}}0&&(module.exports={createThemePreview});