@runtypelabs/persona 4.22.0 → 4.22.1

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 (93) hide show
  1. package/dist/animations/glyph-cycle.d.cts +1 -1
  2. package/dist/animations/glyph-cycle.d.ts +1 -1
  3. package/dist/animations/{types-B_JdVK9o.d.cts → types-9Vxm-PPz.d.cts} +136 -6
  4. package/dist/animations/{types-B_JdVK9o.d.ts → types-9Vxm-PPz.d.ts} +136 -6
  5. package/dist/animations/wipe.d.cts +1 -1
  6. package/dist/animations/wipe.d.ts +1 -1
  7. package/dist/animations-extra.d.cts +136 -6
  8. package/dist/animations-extra.d.ts +136 -6
  9. package/dist/approval-ui.d.cts +148 -14
  10. package/dist/approval-ui.d.ts +148 -14
  11. package/dist/artifacts-ui.d.cts +148 -14
  12. package/dist/artifacts-ui.d.ts +148 -14
  13. package/dist/codegen.cjs +1 -1
  14. package/dist/codegen.js +1 -1
  15. package/dist/context-mentions.d.cts +148 -14
  16. package/dist/context-mentions.d.ts +148 -14
  17. package/dist/event-stream-view-GL3ADRY2.js +1 -0
  18. package/dist/event-stream-view.cjs +1 -1
  19. package/dist/event-stream-view.d.cts +148 -14
  20. package/dist/event-stream-view.d.ts +148 -14
  21. package/dist/event-stream-view.js +1 -1
  22. package/dist/forms-ui.d.cts +161 -23
  23. package/dist/forms-ui.d.ts +161 -23
  24. package/dist/history-view.d.cts +136 -6
  25. package/dist/history-view.d.ts +136 -6
  26. package/dist/index.cjs +67 -67
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +166 -27
  29. package/dist/index.d.ts +166 -27
  30. package/dist/index.global.js +51 -51
  31. package/dist/index.global.js.map +1 -1
  32. package/dist/index.js +67 -67
  33. package/dist/index.js.map +1 -1
  34. package/dist/session-reconnect.d.cts +148 -14
  35. package/dist/session-reconnect.d.ts +148 -14
  36. package/dist/smart-dom-reader.d.cts +148 -14
  37. package/dist/smart-dom-reader.d.ts +148 -14
  38. package/dist/testing.cjs +3 -3
  39. package/dist/testing.d.cts +3 -4
  40. package/dist/testing.d.ts +3 -4
  41. package/dist/testing.js +3 -3
  42. package/dist/theme-editor-preview.cjs +71 -71
  43. package/dist/theme-editor-preview.d.cts +148 -14
  44. package/dist/theme-editor-preview.d.ts +148 -14
  45. package/dist/theme-editor-preview.js +48 -48
  46. package/dist/theme-editor.d.cts +148 -14
  47. package/dist/theme-editor.d.ts +148 -14
  48. package/dist/voice-runtime.d.cts +6 -2
  49. package/dist/voice-runtime.d.ts +6 -2
  50. package/package.json +1 -1
  51. package/src/ask-user-question-tool.ts +1 -1
  52. package/src/client-history-rest.test.ts +2 -1
  53. package/src/client-visitor-history.test.ts +20 -4
  54. package/src/client.composer-options.test.ts +1 -1
  55. package/src/client.interrupt.test.ts +2 -2
  56. package/src/client.test.ts +477 -915
  57. package/src/client.ts +134 -494
  58. package/src/client.unified-tools.test.ts +76 -0
  59. package/src/components/event-stream-badge-theming.test.ts +3 -0
  60. package/src/components/event-stream-view.test.ts +76 -76
  61. package/src/components/event-stream-view.ts +5 -0
  62. package/src/components/tool-bubble.test.ts +12 -0
  63. package/src/components/tool-bubble.ts +13 -2
  64. package/src/event-stream-view-bundle.test.ts +2 -2
  65. package/src/generated/runtype-openapi-contract.ts +129 -1
  66. package/src/internal/runtype-history-provider.test.ts +2 -2
  67. package/src/session-history.test.ts +1 -1
  68. package/src/session.quote.test.ts +1 -1
  69. package/src/session.resubmit-from.test.ts +1 -1
  70. package/src/session.test.ts +5 -5
  71. package/src/session.ts +95 -36
  72. package/src/suggest-replies-tool.ts +1 -1
  73. package/src/testing/mock-stream.test.ts +37 -16
  74. package/src/testing/mock-stream.ts +14 -9
  75. package/src/types.ts +19 -14
  76. package/src/ui.ask-user-question-plugin.test.ts +7 -7
  77. package/src/ui.composer-defer-one.test.ts +6 -34
  78. package/src/ui.composer-draft-persistence.test.ts +1 -1
  79. package/src/ui.composer-quote.test.ts +1 -1
  80. package/src/ui.message-history-actions.test.ts +1 -1
  81. package/src/ui.streaming-coalescing.test.ts +10 -13
  82. package/src/ui.ts +67 -32
  83. package/src/ui.typing-indicator.test.ts +216 -0
  84. package/src/ui.voice-custom-provider.test.ts +211 -0
  85. package/src/utils/event-stream-buffer.test.ts +13 -13
  86. package/src/utils/event-stream-capture.test.ts +20 -20
  87. package/src/utils/throughput-tracker.test.ts +100 -142
  88. package/src/utils/throughput-tracker.ts +18 -132
  89. package/src/utils/voice-support.ts +18 -1
  90. package/src/voice/voice-turn-tracker.ts +18 -0
  91. package/src/webmcp-bridge.ts +1 -1
  92. package/dist/event-stream-view-FKWDY3UB.js +0 -1
  93. package/src/utils/__fixtures__/unified-translator.oracle.ts +0 -717
package/dist/index.js CHANGED
@@ -1,31 +1,31 @@
1
- var CM=Object.defineProperty;var Da=(e,t)=>()=>(e&&(t=e(e=0)),t);var Qy=(e,t)=>{for(var n in t)CM(e,n,{get:t[n],enumerable:!0})};var Xy={};Qy(Xy,{DOMPurify:()=>xM,Marked:()=>wM});import{Marked as wM}from"marked";import xM from"dompurify";var Jy=Da(()=>{"use strict"});var Li,kg=Da(()=>{"use strict";Li=class{constructor(t=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=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*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 t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,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 t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}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 t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);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 a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of a)l()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function aP(e){return e.replace(/\/+$/,"")}async function lP(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var sd,vv=Da(()=>{"use strict";kg();sd=class{constructor(t){this.opts=t;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 Li(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let r=await this.ensurePlayer();if(t!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.generation&&o.onStart?.()}),r.onFinished(()=>{t===this.generation&&o.onEnd?.()});let s=`${aP(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=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(t!==this.generation)return;if(!a.ok||!a.body)throw new Error(await lP(a));let l=a.body.getReader();for(;;){let{done:d,value:p}=await l.read();if(t!==this.generation){await l.cancel().catch(()=>{});return}if(d)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(t!==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 id,Cv=Da(()=>{"use strict";id=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{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(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var wv={};Qy(wv,{FallbackSpeechEngine:()=>id,RuntypeSpeechEngine:()=>sd});var xv=Da(()=>{"use strict";vv();Cv()});import{Marked as MM}from"marked";import EM from"dompurify";var vt=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:u=>{o=u,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(m=>(r=m,m)).catch(m=>{throw s=null,m}),s),provide:u=>{r=u},getSync:()=>r}};var{setLoader:bH,load:SM,provide:AM,getSync:Zu}=vt({fallbackImport:()=>Promise.resolve().then(()=>(Jy(),Xy))}),Nc=new Set,Zy=()=>{let e=[...Nc];Nc.clear();for(let t of e)try{t()}catch{}};var eg=()=>{let e=Zu();return e?Promise.resolve(e):SM().then(t=>(Zy(),t))},Na=e=>Zu()?()=>{}:(Nc.add(e),()=>{Nc.delete(e)}),eb=e=>{AM(e),Zy()},Oo=Zu;eb({Marked:MM,DOMPurify:EM});import{Ban as TM,Bell as kM,Bookmark as PM,Building as LM,Calendar as IM,CalendarDays as RM,Camera as HM,ChartColumn as WM,CircleCheck as OM,CircleX as BM,Clock as _M,CreditCard as DM,DollarSign as NM,EyeOff as FM,Files as $M,Film as UM,Flag as jM,Folder as qM,FolderOpen as zM,Funnel as VM,Gift as KM,Globe as GM,Hash as YM,Headphones as QM,Heart as XM,House as JM,Image as ZM,Info as eE,Key as tE,Lightbulb as nE,Link as oE,Lock as rE,Mail as sE,MapPin as iE,MessageCircle as aE,Monitor as lE,Moon as cE,Package as dE,Pause as pE,PenLine as uE,Percent as gE,Phone as mE,Play as fE,Receipt as hE,RotateCw as yE,Save as bE,Settings as vE,Share as CE,Shield as wE,ShoppingBag as xE,ShoppingCart as SE,Smartphone as AE,Sparkles as ME,Store as EE,Sun as TE,Tag as kE,Timer as PE,TriangleAlert as LE,Truck as IE,User as RE,VolumeX as HE,Wallet as WE,Zap as OE}from"lucide";var tb={user:RE,mail:sE,phone:mE,calendar:IM,clock:_M,building:LM,"map-pin":iE,lock:rE,key:tE,"credit-card":DM,hash:YM,globe:GM,link:oE,"circle-check":OM,"circle-x":BM,"triangle-alert":LE,info:eE,ban:TM,shield:wE,house:JM,"pen-line":uE,save:bE,share:CE,funnel:VM,settings:vE,"rotate-cw":yE,"shopping-cart":SE,"shopping-bag":xE,package:dE,truck:IE,tag:kE,gift:KM,receipt:hE,wallet:WE,store:EE,"dollar-sign":NM,percent:gE,play:fE,pause:pE,"volume-x":HE,camera:HM,image:ZM,film:UM,headphones:QM,"message-circle":aE,bell:kM,heart:XM,"eye-off":FM,bookmark:PM,"calendar-days":RM,timer:PE,folder:qM,"folder-open":zM,files:$M,"chart-column":WM,sparkles:ME,zap:OE,sun:TE,moon:cE,flag:jM,lightbulb:nE,monitor:lE,smartphone:AE};var Wt=(e,t=24,n="currentColor",o=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),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"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([p,u])=>{p!=="stroke"&&d.setAttribute(p,String(u))}),r.appendChild(d)}),r};var{setLoader:TH,load:BE}=vt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")});var Fc=BE;import{Activity as _E,ArrowDown as DE,ArrowLeft as NE,ArrowRight as FE,ArrowUp as $E,ArrowUpRight as UE,AtSign as jE,Bot as qE,Check as zE,ChevronDown as VE,ChevronLeft as KE,ChevronRight as GE,ChevronUp as YE,Clipboard as QE,ClipboardCopy as XE,CodeXml as JE,Copy as ZE,Download as eT,Ellipsis as tT,EllipsisVertical as nT,ExternalLink as oT,Eye as rT,File as sT,FileCode as iT,FileSpreadsheet as aT,FileText as lT,History as cT,ImagePlus as dT,Loader as pT,LoaderCircle as uT,Maximize as gT,Menu as mT,MessageSquare as fT,Mic as hT,Minimize as yT,Minus as bT,PanelLeft as vT,Paperclip as CT,Pencil as wT,Plus as xT,Quote as ST,RefreshCw as AT,Search as MT,Send as ET,ShieldAlert as TT,ShieldCheck as kT,ShieldX as PT,Square as LT,Star as IT,ThumbsDown as RT,ThumbsUp as HT,Trash as WT,Trash2 as OT,Upload as BT,Volume2 as _T,X as DT}from"lucide";var NT={activity:_E,"arrow-down":DE,"arrow-up":$E,"arrow-up-right":UE,bot:qE,"chevron-down":VE,"chevron-up":YE,"chevron-right":GE,"chevron-left":KE,check:zE,clipboard:QE,"clipboard-copy":XE,"code-xml":JE,copy:ZE,file:sT,"file-code":iT,"file-spreadsheet":aT,"file-text":lT,"image-plus":dT,loader:pT,"loader-circle":uT,mic:hT,paperclip:CT,quote:ST,"refresh-cw":AT,search:MT,send:ET,"shield-alert":TT,"shield-check":kT,"shield-x":PT,square:LT,"thumbs-down":RT,"thumbs-up":HT,upload:BT,"volume-2":_T,x:DT,"at-sign":jE,"arrow-left":NE,"arrow-right":FE,"external-link":oT,ellipsis:tT,"ellipsis-vertical":nT,menu:mT,"panel-left":vT,plus:xT,minus:bT,pencil:wT,trash:WT,"trash-2":OT,download:eT,maximize:gT,minimize:yT,"message-square":fT,star:IT,eye:rT,history:cT},FT=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],ks=new Map(Object.entries(NT)),wi=new Set,xi=!1,$c=new Set,ng=e=>{let t=[...$c];e&&$c.clear();for(let n of t)try{n()}catch{}},nb=e=>xi?()=>{}:($c.add(e),()=>{$c.delete(e)}),og=()=>{let e=0;for(let t of[...wi]){let n=ks.get(t.name);if(!n)continue;wi.delete(t),e++;let o=Wt(n,t.size,t.color,t.strokeWidth);if(o)for(t.el.removeAttribute("data-persona-icon-pending");o.firstChild;)t.el.appendChild(o.firstChild)}return e},$T=e=>{for(let[t,n]of Object.entries(e))ks.set(t,n);og()>0&&!xi&&ng(!1)},ob=e=>{if(!xi){for(let[t,n]of Object.entries(e))ks.has(t)||ks.set(t,n);xi=!0,og(),ng(!0)}},tg=!1,UT=()=>{Fc().then(e=>{if(!xi){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))ks.has(t)||ks.set(t,n);xi=!0,og(),ng(!0)}}).catch(e=>{tg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},jT=(e,t,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},pe=(e,t=24,n="currentColor",o=2)=>{let r=ks.get(e);if(r)return Wt(r,t,n,o);if(FT.includes(e)){tg&&(tg=!1);let s=jT(t,n,o);if(wi.size>=500){let a=wi.values().next().value;a&&wi.delete(a)}return wi.add({el:s,name:e,size:t,color:n,strokeWidth:o}),UT(),s}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null};ob(tb);var qT=e=>{if(!e)return;let t={},n=e;if(n.heading){let o=n.heading;t.heading=(r,s,a)=>o({type:"heading",raw:a,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;t.code=(r,s,a)=>o({type:"code",raw:"",text:r,lang:s,escaped:a})}if(n.blockquote){let o=n.blockquote;t.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;t.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;t.link=(r,s,a)=>o({type:"link",raw:"",href:r,title:s??null,text:a,tokens:[]})}if(n.image){let o=n.image;t.image=(r,s,a)=>o({type:"image",raw:"",href:r,title:s??null,text:a})}if(n.list){let o=n.list;t.list=(r,s,a)=>o({type:"list",raw:"",ordered:s,start:a,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;t.listitem=(r,s,a)=>o({type:"list_item",raw:"",task:s,checked:a,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;t.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;t.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;t.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;t.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;t.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;t.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;t.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;t.checkbox=r=>o({checked:r})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Uc=e=>{let t=null;return n=>{let o=Oo();if(!o)return Br(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=qT(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},jc=e=>e?Uc({markedOptions:e.options,renderer:e.renderer}):Uc(),zT=Uc(),sb=e=>zT(e),Br=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),ib=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),rb=e=>`%%FORM_PLACEHOLDER_${e}%%`,ab=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=rb(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=rb(t.length);return t.push({token:s,type:r}),s}),n},VT=e=>{let t=jc(e);return n=>{let o=[],r=ab(n,o),s=t(r);return o.forEach(({token:a,type:l})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${ib(l)}"></div>`;s=s.replace(d,u)}),s}},KT=e=>{let t=[],n=ab(e,t),o=sb(n);return t.forEach(({token:r,type:s})=>{let a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${ib(s)}"></div>`;o=o.replace(a,d)}),o};var GT={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"]},YT=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,lb=()=>{let e=null;return t=>{let n=Oo();if(!n)return Br(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!YT.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,GT)}},rg=e=>e===!1?null:typeof e=="function"?e:lb();var cb=/^\s*\|?[\s:|-]*-[\s:|-]*$/,db=e=>e.includes("|"),pb=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},QT=e=>`| ${e.join(" | ")} |`,XT=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,JT=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),ub=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
- `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!db(r)||cb.test(r)||!cb.test(s))continue;let a=pb(r).length;if(a<1)continue;let l=XT(a);t[o+1]!==l&&(t[o+1]=l,n=!0);let d=o+2;for(;d<t.length;d++){let p=t[d];if(p.trim()===""||!db(p))break;let u=QT(JT(pb(p),a));t[d]!==u&&(t[d]=u,n=!0)}o=d-1}return n?t.join(`
3
- `):e};var gb="var(--persona-md-table-scroll-fade, 24px)",mb=new WeakSet;function hb(e){e.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 fb(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":gb),e.style.setProperty("--persona-fade-r",r<=1?"0px":gb)}function sg(e){mb.has(e)||(mb.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&fb(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(fb)}var qc="webmcp:",ig=new Map,zc=e=>{ig.clear();for(let t of e){let n=t.title?.trim();n&&ig.set(t.name,n)}},Si=e=>ig.get(Cb(e)),yb=null;function vb(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${ZT(t.join(""))}`}function bb(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.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 ZT(e){let t=bb(e,0).toString(36),n=bb(e,2654435761).toString(36);return`${t}.${n}`}var Cb=e=>e.startsWith(qc)?e.slice(qc.length):e,Ps=e=>e.startsWith(qc),Vc=()=>yb?yb():import("@mcp-b/webmcp-polyfill");var{setLoader:qH,load:ek}=vt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var wb=ek;function Fn(e){return e==="card"?"collapsed":e}function Ls(e){return e.split(";",1)[0].trim().toLowerCase()}function tk(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Ls(r)===t)return{mode:Fn(s),selector:Ls(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ls(r)===o)return{mode:Fn(s),selector:o}}function xb(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:Fn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Ls(t.file.mimeType):void 0,d=l?tk(o.files.byMediaType,l):void 0;if(l&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:l,selector:d.selector}};if(o.files.default)return{mode:Fn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:Fn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:Fn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:Fn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:Fn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function cr(e,t){return xb(e,t).mode}function Fa(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var nk="agent_",ok="flow_";function Sb(e){return e.startsWith(nk)?{kind:"agentId",agentId:e}:e.startsWith(ok)?{kind:"flowId",flowId:e}:null}function Ab(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let p=Sb(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let d=t?.[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(l).payload}}let r=Sb(n);if(r)return r;let s=t?.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.`)}function rk(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function $a(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Is(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Mb(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}import{parse as sk,ARR as ik,OBJ as ak,STR as lk}from"partial-json";var M=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Q=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let l of Object.keys(a)){let d=a[l];d!=null&&(s[l]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},mn=(...e)=>e.filter(Boolean).join(" ");var Kc="ask_user_question",Ua=8,Ai="data-persona-ask-sheet-for",ck="Other",dk="Other\u2026",Tb="Type your own answer here",kb="Send",pk="Next",uk="Back",gk="Submit all",mk="Skip",fk=3,ag="data-ask-current-index",lg="data-ask-question-count",Pb="data-ask-answers",cg="data-ask-grouped",Lb="data-ask-layout",hk=e=>e.layout==="pills"?"pills":"rows",yk=e=>e.getAttribute(Lb)==="pills"?"pills":"rows",Eb=!1,Ib=e=>e.replace(/["\\]/g,"\\$&"),_r=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Kc,Gc=e=>e?.features?.askUserQuestion??{},Dr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=sk(r,lk|ak|ik);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ja=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ua&&!Eb&&(Eb=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ua}.`)),t.slice(0,Ua)},bk=e=>ja(e)[0]??null,vk=(e,t)=>ja(e)[t]??null,Rb=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Hb=(e,t,n)=>{if(e!=="rows")return null;let o=M("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=M("span","persona-ask-row-check");o.appendChild(r)}else{let r=M("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Ck=(e,t,n,o)=>{let s=M("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(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=M("span","persona-ask-row-content"),l=M("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let p=M("span","persona-ask-row-description");p.textContent=e.description,a.appendChild(p)}s.appendChild(a);let d=Hb(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},wk=e=>{let n=M("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},xk=(e,t,n,o)=>{let s=M("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 a=!!e?.multiSelect,d=(Array.isArray(e?.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<fk;u++)s.appendChild(wk(o));return s}if(d.forEach((u,m)=>{s.appendChild(Ck(u,m,o,a))}),e?.allowFreeText!==!1){let u=o==="rows"?ck:dk;if(o==="rows"){let m=M("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(d.length)),m.setAttribute("data-ask-other-row","true");let y=M("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=t.freeTextPlaceholder??Tb,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??u),y.appendChild(h),m.appendChild(y);let C=Hb(o,a,d.length);C&&m.appendChild(C),s.appendChild(m)}else{let m=M("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=t.freeTextLabel??u,s.appendChild(m)}}return s},Wb=(e,t)=>{let o=M("div",t==="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=e.freeTextPlaceholder??Tb,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=M("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??kb,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Sk=e=>{let t=M("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=M("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??kb,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Ak=(e,t,n)=>{let o=M("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=M("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??uk,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=M("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=M("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??mk,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=M("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=e===t-1;return l.textContent=d?n.submitAllLabel??gk:n.nextLabel??pk,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Rs=e=>{let t=e.getAttribute(Pb);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Ob=(e,t)=>{e.setAttribute(Pb,JSON.stringify(t))},no=e=>{let t=Number(e.getAttribute(ag)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Mk=(e,t)=>{e.setAttribute(ag,String(Math.max(0,Math.floor(t))))},Mi=e=>{let t=Number(e.getAttribute(lg)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Nr=e=>e.getAttribute(cg)==="true",Ek=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},Tk=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Yc=(e,t)=>{let{payload:n}=Dr(t),o=ja(n),r=Rs(e),s={},a=new Set;return o.forEach((l,d)=>{let p=typeof l?.question=="string"?l.question:"";p&&(a.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),a.add(p),Object.prototype.hasOwnProperty.call(r,d)&&(s[p]=r[d]))}),s},Bb=e=>{let t=Rs(e),n=no(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{let p=d.getAttribute("data-option-label")??"",u=r.has(p);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>d.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},_b=e=>{if(!Nr(e))return;let t=Rs(e),n=no(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},dg=(e,t,n)=>{let o=Gc(n),r=yk(e),{payload:s,complete:a}=Dr(t),l=Nr(e),d=no(e),p=Mi(e),u=l?vk(s,d):bk(s),m=!!u?.multiSelect,y=e.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=l?`${d+1}/${p}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let C=e.querySelector('[data-ask-question="true"]');if(C){let O=typeof u?.question=="string"?u.question:"";C.textContent=O,C.classList.toggle("persona-ask-question-skeleton",!O&&!a)}let S=e.querySelector('[data-ask-pill-list="true"]');if(S){let O=xk(u,o,a,r);S.replaceWith(O)}if(r!=="rows"){let O=e.querySelector('[data-ask-free-text-row="true"]');O&&O.replaceWith(Wb(o,r))}let x=e.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!x?e.appendChild(Sk(o)):(!m||l)&&x&&x.remove(),e.setAttribute("data-multi-select",m?"true":"false");let P=e.querySelector('[data-ask-nav-row="true"]');if(l){let O=Ak(d,p,o);P?P.replaceWith(O):e.appendChild(O)}else P&&P.remove();Bb(e),_b(e)},kk=(e,t,n)=>{let o=Gc(t),r=hk(o),s=e.toolCall.id,a=ja(n),l=Math.max(1,a.length),d=l>1,p=Ek(e,a),u=d?Tk(e,l):0,m=M("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(Ai,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",e.id),m.setAttribute(lg,String(l)),m.setAttribute(ag,String(u)),m.setAttribute(cg,d?"true":"false"),m.setAttribute(Lb,r),Ob(m,p),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Rb(m,o);let y=M("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=M("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",y.appendChild(h);let C=M("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",y.appendChild(C),m.appendChild(y);let x=M("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 x.setAttribute("data-ask-pill-list","true"),x.setAttribute("role","group"),m.appendChild(x),r!=="rows"&&m.appendChild(Wb(o,r)),dg(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Pk=(e,t,n)=>{let{payload:o}=Dr(t),r=Math.max(1,ja(o).length);r>Mi(e)&&(e.setAttribute(lg,String(r)),r>1&&!Nr(e)&&e.setAttribute(cg,"true")),dg(e,t,n)},Lk=(e,t)=>{let n=M("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=Gc(t);Rb(n,o);let r=M("span","persona-ask-stub-label"),{complete:s}=Dr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},qa=(e,t,n)=>{if(!n||!_r(e)||Gc(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Ai}]`).forEach(p=>{p.getAttribute(Ai)!==r&&p.remove()});let a=n.querySelector(`[${Ai}="${Ib(r)}"]`);if(a){Pk(a,e,t);return}let{payload:l}=Dr(e),d=kk(e,t,l);n.appendChild(d)},Hs=(e,t)=>{if(!e)return;let n=t?`[${Ai}="${Ib(t)}"]`:`[${Ai}]`;e.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)})},pg=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Fr=(e,t)=>{let n=Rs(e),o=no(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Ob(e,n),Bb(e),_b(e)},Qc=(e,t,n,o)=>{let r=Mi(e),s=Math.max(0,Math.min(r-1,o));Mk(e,s),dg(e,t,n)};var dr="suggest_replies";var Nb={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},ug={name:dr,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:Nb,origin:"sdk",annotations:{readOnlyHint:!0}},Fb=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ei=e=>e.variant==="tool"&&e.toolCall?.name===dr,$b=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.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 a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});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},gg=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ei(n))continue;let o=$b(n.toolCall?.args);return o.length>0?o:null}return null},Db=new Set,Ik=(e,t,n)=>{let o=`${e}:${t}:${n}`;Db.has(o)||(Db.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},$r=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let l=t?.[a],d=n?.[a];l===void 0||d===void 0||l!==d&&Ik(a,d,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var Ub={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ua,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},jb={name:Kc,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:Ub,origin:"sdk",annotations:{readOnlyHint:!0}},za=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(jb),$r(e).expose&&t.push(ug),t};import{parse as qb,STR as zb,OBJ as Vb}from"partial-json";var Xc=e=>e.replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Jc=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Rk=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Kb=e=>e.status==="complete"?Rk(e):e.status==="pending"?"Waiting":"",Hk=15e3,Wk=1200,Gb=(e,t)=>{let n=t?.durationMs??Hk,o=t?.chars??Wk;return typeof e.durationMs=="number"?e.durationMs<n:(e.chunks??[]).join("").length<o},Ok=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.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 Yb=e=>e.status==="complete"?Ok(e):"Using tool...",Zc=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ka=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Zc(t)},ed=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Zc(t)},mg=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Ka(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},td=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Va(o,n.slice(s,a.index),[]),a[1]!==void 0?Va(o,a[1],["bold"]):a[2]!==void 0?Va(o,a[2],["italic"]):a[3]!==void 0&&Va(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Va(o,n.slice(s),[]),o},Va=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Bk=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
1
+ var AM=Object.defineProperty;var Wa=(e,t)=>()=>(e&&(t=e(e=0)),t);var Jy=(e,t)=>{for(var n in t)AM(e,n,{get:t[n],enumerable:!0})};var Zy={};Jy(Zy,{DOMPurify:()=>EM,Marked:()=>MM});import{Marked as MM}from"marked";import EM from"dompurify";var eb=Wa(()=>{"use strict"});var Ai,Pg=Wa(()=>{"use strict";Ai=class{constructor(t=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=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*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 t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,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 t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}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 t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);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 a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of a)l()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function pk(e){return e.replace(/\/+$/,"")}async function uk(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var nd,xv=Wa(()=>{"use strict";Pg();nd=class{constructor(t){this.opts=t;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 Ai(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let r=await this.ensurePlayer();if(t!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.generation&&o.onStart?.()}),r.onFinished(()=>{t===this.generation&&o.onEnd?.()});let s=`${pk(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=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(t!==this.generation)return;if(!a.ok||!a.body)throw new Error(await uk(a));let l=a.body.getReader();for(;;){let{done:d,value:p}=await l.read();if(t!==this.generation){await l.cancel().catch(()=>{});return}if(d)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(t!==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 od,Sv=Wa(()=>{"use strict";od=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{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(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var Av={};Jy(Av,{FallbackSpeechEngine:()=>od,RuntypeSpeechEngine:()=>nd});var Mv=Wa(()=>{"use strict";xv();Sv()});import{Marked as kM}from"marked";import LM from"dompurify";var ft=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:u=>{o=u,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(m=>(r=m,m)).catch(m=>{throw s=null,m}),s),provide:u=>{r=u},getSync:()=>r}};var{setLoader:xH,load:TM,provide:PM,getSync:Zu}=ft({fallbackImport:()=>Promise.resolve().then(()=>(eb(),Zy))}),Bc=new Set,tb=()=>{let e=[...Bc];Bc.clear();for(let t of e)try{t()}catch{}};var eg=()=>{let e=Zu();return e?Promise.resolve(e):TM().then(t=>(tb(),t))},Oa=e=>Zu()?()=>{}:(Bc.add(e),()=>{Bc.delete(e)}),nb=e=>{PM(e),tb()},Io=Zu;nb({Marked:kM,DOMPurify:LM});import{Ban as IM,Bell as RM,Bookmark as HM,Building as WM,Calendar as OM,CalendarDays as BM,Camera as _M,ChartColumn as DM,CircleCheck as NM,CircleX as FM,Clock as $M,CreditCard as UM,DollarSign as jM,EyeOff as qM,Files as zM,Film as VM,Flag as KM,Folder as GM,FolderOpen as YM,Funnel as QM,Gift as XM,Globe as JM,Hash as ZM,Headphones as eE,Heart as tE,House as nE,Image as oE,Info as rE,Key as sE,Lightbulb as iE,Link as aE,Lock as lE,Mail as cE,MapPin as dE,MessageCircle as pE,Monitor as uE,Moon as gE,Package as mE,Pause as fE,PenLine as hE,Percent as yE,Phone as bE,Play as vE,Receipt as CE,RotateCw as wE,Save as xE,Settings as SE,Share as AE,Shield as ME,ShoppingBag as EE,ShoppingCart as TE,Smartphone as PE,Sparkles as kE,Store as LE,Sun as IE,Tag as RE,Timer as HE,TriangleAlert as WE,Truck as OE,User as BE,VolumeX as _E,Wallet as DE,Zap as NE}from"lucide";var ob={user:BE,mail:cE,phone:bE,calendar:OM,clock:$M,building:WM,"map-pin":dE,lock:lE,key:sE,"credit-card":UM,hash:ZM,globe:JM,link:aE,"circle-check":NM,"circle-x":FM,"triangle-alert":WE,info:rE,ban:IM,shield:ME,house:nE,"pen-line":hE,save:xE,share:AE,funnel:QM,settings:SE,"rotate-cw":wE,"shopping-cart":TE,"shopping-bag":EE,package:mE,truck:OE,tag:RE,gift:XM,receipt:CE,wallet:DE,store:LE,"dollar-sign":jM,percent:yE,play:vE,pause:fE,"volume-x":_E,camera:_M,image:oE,film:VM,headphones:eE,"message-circle":pE,bell:RM,heart:tE,"eye-off":qM,bookmark:HM,"calendar-days":BM,timer:HE,folder:GM,"folder-open":YM,files:zM,"chart-column":DM,sparkles:kE,zap:NE,sun:IE,moon:gE,flag:KM,lightbulb:iE,monitor:uE,smartphone:PE};var It=(e,t=24,n="currentColor",o=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),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"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([p,u])=>{p!=="stroke"&&d.setAttribute(p,String(u))}),r.appendChild(d)}),r};var{setLoader:IH,load:FE}=ft({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")});var _c=FE;import{Activity as $E,ArrowDown as UE,ArrowLeft as jE,ArrowRight as qE,ArrowUp as zE,ArrowUpRight as VE,AtSign as KE,Bot as GE,Check as YE,ChevronDown as QE,ChevronLeft as XE,ChevronRight as JE,ChevronUp as ZE,Clipboard as eT,ClipboardCopy as tT,CodeXml as nT,Copy as oT,Download as rT,Ellipsis as sT,EllipsisVertical as iT,ExternalLink as aT,Eye as lT,File as cT,FileCode as dT,FileSpreadsheet as pT,FileText as uT,History as gT,ImagePlus as mT,Loader as fT,LoaderCircle as hT,Maximize as yT,Menu as bT,MessageSquare as vT,Mic as CT,Minimize as wT,Minus as xT,PanelLeft as ST,Paperclip as AT,Pencil as MT,Plus as ET,Quote as TT,RefreshCw as PT,Search as kT,Send as LT,ShieldAlert as IT,ShieldCheck as RT,ShieldX as HT,Square as WT,Star as OT,ThumbsDown as BT,ThumbsUp as _T,Trash as DT,Trash2 as NT,Upload as FT,Volume2 as $T,X as UT}from"lucide";var jT={activity:$E,"arrow-down":UE,"arrow-up":zE,"arrow-up-right":VE,bot:GE,"chevron-down":QE,"chevron-up":ZE,"chevron-right":JE,"chevron-left":XE,check:YE,clipboard:eT,"clipboard-copy":tT,"code-xml":nT,copy:oT,file:cT,"file-code":dT,"file-spreadsheet":pT,"file-text":uT,"image-plus":mT,loader:fT,"loader-circle":hT,mic:CT,paperclip:AT,quote:TT,"refresh-cw":PT,search:kT,send:LT,"shield-alert":IT,"shield-check":RT,"shield-x":HT,square:WT,"thumbs-down":BT,"thumbs-up":_T,upload:FT,"volume-2":$T,x:UT,"at-sign":KE,"arrow-left":jE,"arrow-right":qE,"external-link":aT,ellipsis:sT,"ellipsis-vertical":iT,menu:bT,"panel-left":ST,plus:ET,minus:xT,pencil:MT,trash:DT,"trash-2":NT,download:rT,maximize:yT,minimize:wT,"message-square":vT,star:OT,eye:lT,history:gT},qT=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],ws=new Map(Object.entries(jT)),fi=new Set,hi=!1,Dc=new Set,ng=e=>{let t=[...Dc];e&&Dc.clear();for(let n of t)try{n()}catch{}},rb=e=>hi?()=>{}:(Dc.add(e),()=>{Dc.delete(e)}),og=()=>{let e=0;for(let t of[...fi]){let n=ws.get(t.name);if(!n)continue;fi.delete(t),e++;let o=It(n,t.size,t.color,t.strokeWidth);if(o)for(t.el.removeAttribute("data-persona-icon-pending");o.firstChild;)t.el.appendChild(o.firstChild)}return e},zT=e=>{for(let[t,n]of Object.entries(e))ws.set(t,n);og()>0&&!hi&&ng(!1)},sb=e=>{if(!hi){for(let[t,n]of Object.entries(e))ws.has(t)||ws.set(t,n);hi=!0,og(),ng(!0)}},tg=!1,VT=()=>{_c().then(e=>{if(!hi){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))ws.has(t)||ws.set(t,n);hi=!0,og(),ng(!0)}}).catch(e=>{tg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},KT=(e,t,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},le=(e,t=24,n="currentColor",o=2)=>{let r=ws.get(e);if(r)return It(r,t,n,o);if(qT.includes(e)){tg&&(tg=!1);let s=KT(t,n,o);if(fi.size>=500){let a=fi.values().next().value;a&&fi.delete(a)}return fi.add({el:s,name:e,size:t,color:n,strokeWidth:o}),VT(),s}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null};sb(ob);function ib(e,t){let n=e.voiceRecognition,o=t.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function In(e){return e?.type==="runtype"||e?.type==="custom"}var GT=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function ab(e){try{if(e?.type==="custom"&&e.custom){let t=e.custom,n=typeof t=="function"?t():t;return!!n&&typeof n.startListening=="function"}return e?.type==="runtype"&&e.runtype?!0:GT()}catch{return!1}}var YT=e=>{if(!e)return;let t={},n=e;if(n.heading){let o=n.heading;t.heading=(r,s,a)=>o({type:"heading",raw:a,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;t.code=(r,s,a)=>o({type:"code",raw:"",text:r,lang:s,escaped:a})}if(n.blockquote){let o=n.blockquote;t.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;t.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;t.link=(r,s,a)=>o({type:"link",raw:"",href:r,title:s??null,text:a,tokens:[]})}if(n.image){let o=n.image;t.image=(r,s,a)=>o({type:"image",raw:"",href:r,title:s??null,text:a})}if(n.list){let o=n.list;t.list=(r,s,a)=>o({type:"list",raw:"",ordered:s,start:a,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;t.listitem=(r,s,a)=>o({type:"list_item",raw:"",task:s,checked:a,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;t.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;t.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;t.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;t.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;t.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;t.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;t.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;t.checkbox=r=>o({checked:r})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Nc=e=>{let t=null;return n=>{let o=Io();if(!o)return Ir(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=YT(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Fc=e=>e?Nc({markedOptions:e.options,renderer:e.renderer}):Nc(),QT=Nc(),cb=e=>QT(e),Ir=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),db=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),lb=e=>`%%FORM_PLACEHOLDER_${e}%%`,pb=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=lb(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=lb(t.length);return t.push({token:s,type:r}),s}),n},XT=e=>{let t=Fc(e);return n=>{let o=[],r=pb(n,o),s=t(r);return o.forEach(({token:a,type:l})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${db(l)}"></div>`;s=s.replace(d,u)}),s}},JT=e=>{let t=[],n=pb(e,t),o=cb(n);return t.forEach(({token:r,type:s})=>{let a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${db(s)}"></div>`;o=o.replace(a,d)}),o};var ZT={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"]},eP=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ub=()=>{let e=null;return t=>{let n=Io();if(!n)return Ir(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!eP.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,ZT)}},rg=e=>e===!1?null:typeof e=="function"?e:ub();var gb=/^\s*\|?[\s:|-]*-[\s:|-]*$/,mb=e=>e.includes("|"),fb=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},tP=e=>`| ${e.join(" | ")} |`,nP=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,oP=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),hb=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
+ `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!mb(r)||gb.test(r)||!gb.test(s))continue;let a=fb(r).length;if(a<1)continue;let l=nP(a);t[o+1]!==l&&(t[o+1]=l,n=!0);let d=o+2;for(;d<t.length;d++){let p=t[d];if(p.trim()===""||!mb(p))break;let u=tP(oP(fb(p),a));t[d]!==u&&(t[d]=u,n=!0)}o=d-1}return n?t.join(`
3
+ `):e};var yb="var(--persona-md-table-scroll-fade, 24px)",bb=new WeakSet;function Cb(e){e.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 vb(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":yb),e.style.setProperty("--persona-fade-r",r<=1?"0px":yb)}function sg(e){bb.has(e)||(bb.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&vb(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(vb)}var $c="webmcp:",ig=new Map,Uc=e=>{ig.clear();for(let t of e){let n=t.title?.trim();n&&ig.set(t.name,n)}},yi=e=>ig.get(Ab(e)),wb=null;function Sb(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${rP(t.join(""))}`}function xb(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.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 rP(e){let t=xb(e,0).toString(36),n=xb(e,2654435761).toString(36);return`${t}.${n}`}var Ab=e=>e.startsWith($c)?e.slice($c.length):e,xs=e=>e.startsWith($c),jc=()=>wb?wb():import("@mcp-b/webmcp-polyfill");var{setLoader:YH,load:sP}=ft({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var Mb=sP;function Un(e){return e==="card"?"collapsed":e}function Ss(e){return e.split(";",1)[0].trim().toLowerCase()}function iP(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Ss(r)===t)return{mode:Un(s),selector:Ss(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ss(r)===o)return{mode:Un(s),selector:o}}function Eb(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:Un(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Ss(t.file.mimeType):void 0,d=l?iP(o.files.byMediaType,l):void 0;if(l&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:l,selector:d.selector}};if(o.files.default)return{mode:Un(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:Un(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:Un(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:Un(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:Un(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function sr(e,t){return Eb(e,t).mode}function Ba(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var aP="agent_",lP="flow_";function Tb(e){return e.startsWith(aP)?{kind:"agentId",agentId:e}:e.startsWith(lP)?{kind:"flowId",flowId:e}:null}function Pb(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let p=Tb(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let d=t?.[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(l).payload}}let r=Tb(n);if(r)return r;let s=t?.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.`)}function cP(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function _a(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function As(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function kb(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}import{parse as dP,ARR as pP,OBJ as uP,STR as gP}from"partial-json";var E=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var G=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let l of Object.keys(a)){let d=a[l];d!=null&&(s[l]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},gn=(...e)=>e.filter(Boolean).join(" ");var qc="ask_user_question",Da=8,bi="data-persona-ask-sheet-for",mP="Other",fP="Other\u2026",Ib="Type your own answer here",Rb="Send",hP="Next",yP="Back",bP="Submit all",vP="Skip",CP=3,ag="data-ask-current-index",lg="data-ask-question-count",Hb="data-ask-answers",cg="data-ask-grouped",Wb="data-ask-layout",wP=e=>e.layout==="pills"?"pills":"rows",xP=e=>e.getAttribute(Wb)==="pills"?"pills":"rows",Lb=!1,Ob=e=>e.replace(/["\\]/g,"\\$&"),Rr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===qc,zc=e=>e?.features?.askUserQuestion??{},Hr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=dP(r,gP|uP|pP);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Na=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Da&&!Lb&&(Lb=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Da}.`)),t.slice(0,Da)},SP=e=>Na(e)[0]??null,AP=(e,t)=>Na(e)[t]??null,Bb=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},_b=(e,t,n)=>{if(e!=="rows")return null;let o=E("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=E("span","persona-ask-row-check");o.appendChild(r)}else{let r=E("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},MP=(e,t,n,o)=>{let s=E("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(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=E("span","persona-ask-row-content"),l=E("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let p=E("span","persona-ask-row-description");p.textContent=e.description,a.appendChild(p)}s.appendChild(a);let d=_b(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},EP=e=>{let n=E("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},TP=(e,t,n,o)=>{let s=E("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 a=!!e?.multiSelect,d=(Array.isArray(e?.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<CP;u++)s.appendChild(EP(o));return s}if(d.forEach((u,m)=>{s.appendChild(MP(u,m,o,a))}),e?.allowFreeText!==!1){let u=o==="rows"?mP:fP;if(o==="rows"){let m=E("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(d.length)),m.setAttribute("data-ask-other-row","true");let y=E("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=t.freeTextPlaceholder??Ib,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??u),y.appendChild(h),m.appendChild(y);let v=_b(o,a,d.length);v&&m.appendChild(v),s.appendChild(m)}else{let m=E("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=t.freeTextLabel??u,s.appendChild(m)}}return s},Db=(e,t)=>{let o=E("div",t==="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=e.freeTextPlaceholder??Ib,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=E("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Rb,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},PP=e=>{let t=E("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=E("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Rb,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},kP=(e,t,n)=>{let o=E("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=E("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??yP,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=E("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=E("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??vP,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=E("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=e===t-1;return l.textContent=d?n.submitAllLabel??bP:n.nextLabel??hP,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ms=e=>{let t=e.getAttribute(Hb);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Nb=(e,t)=>{e.setAttribute(Hb,JSON.stringify(t))},to=e=>{let t=Number(e.getAttribute(ag)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},LP=(e,t)=>{e.setAttribute(ag,String(Math.max(0,Math.floor(t))))},vi=e=>{let t=Number(e.getAttribute(lg)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Wr=e=>e.getAttribute(cg)==="true",IP=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},RP=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Vc=(e,t)=>{let{payload:n}=Hr(t),o=Na(n),r=Ms(e),s={},a=new Set;return o.forEach((l,d)=>{let p=typeof l?.question=="string"?l.question:"";p&&(a.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),a.add(p),Object.prototype.hasOwnProperty.call(r,d)&&(s[p]=r[d]))}),s},Fb=e=>{let t=Ms(e),n=to(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{let p=d.getAttribute("data-option-label")??"",u=r.has(p);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>d.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},$b=e=>{if(!Wr(e))return;let t=Ms(e),n=to(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},dg=(e,t,n)=>{let o=zc(n),r=xP(e),{payload:s,complete:a}=Hr(t),l=Wr(e),d=to(e),p=vi(e),u=l?AP(s,d):SP(s),m=!!u?.multiSelect,y=e.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=l?`${d+1}/${p}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let O=typeof u?.question=="string"?u.question:"";v.textContent=O,v.classList.toggle("persona-ask-question-skeleton",!O&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let O=TP(u,o,a,r);x.replaceWith(O)}if(r!=="rows"){let O=e.querySelector('[data-ask-free-text-row="true"]');O&&O.replaceWith(Db(o,r))}let w=e.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!w?e.appendChild(PP(o)):(!m||l)&&w&&w.remove(),e.setAttribute("data-multi-select",m?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(l){let O=kP(d,p,o);k?k.replaceWith(O):e.appendChild(O)}else k&&k.remove();Fb(e),$b(e)},HP=(e,t,n)=>{let o=zc(t),r=wP(o),s=e.toolCall.id,a=Na(n),l=Math.max(1,a.length),d=l>1,p=IP(e,a),u=d?RP(e,l):0,m=E("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(bi,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",e.id),m.setAttribute(lg,String(l)),m.setAttribute(ag,String(u)),m.setAttribute(cg,d?"true":"false"),m.setAttribute(Wb,r),Nb(m,p),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Bb(m,o);let y=E("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=E("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",y.appendChild(h);let v=E("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",y.appendChild(v),m.appendChild(y);let w=E("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 w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),m.appendChild(w),r!=="rows"&&m.appendChild(Db(o,r)),dg(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},WP=(e,t,n)=>{let{payload:o}=Hr(t),r=Math.max(1,Na(o).length);r>vi(e)&&(e.setAttribute(lg,String(r)),r>1&&!Wr(e)&&e.setAttribute(cg,"true")),dg(e,t,n)},OP=(e,t)=>{let n=E("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=zc(t);Bb(n,o);let r=E("span","persona-ask-stub-label"),{complete:s}=Hr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Fa=(e,t,n)=>{if(!n||!Rr(e)||zc(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${bi}]`).forEach(p=>{p.getAttribute(bi)!==r&&p.remove()});let a=n.querySelector(`[${bi}="${Ob(r)}"]`);if(a){WP(a,e,t);return}let{payload:l}=Hr(e),d=HP(e,t,l);n.appendChild(d)},Es=(e,t)=>{if(!e)return;let n=t?`[${bi}="${Ob(t)}"]`:`[${bi}]`;e.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)})},pg=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Or=(e,t)=>{let n=Ms(e),o=to(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Nb(e,n),Fb(e),$b(e)},Kc=(e,t,n,o)=>{let r=vi(e),s=Math.max(0,Math.min(r-1,o));LP(e,s),dg(e,t,n)};var ir="suggest_replies";var jb={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},ug={name:ir,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:jb,origin:"sdk",annotations:{readOnlyHint:!0}},qb=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ci=e=>e.variant==="tool"&&e.toolCall?.name===ir,zb=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.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 a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});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},gg=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ci(n))continue;let o=zb(n.toolCall?.args);return o.length>0?o:null}return null},Ub=new Set,BP=(e,t,n)=>{let o=`${e}:${t}:${n}`;Ub.has(o)||(Ub.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Br=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let l=t?.[a],d=n?.[a];l===void 0||d===void 0||l!==d&&BP(a,d,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var Vb={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Da,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},Kb={name:qc,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:Vb,origin:"sdk",annotations:{readOnlyHint:!0}},$a=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Kb),Br(e).expose&&t.push(ug),t};import{parse as Gb,STR as Yb,OBJ as Qb}from"partial-json";var Gc=e=>e.replace(/\\n/g,`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Yc=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},_P=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Xb=e=>e.status==="complete"?_P(e):e.status==="pending"?"Waiting":"",DP=15e3,NP=1200,Jb=(e,t)=>{let n=t?.durationMs??DP,o=t?.chars??NP;return typeof e.durationMs=="number"?e.durationMs<n:(e.chunks??[]).join("").length<o},FP=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.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 Zb=e=>e.status==="complete"?FP(e):"Using tool...",Qc=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ja=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Qc(t)},Xc=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Qc(t)},mg=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=ja(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Jc=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Ua(o,n.slice(s,a.index),[]),a[1]!==void 0?Ua(o,a[1],["bold"]):a[2]!==void 0?Ua(o,a[2],["italic"]):a[3]!==void 0&&Ua(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ua(o,n.slice(s),[]),o},Ua=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},$P=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
5
5
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
6
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Ga=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},fg=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},hg=()=>{let e=Bk();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},yg=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=qb(n,zb|Vb);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Xc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Xc(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},_k=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=l=>typeof l=="string"?Xc(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Xc(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let l=qb(s,zb|Vb),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},bg=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Qb="4.22.0";var fo=Qb;var Ti="[Image]";function Nk(e){return typeof e=="string"?[{type:"text",text:e}]:e}function vg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ya(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Fk(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ho(e){return{type:"text",text:e}}function Cg(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function $k(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Uk(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Xb=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],jk=["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"],pr=[...Xb,...jk];function qk(e){return Xb.includes(e)||e.startsWith("image/")}function nd(e){return qk(e.type)}function Jb(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function Zb(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;nd(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function ev(e,t=pr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function zk(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function tv(e,t){let n=zk(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Vk=["user","assistant","system"],Kk=0;function nv(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function od(e){return typeof e=="string"?e:void 0}function Gk(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?ho(t.text):null;case"image":return typeof t.image=="string"?Cg(t.image,{mimeType:od(t.mimeType),alt:od(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?Jb(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...od(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...od(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function Yk(e,t){let n=nv(t),o=e.map(a=>nv(a.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let a=o[s];if(a!==null){r[s]=a,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let d=l-s+1,p=s>0?r[s-1]:null,u=l+1<o.length?o[l+1]:null,m=u!==null&&n!==null?Math.min(u,n):u??n;for(let y=0;y<d;y+=1)r[s+y]=m!==null?m-(d-y):p!==null?p+y+1:Kk+y;s=l+1}return r.map(a=>new Date(a).toISOString())}function ov(e,t){let n=Yk(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!Vk.includes(r.role))return;let a=r.role,l=n[s];if(r.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:r.id,role:a,content:"",createdAt:l,agentMetadata:d});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:a,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:a,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let d=r.content.map(Gk).filter(u=>u!==null),p=vg(d);o.push({id:r.id,role:a,content:p||(Ya(d)?Ti:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Qa(e){let t=e.content;if(typeof t!="string"||t==="")return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof n=="string"&&n===t))return t}function Xa(e,t){let n=new Map;for(let o of e)n.set(o.id,o);for(let o of t)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),a=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(a)&&s!==a)return s-a;let l=o.sequence??0,d=r.sequence??0;return l!==d?l-d:o.id.localeCompare(r.id)})}var Qk="https://api.runtype.com/v1/dispatch",rv="https://api.runtype.com",$e=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},sv=32768,wg=49152,iv=e=>{let t=e??{},n=typeof t.targetId=="string"?t.targetId:typeof t.flowId=="string"?t.flowId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:n,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},av=e=>"reason"in e?e.reason:void 0,lv="The identity proof was not admitted; account history is unavailable",cv="The identity proof was rejected",dv="The request carried no visitor credential",pv="The stored visitor belongs to a different signed-in user",xg=(e,t)=>e instanceof $e&&e.code===t;function Xk(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Sg=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Jk(e){switch(e){case"json":return yg;case"regex-json":return hg;case"xml":return bg;default:return fg}}var uv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Zk(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=uv(n);if(!uv(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Ga(e);return Ga(t)!==null&&a===null?t:e}var ki=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Qk,this.headers={"Content-Type":"application/json","X-Persona-Version":fo,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Jk(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,t.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(t.webmcp))}createWebMcpBridge(t){return wb().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:zc,getToolDisplayTitle:Si,loadPolyfill:Vc});return this.pendingWebMcpConfirmHandler!==void 0&&o.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=o,o}).catch(n=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.pendingWebMcpConfirmHandler=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Ab(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)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||rv}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new $e("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:t.after}),d=await fetch(`${a}?${l}`,{method:"GET",headers:{"X-Persona-Version":fo,"X-Visitor-Token":s},signal:t.signal});if(d.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(d),null,!0);continue}if(!d.ok)throw await this.historyErrorFor(d,!0);return d}}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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let t=this.historyIdentityStatus;return t?.state==="browser_only"?t:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&av(n)===av(t);if(this.historyIdentityStatus=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let n=this.isHistoryCapable()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.routing(),a=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,d={token:this.config.clientToken,...a&&{flowId:a},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...l?{conversationId:l}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fo},body:JSON.stringify(d)});if(p.status===400&&o){let m={...d};delete m.durableRecovery,p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fo},body:JSON.stringify(m)})}if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new $e("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw p.status===403&&m.error==="durable_recovery_disabled"?new $e("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&m.error==="visitor_required"?new $e("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new $e("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):p.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId??u.flow?.id?{targetId:u.targetId??u.flow?.id}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.createClientSession({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,t,!1)}catch(r){if(!xg(r,"not_found")&&!xg(r,"visitor_required")&&!xg(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(t,n)):this.doOrdinaryInit(t,n)}async doOrdinaryInit(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,t,n)}async reinitWithProof(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:t}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),s}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&t.durableRecovery?.enabled!==!0)return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new $e("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new $e("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:t,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fo},body:JSON.stringify(r)});if(!s.ok){let a=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(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,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:t,comment:n})}async submitNPSFeedback(t,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:t,comment:n})}historyUrl(t,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new $e("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new $e("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new $e("proof_not_admitted",lv);return r}async readErrorCode(t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new $e("invalid_identity_proof",cv);if(r.includes("visitor token required"))throw new $e("visitor_token_missing",dv);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new $e("visitor_identity_mismatch",pv);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new $e("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,n){let o=await this.readErrorCode(t);if(t.status===404)return new $e("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new $e("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new $e("proof_not_admitted",lv);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new $e("invalid_identity_proof",cv)):r.includes("visitor token required")?new $e("visitor_token_missing",dv):r.includes("visitor_identity_mismatch")?new $e("visitor_identity_mismatch",pv):new $e("unauthorized",o||"History request was not authorized")}return new $e("request_failed",o||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new $e("identity_contract_violation","Server reported an ignored identity proof on a success response"):new $e("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new $e("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let d=a?.revision()??0,p=await this.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new $e("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":fo,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),y=await u.json().catch(()=>{});if(a&&a.revision()!==d)throw new $e("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),y}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new $e("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let n=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(iv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}}),r=o&&typeof o.conversation=="object"&&o.conversation!==null?o.conversation:o;return{summary:iv(r),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(t,n){this.assertHistoryUsable();let o=0;for(let d of n){let p=d.displayContent.length;if(p>sv)throw new $e("payload_too_large",`displayContent exceeds the ${sv} character limit`);o+=p}if(o>wg)throw new $e("payload_too_large",`Display projection batch exceeds the ${wg} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,s=r?.revision()??0,a=await this.historyFetch(`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=wg,trackIdentity:!1}),l=typeof a?.conversationRevision=="string"?a.conversationRevision:null;return l&&this.clientSession?.conversationId===t&&(r?.revision()??0)===s&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(t){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){let o=Mb();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=await this.initSession();if(new Date>=new Date(a.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let C=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:C}),C}let l=await this.buildPayload(t.messages),d=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null,p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([C])=>C!=="sessionId"&&C!=="session_id")):void 0,u=this.isHistoryCapable(),m={sessionId:a.sessionId,messages:t.messages.filter(Sg).map(C=>{let S=u?Qa(C):void 0;return{id:C.id,role:C.role,content:C.contentParts??C.llmContent??C.rawContent??C.content,...S!==void 0&&{displayContent:S}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},{response:y,commit:h}=await this.sendWithClientToolsDiff(a.sessionId,l.clientTools,C=>{let S={...m,...C};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fo,...d?{"X-Visitor-Token":d}:{}},body:JSON.stringify(S),signal:t.signal})});if(!y.ok){let C=await y.json().catch(()=>({error:"Chat request failed"}));if(y.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let x=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:x}),x}if(y.status===429){let x=new Error(C.hint||"Message limit reached for this session.");throw s({type:"error",error:x}),x}if(y.status===410&&C.error==="conversation_deleted"){let x=new $e("conversation_deleted","This conversation was deleted");throw s({type:"error",error:x}),x}let S=new Error(C.error||"Failed to send message");throw s({type:"error",error:S}),S}if(!y.body){let C=new Error("No response body received");throw s({type:"error",error:C}),C}h(),s({type:"status",status:"connected"});try{await this.streamResponse(y.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof $e)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let o=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?vb(n):void 0,l=this.clientToolsFingerprintSessionId===t,d=s&&l&&this.lastSentClientToolsFingerprint===a,p=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,u=!1,m;for(let y=0;;y++){if(m=await o({...s&&(u||!d)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),m.status===409&&y===0&&s&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:p&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||rv}/resume`,a,l=null;if(r){let u=await this.initSession();a=u.sessionId,u.durableRecovery?.enabled===!0&&(l=await this.readVisitorToken())}let d={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...this.headers};this.getHeaders&&Object.assign(d,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(a&&(p.sessionId=a),r&&a){let u=[...za(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:y}=await this.sendWithClientToolsDiff(a,u,h=>{let C={...p,...h};return this.debug&&console.debug("[AgentWidgetClient] client token resume",C),fetch(s,{method:"POST",headers:d,body:JSON.stringify(C),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&y(),m}return fetch(s,{method:"POST",headers:d,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,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(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(t,n){let o=n?.selectedModelId;return!o||!("model"in t)?t:this.config.composer?.models?.some(s=>s.id===o)?{...t,model:o}:t}async buildAgentPayload(t,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Sg).filter(p=>p.role==="user"||p.role==="assistant"||p.role==="system").filter(p=>!p.variant||p.variant==="assistant").sort((p,u)=>{let m=new Date(p.createdAt).getTime(),y=new Date(u.createdAt).getTime();return m-y}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...za(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(a.clientTools=l);let d=await this.buildContextAggregate(t);return d&&(a.context=d),a}async buildPayload(t,n){let o=t.slice().filter(Sg).sort((p,u)=>{let m=new Date(p.createdAt).getTime(),y=new Date(u.createdAt).getTime();return m-y}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,u]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=u);let a=[...za(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(s.clientTools=a);let l=await this.buildContextAggregate(t);l&&(s.context=l);let d=this.normalizeComposerOptions(n);if(d&&(s.composerOptions=d),this.requestMiddleware)try{let p=await this.requestMiddleware({payload:{...s},config:this.config});if(p&&typeof p=="object"){let u=p;return s.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=s.clientTools),u}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=m,r(m),m},p=u=>o.current?o.current:d(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.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(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",d=Date.now(),p=0,u=()=>d+p++,m=D=>{let X=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,v=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,_=D.tools?D.tools.map(F=>({...F,chunks:F.chunks?[...F.chunks]:void 0})):void 0;return{...D,reasoning:X,toolCall:v,tools:_}},y=D=>{if(D.role!=="assistant"||D.variant)return!0;let X=Array.isArray(D.contentParts)&&D.contentParts.length>0,v=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||X||v||!!D.stopReason},h=D=>{y(D)&&n({type:"message",message:m(D)})},C=null,S=null,x={current:null},P={current:null},O=null,$="",T=new Map,R=new Map,A=new Map,N=new Map,G=new Map,ae={lastId:null,byStep:new Map},Y={lastId:null,byCall:new Map},E=D=>{if(D==null)return null;try{return String(D)}catch{return null}},B=D=>E(D.stepId??D.step_id??D.step??D.parentId??D.flowStepId??D.flow_step_id),H=D=>E(D.callId??D.call_id??D.requestId??D.request_id??D.toolCallId??D.tool_call_id??D.stepId??D.step_id),L=o,ee=!1,K=()=>{if(C)return C;let D,X="",v=O;return!ee&&L?(D=L,ee=!0,X=r??""):L&&v?D=`${L}_${v}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,C={id:D,role:"assistant",content:X,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},h(C),C},ue=(D,X)=>{ae.lastId=X,D&&ae.byStep.set(D,X)},le=(D,X)=>{let v=D.reasoningId??D.id,_=B(D);if(v){let U=String(v);return ue(_,U),U}if(_){let U=ae.byStep.get(_);if(U)return ae.lastId=U,U}if(ae.lastId&&!X)return ae.lastId;if(!X)return null;let F=`reason-${u()}`;return ue(_,F),F},me=D=>{let X=N.get(D);if(X)return X;let v={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:D,status:"streaming",chunks:[]}};return N.set(D,v),h(v),v},Re=(D,X)=>{Y.lastId=X,D&&Y.byCall.set(D,X)},He=new Set,ve=new Map,Ge=new Set,be=new Map,j=D=>{if(!D)return!1;let X=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return X==="emit_artifact_markdown"||X==="emit_artifact_component"},_e=(D,X)=>{let v=D.toolId??D.id,_=H(D);if(v){let U=String(v);return Re(_,U),U}if(_){let U=Y.byCall.get(_);if(U)return Y.lastId=U,U}if(Y.lastId&&!X)return Y.lastId;if(!X)return null;let F=`tool-${u()}`;return Re(_,F),F},Fe=D=>{let X=G.get(D);if(X)return X;let v={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:D,status:"pending"}};return G.set(D,v),h(v),v},mt=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let X=Number(D);if(!Number.isNaN(X)&&Number.isFinite(X))return X;let v=Date.parse(D);if(!Number.isNaN(v))return v}return Date.now()},Ce=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Ee=new Map,he=new Map,Pe=new Map,At=(D,X,v)=>{let _=Pe.get(D);_||(_=[],Pe.set(D,_));let F=0,U=_.length;for(;F<U;){let re=F+U>>>1;_[re].seq<X?F=re+1:U=re}_[F]?.seq===X?_[F]={seq:X,text:v}:_.splice(F,0,{seq:X,text:v});let te="";for(let re=0;re<_.length;re++)te+=_[re].text;return te},Yt=(D,X)=>{let v=Ce(X),_=he.get(D.id),F=Zk(_,v);D.rawContent=F;let U=Ee.get(D.id),te=Oe=>{let Ot=D.content??"";Oe.trim()!==""&&(Ot.trim().length===0||Oe.startsWith(Ot)||Oe.trimStart().startsWith(Ot.trim()))&&(D.content=Oe)},re=()=>{if(U){let Oe=U.close?.();Oe instanceof Promise&&Oe.catch(()=>{})}Ee.delete(D.id),he.delete(D.id),D.streaming=!1,h(D)};if(!U){te(v),re();return}let ie=Ga(F);if(ie!==null&&ie.trim()!==""){te(ie),re();return}let ce=Oe=>{let Ot=typeof Oe=="string"?Oe:Oe?.text??null;if(Ot!==null&&Ot.trim()!=="")return Ot;let kt=U.getExtractedText();return kt!==null&&kt.trim()!==""?kt:v},Ut;try{Ut=U.processChunk(F)}catch{te(v),re();return}if(Ut instanceof Promise){Ut.then(Oe=>{te(ce(Oe)),re()}).catch(()=>{te(v),re()});return}te(ce(Ut)),re()},ft=null,pn=(D,X,v,_)=>{D.rawContent=X,Ee.has(D.id)||Ee.set(D.id,this.createStreamParser());let F=Ee.get(D.id),U=X.trim().startsWith("{")||X.trim().startsWith("[");if(U&&he.set(D.id,X),F.__isPlainTextParser===!0){D.content=_!==void 0?X:D.content+v,he.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D);return}let re=F.processChunk(X);if(re instanceof Promise)re.then(ie=>{let ce=typeof ie=="string"?ie:ie?.text??null;ce!==null&&ce.trim()!==""?(D.content=ce,h(D)):!U&&!X.trim().startsWith("<")&&(D.content=_!==void 0?X:D.content+v,he.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D))}).catch(()=>{D.content=_!==void 0?X:D.content+v,he.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D)});else{let ie=typeof re=="string"?re:re?.text??null;ie!==null&&ie.trim()!==""?(D.content=ie,h(D)):!U&&!X.trim().startsWith("<")&&(D.content=_!==void 0?X:D.content+v,he.delete(D.id),Ee.delete(D.id),D.rawContent=void 0,h(D))}},zn=(D,X)=>{let v=X??D.content;if(v==null||v===""){D.streaming=!1,h(D);return}let F=he.get(D.id)??Ce(v);D.rawContent=F;let U=Ee.get(D.id),te=null,re=!1;if(U&&(te=U.getExtractedText(),te===null&&(te=Ga(F)),te===null)){let ie=U.processChunk(F);ie instanceof Promise?(re=!0,ie.then(ce=>{let Ut=typeof ce=="string"?ce:ce?.text??null;Ut!==null&&(D.content=Ut,D.streaming=!1,Ee.delete(D.id),he.delete(D.id),h(D))}).catch(()=>{})):te=typeof ie=="string"?ie:ie?.text??null}if(!re){te!==null&&te.trim()!==""?D.content=te:he.has(D.id)||(D.content=Ce(v));let ie=Ee.get(D.id);if(ie){let ce=ie.close?.();ce instanceof Promise&&ce.catch(()=>{}),Ee.delete(D.id)}he.delete(D.id),D.streaming=!1,h(D)}},an=(D,X,v)=>{let _=R.get(D);if(_)return _;let F={id:`nested-${X}-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:D,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:X}};return R.set(D,F),h(F),F},Co=[],Vn,ro=new Map,Us=0,wo="agent",jo=!1,Gr=null,et=null,Pn=new Map,so=this.config.iterationDisplay??"separate";for(Vn=()=>{for(let D=0;D<Co.length;D++){let X=Co[D].payloadType,v=Co[D].payload;if(!jo&&wo!=="flow"&&typeof v.stepType=="string"&&(wo="flow"),X==="reasoning_start"){let _=typeof v.id=="string"?v.id:null,F=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(_&&F){T.set(_,F),an(_,F,"reasoning");continue}let U=le(v,!0)??`reason-${u()}`,te=me(U);te.reasoning=te.reasoning??{id:U,status:"streaming",chunks:[]},te.reasoning.startedAt=te.reasoning.startedAt??mt(v.startedAt??v.timestamp),te.reasoning.completedAt=void 0,te.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(te.reasoning.scope=v.scope),te.streaming=!0,te.reasoning.status="streaming",h(te)}else if(X==="reasoning_delta"){let _=typeof v.id=="string"?v.id:null;if(_&&T.has(_)&&R.has(_)){let re=R.get(_),ie=v.reasoningText??v.text??v.delta??"";ie&&v.hidden!==!0&&re.reasoning&&(re.reasoning.chunks.push(String(ie)),h(re));continue}let F=le(v,!1)??le(v,!0)??`reason-${u()}`,U=me(F);U.reasoning=U.reasoning??{id:F,status:"streaming",chunks:[]},U.reasoning.startedAt=U.reasoning.startedAt??mt(v.startedAt??v.timestamp);let te=v.reasoningText??v.text??v.delta??"";if(te&&v.hidden!==!0){let re=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(re!==void 0){let ie=At(F,re,String(te));U.reasoning.chunks=[ie]}else U.reasoning.chunks.push(String(te))}if(U.reasoning.status=v.done?"complete":"streaming",v.done){U.reasoning.completedAt=mt(v.completedAt??v.timestamp);let re=U.reasoning.startedAt??Date.now();U.reasoning.durationMs=Math.max(0,(U.reasoning.completedAt??Date.now())-re)}U.streaming=U.reasoning.status!=="complete",h(U)}else if(X==="reasoning_complete"){let _=typeof v.id=="string"?v.id:null;if(_&&T.has(_)&&R.has(_)){let ie=R.get(_);if(ie.reasoning){let ce=typeof v.text=="string"?v.text:"";ce&&ie.reasoning.chunks.length===0&&ie.reasoning.chunks.push(ce),ie.reasoning.status="complete",ie.streaming=!1,h(ie)}T.delete(_),R.delete(_);continue}let F=le(v,!1)??le(v,!0)??`reason-${u()}`,U=typeof v.text=="string"?v.text:"";!N.get(F)&&(U||v.scope==="loop")&&me(F);let te=N.get(F);if(te?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(te.reasoning.scope=v.scope),U&&te.reasoning.chunks.length===0&&te.reasoning.chunks.push(U),te.reasoning.status="complete",te.reasoning.completedAt=mt(v.completedAt??v.timestamp);let ie=te.reasoning.startedAt??Date.now();te.reasoning.durationMs=Math.max(0,(te.reasoning.completedAt??Date.now())-ie),te.streaming=!1,h(te)}let re=B(v);re&&ae.byStep.delete(re)}else if(X==="tool_start"){C&&(C.streaming=!1,h(C),C=null),typeof v.iteration=="number"&&(Us=v.iteration);let _=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??_e(v,!0)??`tool-${u()}`,F=v.toolName??v.name;if(j(F)){He.add(_);continue}Re(H(v),_);let U=Fe(_),te=U.toolCall??{id:_,status:"pending"};te.name=F??te.name,te.status="running",v.parameters!==void 0?te.args=v.parameters:v.args!==void 0&&(te.args=v.args),te.startedAt=te.startedAt??mt(v.startedAt??v.timestamp),te.completedAt=void 0,te.durationMs=void 0,U.toolCall=te,U.streaming=!0,v.executionId&&(U.agentMetadata={executionId:v.executionId,iteration:v.iteration}),h(U)}else if(X==="tool_output_delta"){let _=_e(v,!1)??_e(v,!0)??`tool-${u()}`;if(He.has(_))continue;let F=Fe(_),U=F.toolCall??{id:_,status:"running"};U.startedAt=U.startedAt??mt(v.startedAt??v.timestamp);let te=v.text??v.delta??v.message??"";te&&(U.chunks=U.chunks??[],U.chunks.push(String(te))),U.status="running",F.toolCall=U,F.streaming=!0;let re=v.agentContext;(re||v.executionId)&&(F.agentMetadata=F.agentMetadata??{executionId:re?.executionId??v.executionId,iteration:re?.iteration??v.iteration}),h(F)}else if(X==="tool_complete"){let _=_e(v,!1)??_e(v,!0)??`tool-${u()}`;if(He.has(_)){He.delete(_);continue}let F=Fe(_),U=F.toolCall??{id:_,status:"running"};U.status="complete",v.result!==void 0&&(U.result=v.result),typeof v.duration=="number"&&(U.duration=v.duration),U.completedAt=mt(v.completedAt??v.timestamp);let te=v.duration??v.executionTime;if(typeof te=="number")U.durationMs=te;else{let ce=U.startedAt??Date.now();U.durationMs=Math.max(0,(U.completedAt??Date.now())-ce)}F.toolCall=U,F.streaming=!1;let re=v.agentContext;(re||v.executionId)&&(F.agentMetadata=F.agentMetadata??{executionId:re?.executionId??v.executionId,iteration:re?.iteration??v.iteration}),h(F);let ie=H(v);ie&&Y.byCall.delete(ie)}else if(X==="await"&&v.toolName){let _=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,F=_??v.toolId??`local-${u()}`,U=Fe(F),te=v.toolName,re=v.origin==="webmcp"&&!Ps(te)?`webmcp:${te}`:te,ie=Ps(re),ce=U.toolCall??{id:F,status:"pending"};ce.name=re,ce.args=v.parameters,ce.status=ie?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??mt(v.startedAt??v.timestamp??v.awaitedAt),ie?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,U.toolCall=ce,U.streaming=!1,U.agentMetadata={...U.agentMetadata,executionId:v.executionId??U.agentMetadata?.executionId,awaitingLocalTool:!0,..._?{webMcpToolCallId:_}:{}},h(U)}else if(X==="text_start"){let _=typeof v.id=="string"?v.id:null,F=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(_&&F){T.set(_,F);continue}let U=C;U&&(wo==="flow"?(zn(U),ft=U):(U.streaming=!1,h(U)),C=null),O=typeof v.id=="string"?v.id:O,$=""}else if(X==="text_delta"){let _=typeof v.id=="string"?v.id:null,F=_?T.get(_):void 0;if(_&&F){let re=typeof v.delta=="string"?v.delta:"",ie=(A.get(_)??"")+re;if(A.set(_,ie),ie.trim()==="")continue;let ce=an(_,F);ce.agentMetadata={...ce.agentMetadata,executionId:v.executionId,parentToolId:F},pn(ce,ie,re,void 0);continue}if(O=typeof v.id=="string"?v.id:O,wo==="flow"){let re=typeof v.delta=="string"?v.delta:"";if($+=re,$.trim()==="")continue;let ie=K();ie.agentMetadata={executionId:v.executionId,iteration:v.iteration},pn(ie,$,re,void 0),S=ie;continue}let U=typeof v.delta=="string"?v.delta:"";$+=U;let te=K();te.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:Gr??void 0,agentName:et?.agentName},pn(te,$,U,void 0),S=te}else if(X==="text_complete"){let _=typeof v.id=="string"?v.id:null;if(_&&T.has(_)){let U=R.get(_);U&&zn(U),T.delete(_),A.delete(_),R.delete(_);continue}let F=C;F&&(wo==="flow"?(zn(F),ft=F):((F.content??"")===""&&typeof v.text=="string"&&(F.content=v.text),F.streaming=!1,h(F)),C=null),O=null,$=""}else if(X==="step_complete"){let _=v.stepType,F=v.executionType;if(_==="tool"||F==="context")continue;if(v.success===!1){let U=v.error,te=typeof U=="string"&&U!==""?U:U!=null&&typeof U=="object"&&Reflect.has(U,"message")?String(U.message??"Step failed"):"Step failed";n({type:"error",error:new Error(te)});let re=C;re&&re.streaming&&(re.streaming=!1,h(re)),n({type:"status",status:"idle"});continue}{let U=ft;ft=null;let te=v.stopReason,re=v.result?.response;if(U)te&&(U.stopReason=te),re!=null?Yt(U,re):U.streaming!==!1&&(Ee.delete(U.id),he.delete(U.id),U.streaming=!1,h(U));else{let ie=re!=null&&re!=="";if(ie||te){let ce=K();te&&(ce.stopReason=te),ie?zn(ce,re):(ce.streaming=!1,h(ce))}}continue}}else if(X==="execution_start")wo=v.kind==="flow"?"flow":"agent",jo=!0,wo==="agent"&&(et={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:mt(v.startedAt)});else if(X==="turn_start"){let _=typeof v.iteration=="number"?v.iteration:Us;if(_!==Us){if(et&&(et.currentIteration=_),so==="separate"&&_>1){let F=C;F&&(F.streaming=!1,h(F),Pn.set(_-1,F),C=null)}Us=_}Gr=typeof v.id=="string"?v.id:null,S=null}else if(X==="tool_input_delta"){let _=v.toolCallId??Y.lastId;if(_){let F=G.get(_);F?.toolCall&&(F.toolCall.chunks=F.toolCall.chunks??[],F.toolCall.chunks.push(v.delta??""),h(F))}}else{if(X==="tool_input_complete")continue;if(X==="turn_complete"){let _=v.stopReason,F=C??S;if(_&&F!==null){let U=v.id;(!U||F.agentMetadata?.turnId===U)&&(F.stopReason=_,h(F))}Gr===v.id&&(Gr=null)}else if(X==="media_start"){let _=String(v.id);ro.set(_,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(X==="media_delta"){let _=ro.get(String(v.id));_&&typeof v.delta=="string"&&_.parts.push(v.delta)}else if(X==="media_complete"){let _=String(v.id),F=ro.get(_);ro.delete(_);let U=(typeof v.mediaType=="string"?v.mediaType:void 0)??F?.mediaType??"application/octet-stream",te=typeof v.data=="string"?v.data:void 0,re=typeof v.url=="string"?v.url:F&&F.parts.length>0?F.parts.join(""):void 0,ie=null;if(te)ie={type:"media",data:te,mediaType:U};else if(re){let Ot=U.toLowerCase();ie={type:Ot==="image"||Ot.startsWith("image/")?"image-url":"file-url",url:re,mediaType:U}}let ce=v.toolCallId??F?.toolCallId,Ut=ie?[ie]:[],Oe=[];for(let Ot of Ut){if(!Ot||typeof Ot!="object")continue;let kt=Ot,qo=typeof kt.type=="string"?kt.type:void 0,hr=typeof kt.mediaType=="string"?kt.mediaType.toLowerCase():"",jt=null,qt="";if(qo==="media"){let Cn=typeof kt.data=="string"?kt.data:void 0;if(!Cn)continue;qt=hr.length>0?hr:"application/octet-stream",jt=`data:${qt};base64,${Cn}`}else if(qo==="image-url"){let Cn=typeof kt.url=="string"?kt.url:void 0;if(!Cn)continue;qt=hr,jt=Cn}else if(qo==="file-url"){let Cn=typeof kt.url=="string"?kt.url:void 0;if(!Cn)continue;qt=hr,jt=Cn}else continue;if(jt)if(qo==="image-url"||qt.startsWith("image/"))Oe.push({type:"image",image:jt,...qt.includes("/")?{mimeType:qt}:{}});else if(qt.startsWith("audio/"))Oe.push({type:"audio",audio:jt,mimeType:qt});else if(qt.startsWith("video/"))Oe.push({type:"video",video:jt,mimeType:qt});else{let Cn=qt||"application/octet-stream";Oe.push({type:"file",data:jt,mimeType:Cn,filename:Xk(Cn)})}}if(Oe.length>0){let Ot=u(),kt=ce,hr={id:`agent-media-${typeof kt=="string"&&kt.length>0?`${kt}-${Ot}`:String(Ot)}`,role:"assistant",content:"",contentParts:Oe,createdAt:new Date().toISOString(),streaming:!1,sequence:Ot,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:Us}};h(hr);let jt=C;jt&&(jt.streaming=!1,h(jt)),C=null,x.current=null}}else if(X==="execution_complete"){let _=v.kind??wo;_==="agent"&&et&&(et.status=v.success?"complete":"error",et.completedAt=mt(v.completedAt),et.stopReason=v.stopReason);let F=C;F&&(_==="flow"&&F.streaming!==!1?zn(F):(F.streaming=!1,h(F)),C=null),O=null,$="",ft=null,n({type:"status",status:"idle",terminal:!0})}else if(X==="execution_error"){let _=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(_)})}else if(X!=="ping"){if(X==="approval_start"){let _=v.approvalId??`approval-${u()}`,F={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:_,status:"pending",agentId:et?.agentId??"virtual",executionId:v.executionId??et?.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}};h(F)}else if(X==="step_await"&&v.awaitReason==="approval_required"){let _=v.approvalId??`approval-${u()}`,F={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:_,status:"pending",agentId:et?.agentId??"virtual",executionId:v.executionId??et?.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}};h(F)}else if(X==="approval_complete"){let _=v.approvalId;if(_){let U={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:_,status:v.decision??"approved",agentId:et?.agentId??"virtual",executionId:v.executionId??et?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};h(U)}}else if(X==="artifact_start"||X==="artifact_delta"||X==="artifact_update"||X==="artifact_complete"){if(X==="artifact_start"){let _=v.artifactType,F=String(v.id),U=typeof v.title=="string"?v.title:void 0,te=v.file,re;te&&typeof te=="object"&&!Array.isArray(te)&&typeof te.path=="string"&&typeof te.mimeType=="string"&&(re={path:te.path,mimeType:te.mimeType,...typeof te.language=="string"?{language:te.language}:{}}),n({type:"artifact_start",id:F,artifactType:_,title:U,component:typeof v.component=="string"?v.component:void 0,...re?{file:re}:{}});let ie=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(be.set(F,{markdown:"",title:U,file:re,...ie?{props:ie}:{}}),!Ge.has(F)){Ge.add(F);let ce=cr(this.config.features?.artifacts,{artifactType:_,...re?{file:re}:{}}),Ut=typeof v.component=="string"?v.component:void 0,Oe={id:`artifact-ref-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:Fa(ce,{artifactId:F,title:U,artifactType:_,status:"streaming",...re?{file:re}:{},...Ut?{component:Ut}:{}})};ve.set(F,Oe),h(Oe)}}else if(X==="artifact_delta"){let _=String(v.id),F=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:_,artDelta:F});let U=be.get(_);U&&(U.markdown+=F)}else if(X==="artifact_update"){let _=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:_,component:typeof v.component=="string"?v.component:void 0});let F=be.get(String(v.id));F&&(F.props={...F.props??{},..._})}else if(X==="artifact_complete"){let _=String(v.id);n({type:"artifact_complete",id:_});let F=ve.get(_);if(F){F.streaming=!1;try{let U=JSON.parse(F.rawContent??"{}");if(U.props){U.props.status="complete";let te=be.get(_);te?.markdown&&(U.props.markdown=te.markdown),te?.file&&(U.props.file=te.file),U.component==="PersonaArtifactInline"&&te?.props&&Object.keys(te.props).length>0&&(U.props.componentProps=te.props)}F.rawContent=JSON.stringify(U)}catch{}be.delete(_),h(F),ve.delete(_)}}}else if(X==="transcript_insert"){let _=v.message;if(!_||typeof _!="object")continue;let F=String(_.id??`msg-${u()}`),U=_.role,re={id:F,role:U==="user"?"user":U==="system"?"system":"assistant",content:typeof _.content=="string"?_.content:"",rawContent:typeof _.rawContent=="string"?_.rawContent:void 0,createdAt:typeof _.createdAt=="string"?_.createdAt:new Date().toISOString(),streaming:_.streaming===!0,...typeof _.variant=="string"?{variant:_.variant}:{},sequence:u()};if(h(re),re.rawContent)try{let ce=JSON.parse(re.rawContent)?.props?.artifactId;typeof ce=="string"&&Ge.add(ce)}catch{}C=null,x.current=null,Ee.delete(F),he.delete(F)}else if(X==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let _=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(_)});let F=C;F&&F.streaming&&(F.streaming=!1,h(F)),n({type:"status",status:"idle"})}}else if(X==="step_error"||X==="dispatch_error"||X==="flow_error"){let _=null;if(v.error instanceof Error)_=v.error;else if(X==="dispatch_error"){let F=v.message??v.error;F!=null&&F!==""&&(_=new Error(String(F)))}else{let F=v.error;typeof F=="string"&&F!==""?_=new Error(F):F!=null&&typeof F=="object"&&Reflect.has(F,"message")&&(_=new Error(String(F.message??F)))}if(_){n({type:"error",error:_});let F=C;F&&F.streaming&&(F.streaming=!1,h(F)),n({type:"status",status:"idle"})}}}}}Co.length=0};;){let{done:D,value:X}=await s.read();if(D)break;l+=a.decode(X,{stream:!0});let v=l.split(`
6
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},qa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},fg=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},hg=()=>{let e=$P();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},yg=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Gb(n,Yb|Qb);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Gc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Gc(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},UP=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=l=>typeof l=="string"?Gc(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Gc(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let l=Gb(s,Yb|Qb),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},bg=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ev="4.22.1";var Ro=ev;var wi="[Image]";function qP(e){return typeof e=="string"?[{type:"text",text:e}]:e}function vg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function za(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function zP(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function mo(e){return{type:"text",text:e}}function Cg(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function VP(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function KP(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var tv=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],GP=["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"],ar=[...tv,...GP];function YP(e){return tv.includes(e)||e.startsWith("image/")}function Zc(e){return YP(e.type)}function nv(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function ov(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Zc(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function rv(e,t=ar,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function QP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function sv(e,t){let n=QP(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var XP=["user","assistant","system"],JP=0;function iv(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function ed(e){return typeof e=="string"?e:void 0}function ZP(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?mo(t.text):null;case"image":return typeof t.image=="string"?Cg(t.image,{mimeType:ed(t.mimeType),alt:ed(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?nv(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...ed(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...ed(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function ek(e,t){let n=iv(t),o=e.map(a=>iv(a.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let a=o[s];if(a!==null){r[s]=a,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let d=l-s+1,p=s>0?r[s-1]:null,u=l+1<o.length?o[l+1]:null,m=u!==null&&n!==null?Math.min(u,n):u??n;for(let y=0;y<d;y+=1)r[s+y]=m!==null?m-(d-y):p!==null?p+y+1:JP+y;s=l+1}return r.map(a=>new Date(a).toISOString())}function av(e,t){let n=ek(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!XP.includes(r.role))return;let a=r.role,l=n[s];if(r.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:r.id,role:a,content:"",createdAt:l,agentMetadata:d});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:a,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:a,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let d=r.content.map(ZP).filter(u=>u!==null),p=vg(d);o.push({id:r.id,role:a,content:p||(za(d)?wi:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Va(e){let t=e.content;if(typeof t!="string"||t==="")return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof n=="string"&&n===t))return t}function Ka(e,t){let n=new Map;for(let o of e)n.set(o.id,o);for(let o of t)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),a=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(a)&&s!==a)return s-a;let l=o.sequence??0,d=r.sequence??0;return l!==d?l-d:o.id.localeCompare(r.id)})}var tk="https://api.runtype.com/v1/dispatch",lv="https://api.runtype.com",Ne=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},cv=32768,wg=49152,dv=e=>{let t=e??{},n=typeof t.targetId=="string"?t.targetId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:n,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},pv=e=>"reason"in e?e.reason:void 0,uv="The identity proof was not admitted; account history is unavailable",gv="The identity proof was rejected",mv="The request carried no visitor credential",fv="The stored visitor belongs to a different signed-in user",xg=(e,t)=>e instanceof Ne&&e.code===t;function nk(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Sg=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function ok(e){switch(e){case"json":return yg;case"regex-json":return hg;case"xml":return bg;default:return fg}}var hv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function rk(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=hv(n);if(!hv(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=qa(e);return qa(t)!==null&&a===null?t:e}var xi=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??tk,this.headers={"Content-Type":"application/json","X-Persona-Version":Ro,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??ok(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,t.webmcp?.enabled===!0&&(this.webMcpBridgePromise=this.createWebMcpBridge(t.webmcp))}createWebMcpBridge(t){return Mb().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Uc,getToolDisplayTitle:yi,loadPolyfill:jc});return this.pendingWebMcpConfirmHandler!==void 0&&o.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=o,o}).catch(n=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.pendingWebMcpConfirmHandler=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Pb(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)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||lv}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new Ne("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:t.after}),d=await fetch(`${a}?${l}`,{method:"GET",headers:{"X-Persona-Version":Ro,"X-Visitor-Token":s},signal:t.signal});if(d.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(d),null,!0);continue}if(!d.ok)throw await this.historyErrorFor(d,!0);return d}}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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let t=this.historyIdentityStatus;return t?.state==="browser_only"?t:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&pv(n)===pv(t);if(this.historyIdentityStatus=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let n=this.isHistoryCapable()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.routing(),a=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,d={token:this.config.clientToken,...a&&{flowId:a},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...l?{conversationId:l}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ro},body:JSON.stringify(d)});if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new Ne("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw p.status===403&&m.error==="durable_recovery_disabled"?new Ne("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&m.error==="visitor_required"?new Ne("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new Ne("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):p.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.createClientSession({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,t,!1)}catch(r){if(!xg(r,"not_found")&&!xg(r,"visitor_required")&&!xg(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(t,n)):this.doOrdinaryInit(t,n)}async doOrdinaryInit(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,t,n)}async reinitWithProof(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:t}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),s}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&t.durableRecovery?.enabled!==!0)return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Ne("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new Ne("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:t,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ro},body:JSON.stringify(r)});if(!s.ok){let a=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(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,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:t,comment:n})}async submitNPSFeedback(t,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:t,comment:n})}historyUrl(t,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new Ne("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Ne("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Ne("proof_not_admitted",uv);return r}async readErrorCode(t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Ne("invalid_identity_proof",gv);if(r.includes("visitor token required"))throw new Ne("visitor_token_missing",mv);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Ne("visitor_identity_mismatch",fv);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new Ne("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,n){let o=await this.readErrorCode(t);if(t.status===404)return new Ne("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new Ne("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Ne("proof_not_admitted",uv);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Ne("invalid_identity_proof",gv)):r.includes("visitor token required")?new Ne("visitor_token_missing",mv):r.includes("visitor_identity_mismatch")?new Ne("visitor_identity_mismatch",fv):new Ne("unauthorized",o||"History request was not authorized")}return new Ne("request_failed",o||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new Ne("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Ne("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new Ne("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let d=a?.revision()??0,p=await this.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new Ne("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Ro,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),y=await u.json().catch(()=>{});if(a&&a.revision()!==d)throw new Ne("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),y}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new Ne("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let n=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(dv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:dv(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(t,n){this.assertHistoryUsable();let o=0;for(let d of n){let p=d.displayContent.length;if(p>cv)throw new Ne("payload_too_large",`displayContent exceeds the ${cv} character limit`);o+=p}if(o>wg)throw new Ne("payload_too_large",`Display projection batch exceeds the ${wg} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,s=r?.revision()??0,a=await this.historyFetch(`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=wg,trackIdentity:!1}),l=typeof a?.conversationRevision=="string"?a.conversationRevision:null;return l&&this.clientSession?.conversationId===t&&(r?.revision()??0)===s&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(t){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){let o=kb();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=await this.initSession();if(new Date>=new Date(a.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let v=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:v}),v}let l=await this.buildPayload(t.messages),d=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null,p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([v])=>v!=="sessionId"&&v!=="session_id")):void 0,u=this.isHistoryCapable(),m={sessionId:a.sessionId,messages:t.messages.filter(Sg).map(v=>{let x=u?Va(v):void 0;return{id:v.id,role:v.role,content:v.contentParts??v.llmContent??v.rawContent??v.content,...x!==void 0&&{displayContent:x}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},{response:y,commit:h}=await this.sendWithClientToolsDiff(a.sessionId,l.clientTools,v=>{let x={...m,...v};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",x),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ro,...d?{"X-Visitor-Token":d}:{}},body:JSON.stringify(x),signal:t.signal})});if(!y.ok){let v=await y.json().catch(()=>({error:"Chat request failed"}));if(y.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let w=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:w}),w}if(y.status===429){let w=new Error(v.hint||"Message limit reached for this session.");throw s({type:"error",error:w}),w}if(y.status===410&&v.error==="conversation_deleted"){let w=new Ne("conversation_deleted","This conversation was deleted");throw s({type:"error",error:w}),w}let x=new Error(v.error||"Failed to send message");throw s({type:"error",error:x}),x}if(!y.body){let v=new Error("No response body received");throw s({type:"error",error:v}),v}h(),s({type:"status",status:"connected"});try{await this.streamResponse(y.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof Ne)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let o=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?Sb(n):void 0,l=this.clientToolsFingerprintSessionId===t,d=s&&l&&this.lastSentClientToolsFingerprint===a,p=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,u=!1,m;for(let y=0;;y++){if(m=await o({...s&&(u||!d)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),m.status===409&&y===0&&s&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:p&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||lv}/resume`,a,l=null;if(r){let u=await this.initSession();a=u.sessionId,u.durableRecovery?.enabled===!0&&(l=await this.readVisitorToken())}let d={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...this.headers};this.getHeaders&&Object.assign(d,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(a&&(p.sessionId=a),r&&a){let u=[...$a(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:y}=await this.sendWithClientToolsDiff(a,u,h=>{let v={...p,...h};return this.debug&&console.debug("[AgentWidgetClient] client token resume",v),fetch(s,{method:"POST",headers:d,body:JSON.stringify(v),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&y(),m}return fetch(s,{method:"POST",headers:d,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,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(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(t,n){let o=n?.selectedModelId;return!o||!("model"in t)?t:this.config.composer?.models?.some(s=>s.id===o)?{...t,model:o}:t}async buildAgentPayload(t,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Sg).filter(p=>p.role==="user"||p.role==="assistant"||p.role==="system").filter(p=>!p.variant||p.variant==="assistant").sort((p,u)=>{let m=new Date(p.createdAt).getTime(),y=new Date(u.createdAt).getTime();return m-y}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...$a(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(a.clientTools=l);let d=await this.buildContextAggregate(t);return d&&(a.context=d),a}async buildPayload(t,n){let o=t.slice().filter(Sg).sort((p,u)=>{let m=new Date(p.createdAt).getTime(),y=new Date(u.createdAt).getTime();return m-y}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,u]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=u);let a=[...$a(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(s.clientTools=a);let l=await this.buildContextAggregate(t);l&&(s.context=l);let d=this.normalizeComposerOptions(n);if(d&&(s.composerOptions=d),this.requestMiddleware)try{let p=await this.requestMiddleware({payload:{...s},config:this.config});if(p&&typeof p=="object"){let u=p;return s.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=s.clientTools),u}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=m,r(m),m},p=u=>o.current?o.current:d(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.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(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",d=Date.now(),p=0,u=()=>d+p++,m=q=>{let S=q.reasoning?{...q.reasoning,chunks:[...q.reasoning.chunks]}:void 0,N=q.toolCall?{...q.toolCall,chunks:q.toolCall.chunks?[...q.toolCall.chunks]:void 0}:void 0,z=q.tools?q.tools.map(Y=>({...Y,chunks:Y.chunks?[...Y.chunks]:void 0})):void 0;return{...q,reasoning:S,toolCall:N,tools:z}},y=q=>{if(q.role!=="assistant"||q.variant)return!0;let S=Array.isArray(q.contentParts)&&q.contentParts.length>0,N=typeof q.rawContent=="string"&&q.rawContent.trim()!=="";return typeof q.content=="string"&&q.content.trim()!==""||S||N||!!q.stopReason},h=q=>{y(q)&&n({type:"message",message:m(q)})},v=null,x=null,w={current:null},k={current:null},O=null,D="",T=new Map,I=new Map,A=new Map,_=new Map,K=new Map,ie=o,Z=!1,M=()=>{if(v)return v;let q,S="",N=O;return!Z&&ie?(q=ie,Z=!0,S=r??""):ie&&N?q=`${ie}_${N}`:q=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:q,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},h(v),v},B=q=>{let S=_.get(q);if(S)return S;let N={id:`reason-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:q,status:"streaming",chunks:[]}};return _.set(q,N),h(N),N},H=new Set,R=new Map,J=new Set,V=new Map,pe=q=>{if(!q)return!1;let S=q.replace(/_+/g,"_").replace(/^_|_$/g,"");return S==="emit_artifact_markdown"||S==="emit_artifact_component"},se=q=>{let S=K.get(q);if(S)return S;let N={id:`tool-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:q,status:"pending"}};return K.set(q,N),h(N),N},ge=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){let S=Number(q);if(!Number.isNaN(S)&&Number.isFinite(S))return S;let N=Date.parse(q);if(!Number.isNaN(N))return N}return Date.now()},Ie=q=>{if(typeof q=="string")return q;if(q==null)return"";try{return JSON.stringify(q)}catch{return String(q)}},ye=new Map,ce=new Map,Je=(q,S)=>{let N=Ie(S),z=ce.get(q.id),Y=rk(z,N);q.rawContent=Y;let ee=ye.get(q.id),he=Ke=>{let je=q.content??"";Ke.trim()!==""&&(je.trim().length===0||Ke.startsWith(je)||Ke.trimStart().startsWith(je.trim()))&&(q.content=Ke)},Te=()=>{if(ee){let Ke=ee.close?.();Ke instanceof Promise&&Ke.catch(()=>{})}ye.delete(q.id),ce.delete(q.id),q.streaming=!1,h(q)};if(!ee){he(N),Te();return}let ke=qa(Y);if(ke!==null&&ke.trim()!==""){he(ke),Te();return}let He=Ke=>{let je=typeof Ke=="string"?Ke:Ke?.text??null;if(je!==null&&je.trim()!=="")return je;let ht=ee.getExtractedText();return ht!==null&&ht.trim()!==""?ht:N},rt;try{rt=ee.processChunk(Y)}catch{he(N),Te();return}if(rt instanceof Promise){rt.then(Ke=>{he(He(Ke)),Te()}).catch(()=>{he(N),Te()});return}he(He(rt)),Te()},fe=null,F=(q,S,N,z)=>{q.rawContent=S,ye.has(q.id)||ye.set(q.id,this.createStreamParser());let Y=ye.get(q.id),ee=S.trim().startsWith("{")||S.trim().startsWith("[");if(ee&&ce.set(q.id,S),Y.__isPlainTextParser===!0){q.content=z!==void 0?S:q.content+N,ce.delete(q.id),ye.delete(q.id),q.rawContent=void 0,h(q);return}let Te=Y.processChunk(S);if(Te instanceof Promise)Te.then(ke=>{let He=typeof ke=="string"?ke:ke?.text??null;He!==null&&He.trim()!==""?(q.content=He,h(q)):!ee&&!S.trim().startsWith("<")&&(q.content=z!==void 0?S:q.content+N,ce.delete(q.id),ye.delete(q.id),q.rawContent=void 0,h(q))}).catch(()=>{q.content=z!==void 0?S:q.content+N,ce.delete(q.id),ye.delete(q.id),q.rawContent=void 0,h(q)});else{let ke=typeof Te=="string"?Te:Te?.text??null;ke!==null&&ke.trim()!==""?(q.content=ke,h(q)):!ee&&!S.trim().startsWith("<")&&(q.content=z!==void 0?S:q.content+N,ce.delete(q.id),ye.delete(q.id),q.rawContent=void 0,h(q))}},Oe=(q,S)=>{let N=S??q.content;if(N==null||N===""){q.streaming=!1,h(q);return}let Y=ce.get(q.id)??Ie(N);q.rawContent=Y;let ee=ye.get(q.id),he=null,Te=!1;if(ee&&(he=ee.getExtractedText(),he===null&&(he=qa(Y)),he===null)){let ke=ee.processChunk(Y);ke instanceof Promise?(Te=!0,ke.then(He=>{let rt=typeof He=="string"?He:He?.text??null;rt!==null&&(q.content=rt,q.streaming=!1,ye.delete(q.id),ce.delete(q.id),h(q))}).catch(()=>{})):he=typeof ke=="string"?ke:ke?.text??null}if(!Te){he!==null&&he.trim()!==""?q.content=he:ce.has(q.id)||(q.content=Ie(N));let ke=ye.get(q.id);if(ke){let He=ke.close?.();He instanceof Promise&&He.catch(()=>{}),ye.delete(q.id)}ce.delete(q.id),q.streaming=!1,h(q)}},Ue=(q,S,N)=>{let z=I.get(q);if(z)return z;let Y={id:`nested-${S}-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...N?{variant:N}:{},...N==="reasoning"?{reasoning:{id:q,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:S}};return I.set(q,Y),h(Y),Y},Bt=[],be,Be=new Map,ve=0,xe="agent",bt=!1,Rt=null,ut=null,vn=this.config.iterationDisplay??"separate";for(be=()=>{for(let q=0;q<Bt.length;q++){let S=Bt[q];if(!bt&&xe!=="flow"&&typeof S.stepType=="string"&&(xe="flow"),S.type==="reasoning_start"){let N=typeof S.id=="string"?S.id:null,z=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(N&&z){T.set(N,z),Ue(N,z,"reasoning");continue}let Y=S.id,ee=B(Y);ee.reasoning=ee.reasoning??{id:Y,status:"streaming",chunks:[]},ee.reasoning.startedAt=ee.reasoning.startedAt??Date.now(),ee.reasoning.completedAt=void 0,ee.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(ee.reasoning.scope=S.scope),ee.streaming=!0,ee.reasoning.status="streaming",h(ee)}else if(S.type==="reasoning_delta"){let N=typeof S.id=="string"?S.id:null;if(N&&T.has(N)&&I.has(N)){let ee=I.get(N),he=S.delta;he&&ee.reasoning&&(ee.reasoning.chunks.push(String(he)),h(ee));continue}let z=S.id,Y=B(z);Y.reasoning=Y.reasoning??{id:z,status:"streaming",chunks:[]},Y.reasoning.startedAt=Y.reasoning.startedAt??Date.now(),S.delta&&Y.reasoning.chunks.push(S.delta),Y.reasoning.status="streaming",Y.streaming=!0,h(Y)}else if(S.type==="reasoning_complete"){let N=typeof S.id=="string"?S.id:null;if(N&&T.has(N)&&I.has(N)){let he=I.get(N);if(he.reasoning){let Te=typeof S.text=="string"?S.text:"";Te&&he.reasoning.chunks.length===0&&he.reasoning.chunks.push(Te),he.reasoning.status="complete",he.streaming=!1,h(he)}T.delete(N),I.delete(N);continue}let z=S.id,Y=typeof S.text=="string"?S.text:"";!_.get(z)&&(Y||S.scope==="loop")&&B(z);let ee=_.get(z);if(ee?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(ee.reasoning.scope=S.scope),Y&&ee.reasoning.chunks.length===0&&ee.reasoning.chunks.push(Y),ee.reasoning.status="complete",ee.reasoning.completedAt=Date.now();let he=ee.reasoning.startedAt??Date.now();ee.reasoning.durationMs=Math.max(0,(ee.reasoning.completedAt??Date.now())-he),ee.streaming=!1,h(ee)}}else if(S.type==="tool_start"){v&&(v.streaming=!1,h(v),v=null),typeof S.iteration=="number"&&(ve=S.iteration);let N=S.toolCallId,z=S.toolName;if(pe(z)){H.add(N);continue}let Y=se(N),ee=Y.toolCall??{id:N,status:"pending"};ee.name=z??ee.name,ee.status="running",ee.success=void 0,ee.error=void 0,ee.duration=void 0,S.parameters!==void 0&&(ee.args=S.parameters),ee.startedAt=ee.startedAt??ge(S.startedAt),ee.completedAt=void 0,ee.durationMs=void 0,Y.toolCall=ee,Y.streaming=!0,S.executionId&&(Y.agentMetadata={executionId:S.executionId,iteration:S.iteration}),h(Y)}else if(S.type==="tool_output_delta"){let N=S.toolCallId;if(H.has(N))continue;let z=se(N),Y=z.toolCall??{id:N,status:"running"};Y.startedAt=Y.startedAt??Date.now();let ee=S.delta;ee&&(Y.chunks=Y.chunks??[],Y.chunks.push(String(ee))),Y.status="running",z.toolCall=Y,z.streaming=!0,S.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:S.executionId,iteration:ve}),h(z)}else if(S.type==="tool_complete"){let N=S.toolCallId;if(H.has(N)){H.delete(N);continue}let z=se(N),Y=z.toolCall??{id:N,status:"running"};Y.status="complete",S.result!==void 0&&(Y.result=S.result),Y.name=S.toolName??Y.name,Y.success=S.success,Y.error=S.error,Y.completedAt=Date.now();let ee=S.executionTime;if(typeof ee=="number")Y.durationMs=ee,Y.duration=ee;else{let he=Y.startedAt??Date.now();Y.durationMs=Math.max(0,(Y.completedAt??Date.now())-he)}z.toolCall=Y,z.streaming=!1,S.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:S.executionId,iteration:S.iteration??ve}),h(z)}else if(S.type==="await"&&S.toolName){let N=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,z=N??S.toolId??`local-${u()}`,Y=se(z),ee=S.toolName,he=S.origin==="webmcp"&&!xs(ee)?`webmcp:${ee}`:ee,Te=xs(he),ke=Y.toolCall??{id:z,status:"pending"};ke.name=he,ke.args=S.parameters,ke.status=Te?"running":"complete",ke.chunks=ke.chunks??[],ke.startedAt=ke.startedAt??ge(S.awaitedAt),Te?(ke.completedAt=void 0,ke.duration=void 0,ke.durationMs=void 0):ke.completedAt=ke.completedAt??ke.startedAt,Y.toolCall=ke,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:S.executionId??Y.agentMetadata?.executionId,awaitingLocalTool:!0,...N?{webMcpToolCallId:N}:{}},h(Y)}else if(S.type==="text_start"){let N=typeof S.id=="string"?S.id:null,z=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(N&&z){T.set(N,z);continue}let Y=v;Y&&(xe==="flow"?(Oe(Y),fe=Y):(Y.streaming=!1,h(Y)),v=null),O=typeof S.id=="string"?S.id:O,D=""}else if(S.type==="text_delta"){let N=typeof S.id=="string"?S.id:null,z=N?T.get(N):void 0;if(N&&z){let he=typeof S.delta=="string"?S.delta:"",Te=(A.get(N)??"")+he;if(A.set(N,Te),Te.trim()==="")continue;let ke=Ue(N,z);ke.agentMetadata={...ke.agentMetadata,executionId:S.executionId,parentToolId:z},F(ke,Te,he,void 0);continue}if(O=typeof S.id=="string"?S.id:O,xe==="flow"){let he=typeof S.delta=="string"?S.delta:"";if(D+=he,D.trim()==="")continue;let Te=M();Te.agentMetadata={executionId:S.executionId,iteration:ve},F(Te,D,he,void 0),x=Te;continue}let Y=typeof S.delta=="string"?S.delta:"";D+=Y;let ee=M();ee.agentMetadata={executionId:S.executionId,iteration:ve,turnId:Rt??void 0,agentName:ut?.agentName},F(ee,D,Y,void 0),x=ee}else if(S.type==="text_complete"){let N=typeof S.id=="string"?S.id:null;if(N&&T.has(N)){let Y=I.get(N);Y&&Oe(Y),T.delete(N),A.delete(N),I.delete(N);continue}let z=v;z&&(xe==="flow"?(Oe(z),fe=z):((z.content??"")===""&&typeof S.text=="string"&&(z.content=S.text),z.streaming=!1,h(z)),v=null),O=null,D=""}else if(S.type==="step_complete"){if(S.stepType==="tool")continue;if(S.success===!1){let N=S.error||"Step failed";n({type:"error",error:new Error(N)});let z=v;z&&z.streaming&&(z.streaming=!1,h(z)),n({type:"status",status:"idle"});continue}{let N=fe;fe=null;let z=S.stopReason,ee=(S.result&&typeof S.result=="object"?S.result:null)?.response;if(N)z&&(N.stopReason=z),ee!=null?Je(N,ee):N.streaming!==!1&&(ye.delete(N.id),ce.delete(N.id),N.streaming=!1,h(N));else{let he=ee!=null&&ee!=="";if(he||z){let Te=M();z&&(Te.stopReason=z),he?Oe(Te,ee):(Te.streaming=!1,h(Te))}}continue}}else if(S.type==="execution_start")xe=S.kind==="flow"?"flow":"agent",bt=!0,xe==="agent"&&(ut={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??""});else if(S.type==="turn_start"){let N=typeof S.iteration=="number"?S.iteration:ve;if(N!==ve){if(vn==="separate"&&N>1){let z=v;z&&(z.streaming=!1,h(z),v=null)}ve=N}Rt=typeof S.id=="string"?S.id:null,x=null}else if(S.type==="tool_input_delta"){let N=S.toolCallId;if(N){let z=K.get(N);z?.toolCall&&(z.toolCall.chunks=z.toolCall.chunks??[],z.toolCall.chunks.push(S.delta??""),h(z))}}else if(S.type==="tool_input_complete"){if(H.has(S.toolCallId))continue;let N=se(S.toolCallId),z=N.toolCall;z.args=S.parameters,z.name=S.toolName??z.name,h(N)}else if(S.type==="turn_complete"){let N=S.stopReason,z=v??x;if(N&&z!==null){let Y=S.id;(!Y||z.agentMetadata?.turnId===Y)&&(z.stopReason=N,h(z))}Rt===S.id&&(Rt=null)}else if(S.type==="media_start"){let N=String(S.id);Be.set(N,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,toolCallId:S.toolCallId,parts:[]})}else if(S.type==="media_delta"){let N=Be.get(String(S.id));N&&typeof S.delta=="string"&&N.parts.push(S.delta)}else if(S.type==="media_complete"){let N=String(S.id),z=Be.get(N);Be.delete(N);let Y=(typeof S.mediaType=="string"?S.mediaType:void 0)??z?.mediaType??"application/octet-stream",ee=typeof S.data=="string"?S.data:void 0,he=typeof S.url=="string"?S.url:z&&z.parts.length>0?z.parts.join(""):void 0,Te=null;if(ee)Te={type:"media",data:ee,mediaType:Y};else if(he){let Ke=Y.toLowerCase();Te={type:Ke==="image"||Ke.startsWith("image/")?"image-url":"file-url",url:he,mediaType:Y}}let ke=S.toolCallId??z?.toolCallId,He=Te?[Te]:[],rt=[];for(let Ke of He){if(!Ke||typeof Ke!="object")continue;let je=Ke,ht=typeof je.type=="string"?je.type:void 0,Gt=typeof je.mediaType=="string"?je.mediaType.toLowerCase():"",Ht=null,sn="";if(ht==="media"){let Cn=typeof je.data=="string"?je.data:void 0;if(!Cn)continue;sn=Gt.length>0?Gt:"application/octet-stream",Ht=`data:${sn};base64,${Cn}`}else if(ht==="image-url"){let Cn=typeof je.url=="string"?je.url:void 0;if(!Cn)continue;sn=Gt,Ht=Cn}else if(ht==="file-url"){let Cn=typeof je.url=="string"?je.url:void 0;if(!Cn)continue;sn=Gt,Ht=Cn}else continue;if(Ht)if(ht==="image-url"||sn.startsWith("image/"))rt.push({type:"image",image:Ht,...sn.includes("/")?{mimeType:sn}:{}});else if(sn.startsWith("audio/"))rt.push({type:"audio",audio:Ht,mimeType:sn});else if(sn.startsWith("video/"))rt.push({type:"video",video:Ht,mimeType:sn});else{let Cn=sn||"application/octet-stream";rt.push({type:"file",data:Ht,mimeType:Cn,filename:nk(Cn)})}}if(rt.length>0){let Ke=u(),je=ke,Gt={id:`agent-media-${typeof je=="string"&&je.length>0?`${je}-${Ke}`:String(Ke)}`,role:"assistant",content:"",contentParts:rt,createdAt:new Date().toISOString(),streaming:!1,sequence:Ke,agentMetadata:{executionId:S.executionId,iteration:ve}};h(Gt);let Ht=v;Ht&&(Ht.streaming=!1,h(Ht)),v=null,w.current=null}}else if(S.type==="execution_complete"){let N=v;N&&(S.kind==="flow"&&N.streaming!==!1?Oe(N):(N.streaming=!1,h(N)),v=null),O=null,D="",fe=null,n({type:"status",status:"idle",terminal:!0})}else if(S.type==="execution_error"){let N=typeof S.error=="string"?S.error:S.error?.message??"Execution error";n({type:"error",error:new Error(N)})}else if(S.type!=="ping"){if(S.type==="approval_start"){let N=S.approvalId??`approval-${u()}`,z={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:"pending",agentId:ut?.agentId??"virtual",executionId:S.executionId??ut?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters}};h(z)}else if(S.type==="approval_complete"){let N=S.approvalId;if(N){let Y={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:S.decision??"approved",agentId:ut?.agentId??"virtual",executionId:S.executionId??ut?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(Y)}}else if(S.type==="artifact_start"||S.type==="artifact_delta"||S.type==="artifact_update"||S.type==="artifact_complete"){if(S.type==="artifact_start"){let N=S.artifactType,z=String(S.id),Y=typeof S.title=="string"?S.title:void 0,ee=S.file,he;if(ee&&typeof ee=="object"&&!Array.isArray(ee)&&typeof ee.path=="string"&&typeof ee.mimeType=="string"&&(he={path:ee.path,mimeType:ee.mimeType,...typeof ee.language=="string"?{language:ee.language}:{}}),n({type:"artifact_start",id:z,artifactType:N,title:Y,component:typeof S.component=="string"?S.component:void 0,...he?{file:he}:{}}),V.set(z,{markdown:"",title:Y,file:he}),!J.has(z)){J.add(z);let Te=sr(this.config.features?.artifacts,{artifactType:N,...he?{file:he}:{}}),ke=typeof S.component=="string"?S.component:void 0,He={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:Ba(Te,{artifactId:z,title:Y,artifactType:N,status:"streaming",...he?{file:he}:{},...ke?{component:ke}:{}})};R.set(z,He),h(He)}}else if(S.type==="artifact_delta"){let N=String(S.id),z=typeof S.delta=="string"?S.delta:String(S.delta??"");n({type:"artifact_delta",id:N,artDelta:z});let Y=V.get(N);Y&&(Y.markdown+=z)}else if(S.type==="artifact_update"){let N=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};n({type:"artifact_update",id:String(S.id),props:N,component:typeof S.component=="string"?S.component:void 0});let z=V.get(String(S.id));z&&(z.props={...z.props??{},...N})}else if(S.type==="artifact_complete"){let N=String(S.id);n({type:"artifact_complete",id:N});let z=R.get(N);if(z){z.streaming=!1;try{let Y=JSON.parse(z.rawContent??"{}");if(Y.props){Y.props.status="complete";let ee=V.get(N);ee?.markdown&&(Y.props.markdown=ee.markdown),ee?.file&&(Y.props.file=ee.file),Y.component==="PersonaArtifactInline"&&ee?.props&&Object.keys(ee.props).length>0&&(Y.props.componentProps=ee.props)}z.rawContent=JSON.stringify(Y)}catch{}V.delete(N),h(z),R.delete(N)}}}else if(S.type==="error"&&S.recoverable===!1&&S.error!=null&&S.error!==""){let N=typeof S.error=="string"?S.error:S.error?.message!=null?String(S.error.message):"Execution error";n({type:"error",error:new Error(N)});let z=v;z&&z.streaming&&(z.streaming=!1,h(z)),n({type:"status",status:"idle"})}}}Bt.length=0};;){let{done:q,value:S}=await s.read();if(q)break;l+=a.decode(S,{stream:!0});let N=l.split(`
7
7
 
8
- `);l=v.pop()??"";for(let _ of v){let F=_.split(`
9
- `),U="message",te="",re=null;for(let Oe of F)Oe.startsWith("event:")?U=Oe.replace("event:","").trim():Oe.startsWith("data:")?te+=Oe.replace("data:","").trim():Oe.startsWith("id:")&&(re=Oe.slice(3).trim());let ie=()=>{re!==null&&re!==""&&n({type:"cursor",id:re})};if(!te){ie();continue}let ce;try{ce=JSON.parse(te)}catch(Oe){n({type:"error",error:Oe instanceof Error?Oe:new Error("Failed to parse chat stream payload")});continue}let Ut=U!=="message"?U:ce.type??"message";if(this.onSSEEvent?.(Ut,ce),this.parseSSEEvent){x.current=C;let Oe=await this.handleCustomSSEEvent(ce,n,x,h,u,P);if(x.current&&x.current!==C&&(C=x.current),Oe){ie();continue}}Co.push({payloadType:Ut,payload:ce}),Vn(),ie()}}Vn()}};function eP(e){let t=0;for(let n of e.split(`
10
- `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function gv(e,t){let n="`".repeat(Math.max(3,eP(t)+1));return`${n}${e}
8
+ `);l=N.pop()??"";for(let z of N){let Y=z.split(`
9
+ `),ee="message",he="",Te=null;for(let je of Y)je.startsWith("event:")?ee=je.replace("event:","").trim():je.startsWith("data:")?he+=je.replace("data:","").trim():je.startsWith("id:")&&(Te=je.slice(3).trim());let ke=()=>{Te!==null&&Te!==""&&n({type:"cursor",id:Te})};if(!he){ke();continue}let He;try{He=JSON.parse(he)}catch(je){n({type:"error",error:je instanceof Error?je:new Error("Failed to parse chat stream payload")});continue}let rt=He!==null&&typeof He=="object"&&!Array.isArray(He)?He:null,Ke=ee!=="message"?ee:typeof rt?.type=="string"?rt.type:"message";if(this.onSSEEvent?.(Ke,He),this.parseSSEEvent){w.current=v;let je=await this.handleCustomSSEEvent(He,n,w,h,u,k);if(w.current&&w.current!==v&&(v=w.current),je){ke();continue}}rt&&(Bt.push({...rt,type:Ke}),be()),ke()}}be()}};function sk(e){let t=0;for(let n of e.split(`
10
+ `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function yv(e,t){let n="`".repeat(Math.max(3,sk(t)+1));return`${n}${e}
11
11
  ${t}
12
- ${n}`}var tP=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function nP(e){let t=e?.text?.trim()??"";return t?gv(tP(e),t):""}function mv(e){let t=nP(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[ho(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
12
+ ${n}`}var ik=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function ak(e){let t=e?.text?.trim()??"";return t?yv(ik(e),t):""}function bv(e){let t=ak(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[mo(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
13
13
 
14
- `)}:{}}function rd(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function fv(e,t){let n=e.findIndex(r=>r.id===t);if(n===-1||e[n].role!=="user")return null;let o=n+1;for(;o<e.length&&e[o].role!=="user";)o+=1;return{start:n,end:o}}function Ag(e,t){let n=e.findIndex(o=>o.id===t);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(e[o].role==="user")return e[o].id;return null}function hv(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return Ag(e,n.id)?n.id:null}return null}function Mg(e){return e.role!=="user"||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content=="string"&&e.content.length>0}var yo=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function oP(e){return e instanceof yo}function Ja(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Ws=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(l=>l.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Ja(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Pi=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"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(t,"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(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};var rP=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function yv(e){try{if(e?.type==="custom"&&e.custom){let t=e.custom,n=typeof t=="function"?t():t;return!!n&&typeof n.startListening=="function"}return e?.type==="runtype"&&e.runtype?!0:rP()}catch{return!1}}var{setLoader:IW,load:sP}=vt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var Eg=sP;function Tg(e){if(!e)return"";let t=iP(e);return bv(t!==null?t:e)}function iP(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function bv(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
14
+ `)}:{}}function td(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function vv(e,t){let n=e.findIndex(r=>r.id===t);if(n===-1||e[n].role!=="user")return null;let o=n+1;for(;o<e.length&&e[o].role!=="user";)o+=1;return{start:n,end:o}}function Ag(e,t){let n=e.findIndex(o=>o.id===t);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(e[o].role==="user")return e[o].id;return null}function Cv(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return Ag(e,n.id)?n.id:null}return null}function Mg(e){return e.role!=="user"||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content=="string"&&e.content.length>0}var fo=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function lk(e){return e instanceof fo}function Ga(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Ts=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(l=>l.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Ga(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Si=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"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(t,"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(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};var Ya=class{constructor(){this.cancelled=!1}start(t){this.turnId=t,this.cancelled=!1}cancel(){this.cancelled=!0}accepts(t){return!this.cancelled&&(!t||!this.turnId||t===this.turnId)}};var{setLoader:BW,load:ck}=ft({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var Eg=ck;function Tg(e){if(!e)return"";let t=dk(e);return wv(t!==null?t:e)}function dk(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function wv(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
15
15
  `),t=t.replace(/\n{2,}/g,`
16
- `),t.trim()}var Sv=null;var Pg=()=>Sv?Sv():Promise.resolve().then(()=>(xv(),wv));var{setLoader:UW,load:cP}=vt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var Av=cP;var dP=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function pP(e,t){return dP.some(n=>e[n]!==t[n])}var Bo=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function Lg(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(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}
16
+ `),t.trim()}var Ev=null;var kg=()=>Ev?Ev():Promise.resolve().then(()=>(Mv(),Av));var{setLoader:KW,load:gk}=ft({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var Tv=gk;var mk=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function fk(e,t){return mk.some(n=>e[n]!==t[n])}var Ho=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function Lg(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(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}
17
17
 
18
- _Details: ${n.message}_`:o}var Ig=e=>({isError:!0,content:[{type:"text",text:e}]}),uP=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Mv=e=>Ps(e)||e===dr,Za=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;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.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Pi(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(Ps(n.name)||n.name===dr&&$r(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.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?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new ki(t,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&Eg().catch(()=>{})}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Pg().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return yv(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}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 t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=Ws.isSupported()?new Ws({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return Pg().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new d(p,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):p});if(a&&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(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");let o=++this.voiceSetupGeneration;this.voiceSetupPromise=Eg().then(r=>{o===this.voiceSetupGeneration&&this.wireVoiceProvider(r.createVoiceProvider(n))}).catch(r=>{console.error("Failed to setup voice:",r)}).finally(()=>{o===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(t){try{this.voiceProvider=t;let o=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(r=>{r.provider!=="runtype"&&r.text&&r.text.trim()&&this.sendMessage(r.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((r,s,a)=>{if(r==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!a});else{let l=this.injectMessage({role:"user",content:s,streaming:!1,voiceProcessing:!a});this.pendingVoiceUserMessageId=l.id}if(a){this.pendingVoiceUserMessageId=null;let l=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=l.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!a,voiceProcessing:!a});else{let l=this.injectMessage({role:"assistant",content:s,streaming:!a,voiceProcessing:!a});this.pendingVoiceAssistantMessageId=l.id}a&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(r=>{this.voiceLevel=Number.isFinite(r)?Math.max(0,Math.min(1,r)):0}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(r=>{this.config.voiceRecognition?.onMetrics?.(r)}),this.voiceProvider.onError(r=>{console.error("Voice error:",r),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:o,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(r=>{this.voiceStatus=r,this.voiceActive=r==="listening",this.callbacks.onVoiceStatusChanged?.(r)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new Bo("history_unavailable","No conversation history provider is installed");return t}historyContext(t){let n=this.requireHistoryProvider(),o=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new yo("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.historyGate;t&&await t.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Bo("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.requireHistoryProvider().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.historyContext(t?.scope)})}async openConversation(t,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,a=await o.getPage(t,{context:r});if(s!==this.historyOpenEpoch)throw new Bo("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new Bo("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||t,this.activeConversationRevision=l.conversationRevision||a.conversationRevision||null,this.historyNextMessageCursor=a.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(a.messages),this.emitHistoryState(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(t,n,o){let r=this.requireHistoryProvider(),s=this.historyContext(o?.scope),a=n??this.historyNextMessageCursor;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${a}`,d=this.olderPageRequests.get(l);if(d)return d;let p=this.fetchOlderPage(r,t,a,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,p),p}async fetchOlderPage(t,n,o,r){let s=this.messages[0]?.createdAt,a=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:a.nextCursor};let l=Xa(this.messages,a.messages);this.messages=this.sortMessages(l.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=a.nextCursor;for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(t){let n=this.requireHistoryProvider(),o=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new Bo("superseded","A later action won");await this.installFreshConversation(s)}async installFreshConversation(t){this.discardConversationState(),await this.commitActivation(t),this.activeConversationId=t.conversationId||null,this.activeConversationRevision=t.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(t,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(t,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new Bo("history_unavailable","This history provider cannot update conversations");let s=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(t){let n=this.requireHistoryProvider(),o=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let t=this.requireHistoryProvider();if(!t.resetDevice)throw new Bo("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await t.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(t)}async prepareReplacementConversation(t){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:t});await this.installFreshConversation(o)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new Bo("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(t){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(t,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let a=await t.getPage(n,{context:o}),l=new Set(a.messages.map(m=>m.id)),d=this.messages.some(m=>l.has(m.id)),p=a.messages[0]?.createdAt,u;if(!d)u=a.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,y=this.messages.filter(h=>l.has(h.id)||h.id===m?!0:p!==void 0&&h.createdAt<p);u=Xa(y,a.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of a.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let n of t){let o=Qa(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Qa(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(t,n))}enqueueProjectionFinalization(t,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,n,o){if(this.activeConversationId!==t)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===t&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(t,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(t,r,!0);return}if(s instanceof $e&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(t,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof $e?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,n){let o=this.readPendingProjections();if(!o||o.conversationId!==t)return;let r=new Set(n.map(a=>a.id)),s=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of t.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof $e&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,n,o,r,s){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(a){if(!e.isConversationDeleted(a))throw a;let l=await this.recoverFromDeletedConversation(r);if(!l)throw a;this.recordDispatchedProjections([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!pP(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 ki(this.config,this.historyInternals),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:d,streaming:p=!1,voiceProcessing:u,rawContent:m}=t,h={id:a??(n==="user"?$a():n==="assistant"?Is():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:d,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:y,rawContent:h}=o,S={id:d??(r==="user"?$a():r==="assistant"?Is():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...y!==void 0&&{voiceProcessing:y},...h!==void 0&&{rawContent:h}};n.push(S)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:d}=t,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
18
+ _Details: ${n.message}_`:o}var Ig=e=>({isError:!0,content:[{type:"text",text:e}]}),hk=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Pv=e=>xs(e)||e===ir,Qa=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;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.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new Ya;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new Si(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(xs(n.name)||n.name===ir&&Br(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.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?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new xi(t,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&Eg().catch(()=>{})}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||kg().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return ab(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=Ts.isSupported()?new Ts({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return kg().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new d(p,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):p});if(a&&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(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.voiceDisconnectPromise,r=++this.voiceSetupGeneration;this.voiceSetupPromise=Eg().then(async s=>{await o,r===this.voiceSetupGeneration&&this.wireVoiceProvider(s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(t){try{this.voiceProvider=t;let n=this.voiceSetupGeneration,o=()=>this.voiceProvider===t&&n===this.voiceSetupGeneration,s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{o()&&a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,l,d,p)=>{if(o())if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:l,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=u.id}if(d){this.voiceTurns.start(p?.turnId),this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(p?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:l,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=u.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(a=>{o()&&(this.voiceLevel=Number.isFinite(a)?Math.max(0,Math.min(1,a)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{o()&&this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{o()&&(console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(a=>{o()&&(this.voiceStatus=a,this.voiceActive=a==="listening",(a==="listening"||a==="idle"||a==="disconnected")&&this.settlePendingVoiceTurn(a!=="listening"),this.callbacks.onVoiceStatusChanged?.(a))}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){let t=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let n=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(n)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new Ya,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(t){let n=t?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),t&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new Ho("history_unavailable","No conversation history provider is installed");return t}historyContext(t){let n=this.requireHistoryProvider(),o=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new fo("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.historyGate;t&&await t.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Ho("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.requireHistoryProvider().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.historyContext(t?.scope)})}async openConversation(t,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,a=await o.getPage(t,{context:r});if(s!==this.historyOpenEpoch)throw new Ho("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new Ho("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||t,this.activeConversationRevision=l.conversationRevision||a.conversationRevision||null,this.historyNextMessageCursor=a.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(a.messages),this.emitHistoryState(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(t,n,o){let r=this.requireHistoryProvider(),s=this.historyContext(o?.scope),a=n??this.historyNextMessageCursor;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${a}`,d=this.olderPageRequests.get(l);if(d)return d;let p=this.fetchOlderPage(r,t,a,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,p),p}async fetchOlderPage(t,n,o,r){let s=this.messages[0]?.createdAt,a=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:a.nextCursor};let l=Ka(this.messages,a.messages);this.messages=this.sortMessages(l.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=a.nextCursor;for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(t){let n=this.requireHistoryProvider(),o=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new Ho("superseded","A later action won");await this.installFreshConversation(s)}async installFreshConversation(t){this.discardConversationState(),await this.commitActivation(t),this.activeConversationId=t.conversationId||null,this.activeConversationRevision=t.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(t,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(t,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new Ho("history_unavailable","This history provider cannot update conversations");let s=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(t){let n=this.requireHistoryProvider(),o=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let t=this.requireHistoryProvider();if(!t.resetDevice)throw new Ho("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await t.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(t)}async prepareReplacementConversation(t){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:t});await this.installFreshConversation(o)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new Ho("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(t){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(t,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let a=await t.getPage(n,{context:o}),l=new Set(a.messages.map(m=>m.id)),d=this.messages.some(m=>l.has(m.id)),p=a.messages[0]?.createdAt,u;if(!d)u=a.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,y=this.messages.filter(h=>l.has(h.id)||h.id===m?!0:p!==void 0&&h.createdAt<p);u=Ka(y,a.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of a.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let n of t){let o=Va(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Va(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(t,n))}enqueueProjectionFinalization(t,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,n,o){if(this.activeConversationId!==t)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===t&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(t,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(t,r,!0);return}if(s instanceof Ne&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(t,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof Ne?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,n){let o=this.readPendingProjections();if(!o||o.conversationId!==t)return;let r=new Set(n.map(a=>a.id)),s=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of t.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof Ne&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,n,o,r,s){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(a){if(!e.isConversationDeleted(a))throw a;let l=await this.recoverFromDeletedConversation(r);if(!l)throw a;this.recordDispatchedProjections([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=ib(this.config,o),s=fk(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&In(o.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),a&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new xi(this.config,this.historyInternals),a&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:d,streaming:p=!1,voiceProcessing:u,rawContent:m}=t,h={id:a??(n==="user"?_a():n==="assistant"?As():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:d,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:y,rawContent:h}=o,x={id:d??(r==="user"?_a():r==="assistant"?As():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...y!==void 0&&{voiceProcessing:y},...h!==void 0&&{rawContent:h}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:d}=t,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
19
19
 
20
20
  `),a=[s,n].filter(Boolean).join(`
21
21
 
22
- `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,d=r.contentParts.length>0;if(l){let p=[];s&&p.push(ho(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(d){let p=[];a&&p.push(ho(a)),p.push(...r.contentParts),t.contentParts=p}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim(),r=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!r)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let s=$a(),a=Is();this.activeAssistantMessageId=null;let l=n?.contentParts&&Ya(n.contentParts)?Ti:"",d={id:s,role:"user",content:o||l,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},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(d),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let m=this.messages.find(y=>y.id===s)??d;if(await this.applyMentionBundle(m,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(h=>h.id===s)??d,y=mv({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});y.contentParts&&(m.contentParts=y.contentParts),y.llmContent!==void 0&&(m.llmContent=y.llmContent),(y.contentParts||y.llmContent!==void 0)&&(m.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,p,a,s,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let y=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!y){let h=Lg(m,this.config.errorMessage);if(h){let C={id:a,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(C)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,y||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(t,n){let o=fv(this.messages,t);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,a=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!a?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},u=s?this.toComposerOptionsPayload(s.options):r.composerOptions,m=s?s.contentSegments:r.contentSegments,y=s?s.options?.quote:void 0,h=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(a??"",{...l?.length?{contentParts:[...l]}:{},...m?.length?{contentSegments:[...m]}:{},...u?{composerOptions:u}:{},...y?{quote:y}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:h===!0}),!0}toComposerOptionsPayload(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=Is();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:t},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 a=Lg(r,this.config.errorMessage);if(a){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,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(t,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(t,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 t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.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(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(u=>u.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,p=d&&typeof d=="object"?d.onDecision:void 0;try{let u;if(p?u=await p({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):u=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let y=await u.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(u=>u.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let u=t.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let y=typeof m[0]?.question=="string"?m[0].question:"";y&&(a={[y]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,d=t.toolCall?.args,p=Array.isArray(d?.questions)?d.questions:[];if(p.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=a??{};p.forEach((m,y)=>{let h=typeof m?.question=="string"?m.question:"";if(!h)return;let C=u[h],S=Array.isArray(C)?C.join(", "):typeof C=="string"?C:"";this.appendMessage({id:`ask-user-q-${l}-${y}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${y}`,role:"user",content:S||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});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(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==dr?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let s=async d=>{let p=d.toolCall?.name,u=d.toolCall?.id;if(!p||!u)return null;let m=`${t}:${u}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(m),o.push(m);let y=this.markWebMcpToolRunning(d),h=d.agentMetadata?.webMcpToolCallId??p;if(p===dr)return{dedupeKey:m,resumeKey:h,output:Fb(),toolMessage:d,startedAt:y,completedAt:Date.now()};let C=this.client.executeWebMcpToolCall(p,d.toolCall?.args,r.signal),S;if(!C)S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{S=await C}catch(x){let P=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));return P||this.callbacks.onError?.(x instanceof Error?x:new Error(String(x))),this.markWebMcpToolComplete(d,Ig(P?"Aborted by cancel()":uP(x)),y),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,Ig("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:h,output:S,toolMessage:d,startedAt:y,completedAt:Date.now()}},a;if(this.config.webmcp?.execution==="sequential"){a=[];for(let d of n)a.push(await s(d))}else a=await Promise.all(n.map(s));let l=[];try{if(l=a.filter(u=>u!==null),l.length===0)return;let d={};for(let u of l)d[u.resumeKey]=u.output;let p=await this.client.resumeFlow(t,d,{signal:r.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!p.ok){let u=await p.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${p.status}`)}for(let u of l)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt,u.toolMessage.toolCall?.name===dr?{suggestRepliesResolved:!0}:void 0);p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,Ig("Aborted by cancel()"),u.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let a=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a);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(a)}catch(l){this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{this.webMcpInflightKeys.delete(a)}return}let s=`${n}:${r}`;if(!(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t)))return this.resolveWebMcpToolCallBatch(n,[t])}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.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 t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"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(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=cr(this.config.features?.artifacts,t),r=Fa(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.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 t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=cr(this.config.features?.artifacts,n),s=Fa(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",t=!0)}t&&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(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,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(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.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(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Av().then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>Lg(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Is(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];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 t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){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(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.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=Tg(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ja(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Tg(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),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 a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let u=r.approval,m=n.approval;a.approval={...u,...m,executionId:m.executionId||u.executionId,toolName:m.toolName||u.toolName,description:m.description||u.description,toolType:m.toolType??u.toolType,reason:m.reason??u.reason,parameters:m.parameters??u.parameters}}let l=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(l&&Mv(l)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let u=`${d}:${p}`,m=this.webMcpInflightKeys.has(u),y=this.webMcpResolvedKeys.has(u),h=r.toolCall?.name,C=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&h!==void 0&&Mv(h)&&r.toolCall?.status==="complete";(m||y||C)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,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 a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};import{File as gP,FileCode as mP,FileSpreadsheet as fP,FileText as Rg,X as hP}from"lucide";var yP={add:e=>Zb(e)},bP=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,ad={allowedTypes:pr,maxFileSize:10*1024*1024,maxFiles:4};function vP(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function CP(e){return e==="application/pdf"?Rg:e.startsWith("text/")?Rg:e.includes("word")?Rg:e.includes("excel")||e.includes("spreadsheet")?fP:e==="application/json"?mP:gP}var Ii=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??ad.allowedTypes,maxFileSize:t.maxFileSize??ad.maxFileSize,maxFiles:t.maxFiles??ad.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:yP}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ad.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.destroyed)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=ev(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let a=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,a);continue}let s={id:vP(),file:o,previewUrl:nd(o)?URL.createObjectURL(o):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(s),this.renderPreview(s),n.push(s)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(n.map(o=>this.runAdd(o)))}async runAdd(t){let n=new AbortController;this.pendingAdds.set(t.id,n);let o=()=>this.destroyed||n.signal.aborted||this.pendingAdds.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.adapter().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=bP(s),this.updatePreview(t),this.notify())}});if(o())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(o())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(t.id)===n&&this.pendingAdds.delete(t.id)}this.updatePreview(t),this.notify()}retryAttachment(t){let n=this.attachments.find(o=>o.id===t);!n||n.status!=="error"||this.destroyed||(n.status=this.hasCustomAdapter()?"uploading":"processing",n.progress=this.hasCustomAdapter()?0:void 0,n.error=void 0,this.updatePreview(n),this.notify(),this.runAdd(n))}abortAdd(t){let n=this.pendingAdds.get(t);n&&(this.pendingAdds.delete(t),n.abort())}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];this.abortAdd(t),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.releasePart(o.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(t){let n=this.config.adapter?.remove;if(n)try{let o=n(t,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let t of this.attachments)this.abortAdd(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let t of this.pendingAdds.values())t.abort();this.pendingAdds.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=nd(t.file),o=M("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let u=M("img");u.src=t.previewUrl,u.alt=t.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=M("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=CP(t.file.type),y=Wt(m,20,"var(--persona-muted, #6b7280)",1.5);y&&u.appendChild(y);let h=M("span");h.textContent=tv(t.file.type,t.file.name),h.style.fontSize="8px",h.style.fontWeight="600",h.style.color="var(--persona-muted, #6b7280)",h.style.textTransform="uppercase",h.style.lineHeight="1",u.appendChild(h),o.appendChild(u)}let r=Q("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=M("div","persona-attachment-progress");s.appendChild(M("div","persona-attachment-progress__bar"));let a=Q("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=pe("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?a.appendChild(l):a.textContent="\u21BB",a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,a),o.appendChild(r);let d=M("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let p=Wt(hP,10,"var(--persona-text-inverse, #ffffff)",2);p?d.appendChild(p):(d.textContent="\xD7",d.style.color="var(--persona-text-inverse, #ffffff)",d.style.fontSize="14px",d.style.lineHeight="1"),d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(d),this.previewsContainer.appendChild(o),this.applyPreviewState(o,t)}updatePreview(t){let n=this.previewsContainer?.querySelector(`[data-attachment-id="${t.id}"]`);n&&this.applyPreviewState(n,t)}applyPreviewState(t,n){t.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";t.setAttribute("aria-busy",o?"true":"false"),t.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n,adapter:t?.adapter})}};var Ev=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),wP=(e,t)=>e.length===t.length&&e.every((n,o)=>{let r=t[o];return n.id===r.id&&n.name===r.name&&n.mimeType===r.mimeType&&n.size===r.size&&n.status===r.status&&n.progress===r.progress&&n.error===r.error});function Tv(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,n=null,o=!1,r=!1,s=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",a=()=>{let u=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:u,inputDisabled:e.inputDisabled,sendDisabled:u!=="idle"||e.sendDisabled||e.inputDisabled})},l=()=>(n||(n=a()),n),d=()=>{if(o=!1,r||t.size===0)return;let u=l();for(let m of[...t])try{m(u)}catch(y){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",y)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(d))};return{getState:l,subscribe:u=>(t.add(u),()=>t.delete(u)),setText:u=>{e.text!==u&&(e.text=u,p())},setAttachments:u=>{wP(e.attachments,u)||(e.attachments=[...u],p())},setMentionRefs:u=>{Ev(e.mentionRefs,u)||(e.mentionRefs=[...u],p())},setSelectedModelId:u=>{e.selectedModelId!==u&&(e.selectedModelId=u,p())},setActiveModeIds:u=>{Ev(e.activeModeIds,u)||(e.activeModeIds=[...u],p())},setQuote:u=>{let m=e.quote;m?.text===u?.text&&m?.messageId===u?.messageId&&m?.sourceLabel===u?.sourceLabel||(e.quote=u?{...u}:void 0,p())},setPendingSubmission:u=>{e.pendingSubmission!==u&&(e.pendingSubmission=u,p())},setPreparing:u=>{e.preparing!==u&&(e.preparing=u,p())},setStreaming:u=>{e.streaming!==u&&(e.streaming=u,p())},setInputDisabled:u=>{e.inputDisabled!==u&&(e.inputDisabled=u,p())},setSendDisabled:u=>{e.sendDisabled!==u&&(e.sendDisabled=u,p())},flush:()=>{o&&d()},destroy:()=>{r=!0,o=!1,t.clear()}}}var kn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},kv=(e,t)=>{let n=M("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function Pv(e,t={}){let n=kn(e,"[data-persona-composer-form]"),o=kn(e,"[data-persona-composer-input]");if(!n||!o){let P=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||o))throw new Error(P);return typeof console<"u"&&console.warn(P),null}let r={header:kn(e,"[data-persona-composer-header]"),body:kn(e,"[data-persona-composer-body]"),actionsStart:kn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:kn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:kn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:kn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:kn(e,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=kv("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(a,n):e.appendChild(a));let l=r.body??o.parentElement??n,d=(x,P,O,$,T)=>{if(P)return P;s.add(x);let R=kv(O,$);return T.appendChild(R),R},p=d("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=d("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),y=d("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[],C=(x,P)=>x.target===P.target&&x.type===P.type&&x.handler===P.handler,S=kn(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:a,body:l,actionsStart:p,actionsEnd:u,suggestions:m,status:y,attachmentInput:S,attachmentPreviews:kn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:kn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:kn(e,"[data-persona-composer-submit]")??void 0,micButton:kn(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(x,P,O,$)=>{x.addEventListener(P,O,$),h.push({target:x,type:P,handler:O,options:$})},removeListener:(x,P,O,$)=>{x.removeEventListener(P,O,$),h=h.filter(T=>!C(T,{target:x,type:P,handler:O}))},destroy:()=>{for(let x of h)x.target.removeEventListener(x.type,x.handler,x.options);h=[]}}}var $t={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},sn=1e5,Ri=sn+1;var xP=8,SP=8,Hg=10,Lv=200,Iv=300,Rv=0,cd=e=>Math.max(0,e);function Hv(e){e.delayMs!==void 0&&(Lv=cd(e.delayMs)),e.skipDelayMs!==void 0&&(Iv=cd(e.skipDelayMs))}var AP=()=>Date.now()<Rv,MP=e=>{Rv=e>0?Date.now()+e:0},ld=new WeakMap,Og="data-persona-tooltip-suppressed",EP=e=>typeof e.closest=="function"&&e.closest(`[${Og}]`)!==null;function Wv(e){ld.get(e)?.hide()}var Ov=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,TP=e=>{let t=e.getRootNode?.();return Ov(t)?t:e.ownerDocument.body},Wg=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),kP=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function tn(e){ld.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:a=xP,viewportPadding:l=SP}=e,d=()=>t.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,y=null,h=null,C,S=!1,x=!1,P=!1,O=()=>(typeof o=="function"?o():o).trim(),$=()=>(typeof r=="function"?r():r??"").trim(),T=()=>cd(e.delayMs??Lv),R=()=>cd(e.skipDelayMs??Iv),A=()=>{C!==void 0&&(p().clearTimeout(C),C=void 0)},N=()=>{A();let me=u!==null;h?.(),h=null,u?.remove(),u=null,m=null,y=null,me&&MP(R())},G=()=>{if(!u)return;let me=d(),Re=p(),He=t.getBoundingClientRect(),ve=u.getBoundingClientRect(),Ge=me.documentElement.clientWidth||Re.innerWidth,be=me.documentElement.clientHeight||Re.innerHeight,j=Ge-l-ve.width,_e=He.left+He.width/2-ve.width/2,Fe=Wg(_e,l,j),mt=He.top-l,Ce=be-l-He.bottom,Ee=ve.height+a,he=mt>=Ee||mt>=Ce?"top":"bottom",Pe=he==="top"?He.top-a-ve.height:He.bottom+a,At=be-l-ve.height,Yt=Wg(Pe,l,At),ft=He.left+He.width/2,pn=Math.max(Hg,ve.width-Hg),zn=Wg(ft-Fe,Hg,pn);u.dataset.placement=he,u.style.left=`${Fe}px`,u.style.top=`${Yt}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${zn}px`)},ae=()=>{if(P||!s||u||!t.isConnected||EP(t))return;let me=O(),Re=TP(t);if(!me||!Re)return;let He=d(),ve=p();u=He.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Ri);let Ge=ve.getComputedStyle?.(t);if(Ge){for(let Ee of kP){let he=Ge.getPropertyValue(Ee).trim();he&&u.style.setProperty(Ee,he)}Ge.fontFamily&&(u.style.fontFamily=Ge.fontFamily)}m=He.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=me,u.appendChild(m);let be=$();be&&(y=He.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=be,u.appendChild(y));let j=He.createElement("span");j.className="persona-control-tooltip__arrow",u.appendChild(j),Re.appendChild(u),G(),u.dataset.state="open";let _e=()=>{if(!t.isConnected){N();return}m&&(m.textContent=O()),y&&(y.textContent=$()),G()};ve.addEventListener("scroll",_e,!0),ve.addEventListener("resize",_e);let Fe=t.getRootNode(),mt=Ov(Fe)?Fe:He.documentElement,Ce=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||N()});Ce?.observe(mt,{childList:!0,subtree:!0}),h=()=>{ve.removeEventListener("scroll",_e,!0),ve.removeEventListener("resize",_e),Ce?.disconnect()}},Y=me=>{if(!(P||u)){if(A(),me||T()<=0||AP()){ae();return}C=p().setTimeout(()=>{C=void 0,ae()},T())}},E=()=>{S||x?Y(x):N()},B=()=>{let me=p();(!me.matchMedia||!me.matchMedia("(hover: none)").matches)&&(S=!0,E())},H=()=>{S=!1,E()},L=()=>{try{x=t.matches(":focus-visible")}catch{x=!0}E()},ee=()=>{x=!1,E()},K=()=>{S=!1,x=!1,N()},ue=me=>{me.key==="Escape"&&K()};n.addEventListener("mouseenter",B),n.addEventListener("mouseleave",H),t.addEventListener("focus",L),t.addEventListener("blur",ee),t.addEventListener("keydown",ue),t.addEventListener("click",K);let le={get isOpen(){return u!==null},show:ae,hide:N,reposition:G,destroy:()=>{P||(P=!0,N(),n.removeEventListener("mouseenter",B),n.removeEventListener("mouseleave",H),t.removeEventListener("focus",L),t.removeEventListener("blur",ee),t.removeEventListener("keydown",ue),t.removeEventListener("click",K),ld.delete(t))}};return ld.set(t,le),le}var Bv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Hi(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Bv(s)&&Bv(r)?n[o]=Hi(s,r):n[o]=r}return n}var oo="min(440px, calc(100vw - 24px))",Bg="440px",_g="How can I help...",PP={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:oo,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",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",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)"},at={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",tooltip:{delayMs:200,skipDelayMs:300},launcher:PP,copy:{inputPlaceholder:_g,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",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",borderWidth:"0px",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"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},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 _v(e,t){if(!(!e&&!t))return e?t?Hi(e,t):e:t}function nl(e){return e?{...at,...e,theme:_v(at.theme,e.theme),darkTheme:_v(at.darkTheme,e.darkTheme),launcher:{...at.launcher,...e.launcher,dock:{...at.launcher?.dock,...e.launcher?.dock},clearChat:{...at.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...at.tooltip,...e.tooltip},copy:{...at.copy,...e.copy},sendButton:{...at.sendButton,...e.sendButton},statusIndicator:{...at.statusIndicator,...e.statusIndicator},voiceRecognition:{...at.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=at.features?.artifacts,n=e.features?.artifacts,o=at.features?.scrollToBottom,r=e.features?.scrollToBottom,s=at.features?.scrollBehavior,a=e.features?.scrollBehavior,l=at.features?.streamAnimation,d=e.features?.streamAnimation,p=at.features?.askUserQuestion,u=e.features?.askUserQuestion,m=at.features?.history,y=e.features?.history,h=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},C=o===void 0&&r===void 0?void 0:{...o,...r},S=s===void 0&&a===void 0?void 0:{...s,...a},x=l===void 0&&d===void 0?void 0:{...l,...d},P=p===void 0&&u===void 0?void 0:{...p,...u,styles:{...p?.styles,...u?.styles}},O=m===void 0&&y===void 0?void 0:{...m,...y,copy:{...m?.copy,...y?.copy}};return{...at.features,...e.features,...C!==void 0?{scrollToBottom:C}:{},...S!==void 0?{scrollBehavior:S}:{},...h!==void 0?{artifacts:h}:{},...x!==void 0?{streamAnimation:x}:{},...P!==void 0?{askUserQuestion:P}:{},...O!==void 0?{history:O}:{}}})(),suggestionChips:e.suggestionChips??at.suggestionChips,suggestionChipsConfig:{...at.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...at.layout,...e.layout,header:{...at.layout?.header,...e.layout?.header},messages:{...at.layout?.messages,...e.layout?.messages,avatar:{...at.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...at.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...at.layout?.slots,...e.layout?.slots}},markdown:{...at.markdown,...e.markdown,options:{...at.markdown?.options,...e.markdown?.options}},messageActions:{...at.messageActions,...e.messageActions}}:at}function Dg(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function dd(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function Dv(e,t){e.style.maxHeight=`${t*Dg(e)}px`,e.style.overflowY="auto"}function ol(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function Nv(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Fv(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,o=t.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!Nv(t)}function LP(e){return(e.submitKey??"enter")!=="enter"||Nv(e)?"enter":"send"}function pd(e,t){e.setAttribute("enterkeyhint",LP(t))}function ud(e,t){let n=t?.autocomplete;e.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?e.removeAttribute(r):e.setAttribute(r,s)};o("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),o("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),o("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),o("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function Ng(e){return e===!0?{disabled:!0}:!e||typeof e!="object"?{disabled:!1}:{disabled:!0,reason:typeof e.reason=="string"&&e.reason?e.reason:void 0}}var $n="persona-composer-control",bo="persona-composer-control--glyph",$g=40,fn=24,gd=(e,t,n)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(e);for(let s of n){let a=r.getPropertyValue(s).trim();a?t.style.setProperty(s,a):t.style.removeProperty(s)}},md=(e,t)=>{let n=M("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??_g,n.dir="auto",pd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:ol(n)}),ud(n,e?.composer?.inputAttributes),n.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",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=dd(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let s=()=>{let l=n.style.maxHeight;if(l!==r){let p=parseFloat(l);if(Number.isFinite(p)&&p>0)return p}let d=o*Dg(n);return r=`${d}px`,n.style.maxHeight=r,d},a=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,s());n.style.height=`${l}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:a}},RP="[data-persona-glyph-stack]",Ug=(e,t,n="send")=>{let o=Q("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),o.append(e,t),o},fd=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",d=e?.copy?.sendButtonLabel??"Send",p=e?.copy?.stopButtonLabel??"Stop",u=t.showTooltip??!1,m=t.size,y=parseFloat(m??"")||$g,h=t.backgroundColor,C=t.textColor,S=M("div","persona-send-button-wrapper"),x=Q("button",{className:mn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${$n}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!C&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?C||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":C||void 0,backgroundColor:n&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),P=null,O=null,$=null;if(n){let A=parseFloat(t.iconSize??"")||Math.round(y*.5),N=t.iconStrokeWidth??2,G=C?.trim()||"currentColor";r&&(P=pe(r,A,G,N)),O=pe(s,A,G,N),P&&O?($=Ug(P,O),x.appendChild($)):P?x.appendChild(P):(x.textContent=o,O=null)}else x.textContent=d;x.setAttribute("aria-label",a),S.appendChild(x),tn({anchor:x,trigger:S,text:()=>x.getAttribute("aria-label")??"",enabled:u});let T="send";return{button:x,wrapper:S,setMode:A=>{if(A===T)return;T=A;let N=A==="stop"?l:a;x.setAttribute("aria-label",N),x.setAttribute("data-persona-send-mode",A),n?(x.querySelector(RP)??$)?.setAttribute("data-mode",A):x.textContent=A==="stop"?p:d},glyphStack:$}},Wi=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",s=t.provider?.type==="custom";if(!(o||r||s))return null;let l=t.iconName??"mic",d=t.iconSize,p=parseFloat(d??"")||fn,u=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,y=M("div","persona-send-button-wrapper"),h=Q("button",{className:mn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",$n,!d&&bo),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),S=pe(l,p,m||"currentColor",1.5);S?h.appendChild(S):h.textContent="\u{1F3A4}",y.appendChild(h);let x=t.tooltipText??"Start voice recognition",P=t.showTooltip??!1;return tn({anchor:h,trigger:y,text:()=>h.getAttribute("aria-label")??x,enabled:P}),{button:h,wrapper:y}},hd=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=M("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=M("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??pr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=M("div","persona-send-button-wrapper"),a=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${$n} ${bo}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=pe(r,fn,"currentColor",1.5);l?a.appendChild(l):a.textContent="\u{1F4CE}",a.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(a);let d=t.buttonTooltipText??"Attach file";return tn({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},yd=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=M("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=M("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},bd=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function HP(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function vd(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:d=2147483e3,onOpen:p,onDismiss:u}=e,m=e.container??HP(t),y=!1,h=null,C=()=>{if(!y)return;let P=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${P.width}px`),a&&(n.style.maxWidth=`${P.width}px`);let O=n.getBoundingClientRect(),$=l?.()??null,T=$!=null?P.top+$:P.top,R=o==="top-start"||o==="top-end"?T-r-O.height:P.bottom+r,N=o==="bottom-end"||o==="top-end"?P.right-O.width:P.left,G=a?.()??null;if(G!=null){let ae=Math.max(P.left,P.right-O.width);N=Math.min(Math.max(P.left+G,P.left),ae)}n.style.top=`${R}px`,n.style.left=`${N}px`},S=()=>{y&&(y=!1,h&&(h(),h=null),n.remove())},x=()=>{if(y)return;y=!0,d!=null&&(n.style.zIndex=String(d)),m.appendChild(n),C();let P=(t.ownerDocument??document).defaultView??window,O=t.ownerDocument??document,$=()=>{if(!t.isConnected){S(),u?.("anchor-removed");return}C()},T=A=>{let N=typeof A.composedPath=="function"?A.composedPath():[];N.includes(n)||N.includes(t)||(S(),u?.("outside"))},R=P.setTimeout(()=>{O.addEventListener("pointerdown",T,!0)},0);P.addEventListener("scroll",$,!0),P.addEventListener("resize",$),h=()=>{P.clearTimeout(R),O.removeEventListener("pointerdown",T,!0),P.removeEventListener("scroll",$,!0),P.removeEventListener("resize",$)},p?.()};return{get isOpen(){return y},open:x,close:S,toggle:()=>y?S():x(),reposition:C,destroy:S}}var WP='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',OP=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],jg="data-persona-menu-focus",BP=new Set(["ArrowDown","ArrowUp","Home","End"]);function $v(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(WP)??e}var _P=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function Uv(e){let t=e.label,n=!1,o=M("div","persona-send-button-wrapper"),r=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${$n} ${bo}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=Q("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let L=e.getButtonSize?.()??"";r.style.width=L,r.style.height=L,r.style.minWidth=L,r.style.minHeight=L,r.style.lineHeight="1",r.replaceChildren();let ee=pe("plus",fn,"currentColor",1.5);ee?r.appendChild(ee):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),a();let d=[],p=-1,u=!1,m=()=>{let ee=s.getRootNode().activeElement;return ee instanceof HTMLElement?ee:null},y=()=>{let L=m();for(let ee of d){let K=!!L&&$v(ee)===L;ee.toggleAttribute(jg,K&&u)}},h=()=>d.filter(L=>L.isConnected||s.contains(L)).map($v).filter(L=>!_P(L)),C=(L,ee)=>{L.forEach((K,ue)=>{K.setAttribute("tabindex",ue===ee?"0":"-1")})},S=L=>{let ee=h();if(ee.length===0)return;let K=(L%ee.length+ee.length)%ee.length;p=K,C(ee,K),ee[K].focus(),y()},x=()=>o.ownerDocument??document,P=null,O=null,$=null,T=()=>{P&&(x().removeEventListener("focusin",P,!0),P=null)},R=()=>{O&&(s.removeEventListener("focusin",O),O=null),$&&(s.removeEventListener("pointerdown",$,!0),$=null)},A=null,N=()=>(A||(A=vd({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),T()}})),A),G=()=>A?.isOpen===!0,ae=(L=!1)=>{if(G()){A?.close(),r.setAttribute("aria-expanded","false"),T(),R(),p=-1,u=!1;for(let ee of d)ee.removeAttribute(jg);L&&r.focus()}},Y=(L=0,ee=!1)=>{if(n||G())return;u=ee,gd(r,s,OP),N().open(),r.setAttribute("aria-expanded","true");let K=h();C(K,-1),S(L<0?K.length-1:L),P=ue=>{let le=typeof ue.composedPath=="function"?ue.composedPath():[];le.includes(s)||le.includes(o)||ae()},x().addEventListener("focusin",P,!0),O=()=>y(),s.addEventListener("focusin",O),$=()=>{u=!1},s.addEventListener("pointerdown",$,!0)},E=L=>{L.preventDefault(),L.stopPropagation(),G()?ae(!0):Y(0)},B=L=>{if(L.key==="ArrowDown"||L.key==="Enter"||L.key===" "){L.preventDefault(),u=!0,G()?S(0):Y(0,!0);return}L.key==="ArrowUp"&&(L.preventDefault(),u=!0,G()?S(-1):Y(-1,!0))},H=L=>{switch(BP.has(L.key)&&(u=!0),L.key){case"ArrowDown":L.preventDefault(),S(p+1);return;case"ArrowUp":L.preventDefault(),S(p-1);return;case"Home":L.preventDefault(),S(0);return;case"End":L.preventDefault(),S(h().length-1);return;case"Escape":L.preventDefault(),L.stopPropagation(),ae(!0);return;case"Tab":ae(!0);return;default:}};return r.addEventListener("click",E),r.addEventListener("keydown",B),s.addEventListener("keydown",H),{trigger:o,triggerButton:r,panel:s,setItems:L=>{for(let K of d)L.includes(K)||K.removeAttribute(jg);if(d=[...L],!G())return;let ee=h();C(ee,Math.min(p,ee.length-1)),y()},isOpen:G,open:()=>Y(0),close:ae,setLabel:L=>{L!==t&&(t=L,l())},applyButtonSize:a,destroy:()=>{n=!0,T(),R(),r.removeEventListener("click",E),r.removeEventListener("keydown",B),s.removeEventListener("keydown",H),A?.destroy(),A=null,o.remove(),s.remove(),d=[]}}}var _o={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},jv="data-persona-composer-action",qg="data-persona-composer-disable-when-streaming",DP="core:overflow",NP=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function FP(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let o=M("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function zg(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let o=n.getComputedStyle(e),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,t-r)}var qv=(e,t)=>{!e||typeof console>"u"||console.warn(t)},$P=(e,t)=>t.includes(":")?t:`${e}:${t}`;function UP(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){qv(t,`[Persona] composer action "${l.id}" is already contributed by ${zv(d)}; the ${zv(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of e.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let a=(l,d,p)=>{let u=p?$P(p,l.id):l.id,m=l.order??_o.custom;l.placement==="end"&&m>=_o.send&&(qv(t,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${_o.send-1}.`),m=_o.send-1),s({id:u,placement:l.placement,presentation:l.presentation??"bar",order:m,sequence:r++,source:d,pluginId:p,action:l})};for(let l of e.configActions??[])a(l,"config");for(let l of e.plugins){if(!l.contributeComposerActions)continue;let d;try{d=l.contributeComposerActions(e.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of d??[])a(p,"plugin",l.id)}return n.sort((l,d)=>l.order===d.order?l.sequence-d.sequence:l.order-d.order)}var zv=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",Vv=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,jP=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function qP(e,t){if(!e||e==="always")return!0;let n=jP(t);return e==="when-text"?n:!n}var Ur=e=>e.kind==="custom",Vg=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,zP=e=>{let t=Vg(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},VP='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function KP(e){let t="",n=o=>{if(o.nodeType===Node.TEXT_NODE){t+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(VP)||o.childNodes.forEach(n)};return n(e),t.trim()}var GP=e=>KP(e).length===0;function Kv(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(E,B)=>{let H=E.button;if(!H)return;H.setAttribute("role","menuitem"),H.setAttribute("tabindex","-1"),H.className="persona-composer-overflow-menu__item";for(let K of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])H.style[K]="";H.style.lineHeight="1",B.tooltipText?H.setAttribute("title",B.tooltipText):H.removeAttribute("title"),H.replaceChildren();let L=M("span","persona-composer-overflow-menu__icon");if(B.iconName){let K=pe(B.iconName,16,"currentColor",1.5);K&&L.appendChild(K)}let ee=M("span","persona-composer-overflow-menu__label");ee.textContent=B.shortLabel??B.label,H.append(L,ee)},a=(E,B)=>{let H=E.button;if(!H)return;if(H.setAttribute("aria-label",B.label),B.pressed===void 0?H.removeAttribute("aria-pressed"):H.setAttribute("aria-pressed",B.pressed?"true":"false"),H.toggleAttribute(qg,B.disableWhenStreaming===!0),E.mode==="menu"){E.tooltip?.destroy(),E.tooltip=void 0,s(E,B);return}H.removeAttribute("role"),H.removeAttribute("tabindex"),H.removeAttribute("title");let L=r(),ee=!!B.shortLabel;if(H.className=mn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",$n,bo,ee&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),H.style.width=L&&!ee?L:"",H.style.height=L??"",H.style.minWidth=L&&!ee?L:"",H.style.minHeight=L??"",H.style.fontSize=ee?"":"18px",H.style.lineHeight="1",H.style.color=B.iconColor??"",H.style.backgroundColor=B.backgroundColor??"",H.replaceChildren(),B.iconName){let K=pe(B.iconName,fn,"currentColor",1.5);K&&H.appendChild(K)}if(ee){let K=M("span","persona-composer-action-button__label");K.textContent=B.shortLabel,H.appendChild(K)}else H.firstChild||(H.textContent=B.label);E.tooltip?.destroy(),E.tooltip=tn({anchor:H,trigger:E.element,text:()=>B.tooltipText??B.label,enabled:!!B.tooltipText})},l=(E,B)=>{let H=E.action,L=Q("button",{attrs:{type:"button"}}),ee=L;if(B==="bar"){let le=M("div","persona-send-button-wrapper");le.appendChild(L),ee=le}ee.setAttribute(jv,E.id);let K={resolved:E,element:ee,button:L,owned:!0,managed:!0,busy:!1,visible:!0,mode:B},ue=le=>{if(le.preventDefault(),le.stopPropagation(),K.busy||L.disabled)return;let me=K.resolved.action;K.mode==="menu"&&h?.close(!0);let Re;try{Re=me.onSelect(e.actionContext,le)}catch(He){e.reportError(He,{actionId:K.resolved.id});return}!Re||typeof Re.then!="function"||(K.busy=!0,L.setAttribute("aria-busy","true"),Re.catch(He=>{e.reportError(He,{actionId:K.resolved.id})}).finally(()=>{K.busy=!1,L.removeAttribute("aria-busy")}))};return L.addEventListener("click",ue),K.detach=()=>L.removeEventListener("click",ue),a(K,H),K},d=E=>{let B=E.action,H;try{H=B.render({...e.actionContext,id:E.id,action:B})}catch(L){return e.reportError(L,{actionId:E.id}),null}return H?.element?(H.element.setAttribute(jv,E.id),H.element.toggleAttribute(qg,B.disableWhenStreaming===!0),{resolved:E,element:H.element,owned:!0,managed:!0,destroy:H.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(E,B)=>{if(E.builtIn){let L=E.builtIn.element;return L?{resolved:E,element:L,owned:!1,managed:E.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let H=E.action;return H?Ur(H)?d(E):l(E,B):null},u=E=>{if(E.detach?.(),E.tooltip?.destroy(),E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0,E.owned){try{E.destroy?.()}catch(B){e.reportError(B,{actionId:E.resolved.id})}E.element.remove()}},m=(E,B)=>{for(let H=0;H<B.length;H++){let L=B[H];if(!L.managed)continue;let ee=null;for(let K=H+1;K<B.length;K++){let ue=B[K];if(!ue.managed&&ue.element.parentElement===E){ee=ue.element;break}}ee?(L.element.parentElement!==E||L.element.nextSibling!==ee)&&E.insertBefore(L.element,ee):E.lastChild!==L.element&&E.appendChild(L.element)}},y=(E,B)=>{if(E.button){E.button.disabled=B;return}if(!E.owned)return;let H=E.element;H.toggleAttribute("data-disabled",B),H.setAttribute("aria-disabled",B?"true":"false");let L=H instanceof HTMLButtonElement||H instanceof HTMLSelectElement||H instanceof HTMLInputElement||H instanceof HTMLTextAreaElement?H:H.querySelector("button, select, input, textarea");L&&(L.disabled=B)},h=null,C=null,S=null,x=0,P=()=>{let E=e.getOverflow?.();return E?.enabled===!0?E:void 0},O=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=Uv({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),$=E=>{C!==E&&(S?.disconnect(),C=E,x=zg(E),!(typeof ResizeObserver>"u")&&(S=new ResizeObserver(B=>{let L=B[B.length-1]?.contentRect?.width??zg(E);L!==x&&(x=L,ae())}),S.observe(E)))},T=(E,B)=>{let H=FP(E.collapseAutoActionsBelow,B);if(H===null)return!1;let L=x||zg(B);return L>0&&L<H},R=(E,B,H)=>{if(!B)return"bar";if(E.resolved.builtIn){let ee=NP(E.resolved.id);return ee&&B.includeBuiltIns?.includes(ee)?"menu":"bar"}let L=E.resolved.presentation;return L==="overflow"||L==="auto"&&H?"menu":"bar"},A=E=>{let B=E.menuSlot;if(!B)return;if(!GP(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let H=zP(E.element);if(!H){E.menuLabel?.remove(),E.menuLabel=void 0;return}E.menuLabel||(E.menuLabel=M("span","persona-composer-overflow-menu__label")),E.menuLabel.textContent!==H&&(E.menuLabel.textContent=H),E.menuLabel.parentElement!==B&&B.appendChild(E.menuLabel)},N=(E,B)=>{if(E.mode===B)return E;let H=E.resolved.action;if(H&&!Ur(H)){u(E),t.delete(E.resolved.id);let L=l(E.resolved,B);return t.set(E.resolved.id,L),L}if(B==="menu"){let L=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Og]:""}});L.appendChild(E.element),Wv(Vg(E.element)),E.menuSlot=L;let ee=K=>{let ue=Vg(E.element);if(ue.disabled)return;let le=K.target===ue||ue.contains(K.target);h?.close(!0),le||ue.click()};L.addEventListener("click",ee,!0),E.detachMenuSlot=()=>L.removeEventListener("click",ee,!0),E.managed=!0,A(E)}else E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0;return E.mode=B,E},G=(E,B)=>{let H=B.map(L=>L.menuSlot??L.element);for(H.forEach((L,ee)=>{let K=E.children[ee];K!==L&&(K?E.insertBefore(L,K):E.appendChild(L))});E.children.length>H.length;)E.lastElementChild?.remove()},ae=()=>{if(o)return;let E=e.getBindings();if(!E)return;let B=e.getState(),H=B.phase==="streaming",L=P();L&&$(E.footer);let ee=L?T(L,E.footer):!1,K={start:[],end:[]},ue=[];for(let le of n){let me=t.get(le.id);if(!me)continue;let Re=le.action,He=Re?Vv(Re.visible,B,!0)&&qP(Re.visibility,B):!0;if(me.visible!==He&&(me.visible=He,!He&&me.managed&&(me.menuSlot??me.element).remove()),!!He){if(me=N(me,R(me,L,ee)),Re){let ve=Vv(Re.disabled,B,!1)||Re.disableWhenStreaming===!0&&H;y(me,ve),!Ur(Re)&&Re.pressed!==void 0&&me.button?.setAttribute("aria-pressed",Re.pressed?"true":"false")}me.mode==="menu"?(A(me),ue.push(me)):K[le.placement].push(me)}}if(ue.length>0){let le=O();G(le.panel,ue),le.setItems(ue.map(ve=>ve.menuSlot??ve.element)),le.applyButtonSize();let me=Number.isFinite(L?.order)?L?.order:_o.overflow,Re=K.start.findIndex(ve=>ve.resolved.order>me),He={resolved:{id:DP,placement:"start",presentation:"bar",order:me,sequence:-1,source:"core"},element:le.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};K.start.splice(Re<0?K.start.length:Re,0,He)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));m(E.actionsStart,K.start),m(E.actionsEnd,K.end)};return{resolve:()=>{if(o)return;let E=UP(e.collect()),B=new Set(E.map(H=>H.id));for(let[H,L]of t)B.has(H)||(u(L),t.delete(H));for(let H of E){let L=t.get(H.id);if(!L){let le=p(H,"bar");le&&t.set(H.id,le);continue}let ee=L.resolved.action,K=H.action;if(!!ee!=!!K||ee&&K&&Ur(ee)!==Ur(K)||ee&&K&&Ur(ee)&&Ur(K)&&ee.render!==K.render){u(L),t.delete(H.id);let le=p(H,L.mode);le&&t.set(H.id,le);continue}L.resolved=H,H.builtIn?(L.managed=H.builtIn.managed===!0||L.mode==="menu",H.builtIn.element&&L.mode==="bar"&&(L.element=H.builtIn.element)):K&&!Ur(K)?a(L,K):K&&L.element.toggleAttribute(qg,K.disableWhenStreaming===!0)}n=E,ae()},sync:ae,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,S?.disconnect(),S=null,C=null;for(let E of t.values())u(E);t.clear(),h?.destroy(),h=null,n=[]}}}}var YP="core:model",QP=700,Gv=16,XP=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],Yv=()=>{let e=Q("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Q("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function Qv(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=d=>{let p=e.getSelectedModelId();return d.find(u=>u.id===p)??d[0]},s=()=>{let d=Q("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),p="",u=()=>{let S=e.getModels(),x=S.map(P=>`${P.id}:${P.label}`).join("|");x!==p&&(p=x,d.replaceChildren(...S.map(P=>{let O=Q("option",{attrs:{value:P.id}});return O.textContent=P.label,O}))),d.value=r(S)?.id??""};u(),o=u;let m=()=>{d.value&&e.onSelect(d.value)};d.addEventListener("change",m);let y=S=>S.stopPropagation();d.addEventListener("click",y);let{wrapper:h,chevron:C}=Yv();return h.append(d,C),{element:h,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",y)}}},a=()=>{let d=Q("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=M("span","persona-composer-model-picker-label"),u=M("span","persona-composer-model-picker-suffix");d.append(p,u);let m=Q("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),y=new Map,h="",C=null,S=()=>C?.isOpen===!0,x=(B=!1)=>{S()&&(C?.close(),d.setAttribute("aria-expanded","false"),B&&d.focus())},P=B=>{let H=[...y.values()];if(H.length===0)return;let L=(B%H.length+H.length)%H.length;H[L].focus()},O=B=>{if(S())return;C||(C=vd({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),gd(d,m,XP),C.open(),d.setAttribute("aria-expanded","true");let L=[...y.keys()].indexOf(r(e.getModels())?.id??"");P(B??(L>=0?L:0))},$=B=>{x(!0),e.onSelect(B)},T=B=>{B.preventDefault(),B.stopPropagation();let H=B.currentTarget.getAttribute("data-persona-model-option");H&&$(H)},R=B=>{let H=Q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":B.id}});if(B.icon){let le=pe(B.icon,Gv,"currentColor",1.5);if(le){let me=M("span","persona-composer-model-option-icon");me.appendChild(le),H.appendChild(me)}}let L=M("span","persona-composer-model-option-body"),ee=M("span","persona-composer-model-option-label");if(ee.textContent=B.label,L.appendChild(ee),B.description){let le=M("span","persona-composer-model-option-description");le.textContent=B.description,L.appendChild(le)}H.appendChild(L);let K=M("span","persona-composer-model-option-check");K.setAttribute("aria-hidden","true");let ue=pe("check",Gv,"currentColor",2);return ue&&K.appendChild(ue),H.appendChild(K),H.addEventListener("click",T),H},A=()=>{let B=e.getModels(),H=B.map(K=>`${K.id}:${K.label}:${K.icon??""}:${K.description??""}`).join("|");if(H!==h){h=H;for(let K of y.values())K.removeEventListener("click",T);y.clear(),m.replaceChildren(...B.map(K=>{let ue=R(K);return y.set(K.id,ue),ue}))}let L=r(B);for(let[K,ue]of y)ue.setAttribute("aria-selected",String(K===L?.id));p.textContent=L?.label??"";let ee=e.getSuffix?.()??"";u.textContent=ee,d.setAttribute("aria-label",[t,[L?.label,ee].filter(Boolean).join(" ")].filter(Boolean).join(": "))};A(),o=A;let N=B=>{B.preventDefault(),B.stopPropagation(),S()?x(!0):O()},G=B=>{if(B.key==="ArrowDown"){B.preventDefault(),S()?P(0):O(0);return}B.key==="ArrowUp"&&(B.preventDefault(),S()?P(-1):O(-1))},ae=B=>{let H=[...y.values()],L=H.indexOf(B.target?.closest?.(".persona-composer-model-option"));switch(B.key){case"ArrowDown":B.preventDefault(),P(L+1);return;case"ArrowUp":B.preventDefault(),P(L-1);return;case"Home":B.preventDefault(),P(0);return;case"End":B.preventDefault(),P(H.length-1);return;case"Escape":B.preventDefault(),B.stopPropagation(),x(!0);return;case"Tab":x(!0);return;default:}};d.addEventListener("click",N),d.addEventListener("keydown",G),m.addEventListener("keydown",ae);let{wrapper:Y,chevron:E}=Yv();return Y.append(d,E),{element:Y,destroy:()=>{o===A&&(o=null),d.removeEventListener("click",N),d.removeEventListener("keydown",G),m.removeEventListener("keydown",ae);for(let B of y.values())B.removeEventListener("click",T);y.clear(),C?.destroy(),C=null,m.remove()}}};return{action:{id:YP,kind:"custom",placement:"end",order:QP,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}var Kg="[data-persona-composer-chip-row]";function Cd(e){e.style.display=e.childElementCount>0?"flex":"none"}function Gg(e){let t=e.querySelector(Kg);if(t)return t;let n=Q("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(n,o):e.appendChild(n),n}var JP=":scope > [data-persona-composer-mode]";function Xv(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let u=Q("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let C=M("span","persona-mention-chip-icon"),S=pe(p.iconName,12,"currentColor",1.5);S&&C.appendChild(S),u.appendChild(C)}let m=M("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let y=Q("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=pe("x",12,"currentColor",2);return h?y.appendChild(h):y.textContent="\xD7",y.addEventListener("click",C=>{C.preventDefault(),C.stopPropagation(),e.onRemove(p.id)}),u.appendChild(y),u},a=()=>Array.from(t.querySelectorAll(JP)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),Cd(t)},m=t.ownerDocument.defaultView,y=typeof m?.getComputedStyle=="function"?m.getComputedStyle(p).animationName:"";if(!y||y==="none"){u();return}p.addEventListener("animationend",u,{once:!0}),p.addEventListener("animationcancel",u,{once:!0})},d=()=>{for(let p of a())p.remove()};return{element:t,render:(p,u)=>{if(o)return;let m=u.filter(S=>p.includes(S.id)),y=m.map(S=>`${S.id}:${S.shortLabel??S.label}`).join("|");if(y===n)return;n=y;let h=new Map;for(let S of a()){let x=S.getAttribute("data-persona-composer-mode");x&&m.some(O=>O.id===x)&&!S.hasAttribute("data-persona-chip-exit")?h.set(x,S):S.hasAttribute("data-persona-chip-exit")||l(S)}let C=t.firstChild;for(let S of m){let x=h.get(S.id);x||(x=s(S),r.has(S.id)||(x.setAttribute("data-persona-chip-enter",""),x.addEventListener("animationend",()=>x?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(S.id),x!==C&&t.insertBefore(x,C),C=x.nextSibling}Cd(t)},destroy:()=>{o=!0,d(),Cd(t)}}}var Jv=e=>`core:mode:${e}`;var Yg=e=>Math.min(300+e,499),Zv=e=>`core:mode-group:${e}`;function wd(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function ZP(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function eC(e,t){return e?.length?e.filter(n=>!wd(n.groupId,t)&&!ZP(n.groupId,t)):[]}var e0=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function tC(e,t,n,o){let r=n.find(l=>l.id===t);if(!r)return[...e];let s=e.includes(t),a=new Set(e);if(s)a.delete(t);else{if(e0(r,o)==="single"){let l=n.filter(d=>d.groupId===r.groupId).map(d=>d.id);a=new Set([...a].filter(d=>!l.includes(d)))}a.add(t)}return n.filter(l=>a.has(l.id)).map(l=>l.id)}function xd(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function nC(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function oC(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var t0=16;function rC(e){let t=null;return{action:{id:Zv(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=Q("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",a=p=>{p.preventDefault(),p.stopPropagation();let m=p.currentTarget.getAttribute("data-persona-composer-mode");!m||e.getActiveIds().includes(m)&&e.getGroup()?.selection==="single"||e.onSelect(m)},l=p=>{let u=Q("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let y=pe(p.iconName,t0,"currentColor",1.5);y&&u.appendChild(y)}let m=M("span","persona-composer-segmented-label");return m.textContent=p.shortLabel??p.label,u.appendChild(m),u.addEventListener("click",a),u},d=()=>{let p=e.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=e.getModes(),m=u.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(m!==s){s=m;for(let C of r.values())C.removeEventListener("click",a);r.clear();let h=u.map(C=>{let S=l(C);return r.set(C.id,S),S});o.replaceChildren(...h)}let y=e.getActiveIds();for(let[h,C]of r)C.setAttribute("aria-pressed",String(y.includes(h)))};return d(),t=d,{element:o,destroy:()=>{t===d&&(t=null);for(let p of r.values())p.removeEventListener("click",a);r.clear()}}}},repaint:()=>t?.()}}function sC(e){let t=Q("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let a=M("span","persona-composer-quote-bar"),l=M("div","persona-composer-quote-content");if(s.sourceLabel){let m=M("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let d=Q("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=rd(s.text),l.appendChild(d);let p=Q("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=pe("x",12,"currentColor",2);u?p.appendChild(u):p.textContent="\xD7",p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),e.onDismiss()}),t.replaceChildren(a,l,p)};return{element:t,render:s=>{if(o)return;let a=s?`${s.sourceLabel??""}\0${s.text}`:"";if(a!==n){if(n=a,!s){t.replaceChildren(),t.style.display="none";return}r(s),t.style.display="flex"}},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function iC(e){let t=Q("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(a,l,d,p)=>{let u=Q("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[d]:""}}),m=pe(a,12,"currentColor",2);return m?u.appendChild(m):u.textContent=l,u.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),p()}),u},s=a=>{let l=rd(a.text??"",90);if(l)return l;let d=a.contentParts?.length??0;return d>0?d===1?"1 attachment":`${d} attachments`:(a.mentionRefs?.length??0)>0?a.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:t,render:a=>{if(o||a===n)return;if(n=a,!a){t.replaceChildren(),t.style.display="none";return}let l=M("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let d=Q("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});d.textContent=s(a),t.replaceChildren(l,d,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function aC(e){let t=Q("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=Q("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=e.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=M("div","persona-message-edit-actions"),s=(l,d,p,u)=>{let m=Q("button",{className:`persona-message-edit-button ${d}`,attrs:{type:"button",[p]:""},text:l});return m.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),u()}),m},a=()=>{let l=n.value.trim();l&&e.onSave(l)};return r.append(s(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),s(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",a)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),e.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),a())}),t.append(n,r),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function lC(e){let t=e.text??"";if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function cC(e,t){if(!e||typeof e.text!="string")return;let n=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(d=>n.has(d.sourceId)),r=o.length===(e.mentionRefs?.length??0)&&o.length>0,s=new Set(t.modes.map(d=>d.id)),a=(e.activeModeIds??[]).filter(d=>s.has(d)),l=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:o}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...l?{selectedModelId:l}:{},...a.length?{activeModeIds:a}:{},...e.quote?.text?{quote:e.quote}:{}}}function dC(e){let t=e.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{o||n===null||(r(),e.write())},cancel:r,destroy:()=>{o=!0,r()}}}function pC(e){return e.wrapped||e.text.includes(`
23
- `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function uC(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function gC(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),o=Number.parseFloat(n.lineHeight),r=Number.parseFloat(n.fontSize),s=Number.isFinite(o)&&o>0?o:Number.isFinite(r)&&r>0?r*1.4:0;if(!s)return!1;let a=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-a>s*1.5}function mC(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Qg(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function hC(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var n0=e=>typeof e?.then=="function";function fC(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function yC(e,t,n){let o;try{o=e(Qg(t),{signal:n})}catch(r){return{status:"error",error:r}}return n0(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:fC(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):fC(t,o)}var bC=/\s/;function o0(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
24
- `:o===""||bC.test(o)}function r0(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let a=e[s];if(a===n)return o0(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
25
- `||a==="\uFFFC"||!r&&bC.test(a))return null;s--}return null}function vC(e,t,n){for(let o of n){let r=r0(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function CC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function wC(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.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[t,...n]}function xC(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=M("div","persona-send-button-wrapper"),a=Q("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${$n} ${bo}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=pe(o,fn,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),s.appendChild(a),tn({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}var{setLoader:LB,load:s0}=vt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var Xg=s0;var{setLoader:HB,load:i0}=vt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var SC=i0;function rl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Q("span",{className:mn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=pe(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=M("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Q("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function AC(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=wC(t).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(R=>typeof R.matchCommand=="function")),r=T=>o.some(R=>R.trigger?R.position==="line-start"?T.split(`
26
- `).some(N=>N.startsWith(R.trigger)):(R.position==="anywhere"?T:T.split(`
27
- `)[0]).startsWith(R.trigger):!1),s=(T,R)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:R}))}catch{}},a=!e.chipRow,l=e.chipRow??Q("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,p=null,u=e.textarea,m=null,y=null,h=null,C=null,S=()=>{if(d)return Promise.resolve(d);if(p)return p;let T=Xg().then(R=>(R.setMentionIconRenderer(pe),d=R.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:l,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:$,emit:s}),d)).catch(R=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",R),p===T&&(p=null),null));return p=T,T},x=()=>{SC().then(T=>{let R=T.mountInlineComposer({textarea:e.textarea,renderToken:N=>rl(N,{render:t.renderMentionToken}),onMentionRemoved:N=>d?.untrackMention(N)});m=R.input,y=R.destroy;let A=u;A.replaceWith(R.element),u=R.element,C={next:R.element,prev:A},h?.(R.element,A),d?d.rebindComposer(R.input):p&&p.then(N=>N?.rebindComposer(R.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};t.display==="inline"&&x();let P=[],O=new Map;for(let T of n){if(!T.showButton)continue;let R=xC({config:{...t,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},onOpen:()=>{S().then(A=>A?.openMenu(T.trigger))}});P.push(R),O.set(T.trigger,R.button)}let $=(T,R,A)=>{let N=O.get(R);N&&(N.setAttribute("aria-expanded",T?"true":"false"),T?N.setAttribute("aria-controls",A):N.removeAttribute("aria-controls"))};return{affordanceButtons:P.map(T=>T.wrapper),contextRow:l,handleInput:T=>{if(d){d.handleInput();return}if(!CC(T))return;let R=u,A=R.selectionStart??0;vC(R.value,A,n)&&S().then(N=>N?.handleInput())},handleKeydown:T=>{if(d?.isMenuOpen())return d.handleKeydown(T);if(T.key==="Backspace"&&d?.hasMentions()&&!C){let R=u,A=R.selectionStart===0&&R.selectionEnd===0;if((R.value.length===0||A)&&d.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async T=>r(T)?(d??await S())?.dispatchInlineCommand(T)??null:null,clear:()=>d?.clear(),prefetch:()=>{Xg().catch(()=>{})},onComposerSwap:T=>{h=T,C&&T(C.next,C.prev)},destroy:()=>{d?.destroy(),y?.();for(let T of P)T.wrapper.remove();a&&l.remove()}}}var Sd="16px",Ad="transparent",a0=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?"0px":`${t/4}rem`;return e})(),EC={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"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:a0,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"}},TC={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"}},kC={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:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:oo,maxWidth:Bg,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Sd,canvasBackground:Ad},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},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",itemGap:"8px",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",itemGap:"8px",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",itemGap:"8px",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"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},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",borderRadius:"palette.radius.md"},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"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},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 hn(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;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."))?hn(e,o):o}function Zg(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let d=hn(e,a);d!==void 0&&(t[l]={path:l,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function PC(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function LC(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=LC(s,r):n[o]=r}return n}function l0(e,t){return t?LC(e,t):e}function Md(e,t={}){let n={palette:EC,semantic:TC,components:kC},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:l0(n.components,e?.components)};if(t.validate!==!1){let r=PC(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}var Jg=e=>e.trim()==="0"?"0px":e,MC="--persona-",c0=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let a=t.slice(1);if(!/^[0-9a-f]+$/.test(a))return;a.length===3||a.length===4?n=[0,1,2].map(l=>parseInt(a[l]+a[l],16)):(a.length===6||a.length===8)&&(n=[0,2,4].map(l=>parseInt(a.slice(l,l+2),16)))}else{let a=t.match(/^rgba?\(([^)]+)\)$/);if(a){let l=a[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(d=>{let p=d.endsWith("%"),u=parseFloat(p?d.slice(0,-1):d);return p?u/100*255:u}))}}if(!n||n.some(a=>!Number.isFinite(a)))return;let[o,r,s]=n.map(a=>{let l=Math.max(0,Math.min(255,a))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},d0=.179,nn=(e,t)=>{for(let[n,...o]of t){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):e[MC+s],r!==void 0)break;r!==void 0&&(e[MC+n]=r)}};function em(e){let t=Zg(e),n={};for(let[j,_e]of Object.entries(t)){let Fe=j.replace(/\./g,"-");n[`--persona-${Fe}`]=_e.value}nn(n,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],nn(n,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),nn(n,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,nn(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Sd,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ad,nn(n,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),nn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],a=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],nn(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??a??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??a??n["--persona-muted"],nn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=e.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[j,_e]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Fe=n[`--persona-components-history-overlay-${j}`];Fe&&(n[`--persona-history-overlay-${_e}`]=Fe)}for(let[j,_e]of[["background","bg"],["borderRadius","radius"]]){let Fe=n[`--persona-components-history-menu-${j}`];Fe&&(n[`--persona-history-menu-${_e}`]=Fe)}let m=e.components?.history?.motion;if(m){let j=mt=>{if(mt===void 0)return;let Ce=String(mt).trim();return/^\d+(\.\d+)?$/.test(Ce)?`${Ce}ms`:Ce},_e=j(m.enterDurationMs);_e!==void 0&&(n["--persona-history-enter-ms"]=_e);let Fe=j(m.exitDurationMs);Fe!==void 0&&(n["--persona-history-exit-ms"]=Fe),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let y=n["--persona-components-history-dangerForeground"];y&&(n["--persona-history-danger-fg"]=y),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let j of["scrim","shadow"]){let _e=n[`--persona-components-history-confirm-${j}`];_e&&(n[`--persona-history-confirm-${j}`]=_e)}for(let[j,_e]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Fe=n[`--persona-components-tooltip-${j}`];Fe&&(n[`--persona-tooltip-${_e}`]=Fe)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[j,_e]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Fe=n[`--persona-components-messageActions-${j}`];Fe&&(n[`--persona-message-action-${_e}`]=Fe)}nn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],C=n["--persona-components-introCard-shadow"],S=(!h||h==="transparent"||h==="none")&&(!C||C==="none"),x=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=S&&x==="1.5rem"?"1.5rem 0":x,nn(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),nn(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let P=n["--persona-components-markdown-heading-h1-fontSize"];P&&(n["--persona-md-h1-size"]=P);let O=n["--persona-components-markdown-heading-h1-fontWeight"];O&&(n["--persona-md-h1-weight"]=O);let $=n["--persona-components-markdown-heading-h2-fontSize"];$&&(n["--persona-md-h2-size"]=$);let T=n["--persona-components-markdown-heading-h2-fontWeight"];T&&(n["--persona-md-h2-weight"]=T);let R=n["--persona-components-markdown-prose-fontFamily"];R&&R!=="inherit"&&(n["--persona-md-prose-font-family"]=R),nn(n,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),nn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),nn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),nn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),nn(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","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"],nn(n,[["message-border","components-message-border","border"]]),nn(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let A=e.components,N=A?.iconButton;N&&(N.background&&(n["--persona-icon-btn-bg"]=N.background),N.border&&(n["--persona-icon-btn-border"]=N.border),N.color&&(n["--persona-icon-btn-color"]=N.color),N.padding&&(n["--persona-icon-btn-padding"]=N.padding),N.borderRadius&&(n["--persona-icon-btn-radius"]=N.borderRadius),N.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=N.hoverBackground),N.hoverColor&&(n["--persona-icon-btn-hover-color"]=N.hoverColor),N.activeBackground&&(n["--persona-icon-btn-active-bg"]=N.activeBackground),N.activeBorder&&(n["--persona-icon-btn-active-border"]=N.activeBorder));let G=A?.labelButton;G&&(G.background&&(n["--persona-label-btn-bg"]=G.background),G.border&&(n["--persona-label-btn-border"]=G.border),G.color&&(n["--persona-label-btn-color"]=G.color),G.padding&&(n["--persona-label-btn-padding"]=G.padding),G.borderRadius&&(n["--persona-label-btn-radius"]=G.borderRadius),G.hoverBackground&&(n["--persona-label-btn-hover-bg"]=G.hoverBackground),G.fontSize&&(n["--persona-label-btn-font-size"]=G.fontSize),G.gap&&(n["--persona-label-btn-gap"]=G.gap));let ae=A?.toggleGroup;ae&&(ae.gap&&(n["--persona-toggle-group-gap"]=ae.gap),ae.borderRadius&&(n["--persona-toggle-group-radius"]=ae.borderRadius));let Y=A?.artifact;if(Y?.toolbar){let j=Y.toolbar;j.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=j.iconHoverColor),j.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=j.iconHoverBackground),j.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=j.iconPadding),j.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=j.iconBorderRadius),j.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=j.iconBorder),j.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Jg(j.toggleGroupGap)),j.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=j.toggleBorderRadius),j.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Jg(j.toggleGroupPadding)),j.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=j.toggleGroupBorder),j.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=j.toggleGroupBorderRadius),j.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=hn(e,j.toggleGroupBackground)??j.toggleGroupBackground),j.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=j.copyBackground),j.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=j.copyBorder),j.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=j.copyColor),j.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Jg(j.copyBorderRadius)),j.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=j.copyPadding),j.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=j.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??j.copyMenuBackground),j.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=j.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??j.copyMenuBorder),j.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=j.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??j.copyMenuShadow),j.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=j.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??j.copyMenuBorderRadius),j.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=j.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??j.copyMenuItemHoverBackground),j.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=j.iconBackground),j.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=j.toolbarBorder)}if(Y?.tab){let j=Y.tab;j.background&&(n["--persona-artifact-tab-bg"]=j.background),j.activeBackground&&(n["--persona-artifact-tab-active-bg"]=j.activeBackground),j.activeBorder&&(n["--persona-artifact-tab-active-border"]=j.activeBorder),j.borderRadius&&(n["--persona-artifact-tab-radius"]=j.borderRadius),j.textColor&&(n["--persona-artifact-tab-color"]=j.textColor),j.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=j.hoverBackground),j.listBackground&&(n["--persona-artifact-tab-list-bg"]=j.listBackground),j.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=j.listBorderColor),j.listPadding&&(n["--persona-artifact-tab-list-padding"]=j.listPadding)}if(Y?.pane){let j=Y.pane;if(j.toolbarBackground){let _e=hn(e,j.toolbarBackground)??j.toolbarBackground;n["--persona-artifact-toolbar-bg"]=_e}}if(Y?.card){let j=Y.card;j.background&&(n["--persona-artifact-card-bg"]=j.background),j.border&&(n["--persona-artifact-card-border"]=j.border),j.borderRadius&&(n["--persona-artifact-card-radius"]=j.borderRadius),j.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=j.hoverBackground),j.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=j.hoverBorderColor)}if(Y?.inline){let j=Y.inline;j.background&&(n["--persona-artifact-inline-bg"]=hn(e,j.background)??j.background),j.border&&(n["--persona-artifact-inline-border"]=j.border),j.borderRadius&&(n["--persona-artifact-inline-radius"]=j.borderRadius),j.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=hn(e,j.chromeBackground)??j.chromeBackground),j.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=hn(e,j.chromeBorder)??j.chromeBorder),j.titleColor&&(n["--persona-artifact-inline-title-color"]=hn(e,j.titleColor)??j.titleColor),j.mutedColor&&(n["--persona-artifact-inline-muted-color"]=hn(e,j.mutedColor)??j.mutedColor),j.frameHeight&&(n["--persona-artifact-inline-frame-height"]=j.frameHeight)}let E=A?.code;E&&(E.keywordColor&&(n["--persona-code-keyword-color"]=E.keywordColor),E.stringColor&&(n["--persona-code-string-color"]=E.stringColor),E.commentColor&&(n["--persona-code-comment-color"]=E.commentColor),E.numberColor&&(n["--persona-code-number-color"]=E.numberColor),E.tagColor&&(n["--persona-code-tag-color"]=E.tagColor),E.attrColor&&(n["--persona-code-attr-color"]=E.attrColor),E.propertyColor&&(n["--persona-code-property-color"]=E.propertyColor),E.lineNumberColor&&(n["--persona-code-line-number-color"]=E.lineNumberColor),E.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=E.gutterBorderColor),E.background&&(n["--persona-code-bg"]=hn(e,E.background)??E.background));let B=n["--persona-surface"],H=n["--persona-container"],L=n["--persona-palette-colors-gray-100"]??"#f3f4f6",ee=n["--persona-palette-colors-gray-200"]??"#e5e7eb",K=n["--persona-palette-colors-gray-300"]??"#d1d5db",ue=!H||H===B,le=c0(B??n["--persona-background"]),me=ue&&le!==void 0&&le<d0,Re=me?"rgba(255, 255, 255, 0.08)":L,He=me?"rgba(255, 255, 255, 0.12)":ee,ve=me?"rgba(255, 255, 255, 0.16)":K,Ge=ue?Re:H,be=ue?He:H;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Ge,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??be,ue&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ve),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Ge,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Ge,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Ge,n}var p0={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var u0={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"}}},g0={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},IC=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ed=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",m0=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ed()},tm=e=>m0(e),f0=e=>Md(e),h0=e=>{let t=Hi(g0,e??{})??{};return Md({...t,palette:{...t.palette,colors:{...u0.colors,...t.palette?.colors}}},{validate:!1})},Os=e=>{let t=tm(e),n=IC(e?.theme),o=IC(e?.darkTheme);return t==="dark"?h0(Hi(n??{},o??{})):f0(n)},y0=e=>em(e),Oi=(e,t)=>{let n=Os(t),o=y0(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",tm(t))},sl=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ed())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ed());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};import{Activity as dx,Check as px,Copy as ux}from"lucide";var jr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Td="24px",nm=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",il=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let n=Number(t[1])/100;return n>0&&n<1?n:null},RC=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var HC=null;var om=()=>{if(HC!==null)return HC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},b0="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",kd=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Pd=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),n=t.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return kd("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(kd("unsupported",e),null):(n==="space"&&(o.key=" "),o)},v0=e=>b0.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),WC=(e,t)=>{let n=Pd(e);if(!n)return"";let o=om(),r=v0(n.key);if(!t&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[t?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},Ld=e=>WC(e,!1),al=e=>WC(e,!0),C0=(e,t)=>t.key?.toLowerCase()===e.key&&(om()?t.metaKey:t.ctrlKey)===e.mod&&!(om()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,w0=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},OC=e=>{let t=new Map,n=e?.ownerDocument??(typeof document<"u"?document:null),o=(s,a)=>{if((s.scope??"widget")==="page")return!0;if(!e)return!1;let l=a.composedPath?.();return l?.length?l.includes(e):e.contains(a.target)},r=s=>{if(s.isComposing||!t.size)return;let a=s.composedPath?.()[0]??s.target;for(let l of t.values())if(C0(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&w0(a))){s.preventDefault();try{l.run(s)}catch(d){kd(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=Pd(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=t.get(l);return d?(kd(`${d.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",al(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}};import{Idiomorph as x0}from"idiomorph";var Id=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;x0.morph(e,t.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 a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var BC=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var rm={index:-1,draft:""};function _C(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){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(!a)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 DC(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function NC(){return new Map}function FC(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function $C(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function UC(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function jC(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function qC(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Do(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Bs(e,t){return Do(e)-e.scrollTop<=t}function zC(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:p=!1}=e,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!t&&r&&(!p||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:t&&l&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function VC(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function KC(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function sm(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function GC(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var ll={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},S0=["pre","code","a","script","style"],Rd=e=>({type:e?.type??ll.type,placeholder:e?.placeholder??ll.placeholder,speed:e?.speed??ll.speed,duration:e?.duration??ll.duration,buffer:e?.buffer??ll.buffer}),QC=[{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"}],cl=new Map;for(let e of QC)cl.set(e.name,e);var XC=["wipe","glyph-cycle"],Hd=e=>{cl.set(e.name,e)},A0=e=>{QC.some(t=>t.name===e)||cl.delete(e)},M0=()=>Array.from(cl.keys()),dl=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:cl.get(e)??null,Wd=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
28
- `);return s<0?"":e.slice(0,s)}return e},E0=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},T0=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},im=/\s/,k0=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},P0=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(im.test(s[l])){let d=l;for(;d<s.length&&im.test(s[d]);)d+=1;a.appendChild(o.createTextNode(s.slice(l,d))),l=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let p=l;for(;p<s.length&&!im.test(s[p]);)d.appendChild(E0(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,e)},L0=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let d of l)d&&(/^\s+$/.test(d)?a.appendChild(o.createTextNode(d)):(a.appendChild(T0(o,d,t,n.value)),n.value+=1));r.replaceChild(a,e)},pl=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??S0).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)k0(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=t==="char"?P0:L0;for(let m of l)u(m,n,p);return r.innerHTML},Od=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ul=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},YC=new WeakMap,I0=(e,t)=>{if(!e.styles)return;let n=YC.get(t);if(n||(n=new Set,YC.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},am=new WeakMap,R0=(e,t)=>{if(!e.onAttach)return;let n=am.get(t);if(n||(n=new Map,am.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},JC=e=>{let t=am.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},gl=(e,t)=>{I0(e,t),R0(e,t)};var{setLoader:c_,load:H0}=vt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var ZC=H0;function lm(e,t=sn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var ml=0,qr=null;function cm(e=document){if(ml++,ml===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;qr={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 t=!1;return()=>{if(!t&&(t=!0,ml=Math.max(0,ml-1),ml===0&&qr)){let n=e.body,o=e.defaultView??window;n.style.overflow=qr.originalOverflow,n.style.position=qr.originalPosition,n.style.top=qr.originalTop,n.style.width=qr.originalWidth,o.scrollTo(0,qr.scrollY),qr=null}}}var fl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Tt=e=>(e?.launcher?.mountMode??"floating")==="docked",zr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Un=e=>{let t=e?.launcher?.dock;return{side:t?.side??fl.side,width:t?.width??fl.width,animate:t?.animate??fl.animate,reveal:t?.reveal??fl.reveal,maxHeight:t?.maxHeight??fl.maxHeight}};import{ArrowRight as W0}from"lucide";var dm=e=>e==="followUp"?"follow-up":e,pm=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},O0=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},ew=new WeakSet,B0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,_0=e=>{B0()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},um=e=>{var $,T,R;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:d,chipsConfig:p,session:u,getTextarea:m,eventTarget:y,submitPrompt:h}=e,C=o==="followUp",S=t.behavior,x=()=>{if(u.isStreaming())return;let A={suggestion:{...t},surface:o,source:r,behavior:S},N=y.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:A,bubbles:!0,composed:!0,cancelable:!0}));if(C&&y.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!N)return;for(let ae of d)if(ae.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let G=m();if(S==="fill"){G.value=t.prompt,G.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),G.focus();return}if(h){h(t.prompt);return}G.value="",u.sendMessage(t.prompt)},P=()=>{let A=M("button",`persona-suggestion persona-suggestion--${s}`);if(A.type="button",A.disabled=a,A.dataset.suggestionId=t.id,A.dataset.emphasis=t.emphasis,A.dataset.behavior=S,s==="chip"&&(p?.fontFamily&&(A.style.fontFamily=O0(p.fontFamily)),p?.fontWeight&&(A.style.fontWeight=p.fontWeight),p?.paddingX&&(A.style.paddingLeft=p.paddingX,A.style.paddingRight=p.paddingX),p?.paddingY&&(A.style.paddingTop=p.paddingY,A.style.paddingBottom=p.paddingY)),t.icon){let G=pe(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);G&&(G.classList.add("persona-suggestion__icon"),t.iconColor&&(G.style.color=t.iconColor),A.appendChild(G))}let N=M("span","persona-suggestion__copy");if(N.appendChild(Q("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&N.appendChild(Q("span",{className:"persona-suggestion__description",text:t.description})),A.appendChild(N),s!=="chip"){let G=Wt(W0,16,"currentColor",1.8);G&&(G.classList.add("persona-suggestion__arrow"),A.appendChild(G))}return A.addEventListener("click",x),A},O=null;for(let A of d)if(A.renderSuggestion&&(O=A.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:P,select:x}),O))break;return O??(O=P()),($=O.dataset).suggestionId||($.suggestionId=t.id),(T=O.dataset).behavior||(T.behavior=S),(R=O.dataset).emphasis||(R.emphasis=t.emphasis),O instanceof HTMLButtonElement||O.setAttribute("aria-disabled",a?"true":"false"),O},hl=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,e.scrollWidth-e.clientWidth);if(u<=1){s();return}let m=getComputedStyle(e).direction==="rtl",y=Math.min(u,Math.max(0,Math.abs(e.scrollLeft))),h=4,C=y<=h,S=y>=u-h,x=m?!S:!C,P=m?!C:!S;e.toggleAttribute("data-scroll-left",x),e.toggleAttribute("data-scroll-right",P)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,m,y,h,C,S)=>{e.replaceChildren(),t.length=0,n.length=0;let x=S?.source??"config",P=S?.surface??(x==="config"?"starter":"followUp"),O=P==="followUp",$=S?.variant??"chip",T=S?.behavior??"send",R=S?.overflow??"wrap",A=S?.config??{},N=S?.plugins??[],G=typeof S?.maxItems=="number"?Math.max(0,Math.floor(S.maxItems)):void 0,ae=O?"followUps":"starters";!ew.has(A)&&A.debug===!0&&$!=="chip"&&A.suggestions?.[ae]?.overflow!==void 0&&(ew.add(A),console.info(`[persona] suggestions.${ae}.overflow applies to the "chip" variant only; the "${$}" variant manages its own stacking.`));let Y=K=>K.map(pm).filter(ue=>ue!==null).map(ue=>({...ue,behavior:ue.behavior??T})),E=Y(u??[]);N.forEach(K=>{K.transformSuggestions&&(E=Y(K.transformSuggestions({suggestions:E.map(ue=>({...ue})),surface:P,source:x,config:A})))});let B=G===void 0?E:E.slice(0,G);if(!B.length){e.hidden=!0,o=null,s();return}if(!O&&(h??m.getMessages()).some(ue=>ue.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=dm(P),e.dataset.variant=$,e.dataset.overflow=R;let H=document.createDocumentFragment(),L=m.isStreaming();B.forEach((K,ue)=>{let le=um({item:K,index:ue,surface:P,source:x,variant:$,streaming:L,config:A,plugins:N,chipsConfig:C,session:m,getTextarea:()=>y,eventTarget:e,submitPrompt:S?.submitPrompt});H.appendChild(le),n.push(le),[...le instanceof HTMLButtonElement?[le]:[],...Array.from(le.querySelectorAll("button"))].forEach(Re=>{t.includes(Re)||(Re.disabled=L,t.push(Re))})}),e.appendChild(H),a(),l();let ee=JSON.stringify({normalized:B,surface:P,variant:$,source:x});ee!==o&&(o=ee,_0(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:B.map(K=>({...K})),surface:P,source:x,variant:$},bubbles:!0,composed:!0})),O&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:B.map(K=>K.prompt)},bubbles:!0,composed:!0})))}}};var jn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var D0="persona-header-control",N0="persona-header-control--glyph",F0="persona-header-control--sparse",$0=20,U0={x:[1.4,1.05]},tw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",j0="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Bd=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=U0[t]??[1,1.5],l=!o;e.classList.toggle(N0,l),e.classList.toggle(F0,l&&s!==1);let d=parseFloat(o??"")||$0,p=pe(t,`${Math.round(d*s)}px`,"currentColor",a);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),e.replaceChildren(p)):r&&(e.textContent=r)},_s=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=tw,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:y,borderRadius:h,paddingX:C,paddingY:S,hidden:x,extraClassName:P,attrs:O}=e,$=M("div",a),T=!!(m||y),R=Q("button",{className:mn(D0,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!T&&"persona-border-none",!h&&"persona-rounded-full",P),attrs:{type:"button","aria-label":t,...O},style:{width:l,height:l,minWidth:l,minHeight:l,display:x?"none":void 0,color:p||yn.actionIconColor,backgroundColor:u,border:T?`${m||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:h,paddingLeft:C,paddingRight:C,paddingTop:S,paddingBottom:S}});return r?Bd(R,r,{iconSize:d,iconText:s}):s&&(R.textContent=s),$.appendChild(R),tn({anchor:R,trigger:$,text:()=>R.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:R,wrapper:$}},Bi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=tw,buttonSize:r,iconSize:s}=t,a=e?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=_s({ariaLabel:l,tooltip:d,iconName:a.closeButtonIconName??"x",iconText:a.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??a.closeButtonSize,iconSize:s,color:a.closeButtonColor,backgroundColor:a.closeButtonBackgroundColor,borderWidth:a.closeButtonBorderWidth,borderColor:a.closeButtonBorderColor,borderRadius:a.closeButtonBorderRadius,paddingX:a.closeButtonPaddingX,paddingY:a.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:u}},_i=(e,t={})=>{let{wrapperClassName:n=j0,buttonSize:o,iconSize:r}=t,a=(e?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=_s({ariaLabel:l,tooltip:d,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:p,wrapper:u}};var yn={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))",minHeight:"var(--persona-header-min-height, auto)"},gm={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},q0={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},Vr=e=>{let{config:t,showClose:n=!0}=e,o=Q("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:{minHeight:yn.minHeight,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=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,p=Q("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(d){let R=parseFloat(s)||24,A=pe(d,R*.6,"currentColor",1);A?p.replaceChildren(A):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let R=M("img");R.src=t.launcher.iconUrl,R.alt="",R.className="persona-rounded-xl persona-object-cover",R.style.height=s,R.style.width=s,p.replaceChildren(R)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let u=M("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Q("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:yn.titleColor,...gm}}),y=Q("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:yn.subtitleColor,...q0}});u.append(m,y),l?o.append(u):o.append(p,u);let h=r.clearChat??{},C=h.enabled??!0,S=h.placement??"inline",x=null,P=null;if(C){let A=_i(t,{wrapperClassName:S==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});x=A.button,P=A.wrapper,S==="top-right"&&(P.style.right="48px"),S==="inline"&&o.appendChild(P)}let O=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&S==="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:$,wrapper:T}=Bi(t,{showClose:n,wrapperClassName:O});return a!=="top-right"&&o.appendChild(T),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:y,closeButton:$,closeButtonWrapper:T,clearChatButton:x,clearChatButtonWrapper:P}},Di=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Ni(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=e,l=M("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(Ri)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let C of t){if(C.dividerBefore){let P=document.createElement("hr");l.appendChild(P)}let S=document.createElement("button");if(S.type="button",S.setAttribute("role","menuitem"),S.setAttribute("data-dropdown-item-id",C.id),C.destructive&&S.setAttribute("data-destructive",""),C.icon){let P=pe(C.icon,16,"currentColor",1.5);P&&S.appendChild(P)}let x=document.createElement("span");x.textContent=C.label,S.appendChild(x),S.addEventListener("click",P=>{P.stopPropagation(),m(),n(C.id)}),l.appendChild(S)}let d=null;function p(){if(!s)return;let C=o.getBoundingClientRect();l.style.top=`${C.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-C.right}px`,l.style.left="auto"):(l.style.left=`${C.left}px`,l.style.right="auto")}function u(){let C=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),C&&a?.(!0),requestAnimationFrame(()=>{let S=x=>{!l.contains(x.target)&&!o.contains(x.target)&&m()};document.addEventListener("click",S,!0),d=()=>document.removeEventListener("click",S,!0)})}function m(){let C=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,C&&a?.(!1)}function y(){l.classList.contains("persona-hidden")?u():m()}function h(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:m,toggle:y,destroy:h}}function qn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=e,p=M("button",mn(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=pe(t,o??16,"currentColor",r??2);if(u&&p.appendChild(u),l&&p.addEventListener("click",l),d)for(let[m,y]of Object.entries(d))p.setAttribute(m,y);return p}function nw(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:d}=e,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let u=M("button",p);if(u.type="button",u.setAttribute("aria-label",n),t){let y=pe(t,s??14,"currentColor",2);y&&u.appendChild(y)}let m=M("span");if(m.textContent=n,u.appendChild(m),l&&u.addEventListener("click",l),d)for(let[y,h]of Object.entries(d))u.setAttribute(y,h);return u}function _d(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=M("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function d(){for(let u of l)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of t){let m;u.icon?m=qn({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,d(),o(u.id)}}):(m=M("button","persona-icon-btn"+(u.className?" "+u.className:"")),m.type="button",m.setAttribute("aria-label",u.label),m.title=u.label,m.textContent=u.label,m.addEventListener("click",()=>{a=u.id,d(),o(u.id)})),m.setAttribute("aria-pressed",u.id===a?"true":"false"),l.push({id:u.id,btn:m}),s.appendChild(m)}function p(u){a=u,d()}return{element:s,setSelected:p}}function z0(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:d="bottom-left",portal:p,chevronLabel:u="More options",chevronIconSize:m,className:y,primaryClassName:h,chevronClassName:C}=e,S=M("div","persona-split-btn"+(y?" "+y:"")),x={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},P=r&&n?qn({...x,icon:n,size:o??14}):nw({...x,icon:n,iconSize:o??14}),O=qn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(C?" "+C:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});S.append(P,O);let $=null,T=()=>{if($)return $;let R=(typeof p=="function"?p():p)??void 0;return $=Ni({items:s,onSelect:a,anchor:S,position:d,portal:R,onOpenChange:A=>{O.setAttribute("aria-expanded",A?"true":"false")}}),R||S.appendChild($.element),$};return S.isConnected?T():requestAnimationFrame(()=>{$||T()}),O.addEventListener("click",R=>{R.stopPropagation(),T().toggle()}),{element:S,primaryButton:P,chevronButton:O,openMenu:()=>T().show(),closeMenu:()=>$?.hide(),toggleMenu:()=>T().toggle(),destroy:()=>{$?.destroy(),S.remove()}}}function mm(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:d}=e,p=M("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",t);let u=M("span","persona-combo-btn-label");u.textContent=t,p.appendChild(u);let m=pe(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",p.appendChild(m)),d&&(p.style.borderRadius=d.borderRadius??"10px",p.style.padding=d.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=d.background??"",p.style.borderColor=d.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let y=Ni({items:o,onSelect:C=>{p.setAttribute("aria-expanded","false"),r(C)},anchor:p,position:s,portal:a});a||p.appendChild(y.element);let h=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",C=>{if(C.stopPropagation(),h())return;let S=!y.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",S?"false":"true"),y.toggle()}),p.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),p.click())}),{element:p,setLabel:C=>{u.textContent=C,p.setAttribute("aria-label",C)},open:()=>{p.setAttribute("aria-expanded","true"),y.show()},close:()=>{p.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let C=!y.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",C?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),p.remove()}}}var ow=e=>{let t=Vr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.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 t};function V0(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=_s({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Ld(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let a=al(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=Ni({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var rw=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=M("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=yn.minHeight,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 d=r?.titleMenu,p,u;if(d){let T=mm({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:R=>{let A=G=>{G===!1&&T.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:R}}))},N=d.onSelect(R);N instanceof Promise?N.then(A,()=>{}):A(N)},hover:d.hover,className:""});p=T.element,p.style.color=yn.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=M("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=M("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=yn.titleColor,Object.assign(u.style,gm),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let R=r.onTitleClick;p.addEventListener("click",A=>{A.target.closest("button")||R()}),p.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),R())})}let T=r?.titleRowHover;T&&(p.style.borderRadius=T.borderRadius??"10px",p.style.padding=T.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=T.background??"",p.style.borderColor=T.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:y,wrapper:h}=Bi(t,{showClose:n,wrapperClassName:m});o&&y.addEventListener("click",o);let C=M("div","persona-flex persona-items-center persona-gap-1");d||V0(C,r?.trailingActions,r?.onAction??s);let S=a.clearChat??{},x=null,P=null;if(S.enabled??!0){let T=S.placement??"inline",R=_i(t,{wrapperClassName:T==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});x=R.button,P=R.wrapper,T==="top-right"?P.style.right="48px":C.appendChild(P)}C.appendChild(h),l.appendChild(C);let O=M("div");O.style.display="none";let $=M("span");return $.style.display="none",{header:l,iconHolder:O,headerTitle:u,headerSubtitle:$,closeButton:y,closeButtonWrapper:h,clearChatButton:x,clearChatButtonWrapper:P}},fm={default:ow,minimal:rw},sw=e=>fm[e]??fm.default,yl=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=M("div");l.style.display="none";let d=M("span"),p=M("span"),u=M("button");u.style.display="none";let m=M("div");return m.style.display="none",{header:a,iconHolder:l,headerTitle:d,headerSubtitle:p,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=sw(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Fi=e=>{let{config:t}=e,n=Q("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=bd(),r=Q("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:a}=md(t);a();let l=fd(t),d=Wi(t),p=hd(t),u=yd(t),m=Q("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),p&&(p.previewsContainer.style.gap="8px",m.append(p.previewsContainer),r.append(p.input)),r.append(s);let y=Q("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=Q("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),C=Q("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&h.append(p.wrapper),d&&C.append(d.wrapper),C.append(l.wrapper),y.append(h,C),r.append(y),r.addEventListener("click",S=>{S.target!==l.button&&S.target!==l.wrapper&&S.target!==d?.button&&S.target!==d?.wrapper&&S.target!==p?.button&&S.target!==p?.wrapper&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,header:m,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:u,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:y,leftActions:h,rightActions:C,setSendButtonMode:l.setMode}};import{ChevronUp as K0,MessageSquare as G0}from"lucide";var iw=()=>{let e=Q("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=M("span","persona-pill-peek__icon"),n=Wt(G0,16,"currentColor",1.5);n&&t.appendChild(n);let o=M("span","persona-pill-peek__text"),r=M("span","persona-pill-peek__caret"),s=Wt(K0,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Dd=e=>{let{config:t}=e,n=Q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=bd(),r=yd(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=md(t,{defaultMaxLines:5});a();let l=fd(t),d=Wi(t),p=hd(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=Q("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=Q("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let y=Q("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&y.append(d.wrapper),y.append(l.wrapper),u.addEventListener("click",S=>{S.target!==l.button&&S.target!==l.wrapper&&S.target!==d?.button&&S.target!==d?.wrapper&&S.target!==p?.button&&S.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,y);let h=Q("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),p&&h.append(p.previewsContainer),n.append(o,u,r);let C=u;return{footer:n,suggestions:o,composerForm:u,header:h,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:C,leftActions:m,rightActions:y,setSendButtonMode:l.setMode}};var Y0=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Q0=(e,t)=>{if(!e)return null;let n=Y0(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},X0=(e,t)=>{let n=M("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},J0=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},ym=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},bm=320,pw=320,Z0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),eL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),tL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),nL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),oL=e=>{if(!e||e.length===0)return null;let t=Q("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Q("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=M("span","persona-mention-chip-icon"),s=pe(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Q("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},rL=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(rl(o.ref,{readonly:!0,render:t}))}return n},aw="\uE000",lw="\uE001",sL=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${aw}${r}:${y}${lw}`,a=t.map((y,h)=>y.kind==="text"?y.text:s(h)).join(""),l=n(a);if(!t.every((y,h)=>y.kind==="text"||l.includes(s(h)))){e.replaceChildren(rL(t,o));return}e.innerHTML=l;let p=new RegExp(`${aw}${r}:(\\d+)${lw}`),u=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let y=u.nextNode();y;y=u.nextNode())m.push(y);for(let y of m){let h=y;for(let C=p.exec(h.data);C;C=p.exec(h.data)){let S=t[Number(C[1])],x=h.splitText(C.index);x.data=x.data.slice(C[0].length),S?.kind==="mention"&&x.parentNode?.insertBefore(rl(S.ref,{readonly:!0,render:o}),x),h=x}}},iL=(e,t,n)=>{if(e.length===0)return null;try{let o=M("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,d)=>{let p=M("img");p.alt=l.alt?.trim()||`Attached image ${d+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${bm}px`,p.style.maxHeight=`${pw}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,p.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),p.remove(),r===0&&a())}),p.addEventListener("load",()=>{u=!0}),J0(l.image)?(p.src=l.image,o.appendChild(p)):(u=!0,r=Math.max(0,r-1),p.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},aL=e=>{if(e.length===0)return null;try{let t=M("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!ym(o.audio))return;let r=M("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${bm}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},lL=e=>{if(e.length===0)return null;try{let t=M("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!ym(o.video))return;let r=M("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${bm}px`,r.style.maxHeight=`${pw}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},cL=e=>{if(e.length===0)return null;try{let t=M("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!ym(o.data))return;let r=M("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",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},$i=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="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",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},uw=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:$i};if(t){let r=t(o);if(r!==null)return r}return $i()},dL=(e,t)=>{let n=M("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=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=M("img");r.src=o,r.alt=t==="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(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},cw=(e,t,n="div")=>{let o=M(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},bl=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="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"),e==="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"),e==="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},dw={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},pL=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=dw[n??"bubble"]??dw.bubble;o.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},Nd="custom:",uL=e=>`${Nd}${e}`,gw=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),mw=(e,t,n,o)=>{let r=t.showCopy??!0,s=t.showUpvote??!0,a=t.showDownvote??!0,l=t.showReadAloud??!1,d=(t.showRegenerate??!1)&&o?.canRegenerate===!0,p=(t.showEdit??!1)&&o?.canEdit===!0,u=(t.showQuote??!1)&&o?.canQuote!==!1,m=gw(t,e.role);if(!r&&!s&&!a&&!l&&!d&&!p&&!u&&m.length===0){let $=M("div");return $.style.display="none",$.id=`actions-${e.id}`,$.setAttribute("data-actions-for",e.id),$}let y=t.visibility??"hover",h=t.align??"right",C=t.layout??"pill-inside",S={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],x={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[C],P=M("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${S} ${x} ${y==="hover"?"persona-message-actions-hover":""}`);P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id);let O=($,T,R)=>{let A=qn({icon:$,label:T,size:14,className:"persona-message-action-btn",chromeless:!0});return A.setAttribute("data-action",R),A};r&&P.appendChild(O("copy","Copy message","copy")),l&&P.appendChild(O("volume-2","Read aloud","read-aloud")),s&&P.appendChild(O("thumbs-up","Upvote","upvote")),a&&P.appendChild(O("thumbs-down","Downvote","downvote")),d&&P.appendChild(O("refresh-cw","Regenerate response","regenerate")),p&&P.appendChild(O("pencil","Edit message","edit")),u&&P.appendChild(O("quote","Quote message","quote"));for(let $ of m)P.appendChild(O($.iconName??"ellipsis",$.label,uL($.id)));return P},vl=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",d=a.avatar,p=a.timestamp,u=d?.show??!1,m=p?.show??!1,y=d?.position??"left",h=p?.position??"below",C=bl(e.role,l),S=M("div",C.join(" "));S.id=`bubble-${e.id}`,S.setAttribute("data-message-id",e.id),S.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let x=s?.widgetConfig?.theme?.components?.message;pL(S,e.role,l,e.role==="user"?x?.user:x?.assistant),l==="flat"?(S.style.backgroundColor="transparent",S.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(S.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",S.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(S.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",S.style.color="var(--persona-message-assistant-text, var(--persona-text))");let P=Z0(e),O=e.content?.trim()??"",T=P.length>0&&O===Ti,R=Rd(s?.widgetConfig?.features?.streamAnimation),A=s?.widgetConfig?.features?.streamAnimation?.plugins,N=e.role==="assistant"&&R.type!=="none"?dl(R.type,A):null,G=e.role==="assistant"&&N?.isAnimating?.(e)===!0,ae=e.role==="assistant"&&N!==null&&(!!e.streaming||G);ae&&N?.bubbleClass&&S.classList.add(N.bubbleClass);let Y=document.createElement("div");Y.classList.add("persona-message-content"),e.streaming&&Y.classList.add("persona-content-streaming"),ae&&N&&(N.containerClass&&Y.classList.add(N.containerClass),Y.style.setProperty("--persona-stream-step",`${R.speed}ms`),Y.style.setProperty("--persona-stream-duration",`${R.duration}ms`));let E=ae?Wd(e.content??"",R.buffer,N,e,!!e.streaming):e.content??"",B=()=>{let be=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent});return ae&&N?.wrap==="char"?pl(be,"char",e.id,{skipTags:N.skipTags}):ae&&N?.wrap==="word"?pl(be,"word",e.id,{skipTags:N.skipTags}):be},H=null;if(T?(H=document.createElement("div"),H.innerHTML=B(),H.style.display="none",Y.appendChild(H)):e.contentSegments?.length?sL(Y,e.contentSegments,be=>t({text:be,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):Y.innerHTML=B(),ae&&N?.useCaret&&!T&&O){let be=Od(),j=Y.querySelectorAll(".persona-stream-char, .persona-stream-word"),_e=j[j.length-1];if(_e?.parentNode)_e.parentNode.insertBefore(be,_e.nextSibling);else{let Fe=Y.lastElementChild;Fe?Fe.appendChild(be):Y.appendChild(be)}}if(m&&h==="inline"&&e.createdAt){let be=cw(e,p,"span");be.classList.add("persona-timestamp-inline");let j=Y.lastElementChild;j?j.appendChild(be):Y.appendChild(be)}if(P.length>0){let be=iL(P,!T&&!!O,()=>{T&&H&&(H.style.display="")});be?S.appendChild(be):T&&H&&(H.style.display="")}let L=eL(e);if(L.length>0){let be=aL(L);be&&S.appendChild(be)}let ee=tL(e);if(ee.length>0){let be=lL(ee);be&&S.appendChild(be)}let K=nL(e);if(K.length>0){let be=cL(K);be&&S.appendChild(be)}let ue=e.contentSegments?.length?null:oL(e.contextMentions);if(ue&&S.appendChild(ue),S.appendChild(Y),m&&h==="below"&&e.createdAt){let be=cw(e,p);be.classList.add("persona-mt-1"),S.appendChild(be)}let le=e.role==="assistant"?Q0(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let be=!!(E&&E.trim()),j=R.placeholder==="skeleton",_e=j&&R.buffer==="line"&&be;if(be)_e&&S.appendChild(ul());else if(j)S.appendChild(ul());else{let Fe=uw("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);Fe&&S.appendChild(Fe)}}le&&e.stopReason&&!e.streaming&&(O||(Y.style.display="none"),S.appendChild(X0(e.stopReason,le)));let me=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1,Re=s?.actionEligibility,He=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Re?.canEdit===!0||o?.showQuote===!0&&Re?.canQuote===!0||gw(o,"user").length>0);if((me||He)&&o){let be=mw(e,He?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Re);S.appendChild(be)}if(!u||e.role==="system")return S;let ve=M("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ge=dL(d,e.role);return y==="right"||y==="left"&&e.role==="user"?ve.append(S,Ge):ve.append(Ge,S),ve},gL=(e,t,n,o,r,s)=>{let a=n??{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):vl(e,t,n,o,r,s)};var mL=40,fL=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=pe(t.name,mL);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(Q("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Q("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},fw=(e,t,n={})=>{let o=Q("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=M("p","persona-welcome-kicker");r.hidden=!0;let s=M("h2","persona-welcome-title"),a=M("p","persona-welcome-subtitle"),l=Q("div",{className:"persona-welcome-head-text"},r,s),d=Q("div",{className:"persona-welcome-title-row"},o,l);return{host:Q("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},d,a,t),iconHolder:o,kicker:r,title:s,subtitle:a,starterSuggestions:t}},Ui=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},$d=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",fL(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},hL="data-persona-welcome-plugin",hw="data-persona-welcome-overlay",Fd="persona-welcome-overlay-active",vm=new WeakMap,Cm=(e,t,n)=>{n.setAttribute(hL,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(hw,""),e.classList.contains(Fd)||(vm.set(e,e.scrollTop),e.classList.add(Fd),e.scrollTop=0)},wm=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(hw),e.classList.contains(Fd)&&(e.classList.remove(Fd),e.scrollTop=vm.get(e)??e.scrollTop,vm.delete(e))},yw=()=>{let e=Q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Ud=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Q("div",{className:bl("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(Q("div",{className:"persona-flex"},r)),e.hidden=!1},bw=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,vw=(e,t)=>{if(bw()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,a=0;if(o){let C=getComputedStyle(o);r=parseFloat(C.rowGap)||0;let S=e.previousElementSibling,x=e.nextElementSibling,O=o.getBoundingClientRect().top+(parseFloat(C.borderTopWidth)||0)+(parseFloat(C.paddingTop)||0)-o.scrollTop;s=Math.max(0,S?n.top-S.getBoundingClientRect().bottom-r:n.top-O),a=Math.max(0,x?x.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let d=getComputedStyle(e),p=parseFloat(d.paddingTop)||0,u=parseFloat(d.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${u}px`,marginTop:`${s}px`,marginBottom:`${a}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),y=!1,h=()=>{y||(y=!0,e.style.overflow=l,t(m))};return m.finished.then(h).catch(h),m},Cw=(e,t,n)=>{if(t<=1||bw()||typeof e.animate!="function"||!e.isConnected)return null;let o=n==="drop"?-t:t;return e.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var yL="Hello \u{1F44B}",bL="I can answer questions and help you get things done here.",ww=new WeakSet,bn=(e,t)=>!!e&&e[t]!==void 0,vL=(e,t)=>{!e||e.debug!==!0||!t.length||ww.has(e)||(ww.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},No=e=>{let t=e?.welcome,n=e?.copy,o=bn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":bn(t,"dismiss")?t.dismiss:"never",s=[];bn(t,"title")&&bn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),bn(t,"subtitle")&&bn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),bn(t,"variant")&&bn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&bn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&bn(t,"dismiss")&&t.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let a=t?.anchor==="center"?"center":"bottom",l=il(t?.anchorComposerTop)!==null;return bn(t,"anchorComposerTop")&&!l&&s.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),a!=="center"&&(bn(t,"anchorComposerTop")||bn(t,"composerGap"))&&s.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),vL(e,s),{title:bn(t,"title")?t.title:n?.welcomeTitle??yL,kicker:t?.kicker??"",subtitle:bn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??bL,icon:t?.icon,align:t?.align==="start"||t?.align==="center"?t.align:void 0,iconPlacement:t?.icon&&typeof t.icon!="function"&&t.icon.placement==="inline"?"inline":"above",variant:o,dismiss:r,message:o==="hero"?void 0:t?.message,anchor:a,anchorComposerTop:l?t.anchorComposerTop:"44%",composerGap:t?.composerGap?.trim()||Td}},xw=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Ds=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var Sw="16px",Sm="10px",Am="14px",Aw=e=>{let t=e?.launcher?.enabled??!0,n=Tt(e);if(zr(e)){let u=e?.launcher?.composerBar??{},m=M("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=u.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??sn);let y=M("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",m.appendChild(y);let h=M("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=u.expandedSize??"anchored",h.style.zIndex=String(e?.launcher?.zIndex??sn),{wrapper:m,panel:y,pillRoot:h}}if(n){let u=M("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=M("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return u.appendChild(m),{wrapper:u,panel:m}}if(!t){let u=M("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=M("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=e?.launcher?.width??"100%";return u.style.width=y,m.style.width="100%",u.appendChild(m),{wrapper:u,panel:m}}let r=e?.launcher??{},s=r.position&&jn[r.position]?jn[r.position]:jn["bottom-right"],a=M("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??sn);let l=M("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=e?.launcher?.width??e?.launcherWidth??oo;return l.style.width=p,l.style.maxWidth=p,a.appendChild(l),{wrapper:a,panel:l}},Mm=e=>{let t=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":dm(e)}});return t.hidden=!0,t},Mw=(e,t)=>{let n=Mm("starter"),o=fw(e,n,{flatShadow:Tt(e)}),r=No(e);$d(o,r),Ui(t,o.host,Ds(r,e?.initialMessages));let s=yw();return Ud(s,r.message,e),{welcome:o,greetingHost:s}},CL=(e,t)=>{let n=M("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}=Bi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:Sw,iconSize:Sm});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let N=_i(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Sw,iconSize:Am});a=N.button,l=N.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=Q("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Q("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"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=Mw(e,p),{host:y,title:h,subtitle:C}=u,S=u.starterSuggestions,x=M("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),P=Mm("followUp"),O=jr(e,!0);O&&(x.style.maxWidth=O,x.style.marginLeft="auto",x.style.marginRight="auto",x.style.width="100%"),p.append(y,m,x,P);let $=Q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),T=Dd({config:e}),{root:R,textNode:A}=iw();return n.append(d,r,p,$),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:x,starterSuggestions:S,transcriptSuggestions:P,composerOverlay:$,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:y,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:h,introSubtitle:C,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:M("span"),headerTitle:M("span"),headerSubtitle:M("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:R,peekTextNode:A}},Ew=(e,t=!0)=>{if(zr(e))return CL(e,t);let n=Q("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=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?yl(e,o,{showClose:t}):Vr({config:e,showClose:t}),a=Q("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"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=Mw(e,a),{host:p,title:u,subtitle:m}=l,y=l.starterSuggestions,h=M("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),C=Mm("followUp"),S=jr(e,!1);S&&(h.style.maxWidth=S,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),a.append(p,d,h,C);let x=Fi({config:e}),P=e?.layout?.showFooter!==!1;r?Di(n,s,e):(s.header.style.display="none",Di(n,s,e)),n.append(a);let O=Q("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return P||(x.footer.style.display="none"),n.append(x.footer),n.append(O),{container:n,body:a,messagesWrapper:h,starterSuggestions:y,transcriptSuggestions:C,composerOverlay:O,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:d,introKicker:l.kicker,introTitle:u,introSubtitle:m,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:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions,setSendButtonMode:x.setSendButtonMode}};var Em=(e,t)=>{let n=M("button");n.type="button",n.innerHTML=`
22
+ `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,d=r.contentParts.length>0;if(l){let p=[];s&&p.push(mo(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(d){let p=[];a&&p.push(mo(a)),p.push(...r.contentParts),t.contentParts=p}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim(),r=!!n?.replayFields&&(n.replayFields.llmContent!==void 0||n.replayFields.rawContent!==void 0||(n.replayFields.contextMentions?.length??0)>0);if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0)&&!r)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let s=_a(),a=As();this.activeAssistantMessageId=null;let l=n?.contentParts&&za(n.contentParts)?wi:"",d={id:s,role:"user",content:o||l,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},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(d),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let m=this.messages.find(y=>y.id===s)??d;if(await this.applyMentionBundle(m,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(h=>h.id===s)??d,y=bv({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});y.contentParts&&(m.contentParts=y.contentParts),y.llmContent!==void 0&&(m.llmContent=y.llmContent),(y.contentParts||y.llmContent!==void 0)&&(m.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,p,a,s,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let y=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!y){let h=Lg(m,this.config.errorMessage);if(h){let v={id:a,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(v)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,y||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(t,n){let o=vv(this.messages,t);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,a=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!a?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},u=s?this.toComposerOptionsPayload(s.options):r.composerOptions,m=s?s.contentSegments:r.contentSegments,y=s?s.options?.quote:void 0,h=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(a??"",{...l?.length?{contentParts:[...l]}:{},...m?.length?{contentSegments:[...m]}:{},...u?{composerOptions:u}:{},...y?{quote:y}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:h===!0}),!0}toComposerOptionsPayload(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=As();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:t},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 a=Lg(r,this.config.errorMessage);if(a){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,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(t,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(t,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 t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.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(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(u=>u.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,p=d&&typeof d=="object"?d.onDecision:void 0;try{let u;if(p?u=await p({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):u=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let y=await u.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(u=>u.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let u=t.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let y=typeof m[0]?.question=="string"?m[0].question:"";y&&(a={[y]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,d=t.toolCall?.args,p=Array.isArray(d?.questions)?d.questions:[];if(p.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=a??{};p.forEach((m,y)=>{let h=typeof m?.question=="string"?m.question:"";if(!h)return;let v=u[h],x=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${y}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${y}`,role:"user",content:x||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});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(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==ir?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let s=async d=>{let p=d.toolCall?.name,u=d.toolCall?.id;if(!p||!u)return null;let m=`${t}:${u}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(m),o.push(m);let y=this.markWebMcpToolRunning(d),h=d.agentMetadata?.webMcpToolCallId??p;if(p===ir)return{dedupeKey:m,resumeKey:h,output:qb(),toolMessage:d,startedAt:y,completedAt:Date.now()};let v=this.client.executeWebMcpToolCall(p,d.toolCall?.args,r.signal),x;if(!v)x={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{x=await v}catch(w){let k=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));return k||this.callbacks.onError?.(w instanceof Error?w:new Error(String(w))),this.markWebMcpToolComplete(d,Ig(k?"Aborted by cancel()":hk(w)),y),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,Ig("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:h,output:x,toolMessage:d,startedAt:y,completedAt:Date.now()}},a;if(this.config.webmcp?.execution==="sequential"){a=[];for(let d of n)a.push(await s(d))}else a=await Promise.all(n.map(s));let l=[];try{if(l=a.filter(u=>u!==null),l.length===0)return;let d={};for(let u of l)d[u.resumeKey]=u.output;let p=await this.client.resumeFlow(t,d,{signal:r.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!p.ok){let u=await p.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${p.status}`)}for(let u of l)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt,u.toolMessage.toolCall?.name===ir?{suggestRepliesResolved:!0}:void 0);p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,Ig("Aborted by cancel()"),u.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let a=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(a)}catch(l){this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{this.webMcpInflightKeys.delete(a)}return}let s=`${n}:${r}`;if(!(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t)))return this.resolveWebMcpToolCallBatch(n,[t])}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.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 t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"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(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=sr(this.config.features?.artifacts,t),r=Ba(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.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 t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=sr(this.config.features?.artifacts,n),s=Ba(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",t=!0)}t&&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(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,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(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.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(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Tv().then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n}),this.reconnectControllerPromise.catch(()=>{this.reconnectControllerPromise=null})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>Lg(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=As(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];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 t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){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(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.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=Tg(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ga(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Tg(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),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 a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let u=r.approval,m=n.approval;a.approval={...u,...m,executionId:m.executionId||u.executionId,toolName:m.toolName||u.toolName,description:m.description||u.description,toolType:m.toolType??u.toolType,reason:m.reason??u.reason,parameters:m.parameters??u.parameters}}let l=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(l&&Pv(l)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let u=`${d}:${p}`,m=this.webMcpInflightKeys.has(u),y=this.webMcpResolvedKeys.has(u),h=r.toolCall?.name,v=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&h!==void 0&&Pv(h)&&r.toolCall?.status==="complete";(m||y||v)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,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 a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};import{File as yk,FileCode as bk,FileSpreadsheet as vk,FileText as Rg,X as Ck}from"lucide";var wk={add:e=>ov(e)},xk=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,rd={allowedTypes:ar,maxFileSize:10*1024*1024,maxFiles:4};function Sk(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ak(e){return e==="application/pdf"?Rg:e.startsWith("text/")?Rg:e.includes("word")?Rg:e.includes("excel")||e.includes("spreadsheet")?vk:e==="application/json"?bk:yk}var Mi=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??rd.allowedTypes,maxFileSize:t.maxFileSize??rd.maxFileSize,maxFiles:t.maxFiles??rd.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:wk}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:rd.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.destroyed)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=rv(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let a=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,a);continue}let s={id:Sk(),file:o,previewUrl:Zc(o)?URL.createObjectURL(o):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(s),this.renderPreview(s),n.push(s)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(n.map(o=>this.runAdd(o)))}async runAdd(t){let n=new AbortController;this.pendingAdds.set(t.id,n);let o=()=>this.destroyed||n.signal.aborted||this.pendingAdds.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.adapter().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=xk(s),this.updatePreview(t),this.notify())}});if(o())return;t.contentPart=r,t.status="ready",t.progress=void 0,t.error=void 0}catch(r){if(o())return;t.status="error",t.progress=void 0,t.error=r instanceof Error?r.message:String(r??"Upload failed")}finally{this.pendingAdds.get(t.id)===n&&this.pendingAdds.delete(t.id)}this.updatePreview(t),this.notify()}retryAttachment(t){let n=this.attachments.find(o=>o.id===t);!n||n.status!=="error"||this.destroyed||(n.status=this.hasCustomAdapter()?"uploading":"processing",n.progress=this.hasCustomAdapter()?0:void 0,n.error=void 0,this.updatePreview(n),this.notify(),this.runAdd(n))}abortAdd(t){let n=this.pendingAdds.get(t);n&&(this.pendingAdds.delete(t),n.abort())}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];this.abortAdd(t),o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),o.status==="ready"&&o.contentPart&&this.releasePart(o.contentPart),this.updatePreviewsVisibility(),this.notify()}releasePart(t){let n=this.config.adapter?.remove;if(n)try{let o=n(t,{signal:new AbortController().signal});o&&typeof o.catch=="function"&&o.catch(r=>{console.error("[AttachmentManager] adapter.remove failed:",r)})}catch(o){console.error("[AttachmentManager] adapter.remove failed:",o)}}clearAttachments(){for(let t of this.attachments)this.abortAdd(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.pendingAdds.clear(),this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.notify()}destroy(){if(!this.destroyed){this.destroyed=!0;for(let t of this.pendingAdds.values())t.abort();this.pendingAdds.clear();for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer=null}}notify(){this.destroyed||this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Zc(t.file),o=E("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let u=E("img");u.src=t.previewUrl,u.alt=t.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=E("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=Ak(t.file.type),y=It(m,20,"var(--persona-muted, #6b7280)",1.5);y&&u.appendChild(y);let h=E("span");h.textContent=sv(t.file.type,t.file.name),h.style.fontSize="8px",h.style.fontWeight="600",h.style.color="var(--persona-muted, #6b7280)",h.style.textTransform="uppercase",h.style.lineHeight="1",u.appendChild(h),o.appendChild(u)}let r=G("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=E("div","persona-attachment-progress");s.appendChild(E("div","persona-attachment-progress__bar"));let a=G("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=le("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?a.appendChild(l):a.textContent="\u21BB",a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,a),o.appendChild(r);let d=E("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let p=It(Ck,10,"var(--persona-text-inverse, #ffffff)",2);p?d.appendChild(p):(d.textContent="\xD7",d.style.color="var(--persona-text-inverse, #ffffff)",d.style.fontSize="14px",d.style.lineHeight="1"),d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(d),this.previewsContainer.appendChild(o),this.applyPreviewState(o,t)}updatePreview(t){let n=this.previewsContainer?.querySelector(`[data-attachment-id="${t.id}"]`);n&&this.applyPreviewState(n,t)}applyPreviewState(t,n){t.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";t.setAttribute("aria-busy",o?"true":"false"),t.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n,adapter:t?.adapter})}};var kv=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),Mk=(e,t)=>e.length===t.length&&e.every((n,o)=>{let r=t[o];return n.id===r.id&&n.name===r.name&&n.mimeType===r.mimeType&&n.size===r.size&&n.status===r.status&&n.progress===r.progress&&n.error===r.error});function Lv(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,n=null,o=!1,r=!1,s=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",a=()=>{let u=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:u,inputDisabled:e.inputDisabled,sendDisabled:u!=="idle"||e.sendDisabled||e.inputDisabled})},l=()=>(n||(n=a()),n),d=()=>{if(o=!1,r||t.size===0)return;let u=l();for(let m of[...t])try{m(u)}catch(y){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",y)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(d))};return{getState:l,subscribe:u=>(t.add(u),()=>t.delete(u)),setText:u=>{e.text!==u&&(e.text=u,p())},setAttachments:u=>{Mk(e.attachments,u)||(e.attachments=[...u],p())},setMentionRefs:u=>{kv(e.mentionRefs,u)||(e.mentionRefs=[...u],p())},setSelectedModelId:u=>{e.selectedModelId!==u&&(e.selectedModelId=u,p())},setActiveModeIds:u=>{kv(e.activeModeIds,u)||(e.activeModeIds=[...u],p())},setQuote:u=>{let m=e.quote;m?.text===u?.text&&m?.messageId===u?.messageId&&m?.sourceLabel===u?.sourceLabel||(e.quote=u?{...u}:void 0,p())},setPendingSubmission:u=>{e.pendingSubmission!==u&&(e.pendingSubmission=u,p())},setPreparing:u=>{e.preparing!==u&&(e.preparing=u,p())},setStreaming:u=>{e.streaming!==u&&(e.streaming=u,p())},setInputDisabled:u=>{e.inputDisabled!==u&&(e.inputDisabled=u,p())},setSendDisabled:u=>{e.sendDisabled!==u&&(e.sendDisabled=u,p())},flush:()=>{o&&d()},destroy:()=>{r=!0,o=!1,t.clear()}}}var Rn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},Iv=(e,t)=>{let n=E("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function Rv(e,t={}){let n=Rn(e,"[data-persona-composer-form]"),o=Rn(e,"[data-persona-composer-input]");if(!n||!o){let k=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||o))throw new Error(k);return typeof console<"u"&&console.warn(k),null}let r={header:Rn(e,"[data-persona-composer-header]"),body:Rn(e,"[data-persona-composer-body]"),actionsStart:Rn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Rn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Rn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Rn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Rn(e,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=Iv("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(a,n):e.appendChild(a));let l=r.body??o.parentElement??n,d=(w,k,O,D,T)=>{if(k)return k;s.add(w);let I=Iv(O,D);return T.appendChild(I),I},p=d("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=d("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),y=d("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[],v=(w,k)=>w.target===k.target&&w.type===k.type&&w.handler===k.handler,x=Rn(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:a,body:l,actionsStart:p,actionsEnd:u,suggestions:m,status:y,attachmentInput:x,attachmentPreviews:Rn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Rn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Rn(e,"[data-persona-composer-submit]")??void 0,micButton:Rn(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(w,k,O,D)=>{w.addEventListener(k,O,D),h.push({target:w,type:k,handler:O,options:D})},removeListener:(w,k,O,D)=>{w.removeEventListener(k,O,D),h=h.filter(T=>!v(T,{target:w,type:k,handler:O}))},destroy:()=>{for(let w of h)w.target.removeEventListener(w.type,w.handler,w.options);h=[]}}}var qt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},rn=1e5,Ei=rn+1;var Ek=8,Tk=8,Hg=10,Hv=200,Wv=300,Ov=0,id=e=>Math.max(0,e);function Bv(e){e.delayMs!==void 0&&(Hv=id(e.delayMs)),e.skipDelayMs!==void 0&&(Wv=id(e.skipDelayMs))}var Pk=()=>Date.now()<Ov,kk=e=>{Ov=e>0?Date.now()+e:0},sd=new WeakMap,Og="data-persona-tooltip-suppressed",Lk=e=>typeof e.closest=="function"&&e.closest(`[${Og}]`)!==null;function _v(e){sd.get(e)?.hide()}var Dv=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Ik=e=>{let t=e.getRootNode?.();return Dv(t)?t:e.ownerDocument.body},Wg=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),Rk=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function Zt(e){sd.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:a=Ek,viewportPadding:l=Tk}=e,d=()=>t.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,y=null,h=null,v,x=!1,w=!1,k=!1,O=()=>(typeof o=="function"?o():o).trim(),D=()=>(typeof r=="function"?r():r??"").trim(),T=()=>id(e.delayMs??Hv),I=()=>id(e.skipDelayMs??Wv),A=()=>{v!==void 0&&(p().clearTimeout(v),v=void 0)},_=()=>{A();let ge=u!==null;h?.(),h=null,u?.remove(),u=null,m=null,y=null,ge&&kk(I())},K=()=>{if(!u)return;let ge=d(),Ie=p(),ye=t.getBoundingClientRect(),ce=u.getBoundingClientRect(),Je=ge.documentElement.clientWidth||Ie.innerWidth,fe=ge.documentElement.clientHeight||Ie.innerHeight,F=Je-l-ce.width,Oe=ye.left+ye.width/2-ce.width/2,Ue=Wg(Oe,l,F),Bt=ye.top-l,be=fe-l-ye.bottom,Be=ce.height+a,ve=Bt>=Be||Bt>=be?"top":"bottom",xe=ve==="top"?ye.top-a-ce.height:ye.bottom+a,bt=fe-l-ce.height,Rt=Wg(xe,l,bt),ut=ye.left+ye.width/2,vn=Math.max(Hg,ce.width-Hg),q=Wg(ut-Ue,Hg,vn);u.dataset.placement=ve,u.style.left=`${Ue}px`,u.style.top=`${Rt}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${q}px`)},ie=()=>{if(k||!s||u||!t.isConnected||Lk(t))return;let ge=O(),Ie=Ik(t);if(!ge||!Ie)return;let ye=d(),ce=p();u=ye.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Ei);let Je=ce.getComputedStyle?.(t);if(Je){for(let Be of Rk){let ve=Je.getPropertyValue(Be).trim();ve&&u.style.setProperty(Be,ve)}Je.fontFamily&&(u.style.fontFamily=Je.fontFamily)}m=ye.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ge,u.appendChild(m);let fe=D();fe&&(y=ye.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=fe,u.appendChild(y));let F=ye.createElement("span");F.className="persona-control-tooltip__arrow",u.appendChild(F),Ie.appendChild(u),K(),u.dataset.state="open";let Oe=()=>{if(!t.isConnected){_();return}m&&(m.textContent=O()),y&&(y.textContent=D()),K()};ce.addEventListener("scroll",Oe,!0),ce.addEventListener("resize",Oe);let Ue=t.getRootNode(),Bt=Dv(Ue)?Ue:ye.documentElement,be=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||_()});be?.observe(Bt,{childList:!0,subtree:!0}),h=()=>{ce.removeEventListener("scroll",Oe,!0),ce.removeEventListener("resize",Oe),be?.disconnect()}},Z=ge=>{if(!(k||u)){if(A(),ge||T()<=0||Pk()){ie();return}v=p().setTimeout(()=>{v=void 0,ie()},T())}},M=()=>{x||w?Z(w):_()},B=()=>{let ge=p();(!ge.matchMedia||!ge.matchMedia("(hover: none)").matches)&&(x=!0,M())},H=()=>{x=!1,M()},R=()=>{try{w=t.matches(":focus-visible")}catch{w=!0}M()},J=()=>{w=!1,M()},V=()=>{x=!1,w=!1,_()},pe=ge=>{ge.key==="Escape"&&V()};n.addEventListener("mouseenter",B),n.addEventListener("mouseleave",H),t.addEventListener("focus",R),t.addEventListener("blur",J),t.addEventListener("keydown",pe),t.addEventListener("click",V);let se={get isOpen(){return u!==null},show:ie,hide:_,reposition:K,destroy:()=>{k||(k=!0,_(),n.removeEventListener("mouseenter",B),n.removeEventListener("mouseleave",H),t.removeEventListener("focus",R),t.removeEventListener("blur",J),t.removeEventListener("keydown",pe),t.removeEventListener("click",V),sd.delete(t))}};return sd.set(t,se),se}var Nv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ti(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Nv(s)&&Nv(r)?n[o]=Ti(s,r):n[o]=r}return n}var no="min(440px, calc(100vw - 24px))",Bg="440px",_g="How can I help...",Hk={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:no,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",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",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",tooltip:{delayMs:200,skipDelayMs:300},launcher:Hk,copy:{inputPlaceholder:_g,sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",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",borderWidth:"0px",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"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},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 Fv(e,t){if(!(!e&&!t))return e?t?Ti(e,t):e:t}function Za(e){return e?{...lt,...e,theme:Fv(lt.theme,e.theme),darkTheme:Fv(lt.darkTheme,e.darkTheme),launcher:{...lt.launcher,...e.launcher,dock:{...lt.launcher?.dock,...e.launcher?.dock},clearChat:{...lt.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...lt.tooltip,...e.tooltip},copy:{...lt.copy,...e.copy},sendButton:{...lt.sendButton,...e.sendButton},statusIndicator:{...lt.statusIndicator,...e.statusIndicator},voiceRecognition:{...lt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=lt.features?.artifacts,n=e.features?.artifacts,o=lt.features?.scrollToBottom,r=e.features?.scrollToBottom,s=lt.features?.scrollBehavior,a=e.features?.scrollBehavior,l=lt.features?.streamAnimation,d=e.features?.streamAnimation,p=lt.features?.askUserQuestion,u=e.features?.askUserQuestion,m=lt.features?.history,y=e.features?.history,h=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},v=o===void 0&&r===void 0?void 0:{...o,...r},x=s===void 0&&a===void 0?void 0:{...s,...a},w=l===void 0&&d===void 0?void 0:{...l,...d},k=p===void 0&&u===void 0?void 0:{...p,...u,styles:{...p?.styles,...u?.styles}},O=m===void 0&&y===void 0?void 0:{...m,...y,copy:{...m?.copy,...y?.copy}};return{...lt.features,...e.features,...v!==void 0?{scrollToBottom:v}:{},...x!==void 0?{scrollBehavior:x}:{},...h!==void 0?{artifacts:h}:{},...w!==void 0?{streamAnimation:w}:{},...k!==void 0?{askUserQuestion:k}:{},...O!==void 0?{history:O}:{}}})(),suggestionChips:e.suggestionChips??lt.suggestionChips,suggestionChipsConfig:{...lt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...lt.layout,...e.layout,header:{...lt.layout?.header,...e.layout?.header},messages:{...lt.layout?.messages,...e.layout?.messages,avatar:{...lt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...lt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...lt.layout?.slots,...e.layout?.slots}},markdown:{...lt.markdown,...e.markdown,options:{...lt.markdown?.options,...e.markdown?.options}},messageActions:{...lt.messageActions,...e.messageActions}}:lt}function Dg(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function ad(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function $v(e,t){e.style.maxHeight=`${t*Dg(e)}px`,e.style.overflowY="auto"}function el(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function Uv(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function jv(e,t){if(e.key!=="Enter"||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,o=t.submitKey??"enter";return o==="none"?!1:o==="mod-enter"?n:n||!Uv(t)}function Wk(e){return(e.submitKey??"enter")!=="enter"||Uv(e)?"enter":"send"}function ld(e,t){e.setAttribute("enterkeyhint",Wk(t))}function cd(e,t){let n=t?.autocomplete;e.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?e.removeAttribute(r):e.setAttribute(r,s)};o("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),o("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),o("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),o("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function Ng(e){return e===!0?{disabled:!0}:!e||typeof e!="object"?{disabled:!1}:{disabled:!0,reason:typeof e.reason=="string"&&e.reason?e.reason:void 0}}var jn="persona-composer-control",ho="persona-composer-control--glyph",$g=40,mn=24,dd=(e,t,n)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(e);for(let s of n){let a=r.getPropertyValue(s).trim();a?t.style.setProperty(s,a):t.style.removeProperty(s)}},pd=(e,t)=>{let n=E("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??_g,n.dir="auto",ld(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:el(n)}),cd(n,e?.composer?.inputAttributes),n.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",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=ad(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let s=()=>{let l=n.style.maxHeight;if(l!==r){let p=parseFloat(l);if(Number.isFinite(p)&&p>0)return p}let d=o*Dg(n);return r=`${d}px`,n.style.maxHeight=r,d},a=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,s());n.style.height=`${l}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:a}},Bk="[data-persona-glyph-stack]",Ug=(e,t,n="send")=>{let o=G("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),o.append(e,t),o},ud=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",d=e?.copy?.sendButtonLabel??"Send",p=e?.copy?.stopButtonLabel??"Stop",u=t.showTooltip??!1,m=t.size,y=parseFloat(m??"")||$g,h=t.backgroundColor,v=t.textColor,x=E("div","persona-send-button-wrapper"),w=G("button",{className:gn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${jn}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!v&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?v||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":v||void 0,backgroundColor:n&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),k=null,O=null,D=null;if(n){let A=parseFloat(t.iconSize??"")||Math.round(y*.5),_=t.iconStrokeWidth??2,K=v?.trim()||"currentColor";r&&(k=le(r,A,K,_)),O=le(s,A,K,_),k&&O?(D=Ug(k,O),w.appendChild(D)):k?w.appendChild(k):(w.textContent=o,O=null)}else w.textContent=d;w.setAttribute("aria-label",a),x.appendChild(w),Zt({anchor:w,trigger:x,text:()=>w.getAttribute("aria-label")??"",enabled:u});let T="send";return{button:w,wrapper:x,setMode:A=>{if(A===T)return;T=A;let _=A==="stop"?l:a;w.setAttribute("aria-label",_),w.setAttribute("data-persona-send-mode",A),n?(w.querySelector(Bk)??D)?.setAttribute("data-mode",A):w.textContent=A==="stop"?p:d},glyphStack:D}},Pi=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",s=t.provider?.type==="custom";if(!(o||r||s))return null;let l=t.iconName??"mic",d=t.iconSize,p=parseFloat(d??"")||mn,u=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,y=E("div","persona-send-button-wrapper"),h=G("button",{className:gn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",jn,!d&&ho),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),x=le(l,p,m||"currentColor",1.5);x?h.appendChild(x):h.textContent="\u{1F3A4}",y.appendChild(h);let w=t.tooltipText??"Start voice recognition",k=t.showTooltip??!1;return Zt({anchor:h,trigger:y,text:()=>h.getAttribute("aria-label")??w,enabled:k}),{button:h,wrapper:y}},gd=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=E("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=E("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??ar).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=E("div","persona-send-button-wrapper"),a=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${jn} ${ho}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=le(r,mn,"currentColor",1.5);l?a.appendChild(l):a.textContent="\u{1F4CE}",a.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(a);let d=t.buttonTooltipText??"Attach file";return Zt({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},md=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=E("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=E("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},fd=()=>G("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function _k(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function hd(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:d=2147483e3,onOpen:p,onDismiss:u}=e,m=e.container??_k(t),y=!1,h=null,v=()=>{if(!y)return;let k=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${k.width}px`),a&&(n.style.maxWidth=`${k.width}px`);let O=n.getBoundingClientRect(),D=l?.()??null,T=D!=null?k.top+D:k.top,I=o==="top-start"||o==="top-end"?T-r-O.height:k.bottom+r,_=o==="bottom-end"||o==="top-end"?k.right-O.width:k.left,K=a?.()??null;if(K!=null){let ie=Math.max(k.left,k.right-O.width);_=Math.min(Math.max(k.left+K,k.left),ie)}n.style.top=`${I}px`,n.style.left=`${_}px`},x=()=>{y&&(y=!1,h&&(h(),h=null),n.remove())},w=()=>{if(y)return;y=!0,d!=null&&(n.style.zIndex=String(d)),m.appendChild(n),v();let k=(t.ownerDocument??document).defaultView??window,O=t.ownerDocument??document,D=()=>{if(!t.isConnected){x(),u?.("anchor-removed");return}v()},T=A=>{let _=typeof A.composedPath=="function"?A.composedPath():[];_.includes(n)||_.includes(t)||(x(),u?.("outside"))},I=k.setTimeout(()=>{O.addEventListener("pointerdown",T,!0)},0);k.addEventListener("scroll",D,!0),k.addEventListener("resize",D),h=()=>{k.clearTimeout(I),O.removeEventListener("pointerdown",T,!0),k.removeEventListener("scroll",D,!0),k.removeEventListener("resize",D)},p?.()};return{get isOpen(){return y},open:w,close:x,toggle:()=>y?x():w(),reposition:v,destroy:x}}var Dk='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',Nk=["--persona-components-composer-overflowMenu-background","--persona-components-composer-overflowMenu-borderColor","--persona-components-composer-overflowMenu-borderRadius","--persona-components-composer-overflowMenu-foreground","--persona-components-composer-overflowMenu-shadow"],jg="data-persona-menu-focus",Fk=new Set(["ArrowDown","ArrowUp","Home","End"]);function qv(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(Dk)??e}var $k=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function zv(e){let t=e.label,n=!1,o=E("div","persona-send-button-wrapper"),r=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${jn} ${ho}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=G("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let R=e.getButtonSize?.()??"";r.style.width=R,r.style.height=R,r.style.minWidth=R,r.style.minHeight=R,r.style.lineHeight="1",r.replaceChildren();let J=le("plus",mn,"currentColor",1.5);J?r.appendChild(J):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),a();let d=[],p=-1,u=!1,m=()=>{let J=s.getRootNode().activeElement;return J instanceof HTMLElement?J:null},y=()=>{let R=m();for(let J of d){let V=!!R&&qv(J)===R;J.toggleAttribute(jg,V&&u)}},h=()=>d.filter(R=>R.isConnected||s.contains(R)).map(qv).filter(R=>!$k(R)),v=(R,J)=>{R.forEach((V,pe)=>{V.setAttribute("tabindex",pe===J?"0":"-1")})},x=R=>{let J=h();if(J.length===0)return;let V=(R%J.length+J.length)%J.length;p=V,v(J,V),J[V].focus(),y()},w=()=>o.ownerDocument??document,k=null,O=null,D=null,T=()=>{k&&(w().removeEventListener("focusin",k,!0),k=null)},I=()=>{O&&(s.removeEventListener("focusin",O),O=null),D&&(s.removeEventListener("pointerdown",D,!0),D=null)},A=null,_=()=>(A||(A=hd({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),T()}})),A),K=()=>A?.isOpen===!0,ie=(R=!1)=>{if(K()){A?.close(),r.setAttribute("aria-expanded","false"),T(),I(),p=-1,u=!1;for(let J of d)J.removeAttribute(jg);R&&r.focus()}},Z=(R=0,J=!1)=>{if(n||K())return;u=J,dd(r,s,Nk),_().open(),r.setAttribute("aria-expanded","true");let V=h();v(V,-1),x(R<0?V.length-1:R),k=pe=>{let se=typeof pe.composedPath=="function"?pe.composedPath():[];se.includes(s)||se.includes(o)||ie()},w().addEventListener("focusin",k,!0),O=()=>y(),s.addEventListener("focusin",O),D=()=>{u=!1},s.addEventListener("pointerdown",D,!0)},M=R=>{R.preventDefault(),R.stopPropagation(),K()?ie(!0):Z(0)},B=R=>{if(R.key==="ArrowDown"||R.key==="Enter"||R.key===" "){R.preventDefault(),u=!0,K()?x(0):Z(0,!0);return}R.key==="ArrowUp"&&(R.preventDefault(),u=!0,K()?x(-1):Z(-1,!0))},H=R=>{switch(Fk.has(R.key)&&(u=!0),R.key){case"ArrowDown":R.preventDefault(),x(p+1);return;case"ArrowUp":R.preventDefault(),x(p-1);return;case"Home":R.preventDefault(),x(0);return;case"End":R.preventDefault(),x(h().length-1);return;case"Escape":R.preventDefault(),R.stopPropagation(),ie(!0);return;case"Tab":ie(!0);return;default:}};return r.addEventListener("click",M),r.addEventListener("keydown",B),s.addEventListener("keydown",H),{trigger:o,triggerButton:r,panel:s,setItems:R=>{for(let V of d)R.includes(V)||V.removeAttribute(jg);if(d=[...R],!K())return;let J=h();v(J,Math.min(p,J.length-1)),y()},isOpen:K,open:()=>Z(0),close:ie,setLabel:R=>{R!==t&&(t=R,l())},applyButtonSize:a,destroy:()=>{n=!0,T(),I(),r.removeEventListener("click",M),r.removeEventListener("keydown",B),s.removeEventListener("keydown",H),A?.destroy(),A=null,o.remove(),s.remove(),d=[]}}}var Wo={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Vv="data-persona-composer-action",qg="data-persona-composer-disable-when-streaming",Uk="core:overflow",jk=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function qk(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let o=E("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function zg(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let o=n.getComputedStyle(e),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,t-r)}var Kv=(e,t)=>{!e||typeof console>"u"||console.warn(t)},zk=(e,t)=>t.includes(":")?t:`${e}:${t}`;function Vk(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){Kv(t,`[Persona] composer action "${l.id}" is already contributed by ${Gv(d)}; the ${Gv(l)} copy is ignored.`);return}o.set(l.id,l),n.push(l)};for(let l of e.builtIns)s({id:l.id,placement:l.placement,presentation:"bar",order:l.order,sequence:r++,source:"core",builtIn:l});let a=(l,d,p)=>{let u=p?zk(p,l.id):l.id,m=l.order??Wo.custom;l.placement==="end"&&m>=Wo.send&&(Kv(t,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${Wo.send-1}.`),m=Wo.send-1),s({id:u,placement:l.placement,presentation:l.presentation??"bar",order:m,sequence:r++,source:d,pluginId:p,action:l})};for(let l of e.configActions??[])a(l,"config");for(let l of e.plugins){if(!l.contributeComposerActions)continue;let d;try{d=l.contributeComposerActions(e.contributionContext)}catch(p){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,p);continue}for(let p of d??[])a(p,"plugin",l.id)}return n.sort((l,d)=>l.order===d.order?l.sequence-d.sequence:l.order-d.order)}var Gv=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",Yv=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,Kk=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function Gk(e,t){if(!e||e==="always")return!0;let n=Kk(t);return e==="when-text"?n:!n}var _r=e=>e.kind==="custom",Vg=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,Yk=e=>{let t=Vg(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},Qk='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Xk(e){let t="",n=o=>{if(o.nodeType===Node.TEXT_NODE){t+=o.nodeValue??"";return}if(o.nodeType!==Node.ELEMENT_NODE)return;let r=o;typeof r.matches=="function"&&r.matches(Qk)||o.childNodes.forEach(n)};return n(e),t.trim()}var Jk=e=>Xk(e).length===0;function Qv(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(M,B)=>{let H=M.button;if(!H)return;H.setAttribute("role","menuitem"),H.setAttribute("tabindex","-1"),H.className="persona-composer-overflow-menu__item";for(let V of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])H.style[V]="";H.style.lineHeight="1",B.tooltipText?H.setAttribute("title",B.tooltipText):H.removeAttribute("title"),H.replaceChildren();let R=E("span","persona-composer-overflow-menu__icon");if(B.iconName){let V=le(B.iconName,16,"currentColor",1.5);V&&R.appendChild(V)}let J=E("span","persona-composer-overflow-menu__label");J.textContent=B.shortLabel??B.label,H.append(R,J)},a=(M,B)=>{let H=M.button;if(!H)return;if(H.setAttribute("aria-label",B.label),B.pressed===void 0?H.removeAttribute("aria-pressed"):H.setAttribute("aria-pressed",B.pressed?"true":"false"),H.toggleAttribute(qg,B.disableWhenStreaming===!0),M.mode==="menu"){M.tooltip?.destroy(),M.tooltip=void 0,s(M,B);return}H.removeAttribute("role"),H.removeAttribute("tabindex"),H.removeAttribute("title");let R=r(),J=!!B.shortLabel;if(H.className=gn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",jn,ho,J&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),H.style.width=R&&!J?R:"",H.style.height=R??"",H.style.minWidth=R&&!J?R:"",H.style.minHeight=R??"",H.style.fontSize=J?"":"18px",H.style.lineHeight="1",H.style.color=B.iconColor??"",H.style.backgroundColor=B.backgroundColor??"",H.replaceChildren(),B.iconName){let V=le(B.iconName,mn,"currentColor",1.5);V&&H.appendChild(V)}if(J){let V=E("span","persona-composer-action-button__label");V.textContent=B.shortLabel,H.appendChild(V)}else H.firstChild||(H.textContent=B.label);M.tooltip?.destroy(),M.tooltip=Zt({anchor:H,trigger:M.element,text:()=>B.tooltipText??B.label,enabled:!!B.tooltipText})},l=(M,B)=>{let H=M.action,R=G("button",{attrs:{type:"button"}}),J=R;if(B==="bar"){let se=E("div","persona-send-button-wrapper");se.appendChild(R),J=se}J.setAttribute(Vv,M.id);let V={resolved:M,element:J,button:R,owned:!0,managed:!0,busy:!1,visible:!0,mode:B},pe=se=>{if(se.preventDefault(),se.stopPropagation(),V.busy||R.disabled)return;let ge=V.resolved.action;V.mode==="menu"&&h?.close(!0);let Ie;try{Ie=ge.onSelect(e.actionContext,se)}catch(ye){e.reportError(ye,{actionId:V.resolved.id});return}!Ie||typeof Ie.then!="function"||(V.busy=!0,R.setAttribute("aria-busy","true"),Ie.catch(ye=>{e.reportError(ye,{actionId:V.resolved.id})}).finally(()=>{V.busy=!1,R.removeAttribute("aria-busy")}))};return R.addEventListener("click",pe),V.detach=()=>R.removeEventListener("click",pe),a(V,H),V},d=M=>{let B=M.action,H;try{H=B.render({...e.actionContext,id:M.id,action:B})}catch(R){return e.reportError(R,{actionId:M.id}),null}return H?.element?(H.element.setAttribute(Vv,M.id),H.element.toggleAttribute(qg,B.disableWhenStreaming===!0),{resolved:M,element:H.element,owned:!0,managed:!0,destroy:H.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(M,B)=>{if(M.builtIn){let R=M.builtIn.element;return R?{resolved:M,element:R,owned:!1,managed:M.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let H=M.action;return H?_r(H)?d(M):l(M,B):null},u=M=>{if(M.detach?.(),M.tooltip?.destroy(),M.detachMenuSlot?.(),M.detachMenuSlot=void 0,M.menuLabel?.remove(),M.menuLabel=void 0,M.menuSlot?.remove(),M.menuSlot=void 0,M.owned){try{M.destroy?.()}catch(B){e.reportError(B,{actionId:M.resolved.id})}M.element.remove()}},m=(M,B)=>{for(let H=0;H<B.length;H++){let R=B[H];if(!R.managed)continue;let J=null;for(let V=H+1;V<B.length;V++){let pe=B[V];if(!pe.managed&&pe.element.parentElement===M){J=pe.element;break}}J?(R.element.parentElement!==M||R.element.nextSibling!==J)&&M.insertBefore(R.element,J):M.lastChild!==R.element&&M.appendChild(R.element)}},y=(M,B)=>{if(M.button){M.button.disabled=B;return}if(!M.owned)return;let H=M.element;H.toggleAttribute("data-disabled",B),H.setAttribute("aria-disabled",B?"true":"false");let R=H instanceof HTMLButtonElement||H instanceof HTMLSelectElement||H instanceof HTMLInputElement||H instanceof HTMLTextAreaElement?H:H.querySelector("button, select, input, textarea");R&&(R.disabled=B)},h=null,v=null,x=null,w=0,k=()=>{let M=e.getOverflow?.();return M?.enabled===!0?M:void 0},O=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=zv({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),D=M=>{v!==M&&(x?.disconnect(),v=M,w=zg(M),!(typeof ResizeObserver>"u")&&(x=new ResizeObserver(B=>{let R=B[B.length-1]?.contentRect?.width??zg(M);R!==w&&(w=R,ie())}),x.observe(M)))},T=(M,B)=>{let H=qk(M.collapseAutoActionsBelow,B);if(H===null)return!1;let R=w||zg(B);return R>0&&R<H},I=(M,B,H)=>{if(!B)return"bar";if(M.resolved.builtIn){let J=jk(M.resolved.id);return J&&B.includeBuiltIns?.includes(J)?"menu":"bar"}let R=M.resolved.presentation;return R==="overflow"||R==="auto"&&H?"menu":"bar"},A=M=>{let B=M.menuSlot;if(!B)return;if(!Jk(M.element)){M.menuLabel?.remove(),M.menuLabel=void 0;return}let H=Yk(M.element);if(!H){M.menuLabel?.remove(),M.menuLabel=void 0;return}M.menuLabel||(M.menuLabel=E("span","persona-composer-overflow-menu__label")),M.menuLabel.textContent!==H&&(M.menuLabel.textContent=H),M.menuLabel.parentElement!==B&&B.appendChild(M.menuLabel)},_=(M,B)=>{if(M.mode===B)return M;let H=M.resolved.action;if(H&&!_r(H)){u(M),t.delete(M.resolved.id);let R=l(M.resolved,B);return t.set(M.resolved.id,R),R}if(B==="menu"){let R=G("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Og]:""}});R.appendChild(M.element),_v(Vg(M.element)),M.menuSlot=R;let J=V=>{let pe=Vg(M.element);if(pe.disabled)return;let se=V.target===pe||pe.contains(V.target);h?.close(!0),se||pe.click()};R.addEventListener("click",J,!0),M.detachMenuSlot=()=>R.removeEventListener("click",J,!0),M.managed=!0,A(M)}else M.detachMenuSlot?.(),M.detachMenuSlot=void 0,M.menuLabel?.remove(),M.menuLabel=void 0,M.menuSlot?.remove(),M.menuSlot=void 0;return M.mode=B,M},K=(M,B)=>{let H=B.map(R=>R.menuSlot??R.element);for(H.forEach((R,J)=>{let V=M.children[J];V!==R&&(V?M.insertBefore(R,V):M.appendChild(R))});M.children.length>H.length;)M.lastElementChild?.remove()},ie=()=>{if(o)return;let M=e.getBindings();if(!M)return;let B=e.getState(),H=B.phase==="streaming",R=k();R&&D(M.footer);let J=R?T(R,M.footer):!1,V={start:[],end:[]},pe=[];for(let se of n){let ge=t.get(se.id);if(!ge)continue;let Ie=se.action,ye=Ie?Yv(Ie.visible,B,!0)&&Gk(Ie.visibility,B):!0;if(ge.visible!==ye&&(ge.visible=ye,!ye&&ge.managed&&(ge.menuSlot??ge.element).remove()),!!ye){if(ge=_(ge,I(ge,R,J)),Ie){let ce=Yv(Ie.disabled,B,!1)||Ie.disableWhenStreaming===!0&&H;y(ge,ce),!_r(Ie)&&Ie.pressed!==void 0&&ge.button?.setAttribute("aria-pressed",Ie.pressed?"true":"false")}ge.mode==="menu"?(A(ge),pe.push(ge)):V[se.placement].push(ge)}}if(pe.length>0){let se=O();K(se.panel,pe),se.setItems(pe.map(ce=>ce.menuSlot??ce.element)),se.applyButtonSize();let ge=Number.isFinite(R?.order)?R?.order:Wo.overflow,Ie=V.start.findIndex(ce=>ce.resolved.order>ge),ye={resolved:{id:Uk,placement:"start",presentation:"bar",order:ge,sequence:-1,source:"core"},element:se.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};V.start.splice(Ie<0?V.start.length:Ie,0,ye)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));m(M.actionsStart,V.start),m(M.actionsEnd,V.end)};return{resolve:()=>{if(o)return;let M=Vk(e.collect()),B=new Set(M.map(H=>H.id));for(let[H,R]of t)B.has(H)||(u(R),t.delete(H));for(let H of M){let R=t.get(H.id);if(!R){let se=p(H,"bar");se&&t.set(H.id,se);continue}let J=R.resolved.action,V=H.action;if(!!J!=!!V||J&&V&&_r(J)!==_r(V)||J&&V&&_r(J)&&_r(V)&&J.render!==V.render){u(R),t.delete(H.id);let se=p(H,R.mode);se&&t.set(H.id,se);continue}R.resolved=H,H.builtIn?(R.managed=H.builtIn.managed===!0||R.mode==="menu",H.builtIn.element&&R.mode==="bar"&&(R.element=H.builtIn.element)):V&&!_r(V)?a(R,V):V&&R.element.toggleAttribute(qg,V.disableWhenStreaming===!0)}n=M,ie()},sync:ie,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,x?.disconnect(),x=null,v=null;for(let M of t.values())u(M);t.clear(),h?.destroy(),h=null,n=[]}}}}var Zk="core:model",e0=700,Xv=16,t0=["--persona-components-composer-modelPicker-menuBackground","--persona-components-composer-modelPicker-menuBorderRadius","--persona-components-composer-modelPicker-rowHoverBackground","--persona-components-composer-modelPicker-labelColor","--persona-components-composer-modelPicker-descriptionColor"],Jv=()=>{let e=G("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=G("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function Zv(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=d=>{let p=e.getSelectedModelId();return d.find(u=>u.id===p)??d[0]},s=()=>{let d=G("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),p="",u=()=>{let x=e.getModels(),w=x.map(k=>`${k.id}:${k.label}`).join("|");w!==p&&(p=w,d.replaceChildren(...x.map(k=>{let O=G("option",{attrs:{value:k.id}});return O.textContent=k.label,O}))),d.value=r(x)?.id??""};u(),o=u;let m=()=>{d.value&&e.onSelect(d.value)};d.addEventListener("change",m);let y=x=>x.stopPropagation();d.addEventListener("click",y);let{wrapper:h,chevron:v}=Jv();return h.append(d,v),{element:h,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",y)}}},a=()=>{let d=G("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=E("span","persona-composer-model-picker-label"),u=E("span","persona-composer-model-picker-suffix");d.append(p,u);let m=G("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),y=new Map,h="",v=null,x=()=>v?.isOpen===!0,w=(B=!1)=>{x()&&(v?.close(),d.setAttribute("aria-expanded","false"),B&&d.focus())},k=B=>{let H=[...y.values()];if(H.length===0)return;let R=(B%H.length+H.length)%H.length;H[R].focus()},O=B=>{if(x())return;v||(v=hd({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),dd(d,m,t0),v.open(),d.setAttribute("aria-expanded","true");let R=[...y.keys()].indexOf(r(e.getModels())?.id??"");k(B??(R>=0?R:0))},D=B=>{w(!0),e.onSelect(B)},T=B=>{B.preventDefault(),B.stopPropagation();let H=B.currentTarget.getAttribute("data-persona-model-option");H&&D(H)},I=B=>{let H=G("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":B.id}});if(B.icon){let se=le(B.icon,Xv,"currentColor",1.5);if(se){let ge=E("span","persona-composer-model-option-icon");ge.appendChild(se),H.appendChild(ge)}}let R=E("span","persona-composer-model-option-body"),J=E("span","persona-composer-model-option-label");if(J.textContent=B.label,R.appendChild(J),B.description){let se=E("span","persona-composer-model-option-description");se.textContent=B.description,R.appendChild(se)}H.appendChild(R);let V=E("span","persona-composer-model-option-check");V.setAttribute("aria-hidden","true");let pe=le("check",Xv,"currentColor",2);return pe&&V.appendChild(pe),H.appendChild(V),H.addEventListener("click",T),H},A=()=>{let B=e.getModels(),H=B.map(V=>`${V.id}:${V.label}:${V.icon??""}:${V.description??""}`).join("|");if(H!==h){h=H;for(let V of y.values())V.removeEventListener("click",T);y.clear(),m.replaceChildren(...B.map(V=>{let pe=I(V);return y.set(V.id,pe),pe}))}let R=r(B);for(let[V,pe]of y)pe.setAttribute("aria-selected",String(V===R?.id));p.textContent=R?.label??"";let J=e.getSuffix?.()??"";u.textContent=J,d.setAttribute("aria-label",[t,[R?.label,J].filter(Boolean).join(" ")].filter(Boolean).join(": "))};A(),o=A;let _=B=>{B.preventDefault(),B.stopPropagation(),x()?w(!0):O()},K=B=>{if(B.key==="ArrowDown"){B.preventDefault(),x()?k(0):O(0);return}B.key==="ArrowUp"&&(B.preventDefault(),x()?k(-1):O(-1))},ie=B=>{let H=[...y.values()],R=H.indexOf(B.target?.closest?.(".persona-composer-model-option"));switch(B.key){case"ArrowDown":B.preventDefault(),k(R+1);return;case"ArrowUp":B.preventDefault(),k(R-1);return;case"Home":B.preventDefault(),k(0);return;case"End":B.preventDefault(),k(H.length-1);return;case"Escape":B.preventDefault(),B.stopPropagation(),w(!0);return;case"Tab":w(!0);return;default:}};d.addEventListener("click",_),d.addEventListener("keydown",K),m.addEventListener("keydown",ie);let{wrapper:Z,chevron:M}=Jv();return Z.append(d,M),{element:Z,destroy:()=>{o===A&&(o=null),d.removeEventListener("click",_),d.removeEventListener("keydown",K),m.removeEventListener("keydown",ie);for(let B of y.values())B.removeEventListener("click",T);y.clear(),v?.destroy(),v=null,m.remove()}}};return{action:{id:Zk,kind:"custom",placement:"end",order:e0,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}var Kg="[data-persona-composer-chip-row]";function yd(e){e.style.display=e.childElementCount>0?"flex":"none"}function Gg(e){let t=e.querySelector(Kg);if(t)return t;let n=G("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(n,o):e.appendChild(n),n}var n0=":scope > [data-persona-composer-mode]";function eC(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let u=G("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let v=E("span","persona-mention-chip-icon"),x=le(p.iconName,12,"currentColor",1.5);x&&v.appendChild(x),u.appendChild(v)}let m=E("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let y=G("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=le("x",12,"currentColor",2);return h?y.appendChild(h):y.textContent="\xD7",y.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),e.onRemove(p.id)}),u.appendChild(y),u},a=()=>Array.from(t.querySelectorAll(n0)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),yd(t)},m=t.ownerDocument.defaultView,y=typeof m?.getComputedStyle=="function"?m.getComputedStyle(p).animationName:"";if(!y||y==="none"){u();return}p.addEventListener("animationend",u,{once:!0}),p.addEventListener("animationcancel",u,{once:!0})},d=()=>{for(let p of a())p.remove()};return{element:t,render:(p,u)=>{if(o)return;let m=u.filter(x=>p.includes(x.id)),y=m.map(x=>`${x.id}:${x.shortLabel??x.label}`).join("|");if(y===n)return;n=y;let h=new Map;for(let x of a()){let w=x.getAttribute("data-persona-composer-mode");w&&m.some(O=>O.id===w)&&!x.hasAttribute("data-persona-chip-exit")?h.set(w,x):x.hasAttribute("data-persona-chip-exit")||l(x)}let v=t.firstChild;for(let x of m){let w=h.get(x.id);w||(w=s(x),r.has(x.id)||(w.setAttribute("data-persona-chip-enter",""),w.addEventListener("animationend",()=>w?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(x.id),w!==v&&t.insertBefore(w,v),v=w.nextSibling}yd(t)},destroy:()=>{o=!0,d(),yd(t)}}}var tC=e=>`core:mode:${e}`;var Yg=e=>Math.min(300+e,499),nC=e=>`core:mode-group:${e}`;function bd(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function o0(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function oC(e,t){return e?.length?e.filter(n=>!bd(n.groupId,t)&&!o0(n.groupId,t)):[]}var r0=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function rC(e,t,n,o){let r=n.find(l=>l.id===t);if(!r)return[...e];let s=e.includes(t),a=new Set(e);if(s)a.delete(t);else{if(r0(r,o)==="single"){let l=n.filter(d=>d.groupId===r.groupId).map(d=>d.id);a=new Set([...a].filter(d=>!l.includes(d)))}a.add(t)}return n.filter(l=>a.has(l.id)).map(l=>l.id)}function vd(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function sC(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function iC(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var s0=16;function aC(e){let t=null;return{action:{id:nC(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=G("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",a=p=>{p.preventDefault(),p.stopPropagation();let m=p.currentTarget.getAttribute("data-persona-composer-mode");!m||e.getActiveIds().includes(m)&&e.getGroup()?.selection==="single"||e.onSelect(m)},l=p=>{let u=G("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let y=le(p.iconName,s0,"currentColor",1.5);y&&u.appendChild(y)}let m=E("span","persona-composer-segmented-label");return m.textContent=p.shortLabel??p.label,u.appendChild(m),u.addEventListener("click",a),u},d=()=>{let p=e.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=e.getModes(),m=u.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(m!==s){s=m;for(let v of r.values())v.removeEventListener("click",a);r.clear();let h=u.map(v=>{let x=l(v);return r.set(v.id,x),x});o.replaceChildren(...h)}let y=e.getActiveIds();for(let[h,v]of r)v.setAttribute("aria-pressed",String(y.includes(h)))};return d(),t=d,{element:o,destroy:()=>{t===d&&(t=null);for(let p of r.values())p.removeEventListener("click",a);r.clear()}}}},repaint:()=>t?.()}}function lC(e){let t=G("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let a=E("span","persona-composer-quote-bar"),l=E("div","persona-composer-quote-content");if(s.sourceLabel){let m=E("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let d=G("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=td(s.text),l.appendChild(d);let p=G("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=le("x",12,"currentColor",2);u?p.appendChild(u):p.textContent="\xD7",p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),e.onDismiss()}),t.replaceChildren(a,l,p)};return{element:t,render:s=>{if(o)return;let a=s?`${s.sourceLabel??""}\0${s.text}`:"";if(a!==n){if(n=a,!s){t.replaceChildren(),t.style.display="none";return}r(s),t.style.display="flex"}},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function cC(e){let t=G("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(a,l,d,p)=>{let u=G("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[d]:""}}),m=le(a,12,"currentColor",2);return m?u.appendChild(m):u.textContent=l,u.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),p()}),u},s=a=>{let l=td(a.text??"",90);if(l)return l;let d=a.contentParts?.length??0;return d>0?d===1?"1 attachment":`${d} attachments`:(a.mentionRefs?.length??0)>0?a.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:t,render:a=>{if(o||a===n)return;if(n=a,!a){t.replaceChildren(),t.style.display="none";return}let l=E("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let d=G("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});d.textContent=s(a),t.replaceChildren(l,d,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function dC(e){let t=G("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=G("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=e.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=E("div","persona-message-edit-actions"),s=(l,d,p,u)=>{let m=G("button",{className:`persona-message-edit-button ${d}`,attrs:{type:"button",[p]:""},text:l});return m.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),u()}),m},a=()=>{let l=n.value.trim();l&&e.onSave(l)};return r.append(s(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),s(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",a)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),e.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),a())}),t.append(n,r),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function pC(e){let t=e.text??"";if(t.trim().length>0||(e.mentionRefs?.length??0)>0||(e.activeModeIds?.length??0)>0||e.quote||e.selectedModelId)return{text:t,...e.mentionRefs?.length?{mentionRefs:[...e.mentionRefs]}:{},...e.contentSegments?.length?{contentSegments:[...e.contentSegments]}:{},...e.selectedModelId?{selectedModelId:e.selectedModelId}:{},...e.activeModeIds?.length?{activeModeIds:[...e.activeModeIds]}:{},...e.quote?{quote:{...e.quote}}:{}}}function uC(e,t){if(!e||typeof e.text!="string")return;let n=new Set(t.mentionSourceIds),o=(e.mentionRefs??[]).filter(d=>n.has(d.sourceId)),r=o.length===(e.mentionRefs?.length??0)&&o.length>0,s=new Set(t.modes.map(d=>d.id)),a=(e.activeModeIds??[]).filter(d=>s.has(d)),l=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...r?{mentionRefs:o}:{},...r&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...l?{selectedModelId:l}:{},...a.length?{activeModeIds:a}:{},...e.quote?.text?{quote:e.quote}:{}}}function gC(e){let t=e.delay??500,n=null,o=!1,r=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{o||(r(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{o||n===null||(r(),e.write())},cancel:r,destroy:()=>{o=!0,r()}}}function mC(e){return e.wrapped||e.text.includes(`
23
+ `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function fC(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function hC(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),o=Number.parseFloat(n.lineHeight),r=Number.parseFloat(n.fontSize),s=Number.isFinite(o)&&o>0?o:Number.isFinite(r)&&r>0?r*1.4:0;if(!s)return!1;let a=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0);return e.scrollHeight-a>s*1.5}function yC(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Qg(e){return Object.freeze({text:e.text,contentParts:e.contentParts?Object.freeze([...e.contentParts]):void 0,mentionRefs:Object.freeze([...e.mentionRefs]),contentSegments:e.contentSegments?Object.freeze([...e.contentSegments]):void 0,options:Object.freeze({...e.options}),viaVoice:e.viaVoice})}function vC(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var i0=e=>typeof e?.then=="function";function bC(e,t){return t===!1?{status:"canceled"}:!t||typeof t!="object"?{status:"proceed"}:(typeof t.text=="string"&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options}),{status:"proceed"})}function CC(e,t,n){let o;try{o=e(Qg(t),{signal:n})}catch(r){return{status:"error",error:r}}return i0(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:bC(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):bC(t,o)}var wC=/\s/;function a0(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
24
+ `:o===""||wC.test(o)}function l0(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let a=e[s];if(a===n)return a0(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
25
+ `||a==="\uFFFC"||!r&&wC.test(a))return null;s--}return null}function xC(e,t,n){for(let o of n){let r=l0(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function SC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function AC(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.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[t,...n]}function MC(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=E("div","persona-send-button-wrapper"),a=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${jn} ${ho}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=le(o,mn,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),s.appendChild(a),Zt({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}var{setLoader:BB,load:c0}=ft({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var Xg=c0;var{setLoader:NB,load:d0}=ft({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var EC=d0;function tl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=G("span",{className:gn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=le(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=E("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(G("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function TC(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=AC(t).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(I=>typeof I.matchCommand=="function")),r=T=>o.some(I=>I.trigger?I.position==="line-start"?T.split(`
26
+ `).some(_=>_.startsWith(I.trigger)):(I.position==="anywhere"?T:T.split(`
27
+ `)[0]).startsWith(I.trigger):!1),s=(T,I)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:I}))}catch{}},a=!e.chipRow,l=e.chipRow??G("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,p=null,u=e.textarea,m=null,y=null,h=null,v=null,x=()=>{if(d)return Promise.resolve(d);if(p)return p;let T=Xg().then(I=>(I.setMentionIconRenderer(le),d=I.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:l,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:D,emit:s}),d)).catch(I=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",I),p===T&&(p=null),null));return p=T,T},w=()=>{EC().then(T=>{let I=T.mountInlineComposer({textarea:e.textarea,renderToken:_=>tl(_,{render:t.renderMentionToken}),onMentionRemoved:_=>d?.untrackMention(_)});m=I.input,y=I.destroy;let A=u;A.replaceWith(I.element),u=I.element,v={next:I.element,prev:A},h?.(I.element,A),d?d.rebindComposer(I.input):p&&p.then(_=>_?.rebindComposer(I.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};t.display==="inline"&&w();let k=[],O=new Map;for(let T of n){if(!T.showButton)continue;let I=MC({config:{...t,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},onOpen:()=>{x().then(A=>A?.openMenu(T.trigger))}});k.push(I),O.set(T.trigger,I.button)}let D=(T,I,A)=>{let _=O.get(I);_&&(_.setAttribute("aria-expanded",T?"true":"false"),T?_.setAttribute("aria-controls",A):_.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(T=>T.wrapper),contextRow:l,handleInput:T=>{if(d){d.handleInput();return}if(!SC(T))return;let I=u,A=I.selectionStart??0;xC(I.value,A,n)&&x().then(_=>_?.handleInput())},handleKeydown:T=>{if(d?.isMenuOpen())return d.handleKeydown(T);if(T.key==="Backspace"&&d?.hasMentions()&&!v){let I=u,A=I.selectionStart===0&&I.selectionEnd===0;if((I.value.length===0||A)&&d.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async T=>r(T)?(d??await x())?.dispatchInlineCommand(T)??null:null,clear:()=>d?.clear(),prefetch:()=>{Xg().catch(()=>{})},onComposerSwap:T=>{h=T,v&&T(v.next,v.prev)},destroy:()=>{d?.destroy(),y?.();for(let T of k)T.wrapper.remove();a&&l.remove()}}}var Cd="16px",wd="transparent",p0=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?"0px":`${t/4}rem`;return e})(),kC={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"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:p0,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"}},LC={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"}},IC={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:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:no,maxWidth:Bg,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Cd,canvasBackground:wd},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},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",itemGap:"8px",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",itemGap:"8px",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",itemGap:"8px",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"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},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",borderRadius:"palette.radius.md"},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"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},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 fn(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;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."))?fn(e,o):o}function Zg(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let d=fn(e,a);d!==void 0&&(t[l]={path:l,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function RC(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function HC(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=HC(s,r):n[o]=r}return n}function u0(e,t){return t?HC(e,t):e}function xd(e,t={}){let n={palette:kC,semantic:LC,components:IC},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:u0(n.components,e?.components)};if(t.validate!==!1){let r=RC(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}var Jg=e=>e.trim()==="0"?"0px":e,PC="--persona-",g0=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let a=t.slice(1);if(!/^[0-9a-f]+$/.test(a))return;a.length===3||a.length===4?n=[0,1,2].map(l=>parseInt(a[l]+a[l],16)):(a.length===6||a.length===8)&&(n=[0,2,4].map(l=>parseInt(a.slice(l,l+2),16)))}else{let a=t.match(/^rgba?\(([^)]+)\)$/);if(a){let l=a[1].split(/[,/\s]+/).filter(Boolean);l.length>=3&&(n=l.slice(0,3).map(d=>{let p=d.endsWith("%"),u=parseFloat(p?d.slice(0,-1):d);return p?u/100*255:u}))}}if(!n||n.some(a=>!Number.isFinite(a)))return;let[o,r,s]=n.map(a=>{let l=Math.max(0,Math.min(255,a))/255;return l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4)});return .2126*o+.7152*r+.0722*s},m0=.179,en=(e,t)=>{for(let[n,...o]of t){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):e[PC+s],r!==void 0)break;r!==void 0&&(e[PC+n]=r)}};function em(e){let t=Zg(e),n={};for(let[F,Oe]of Object.entries(t)){let Ue=F.replace(/\./g,"-");n[`--persona-${Ue}`]=Oe.value}en(n,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],en(n,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),en(n,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,en(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Cd,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??wd,en(n,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),en(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],a=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],en(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??a??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??a??n["--persona-muted"],en(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=e.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[F,Oe]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ue=n[`--persona-components-history-overlay-${F}`];Ue&&(n[`--persona-history-overlay-${Oe}`]=Ue)}for(let[F,Oe]of[["background","bg"],["borderRadius","radius"]]){let Ue=n[`--persona-components-history-menu-${F}`];Ue&&(n[`--persona-history-menu-${Oe}`]=Ue)}let m=e.components?.history?.motion;if(m){let F=Bt=>{if(Bt===void 0)return;let be=String(Bt).trim();return/^\d+(\.\d+)?$/.test(be)?`${be}ms`:be},Oe=F(m.enterDurationMs);Oe!==void 0&&(n["--persona-history-enter-ms"]=Oe);let Ue=F(m.exitDurationMs);Ue!==void 0&&(n["--persona-history-exit-ms"]=Ue),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let y=n["--persona-components-history-dangerForeground"];y&&(n["--persona-history-danger-fg"]=y),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let F of["scrim","shadow"]){let Oe=n[`--persona-components-history-confirm-${F}`];Oe&&(n[`--persona-history-confirm-${F}`]=Oe)}for(let[F,Oe]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ue=n[`--persona-components-tooltip-${F}`];Ue&&(n[`--persona-tooltip-${Oe}`]=Ue)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[F,Oe]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ue=n[`--persona-components-messageActions-${F}`];Ue&&(n[`--persona-message-action-${Oe}`]=Ue)}en(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],v=n["--persona-components-introCard-shadow"],x=(!h||h==="transparent"||h==="none")&&(!v||v==="none"),w=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=x&&w==="1.5rem"?"1.5rem 0":w,en(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),en(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let k=n["--persona-components-markdown-heading-h1-fontSize"];k&&(n["--persona-md-h1-size"]=k);let O=n["--persona-components-markdown-heading-h1-fontWeight"];O&&(n["--persona-md-h1-weight"]=O);let D=n["--persona-components-markdown-heading-h2-fontSize"];D&&(n["--persona-md-h2-size"]=D);let T=n["--persona-components-markdown-heading-h2-fontWeight"];T&&(n["--persona-md-h2-weight"]=T);let I=n["--persona-components-markdown-prose-fontFamily"];I&&I!=="inherit"&&(n["--persona-md-prose-font-family"]=I),en(n,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),en(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),en(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),en(n,[["md-hr-color","components-markdown-hr-color","divider"]]),en(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","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"],en(n,[["message-border","components-message-border","border"]]),en(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let A=e.components,_=A?.iconButton;_&&(_.background&&(n["--persona-icon-btn-bg"]=_.background),_.border&&(n["--persona-icon-btn-border"]=_.border),_.color&&(n["--persona-icon-btn-color"]=_.color),_.padding&&(n["--persona-icon-btn-padding"]=_.padding),_.borderRadius&&(n["--persona-icon-btn-radius"]=_.borderRadius),_.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=_.hoverBackground),_.hoverColor&&(n["--persona-icon-btn-hover-color"]=_.hoverColor),_.activeBackground&&(n["--persona-icon-btn-active-bg"]=_.activeBackground),_.activeBorder&&(n["--persona-icon-btn-active-border"]=_.activeBorder));let K=A?.labelButton;K&&(K.background&&(n["--persona-label-btn-bg"]=K.background),K.border&&(n["--persona-label-btn-border"]=K.border),K.color&&(n["--persona-label-btn-color"]=K.color),K.padding&&(n["--persona-label-btn-padding"]=K.padding),K.borderRadius&&(n["--persona-label-btn-radius"]=K.borderRadius),K.hoverBackground&&(n["--persona-label-btn-hover-bg"]=K.hoverBackground),K.fontSize&&(n["--persona-label-btn-font-size"]=K.fontSize),K.gap&&(n["--persona-label-btn-gap"]=K.gap));let ie=A?.toggleGroup;ie&&(ie.gap&&(n["--persona-toggle-group-gap"]=ie.gap),ie.borderRadius&&(n["--persona-toggle-group-radius"]=ie.borderRadius));let Z=A?.artifact;if(Z?.toolbar){let F=Z.toolbar;F.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=F.iconHoverColor),F.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=F.iconHoverBackground),F.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=F.iconPadding),F.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=F.iconBorderRadius),F.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=F.iconBorder),F.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Jg(F.toggleGroupGap)),F.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=F.toggleBorderRadius),F.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Jg(F.toggleGroupPadding)),F.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=F.toggleGroupBorder),F.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=F.toggleGroupBorderRadius),F.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=fn(e,F.toggleGroupBackground)??F.toggleGroupBackground),F.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=F.copyBackground),F.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=F.copyBorder),F.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=F.copyColor),F.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Jg(F.copyBorderRadius)),F.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=F.copyPadding),F.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=F.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??F.copyMenuBackground),F.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=F.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??F.copyMenuBorder),F.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=F.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??F.copyMenuShadow),F.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=F.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??F.copyMenuBorderRadius),F.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=F.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??F.copyMenuItemHoverBackground),F.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=F.iconBackground),F.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=F.toolbarBorder)}if(Z?.tab){let F=Z.tab;F.background&&(n["--persona-artifact-tab-bg"]=F.background),F.activeBackground&&(n["--persona-artifact-tab-active-bg"]=F.activeBackground),F.activeBorder&&(n["--persona-artifact-tab-active-border"]=F.activeBorder),F.borderRadius&&(n["--persona-artifact-tab-radius"]=F.borderRadius),F.textColor&&(n["--persona-artifact-tab-color"]=F.textColor),F.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=F.hoverBackground),F.listBackground&&(n["--persona-artifact-tab-list-bg"]=F.listBackground),F.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=F.listBorderColor),F.listPadding&&(n["--persona-artifact-tab-list-padding"]=F.listPadding)}if(Z?.pane){let F=Z.pane;if(F.toolbarBackground){let Oe=fn(e,F.toolbarBackground)??F.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Oe}}if(Z?.card){let F=Z.card;F.background&&(n["--persona-artifact-card-bg"]=F.background),F.border&&(n["--persona-artifact-card-border"]=F.border),F.borderRadius&&(n["--persona-artifact-card-radius"]=F.borderRadius),F.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=F.hoverBackground),F.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=F.hoverBorderColor)}if(Z?.inline){let F=Z.inline;F.background&&(n["--persona-artifact-inline-bg"]=fn(e,F.background)??F.background),F.border&&(n["--persona-artifact-inline-border"]=F.border),F.borderRadius&&(n["--persona-artifact-inline-radius"]=F.borderRadius),F.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=fn(e,F.chromeBackground)??F.chromeBackground),F.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=fn(e,F.chromeBorder)??F.chromeBorder),F.titleColor&&(n["--persona-artifact-inline-title-color"]=fn(e,F.titleColor)??F.titleColor),F.mutedColor&&(n["--persona-artifact-inline-muted-color"]=fn(e,F.mutedColor)??F.mutedColor),F.frameHeight&&(n["--persona-artifact-inline-frame-height"]=F.frameHeight)}let M=A?.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"]=fn(e,M.background)??M.background));let B=n["--persona-surface"],H=n["--persona-container"],R=n["--persona-palette-colors-gray-100"]??"#f3f4f6",J=n["--persona-palette-colors-gray-200"]??"#e5e7eb",V=n["--persona-palette-colors-gray-300"]??"#d1d5db",pe=!H||H===B,se=g0(B??n["--persona-background"]),ge=pe&&se!==void 0&&se<m0,Ie=ge?"rgba(255, 255, 255, 0.08)":R,ye=ge?"rgba(255, 255, 255, 0.12)":J,ce=ge?"rgba(255, 255, 255, 0.16)":V,Je=pe?Ie:H,fe=pe?ye:H;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Je,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??fe,pe&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ce),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Je,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Je,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Je,n}var f0={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var h0={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"}}},y0={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},WC=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Sd=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",b0=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Sd()},tm=e=>b0(e),v0=e=>xd(e),C0=e=>{let t=Ti(y0,e??{})??{};return xd({...t,palette:{...t.palette,colors:{...h0.colors,...t.palette?.colors}}},{validate:!1})},Ps=e=>{let t=tm(e),n=WC(e?.theme),o=WC(e?.darkTheme);return t==="dark"?C0(Ti(n??{},o??{})):v0(n)},w0=e=>em(e),ki=(e,t)=>{let n=Ps(t),o=w0(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",tm(t))},nl=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Sd())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Sd());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};import{Activity as gx,Check as mx,Copy as fx}from"lucide";var Dr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Ad="24px",nm=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",ol=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let n=Number(t[1])/100;return n>0&&n<1?n:null},OC=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var BC=null;var om=()=>{if(BC!==null)return BC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},x0="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Md=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Ed=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),n=t.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return Md("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Md("unsupported",e),null):(n==="space"&&(o.key=" "),o)},S0=e=>x0.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),_C=(e,t)=>{let n=Ed(e);if(!n)return"";let o=om(),r=S0(n.key);if(!t&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[t?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},Td=e=>_C(e,!1),rl=e=>_C(e,!0),A0=(e,t)=>t.key?.toLowerCase()===e.key&&(om()?t.metaKey:t.ctrlKey)===e.mod&&!(om()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,M0=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},DC=e=>{let t=new Map,n=e?.ownerDocument??(typeof document<"u"?document:null),o=(s,a)=>{if((s.scope??"widget")==="page")return!0;if(!e)return!1;let l=a.composedPath?.();return l?.length?l.includes(e):e.contains(a.target)},r=s=>{if(s.isComposing||!t.size)return;let a=s.composedPath?.()[0]??s.target;for(let l of t.values())if(A0(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&M0(a))){s.preventDefault();try{l.run(s)}catch(d){Md(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=Ed(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=t.get(l);return d?(Md(`${d.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",rl(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}};import{Idiomorph as E0}from"idiomorph";var Pd=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;E0.morph(e,t.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 a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var NC=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var rm={index:-1,draft:""};function FC(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){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(!a)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 $C(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function UC(){return new Map}function jC(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function qC(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function zC(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function VC(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function KC(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Oo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ks(e,t){return Oo(e)-e.scrollTop<=t}function GC(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:p=!1}=e,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!t&&r&&(!p||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:t&&l&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function YC(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function QC(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function sm(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function XC(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var sl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},T0=["pre","code","a","script","style"],kd=e=>({type:e?.type??sl.type,placeholder:e?.placeholder??sl.placeholder,speed:e?.speed??sl.speed,duration:e?.duration??sl.duration,buffer:e?.buffer??sl.buffer}),ZC=[{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"}],il=new Map;for(let e of ZC)il.set(e.name,e);var ew=["wipe","glyph-cycle"],Ld=e=>{il.set(e.name,e)},P0=e=>{ZC.some(t=>t.name===e)||il.delete(e)},k0=()=>Array.from(il.keys()),al=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:il.get(e)??null,Id=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
28
+ `);return s<0?"":e.slice(0,s)}return e},L0=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},I0=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},im=/\s/,R0=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},H0=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(im.test(s[l])){let d=l;for(;d<s.length&&im.test(s[d]);)d+=1;a.appendChild(o.createTextNode(s.slice(l,d))),l=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let p=l;for(;p<s.length&&!im.test(s[p]);)d.appendChild(L0(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,e)},W0=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let d of l)d&&(/^\s+$/.test(d)?a.appendChild(o.createTextNode(d)):(a.appendChild(I0(o,d,t,n.value)),n.value+=1));r.replaceChild(a,e)},ll=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??T0).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)R0(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=t==="char"?H0:W0;for(let m of l)u(m,n,p);return r.innerHTML},Rd=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},cl=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},JC=new WeakMap,O0=(e,t)=>{if(!e.styles)return;let n=JC.get(t);if(n||(n=new Set,JC.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},am=new WeakMap,B0=(e,t)=>{if(!e.onAttach)return;let n=am.get(t);if(n||(n=new Map,am.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},tw=e=>{let t=am.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},dl=(e,t)=>{O0(e,t),B0(e,t)};var{setLoader:f_,load:_0}=ft({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var nw=_0;function lm(e,t=rn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var pl=0,Nr=null;function cm(e=document){if(pl++,pl===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Nr={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 t=!1;return()=>{if(!t&&(t=!0,pl=Math.max(0,pl-1),pl===0&&Nr)){let n=e.body,o=e.defaultView??window;n.style.overflow=Nr.originalOverflow,n.style.position=Nr.originalPosition,n.style.top=Nr.originalTop,n.style.width=Nr.originalWidth,o.scrollTo(0,Nr.scrollY),Nr=null}}}var ul={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},St=e=>(e?.launcher?.mountMode??"floating")==="docked",Fr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",qn=e=>{let t=e?.launcher?.dock;return{side:t?.side??ul.side,width:t?.width??ul.width,animate:t?.animate??ul.animate,reveal:t?.reveal??ul.reveal,maxHeight:t?.maxHeight??ul.maxHeight}};import{ArrowRight as D0}from"lucide";var dm=e=>e==="followUp"?"follow-up":e,pm=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},N0=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},ow=new WeakSet,F0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,$0=e=>{F0()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},um=e=>{var D,T,I;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:d,chipsConfig:p,session:u,getTextarea:m,eventTarget:y,submitPrompt:h}=e,v=o==="followUp",x=t.behavior,w=()=>{if(u.isStreaming())return;let A={suggestion:{...t},surface:o,source:r,behavior:x},_=y.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:A,bubbles:!0,composed:!0,cancelable:!0}));if(v&&y.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!_)return;for(let ie of d)if(ie.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let K=m();if(x==="fill"){K.value=t.prompt,K.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),K.focus();return}if(h){h(t.prompt);return}K.value="",u.sendMessage(t.prompt)},k=()=>{let A=E("button",`persona-suggestion persona-suggestion--${s}`);if(A.type="button",A.disabled=a,A.dataset.suggestionId=t.id,A.dataset.emphasis=t.emphasis,A.dataset.behavior=x,s==="chip"&&(p?.fontFamily&&(A.style.fontFamily=N0(p.fontFamily)),p?.fontWeight&&(A.style.fontWeight=p.fontWeight),p?.paddingX&&(A.style.paddingLeft=p.paddingX,A.style.paddingRight=p.paddingX),p?.paddingY&&(A.style.paddingTop=p.paddingY,A.style.paddingBottom=p.paddingY)),t.icon){let K=le(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);K&&(K.classList.add("persona-suggestion__icon"),t.iconColor&&(K.style.color=t.iconColor),A.appendChild(K))}let _=E("span","persona-suggestion__copy");if(_.appendChild(G("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&_.appendChild(G("span",{className:"persona-suggestion__description",text:t.description})),A.appendChild(_),s!=="chip"){let K=It(D0,16,"currentColor",1.8);K&&(K.classList.add("persona-suggestion__arrow"),A.appendChild(K))}return A.addEventListener("click",w),A},O=null;for(let A of d)if(A.renderSuggestion&&(O=A.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:k,select:w}),O))break;return O??(O=k()),(D=O.dataset).suggestionId||(D.suggestionId=t.id),(T=O.dataset).behavior||(T.behavior=x),(I=O.dataset).emphasis||(I.emphasis=t.emphasis),O instanceof HTMLButtonElement||O.setAttribute("aria-disabled",a?"true":"false"),O},gl=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,e.scrollWidth-e.clientWidth);if(u<=1){s();return}let m=getComputedStyle(e).direction==="rtl",y=Math.min(u,Math.max(0,Math.abs(e.scrollLeft))),h=4,v=y<=h,x=y>=u-h,w=m?!x:!v,k=m?!v:!x;e.toggleAttribute("data-scroll-left",w),e.toggleAttribute("data-scroll-right",k)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,m,y,h,v,x)=>{e.replaceChildren(),t.length=0,n.length=0;let w=x?.source??"config",k=x?.surface??(w==="config"?"starter":"followUp"),O=k==="followUp",D=x?.variant??"chip",T=x?.behavior??"send",I=x?.overflow??"wrap",A=x?.config??{},_=x?.plugins??[],K=typeof x?.maxItems=="number"?Math.max(0,Math.floor(x.maxItems)):void 0,ie=O?"followUps":"starters";!ow.has(A)&&A.debug===!0&&D!=="chip"&&A.suggestions?.[ie]?.overflow!==void 0&&(ow.add(A),console.info(`[persona] suggestions.${ie}.overflow applies to the "chip" variant only; the "${D}" variant manages its own stacking.`));let Z=V=>V.map(pm).filter(pe=>pe!==null).map(pe=>({...pe,behavior:pe.behavior??T})),M=Z(u??[]);_.forEach(V=>{V.transformSuggestions&&(M=Z(V.transformSuggestions({suggestions:M.map(pe=>({...pe})),surface:k,source:w,config:A})))});let B=K===void 0?M:M.slice(0,K);if(!B.length){e.hidden=!0,o=null,s();return}if(!O&&(h??m.getMessages()).some(pe=>pe.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=dm(k),e.dataset.variant=D,e.dataset.overflow=I;let H=document.createDocumentFragment(),R=m.isStreaming();B.forEach((V,pe)=>{let se=um({item:V,index:pe,surface:k,source:w,variant:D,streaming:R,config:A,plugins:_,chipsConfig:v,session:m,getTextarea:()=>y,eventTarget:e,submitPrompt:x?.submitPrompt});H.appendChild(se),n.push(se),[...se instanceof HTMLButtonElement?[se]:[],...Array.from(se.querySelectorAll("button"))].forEach(Ie=>{t.includes(Ie)||(Ie.disabled=R,t.push(Ie))})}),e.appendChild(H),a(),l();let J=JSON.stringify({normalized:B,surface:k,variant:D,source:w});J!==o&&(o=J,$0(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:B.map(V=>({...V})),surface:k,source:w,variant:D},bubbles:!0,composed:!0})),O&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:B.map(V=>V.prompt)},bubbles:!0,composed:!0})))}}};var zn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var U0="persona-header-control",j0="persona-header-control--glyph",q0="persona-header-control--sparse",z0=20,V0={x:[1.4,1.05]},rw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",K0="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Hd=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=V0[t]??[1,1.5],l=!o;e.classList.toggle(j0,l),e.classList.toggle(q0,l&&s!==1);let d=parseFloat(o??"")||z0,p=le(t,`${Math.round(d*s)}px`,"currentColor",a);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),e.replaceChildren(p)):r&&(e.textContent=r)},Ls=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=rw,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:y,borderRadius:h,paddingX:v,paddingY:x,hidden:w,extraClassName:k,attrs:O}=e,D=E("div",a),T=!!(m||y),I=G("button",{className:gn(U0,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!T&&"persona-border-none",!h&&"persona-rounded-full",k),attrs:{type:"button","aria-label":t,...O},style:{width:l,height:l,minWidth:l,minHeight:l,display:w?"none":void 0,color:p||hn.actionIconColor,backgroundColor:u,border:T?`${m||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:h,paddingLeft:v,paddingRight:v,paddingTop:x,paddingBottom:x}});return r?Hd(I,r,{iconSize:d,iconText:s}):s&&(I.textContent=s),D.appendChild(I),Zt({anchor:I,trigger:D,text:()=>I.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:I,wrapper:D}},Li=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=rw,buttonSize:r,iconSize:s}=t,a=e?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=Ls({ariaLabel:l,tooltip:d,iconName:a.closeButtonIconName??"x",iconText:a.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??a.closeButtonSize,iconSize:s,color:a.closeButtonColor,backgroundColor:a.closeButtonBackgroundColor,borderWidth:a.closeButtonBorderWidth,borderColor:a.closeButtonBorderColor,borderRadius:a.closeButtonBorderRadius,paddingX:a.closeButtonPaddingX,paddingY:a.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:u}},Ii=(e,t={})=>{let{wrapperClassName:n=K0,buttonSize:o,iconSize:r}=t,a=(e?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=Ls({ariaLabel:l,tooltip:d,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:p,wrapper:u}};var hn={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))",minHeight:"var(--persona-header-min-height, auto)"},gm={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},G0={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},$r=e=>{let{config:t,showClose:n=!0}=e,o=G("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:{minHeight:hn.minHeight,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=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,p=G("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(d){let I=parseFloat(s)||24,A=le(d,I*.6,"currentColor",1);A?p.replaceChildren(A):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let I=E("img");I.src=t.launcher.iconUrl,I.alt="",I.className="persona-rounded-xl persona-object-cover",I.style.height=s,I.style.width=s,p.replaceChildren(I)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let u=E("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=G("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:hn.titleColor,...gm}}),y=G("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:hn.subtitleColor,...G0}});u.append(m,y),l?o.append(u):o.append(p,u);let h=r.clearChat??{},v=h.enabled??!0,x=h.placement??"inline",w=null,k=null;if(v){let A=Ii(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=A.button,k=A.wrapper,x==="top-right"&&(k.style.right="48px"),x==="inline"&&o.appendChild(k)}let O=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:D,wrapper:T}=Li(t,{showClose:n,wrapperClassName:O});return a!=="top-right"&&o.appendChild(T),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:y,closeButton:D,closeButtonWrapper:T,clearChatButton:w,clearChatButtonWrapper:k}},Ri=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Hi(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=e,l=E("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(Ei)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let v of t){if(v.dividerBefore){let k=document.createElement("hr");l.appendChild(k)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",v.id),v.destructive&&x.setAttribute("data-destructive",""),v.icon){let k=le(v.icon,16,"currentColor",1.5);k&&x.appendChild(k)}let w=document.createElement("span");w.textContent=v.label,x.appendChild(w),x.addEventListener("click",k=>{k.stopPropagation(),m(),n(v.id)}),l.appendChild(x)}let d=null;function p(){if(!s)return;let v=o.getBoundingClientRect();l.style.top=`${v.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-v.right}px`,l.style.left="auto"):(l.style.left=`${v.left}px`,l.style.right="auto")}function u(){let v=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),v&&a?.(!0),requestAnimationFrame(()=>{let x=w=>{!l.contains(w.target)&&!o.contains(w.target)&&m()};document.addEventListener("click",x,!0),d=()=>document.removeEventListener("click",x,!0)})}function m(){let v=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,v&&a?.(!1)}function y(){l.classList.contains("persona-hidden")?u():m()}function h(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:m,toggle:y,destroy:h}}function Vn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=e,p=E("button",gn(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=le(t,o??16,"currentColor",r??2);if(u&&p.appendChild(u),l&&p.addEventListener("click",l),d)for(let[m,y]of Object.entries(d))p.setAttribute(m,y);return p}function sw(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:d}=e,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let u=E("button",p);if(u.type="button",u.setAttribute("aria-label",n),t){let y=le(t,s??14,"currentColor",2);y&&u.appendChild(y)}let m=E("span");if(m.textContent=n,u.appendChild(m),l&&u.addEventListener("click",l),d)for(let[y,h]of Object.entries(d))u.setAttribute(y,h);return u}function Wd(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=E("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function d(){for(let u of l)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of t){let m;u.icon?m=Vn({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,d(),o(u.id)}}):(m=E("button","persona-icon-btn"+(u.className?" "+u.className:"")),m.type="button",m.setAttribute("aria-label",u.label),m.title=u.label,m.textContent=u.label,m.addEventListener("click",()=>{a=u.id,d(),o(u.id)})),m.setAttribute("aria-pressed",u.id===a?"true":"false"),l.push({id:u.id,btn:m}),s.appendChild(m)}function p(u){a=u,d()}return{element:s,setSelected:p}}function Y0(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:d="bottom-left",portal:p,chevronLabel:u="More options",chevronIconSize:m,className:y,primaryClassName:h,chevronClassName:v}=e,x=E("div","persona-split-btn"+(y?" "+y:"")),w={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},k=r&&n?Vn({...w,icon:n,size:o??14}):sw({...w,icon:n,iconSize:o??14}),O=Vn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(v?" "+v:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});x.append(k,O);let D=null,T=()=>{if(D)return D;let I=(typeof p=="function"?p():p)??void 0;return D=Hi({items:s,onSelect:a,anchor:x,position:d,portal:I,onOpenChange:A=>{O.setAttribute("aria-expanded",A?"true":"false")}}),I||x.appendChild(D.element),D};return x.isConnected?T():requestAnimationFrame(()=>{D||T()}),O.addEventListener("click",I=>{I.stopPropagation(),T().toggle()}),{element:x,primaryButton:k,chevronButton:O,openMenu:()=>T().show(),closeMenu:()=>D?.hide(),toggleMenu:()=>T().toggle(),destroy:()=>{D?.destroy(),x.remove()}}}function mm(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:d}=e,p=E("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",t);let u=E("span","persona-combo-btn-label");u.textContent=t,p.appendChild(u);let m=le(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",p.appendChild(m)),d&&(p.style.borderRadius=d.borderRadius??"10px",p.style.padding=d.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=d.background??"",p.style.borderColor=d.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let y=Hi({items:o,onSelect:v=>{p.setAttribute("aria-expanded","false"),r(v)},anchor:p,position:s,portal:a});a||p.appendChild(y.element);let h=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",v=>{if(v.stopPropagation(),h())return;let x=!y.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",x?"false":"true"),y.toggle()}),p.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),p.click())}),{element:p,setLabel:v=>{u.textContent=v,p.setAttribute("aria-label",v)},open:()=>{p.setAttribute("aria-expanded","true"),y.show()},close:()=>{p.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let v=!y.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",v?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),p.remove()}}}var iw=e=>{let t=$r({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.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 t};function Q0(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=Ls({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Td(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let a=rl(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=Hi({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var aw=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=E("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=hn.minHeight,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 d=r?.titleMenu,p,u;if(d){let T=mm({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:I=>{let A=K=>{K===!1&&T.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:I}}))},_=d.onSelect(I);_ instanceof Promise?_.then(A,()=>{}):A(_)},hover:d.hover,className:""});p=T.element,p.style.color=hn.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=E("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=E("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=hn.titleColor,Object.assign(u.style,gm),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let I=r.onTitleClick;p.addEventListener("click",A=>{A.target.closest("button")||I()}),p.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),I())})}let T=r?.titleRowHover;T&&(p.style.borderRadius=T.borderRadius??"10px",p.style.padding=T.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=T.background??"",p.style.borderColor=T.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:y,wrapper:h}=Li(t,{showClose:n,wrapperClassName:m});o&&y.addEventListener("click",o);let v=E("div","persona-flex persona-items-center persona-gap-1");d||Q0(v,r?.trailingActions,r?.onAction??s);let x=a.clearChat??{},w=null,k=null;if(x.enabled??!0){let T=x.placement??"inline",I=Ii(t,{wrapperClassName:T==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});w=I.button,k=I.wrapper,T==="top-right"?k.style.right="48px":v.appendChild(k)}v.appendChild(h),l.appendChild(v);let O=E("div");O.style.display="none";let D=E("span");return D.style.display="none",{header:l,iconHolder:O,headerTitle:u,headerSubtitle:D,closeButton:y,closeButtonWrapper:h,clearChatButton:w,clearChatButtonWrapper:k}},fm={default:iw,minimal:aw},lw=e=>fm[e]??fm.default,ml=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=E("div");l.style.display="none";let d=E("span"),p=E("span"),u=E("button");u.style.display="none";let m=E("div");return m.style.display="none",{header:a,iconHolder:l,headerTitle:d,headerSubtitle:p,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=lw(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Wi=e=>{let{config:t}=e,n=G("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=fd(),r=G("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:a}=pd(t);a();let l=ud(t),d=Pi(t),p=gd(t),u=md(t),m=G("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),p&&(p.previewsContainer.style.gap="8px",m.append(p.previewsContainer),r.append(p.input)),r.append(s);let y=G("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=G("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),v=G("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&h.append(p.wrapper),d&&v.append(d.wrapper),v.append(l.wrapper),y.append(h,v),r.append(y),r.addEventListener("click",x=>{x.target!==l.button&&x.target!==l.wrapper&&x.target!==d?.button&&x.target!==d?.wrapper&&x.target!==p?.button&&x.target!==p?.wrapper&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,header:m,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:u,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:y,leftActions:h,rightActions:v,setSendButtonMode:l.setMode}};import{ChevronUp as X0,MessageSquare as J0}from"lucide";var cw=()=>{let e=G("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=E("span","persona-pill-peek__icon"),n=It(J0,16,"currentColor",1.5);n&&t.appendChild(n);let o=E("span","persona-pill-peek__text"),r=E("span","persona-pill-peek__caret"),s=It(X0,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Od=e=>{let{config:t}=e,n=G("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=fd(),r=md(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=pd(t,{defaultMaxLines:5});a();let l=ud(t),d=Pi(t),p=gd(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=G("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=G("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let y=G("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&y.append(d.wrapper),y.append(l.wrapper),u.addEventListener("click",x=>{x.target!==l.button&&x.target!==l.wrapper&&x.target!==d?.button&&x.target!==d?.wrapper&&x.target!==p?.button&&x.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,y);let h=G("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),p&&h.append(p.previewsContainer),n.append(o,u,r);let v=u;return{footer:n,suggestions:o,composerForm:u,header:h,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:v,leftActions:m,rightActions:y,setSendButtonMode:l.setMode}};var Z0=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},eL=(e,t)=>{if(!e)return null;let n=Z0(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},tL=(e,t)=>{let n=E("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},nL=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},ym=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},bm=320,mw=320,oL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),rL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),sL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),iL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),aL=e=>{if(!e||e.length===0)return null;let t=G("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=G("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=E("span","persona-mention-chip-icon"),s=le(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(G("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},lL=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(tl(o.ref,{readonly:!0,render:t}))}return n},dw="\uE000",pw="\uE001",cL=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${dw}${r}:${y}${pw}`,a=t.map((y,h)=>y.kind==="text"?y.text:s(h)).join(""),l=n(a);if(!t.every((y,h)=>y.kind==="text"||l.includes(s(h)))){e.replaceChildren(lL(t,o));return}e.innerHTML=l;let p=new RegExp(`${dw}${r}:(\\d+)${pw}`),u=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let y=u.nextNode();y;y=u.nextNode())m.push(y);for(let y of m){let h=y;for(let v=p.exec(h.data);v;v=p.exec(h.data)){let x=t[Number(v[1])],w=h.splitText(v.index);w.data=w.data.slice(v[0].length),x?.kind==="mention"&&w.parentNode?.insertBefore(tl(x.ref,{readonly:!0,render:o}),w),h=w}}},dL=(e,t,n)=>{if(e.length===0)return null;try{let o=E("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,d)=>{let p=E("img");p.alt=l.alt?.trim()||`Attached image ${d+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${bm}px`,p.style.maxHeight=`${mw}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,p.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),p.remove(),r===0&&a())}),p.addEventListener("load",()=>{u=!0}),nL(l.image)?(p.src=l.image,o.appendChild(p)):(u=!0,r=Math.max(0,r-1),p.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},pL=e=>{if(e.length===0)return null;try{let t=E("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!ym(o.audio))return;let r=E("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${bm}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},uL=e=>{if(e.length===0)return null;try{let t=E("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!ym(o.video))return;let r=E("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${bm}px`,r.style.maxHeight=`${mw}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},gL=e=>{if(e.length===0)return null;try{let t=E("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!ym(o.data))return;let r=E("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",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Oi=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="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",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},fw=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Oi};if(t){let r=t(o);if(r!==null)return r}return Oi()},mL=(e,t)=>{let n=E("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=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=E("img");r.src=o,r.alt=t==="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(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},uw=(e,t,n="div")=>{let o=E(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},fl=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="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"),e==="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"),e==="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},gw={bubble:{padding:"0.75rem 1.25rem",fontSize:"0.875rem",lineHeight:"1.75"},minimal:{padding:"0.5rem 0.75rem",fontSize:"0.875rem",lineHeight:"1.75"},flat:{padding:"0.5rem 0",fontSize:"inherit",lineHeight:"inherit"}},fL=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=gw[n??"bubble"]??gw.bubble;o.padding&&(e.style.padding=`var(--persona-message-${r}-padding, ${s.padding})`),o.fontSize&&(e.style.fontSize=`var(--persona-message-${r}-font-size, ${s.fontSize})`),o.lineHeight&&(e.style.lineHeight=`var(--persona-message-${r}-line-height, ${s.lineHeight})`),o.fontFamily&&(e.style.fontFamily=`var(--persona-message-${r}-font-family, inherit)`)},Bd="custom:",hL=e=>`${Bd}${e}`,hw=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),yw=(e,t,n,o)=>{let r=t.showCopy??!0,s=t.showUpvote??!0,a=t.showDownvote??!0,l=t.showReadAloud??!1,d=(t.showRegenerate??!1)&&o?.canRegenerate===!0,p=(t.showEdit??!1)&&o?.canEdit===!0,u=(t.showQuote??!1)&&o?.canQuote!==!1,m=hw(t,e.role);if(!r&&!s&&!a&&!l&&!d&&!p&&!u&&m.length===0){let D=E("div");return D.style.display="none",D.id=`actions-${e.id}`,D.setAttribute("data-actions-for",e.id),D}let y=t.visibility??"hover",h=t.align??"right",v=t.layout??"pill-inside",x={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],w={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[v],k=E("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${x} ${w} ${y==="hover"?"persona-message-actions-hover":""}`);k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id);let O=(D,T,I)=>{let A=Vn({icon:D,label:T,size:14,className:"persona-message-action-btn",chromeless:!0});return A.setAttribute("data-action",I),A};r&&k.appendChild(O("copy","Copy message","copy")),l&&k.appendChild(O("volume-2","Read aloud","read-aloud")),s&&k.appendChild(O("thumbs-up","Upvote","upvote")),a&&k.appendChild(O("thumbs-down","Downvote","downvote")),d&&k.appendChild(O("refresh-cw","Regenerate response","regenerate")),p&&k.appendChild(O("pencil","Edit message","edit")),u&&k.appendChild(O("quote","Quote message","quote"));for(let D of m)k.appendChild(O(D.iconName??"ellipsis",D.label,hL(D.id)));return k},hl=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",d=a.avatar,p=a.timestamp,u=d?.show??!1,m=p?.show??!1,y=d?.position??"left",h=p?.position??"below",v=fl(e.role,l),x=E("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let w=s?.widgetConfig?.theme?.components?.message;fL(x,e.role,l,e.role==="user"?w?.user:w?.assistant),l==="flat"?(x.style.backgroundColor="transparent",x.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=oL(e),O=e.content?.trim()??"",T=k.length>0&&O===wi,I=kd(s?.widgetConfig?.features?.streamAnimation),A=s?.widgetConfig?.features?.streamAnimation?.plugins,_=e.role==="assistant"&&I.type!=="none"?al(I.type,A):null,K=e.role==="assistant"&&_?.isAnimating?.(e)===!0,ie=e.role==="assistant"&&_!==null&&(!!e.streaming||K);ie&&_?.bubbleClass&&x.classList.add(_.bubbleClass);let Z=document.createElement("div");Z.classList.add("persona-message-content"),e.streaming&&Z.classList.add("persona-content-streaming"),ie&&_&&(_.containerClass&&Z.classList.add(_.containerClass),Z.style.setProperty("--persona-stream-step",`${I.speed}ms`),Z.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let M=ie?Id(e.content??"",I.buffer,_,e,!!e.streaming):e.content??"",B=()=>{let fe=t({text:M,message:e,streaming:!!e.streaming,raw:e.rawContent});return ie&&_?.wrap==="char"?ll(fe,"char",e.id,{skipTags:_.skipTags}):ie&&_?.wrap==="word"?ll(fe,"word",e.id,{skipTags:_.skipTags}):fe},H=null;if(T?(H=document.createElement("div"),H.innerHTML=B(),H.style.display="none",Z.appendChild(H)):e.contentSegments?.length?cL(Z,e.contentSegments,fe=>t({text:fe,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):Z.innerHTML=B(),ie&&_?.useCaret&&!T&&O){let fe=Rd(),F=Z.querySelectorAll(".persona-stream-char, .persona-stream-word"),Oe=F[F.length-1];if(Oe?.parentNode)Oe.parentNode.insertBefore(fe,Oe.nextSibling);else{let Ue=Z.lastElementChild;Ue?Ue.appendChild(fe):Z.appendChild(fe)}}if(m&&h==="inline"&&e.createdAt){let fe=uw(e,p,"span");fe.classList.add("persona-timestamp-inline");let F=Z.lastElementChild;F?F.appendChild(fe):Z.appendChild(fe)}if(k.length>0){let fe=dL(k,!T&&!!O,()=>{T&&H&&(H.style.display="")});fe?x.appendChild(fe):T&&H&&(H.style.display="")}let R=rL(e);if(R.length>0){let fe=pL(R);fe&&x.appendChild(fe)}let J=sL(e);if(J.length>0){let fe=uL(J);fe&&x.appendChild(fe)}let V=iL(e);if(V.length>0){let fe=gL(V);fe&&x.appendChild(fe)}let pe=e.contentSegments?.length?null:aL(e.contextMentions);if(pe&&x.appendChild(pe),x.appendChild(Z),m&&h==="below"&&e.createdAt){let fe=uw(e,p);fe.classList.add("persona-mt-1"),x.appendChild(fe)}let se=e.role==="assistant"?eL(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let fe=!!(M&&M.trim()),F=I.placeholder==="skeleton",Oe=F&&I.buffer==="line"&&fe;if(fe)Oe&&x.appendChild(cl());else if(F)x.appendChild(cl());else{let Ue=fw("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);Ue&&x.appendChild(Ue)}}se&&e.stopReason&&!e.streaming&&(O||(Z.style.display="none"),x.appendChild(tL(e.stopReason,se)));let ge=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1,Ie=s?.actionEligibility,ye=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ie?.canEdit===!0||o?.showQuote===!0&&Ie?.canQuote===!0||hw(o,"user").length>0);if((ge||ye)&&o){let fe=yw(e,ye?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Ie);x.appendChild(fe)}if(!u||e.role==="system")return x;let ce=E("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Je=mL(d,e.role);return y==="right"||y==="left"&&e.role==="user"?ce.append(x,Je):ce.append(Je,x),ce},yL=(e,t,n,o,r,s)=>{let a=n??{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):hl(e,t,n,o,r,s)};var bL=40,vL=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=le(t.name,bL);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(G("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(G("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},bw=(e,t,n={})=>{let o=G("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=E("p","persona-welcome-kicker");r.hidden=!0;let s=E("h2","persona-welcome-title"),a=E("p","persona-welcome-subtitle"),l=G("div",{className:"persona-welcome-head-text"},r,s),d=G("div",{className:"persona-welcome-title-row"},o,l);return{host:G("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},d,a,t),iconHolder:o,kicker:r,title:s,subtitle:a,starterSuggestions:t}},Bi=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},Dd=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",vL(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},CL="data-persona-welcome-plugin",vw="data-persona-welcome-overlay",_d="persona-welcome-overlay-active",vm=new WeakMap,Cm=(e,t,n)=>{n.setAttribute(CL,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(vw,""),e.classList.contains(_d)||(vm.set(e,e.scrollTop),e.classList.add(_d),e.scrollTop=0)},wm=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(vw),e.classList.contains(_d)&&(e.classList.remove(_d),e.scrollTop=vm.get(e)??e.scrollTop,vm.delete(e))},Cw=()=>{let e=G("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Nd=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=G("div",{className:fl("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(G("div",{className:"persona-flex"},r)),e.hidden=!1},ww=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,xw=(e,t)=>{if(ww()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,a=0;if(o){let v=getComputedStyle(o);r=parseFloat(v.rowGap)||0;let x=e.previousElementSibling,w=e.nextElementSibling,O=o.getBoundingClientRect().top+(parseFloat(v.borderTopWidth)||0)+(parseFloat(v.paddingTop)||0)-o.scrollTop;s=Math.max(0,x?n.top-x.getBoundingClientRect().bottom-r:n.top-O),a=Math.max(0,w?w.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let d=getComputedStyle(e),p=parseFloat(d.paddingTop)||0,u=parseFloat(d.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${u}px`,marginTop:`${s}px`,marginBottom:`${a}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),y=!1,h=()=>{y||(y=!0,e.style.overflow=l,t(m))};return m.finished.then(h).catch(h),m},Sw=(e,t,n)=>{if(t<=1||ww()||typeof e.animate!="function"||!e.isConnected)return null;let o=n==="drop"?-t:t;return e.animate([{transform:`translateY(${o}px)`},{transform:"none"}],{duration:260,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var wL="Hello \u{1F44B}",xL="I can answer questions and help you get things done here.",Aw=new WeakSet,yn=(e,t)=>!!e&&e[t]!==void 0,SL=(e,t)=>{!e||e.debug!==!0||!t.length||Aw.has(e)||(Aw.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Bo=e=>{let t=e?.welcome,n=e?.copy,o=yn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":yn(t,"dismiss")?t.dismiss:"never",s=[];yn(t,"title")&&yn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),yn(t,"subtitle")&&yn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),yn(t,"variant")&&yn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&yn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&yn(t,"dismiss")&&t.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let a=t?.anchor==="center"?"center":"bottom",l=ol(t?.anchorComposerTop)!==null;return yn(t,"anchorComposerTop")&&!l&&s.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),a!=="center"&&(yn(t,"anchorComposerTop")||yn(t,"composerGap"))&&s.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),SL(e,s),{title:yn(t,"title")?t.title:n?.welcomeTitle??wL,kicker:t?.kicker??"",subtitle:yn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??xL,icon:t?.icon,align:t?.align==="start"||t?.align==="center"?t.align:void 0,iconPlacement:t?.icon&&typeof t.icon!="function"&&t.icon.placement==="inline"?"inline":"above",variant:o,dismiss:r,message:o==="hero"?void 0:t?.message,anchor:a,anchorComposerTop:l?t.anchorComposerTop:"44%",composerGap:t?.composerGap?.trim()||Ad}},Mw=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Is=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var Ew="16px",Sm="10px",Am="14px",Tw=e=>{let t=e?.launcher?.enabled??!0,n=St(e);if(Fr(e)){let u=e?.launcher?.composerBar??{},m=E("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=u.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??rn);let y=E("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",m.appendChild(y);let h=E("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=u.expandedSize??"anchored",h.style.zIndex=String(e?.launcher?.zIndex??rn),{wrapper:m,panel:y,pillRoot:h}}if(n){let u=E("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=E("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return u.appendChild(m),{wrapper:u,panel:m}}if(!t){let u=E("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=E("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=e?.launcher?.width??"100%";return u.style.width=y,m.style.width="100%",u.appendChild(m),{wrapper:u,panel:m}}let r=e?.launcher??{},s=r.position&&zn[r.position]?zn[r.position]:zn["bottom-right"],a=E("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??rn);let l=E("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=e?.launcher?.width??e?.launcherWidth??no;return l.style.width=p,l.style.maxWidth=p,a.appendChild(l),{wrapper:a,panel:l}},Mm=e=>{let t=G("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":dm(e)}});return t.hidden=!0,t},Pw=(e,t)=>{let n=Mm("starter"),o=bw(e,n,{flatShadow:St(e)}),r=Bo(e);Dd(o,r),Bi(t,o.host,Is(r,e?.initialMessages));let s=Cw();return Nd(s,r.message,e),{welcome:o,greetingHost:s}},AL=(e,t)=>{let n=E("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}=Li(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:Ew,iconSize:Sm});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let _=Ii(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Ew,iconSize:Am});a=_.button,l=_.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=G("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=G("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"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=Pw(e,p),{host:y,title:h,subtitle:v}=u,x=u.starterSuggestions,w=E("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),k=Mm("followUp"),O=Dr(e,!0);O&&(w.style.maxWidth=O,w.style.marginLeft="auto",w.style.marginRight="auto",w.style.width="100%"),p.append(y,m,w,k);let D=G("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),T=Od({config:e}),{root:I,textNode:A}=cw();return n.append(d,r,p,D),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:w,starterSuggestions:x,transcriptSuggestions:k,composerOverlay:D,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:y,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:h,introSubtitle:v,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:E("span"),headerTitle:E("span"),headerSubtitle:E("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:I,peekTextNode:A}},kw=(e,t=!0)=>{if(Fr(e))return AL(e,t);let n=G("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=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?ml(e,o,{showClose:t}):$r({config:e,showClose:t}),a=G("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"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=Pw(e,a),{host:p,title:u,subtitle:m}=l,y=l.starterSuggestions,h=E("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),v=Mm("followUp"),x=Dr(e,!1);x&&(h.style.maxWidth=x,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),a.append(p,d,h,v);let w=Wi({config:e}),k=e?.layout?.showFooter!==!1;r?Ri(n,s,e):(s.header.style.display="none",Ri(n,s,e)),n.append(a);let O=G("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return k||(w.footer.style.display="none"),n.append(w.footer),n.append(O),{container:n,body:a,messagesWrapper:h,starterSuggestions:y,transcriptSuggestions:v,composerOverlay:O,suggestions:w.suggestions,textarea:w.textarea,sendButton:w.sendButton,sendButtonWrapper:w.sendButtonWrapper,micButton:w.micButton,micButtonWrapper:w.micButtonWrapper,composerForm:w.composerForm,statusText:w.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:d,introKicker:l.kicker,introTitle:u,introSubtitle:m,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:w.footer,attachmentButton:w.attachmentButton,attachmentButtonWrapper:w.attachmentButtonWrapper,attachmentInput:w.attachmentInput,attachmentPreviewsContainer:w.attachmentPreviewsContainer,actionsRow:w.actionsRow,leftActions:w.leftActions,rightActions:w.rightActions,setSendButtonMode:w.setSendButtonMode}};var Em=(e,t)=>{let n=E("button");n.type="button",n.innerHTML=`
29
29
  <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>
30
30
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
31
31
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -33,14 +33,14 @@ _Details: ${n.message}_`:o}var Ig=e=>({isError:!0,content:[{type:"text",text:e}]
33
33
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
34
34
  </span>
35
35
  <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>
36
- `,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=Tt(s),d=n.querySelector("[data-role='launcher-title']");if(d){let $=a.title??"Chat Assistant";d.textContent=$,d.setAttribute("title",$)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let $=a.subtitle??"Here to help you get answers fast";p.textContent=$,p.setAttribute("title",$)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||l?u.style.display="none":u.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let $=a.agentIconSize??"40px";if(m.style.height=$,m.style.width=$,a.agentIconBackgroundColor?(m.style.backgroundColor=a.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",a.agentIconName){let T=parseFloat($)||24,R=pe(a.agentIconName,T*.6,"var(--persona-text-inverse, #ffffff)",1.5);R?(m.appendChild(R),m.style.display=""):(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let $=a.agentIconSize??"40px";y.style.height=$,y.style.width=$,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let h=n.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let $=a.callToActionIconSize??"32px";h.style.height=$,h.style.width=$,a.callToActionIconBackgroundColor?(h.style.backgroundColor=a.callToActionIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(h.style.color=a.callToActionIconColor,h.classList.remove("persona-text-persona-call-to-action")):(h.style.color="",h.classList.add("persona-text-persona-call-to-action"));let T=0;if(a.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=a.callToActionIconPadding,T=(parseFloat(a.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),a.callToActionIconHidden)h.style.display="none";else if(h.style.display=l?"none":"",h.innerHTML="",a.callToActionIconName){let R=parseFloat($)||24,A=Math.max(R-T,8),N=pe(a.callToActionIconName,A,"currentColor",1.5);N?h.appendChild(N):h.textContent=a.callToActionIconText??"\u2197"}else h.textContent=a.callToActionIconText??"\u2197"}let C=a.position&&jn[a.position]?jn[a.position]:jn["bottom-right"],S="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",x="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-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?x:`${S} ${C}`,l||(n.style.zIndex=String(a.zIndex??sn));let P="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",O="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=a.border??P,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:O,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=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},wL="teaser-dismissed",kw=new Set,Tw=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${wL}`},xL=(e,t)=>{if(kw.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},SL=(e,t)=>{if(kw.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},AL=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,ML=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Tt(e??{})?null:t},Pw=(e,t)=>{let n=M("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,a=null,l=null,d=null,p=!1,u=!1,m=!1,y=!1,h=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,C=()=>{d!==null&&(clearTimeout(d),d=null)},S=()=>{!s||!p||(p=!1,s.hidden=!0)},x=ee=>{C(),m=!0,S(),SL(Tw(o),ee&&h())},P=ee=>{!r||m||x(ee==="user"&&p)},O=()=>{d=null,!(!s||m||y)&&(u=!0,p=!0,s.hidden=!1,!(AL()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},$=()=>{!r||!s||m||u||y||xL(Tw(o),h())||(C(),d=setTimeout(O,Math.max(0,r.delayMs??0)))},T=()=>{x(h()),t()},R=ee=>{ee.stopPropagation(),x(h())},N=Em(e,()=>{P("user"),t()}),G=()=>{C(),l?.removeEventListener("click",T),a?.removeEventListener("click",R),s?.remove(),s=null,l=null,a=null,p=!1},ae=()=>{l=Q("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",T),a=Q("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",R),s=Q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,N.element)},Y=()=>{let ee=o.launcher?.position??"bottom-right",K=jn[ee]??jn["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",N.element.style.position="";return}n.className=mn("persona-launcher-surface",K),n.setAttribute("data-teaser",ee),n.style.zIndex=String(o.launcher?.zIndex??sn),N.element.style.position="static"},E=ee=>{let K=ML(ee);if(r=K,!K){G();return}s||ae(),l.textContent=K.text,a.hidden=K.dismissible===!1,a.setAttribute("aria-label",K.dismissLabel??"Dismiss message"),$()},B=ee=>{o=ee,N.update(ee),E(ee),Y()},H=(ee,K="user")=>{y=ee,ee&&P(K)},L=()=>{G(),N.destroy(),n.remove()};return n.appendChild(N.element),e&&(E(e),Y()),{element:n,launcher:N,get teaser(){return s?{element:s,show:O,dismiss:x}:null},setPanelOpen:H,update:B,destroy:L}};var Lw=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Aw(e),s=Ew(e,t),a={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,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},p={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:a,panelElements:s,transcript:l,header:d,composer:p,replaceHeader:y=>(d.element.replaceWith(y.header),d.element=y.header,d.iconHolder=y.iconHolder,d.headerTitle=y.headerTitle,d.headerSubtitle=y.headerSubtitle,d.closeButton=y.closeButton,d.closeButtonWrapper=y.closeButtonWrapper,d.clearChatButton=y.clearChatButton,d.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{p.footer.replaceWith(y),p.footer=y}}},Tm=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>Em(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Pw(e,n);return{instance:r,element:r.element}};var EL=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},TL=(e,t,n)=>`${EL(e)}plugin:${t}:${n}`,Iw=e=>{let t=new Map,n=!1,o=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=a=>TL(e(),r,a);return{get:a=>{let l=s(a),d=o();if(d)try{return d.getItem(l)}catch{n=!0}return t.get(l)??null},set:(a,l)=>{let d=s(a),p=o();if(p)try{p.setItem(d,l);return}catch{n=!0}t.set(d,l)},remove:a=>{let l=s(a);t.delete(l);let d=o();if(d)try{d.removeItem(l)}catch{n=!0}}}}};var ji=(e,t,n)=>{let o=n;for(let r of t){let s=M("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};import{ChevronDown as kL,ChevronUp as PL}from"lucide";var LL=["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"],IL="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",RL="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",HL=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),jd=(e,t)=>{let n=M("div",["persona-message-bubble",e,...LL].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},qd=e=>{let t=M("button",e.expandable?IL:RL);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},km=(e,t,n)=>{e.innerHTML="";let o=Wt(t?PL:kL,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},zd=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=M("div","persona-flex persona-items-center");km(o,n.expanded,n.iconColor);let r=M("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),e.append(t,r),o},Vd=e=>{let t=M("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();HL(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Kd=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&km(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},Gd=(e,t,n)=>{let o=n.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),a=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let d=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");d&&km(d,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};var qi=new Set,WL=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
37
- `):""},Rw=(e,t)=>{Gd(e,t,{stateSet:qi,previewKind:"reasoning",iconColor:"currentColor"})},Pm=(e,t)=>{let n=e.reasoning,o=jd("persona-reasoning-bubble",e.id);if(!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&qi.has(e.id),l=n.status!=="complete",d=WL(e,r.previewMaxLines??3),p=qd({expandable:s,expanded:a,bubbleType:"reasoning"}),u=M("div","persona-flex persona-flex-col persona-text-left"),m=M("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",h=t?.reasoning??{},C=String(n.startedAt??Date.now()),S=()=>{let L=M("span","");return L.setAttribute("data-tool-elapsed",C),L.textContent=ed(n),L},x=h.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:y,previewText:d,isActive:l,config:t??{},elapsed:ed(n),createElapsedElement:S});typeof x=="string"&&x.trim()?(m.textContent=x,u.appendChild(m)):x instanceof HTMLElement?u.appendChild(x):(m.textContent=y,u.appendChild(m));let P=M("span","persona-text-xs persona-text-persona-primary");P.textContent=Kb(n),u.appendChild(P);let O=r.loadingAnimation??"none",$=h.activeTextTemplate,T=h.completeTextTemplate,R=l?$:T,A=x instanceof HTMLElement,N=(L,ee)=>{m.textContent="";let K=td(L,""),ue=0;for(let le of K){let me=le.styles.length>0?(()=>{let Re=M("span",le.styles.map(He=>`persona-tool-text-${He}`).join(" "));return m.appendChild(Re),Re})():m;if(le.isDuration&&l)me.appendChild(S());else{let Re=le.isDuration?ed(n):le.text;ee?ue=ji(me,Re,ue):me.appendChild(document.createTextNode(Re))}}};if(!A&&R)if(P.style.display="none",m.style.display="",l&&O!=="none"){let L=h.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),O==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${L}ms`),N(R,!1)):(m.classList.add(`persona-tool-loading-${O}`),m.style.setProperty("--persona-tool-anim-duration",`${L}ms`),O==="shimmer-color"&&(h.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor)),N(R,!0))}else N(R,!1);else if(!A&&l&&O!=="none"){m.style.display="";let L=h.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),O==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${L}ms`);else{m.classList.add(`persona-tool-loading-${O}`),m.style.setProperty("--persona-tool-anim-duration",`${L}ms`),O==="shimmer-color"&&(h.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor));let ee=m.textContent||y;m.textContent="",ji(m,ee,0)}n.status==="complete"&&(m.style.display="none")}else A||(n.status==="complete"?m.style.display="none":m.style.display="");if(r.iconName&&!A){let L=M("span","persona-reasoning-header-icon"),ee=pe(r.iconName,16,"currentColor",2);ee&&(L.appendChild(ee),p.appendChild(L))}let G="currentColor",ae=zd(p,u,{expandable:s,expanded:a,iconColor:G,metaGap:!1}),Y=Vd({bubble:o,previewKind:"reasoning",expanded:a,isActive:l,previewText:d,activePreview:r.activePreview,activeMinHeight:r.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:d,isActive:l,config:t??{}})});if(!s)return o.append(p,Y),o;let E=M("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");E.style.display=a?"":"none";let B=n.chunks.join(""),H=M("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return H.textContent=B||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),E.appendChild(H),Kd({expanded:a,header:p,toggleIcon:ae,content:E,collapsedPreview:Y,iconColor:G}),o.append(p,Y,E),o};var zi=new Set,Hw=e=>e.toggleTextColor||e.headerTextColor||"var(--persona-primary, #171717)",OL=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
38
- `);let r=Jc(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
39
- `):""},Lm=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},BL=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=OL(e,o?.previewMaxLines??3),a=n?Yb(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",d=t?.toolCall??{},p=a;return r==="tool-name"?p=n.name?.trim()||a:r==="tool-preview"&&s&&(p=s),l&&d.activeTextTemplate?p=mg(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=mg(n,d.completeTextTemplate,p)),{summary:p,previewText:s,isActive:l}},Ww=(e,t,n)=>{Gd(e,t,{stateSet:zi,previewKind:"tool",iconColor:Hw(n?.toolCall??{})})},Im=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=jd("persona-tool-bubble",e.id);if(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=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&zi.has(e.id),{summary:d,previewText:p,isActive:u}=BL(e,t),m=qd({expandable:a,expanded:l,bubbleType:"tool"});o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let y=M("div","persona-flex persona-flex-col persona-text-left"),h=M("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(h.style.color=o.headerTextColor);let C=String(n.startedAt??Date.now()),S=()=>{let E=M("span","");return E.setAttribute("data-tool-elapsed",C),E.textContent=Ka(n),E},x=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:t??{},elapsed:Ka(n),createElapsedElement:S});typeof x=="string"&&x.trim()?(h.textContent=x,y.appendChild(h)):x instanceof HTMLElement?y.appendChild(x):(h.textContent=d,y.appendChild(h));let P=s.loadingAnimation??"none",O=o.activeTextTemplate,$=o.completeTextTemplate,T=u?O:$,R=x instanceof HTMLElement,A=(E,B)=>{h.textContent="";let H=n.name?.trim()||"tool",L=td(E,H),ee=0;for(let K of L){let ue=K.styles.length>0?(()=>{let le=M("span",K.styles.map(me=>`persona-tool-text-${me}`).join(" "));return h.appendChild(le),le})():h;if(K.isDuration&&u)ue.appendChild(S());else{let le=K.isDuration?Ka(n):K.text;B?ee=ji(ue,le,ee):ue.appendChild(document.createTextNode(le))}}};if(!R)if(u&&P!=="none"){let E=o.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),P==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${E}ms`),T&&A(T,!1);else if(h.classList.add(`persona-tool-loading-${P}`),h.style.setProperty("--persona-tool-anim-duration",`${E}ms`),P==="shimmer-color"&&(o.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),T)A(T,!0);else{let B=h.textContent||d;h.textContent="",ji(h,B,0)}}else T&&A(T,!1);let N=Hw(o),G=zd(m,y,{expandable:a,expanded:l,iconColor:N,metaGap:!0}),ae=Vd({bubble:r,previewKind:"tool",expanded:l,isActive:u,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:p,isActive:u,config:t??{}})});if(!a)return r.append(m,ae),r;let Y=M("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(Y.style.display=l?"":"none",o.contentBackgroundColor&&(Y.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(Y.style.color=o.contentTextColor),o.contentPaddingX&&(Y.style.paddingLeft=o.contentPaddingX,Y.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(Y.style.paddingTop=o.contentPaddingY,Y.style.paddingBottom=o.contentPaddingY),n.name){let E=M("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?E.style.color=o.contentTextColor:o.headerTextColor&&(E.style.color=o.headerTextColor),E.textContent=n.name,Y.appendChild(E)}if(n.args!==void 0){let E=M("div","persona-space-y-1"),B=M("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Arguments";let H=M("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");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",Lm(H,o),H.textContent=Jc(n.args),E.append(B,H),Y.appendChild(E)}if(n.chunks&&n.chunks.length){let E=M("div","persona-space-y-1"),B=M("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Activity";let H=M("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");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",Lm(H,o),H.textContent=n.chunks.join(""),E.append(B,H),Y.appendChild(E)}if(n.status==="complete"&&n.result!==void 0){let E=M("div","persona-space-y-1"),B=M("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Result";let H=M("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");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",Lm(H,o),H.textContent=Jc(n.result),E.append(B,H),Y.appendChild(E)}if(n.status==="complete"&&typeof n.duration=="number"){let E=M("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(E.style.color=o.contentTextColor),E.textContent=`Duration: ${n.duration}ms`,Y.appendChild(E)}return Kd({expanded:l,header:m,toggleIcon:G,content:Y,collapsedPreview:ae,iconColor:N}),r.append(m,ae,Y),r};var{setLoader:cN,load:_L,provide:dN,getSync:DL}=vt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var Ow=_L;var Bw=DL;var{setLoader:gN,load:NL}=vt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var Rm=NL;var Hm=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Fo=new Hm;var Wm=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:CN,load:FL,provide:wN,getSync:$L}=vt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),Vi=null,Yd=new Set,_w=e=>{if(Vi)return Vi;Vi=e,e.initArtifactsUi({componentRegistry:Fo});for(let o of Wm)Fo.has(o)||Fo.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Oo();t?e.__provideMarkdownParsers(t):Na(()=>{let o=Oo();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>Fc());let n=[...Yd];Yd.clear();for(let o of n)try{o()}catch{}return e};var Qd=()=>FL().then(_w);var ur=()=>{if(Vi)return Vi;let e=$L();return e?_w(e):null},Om=e=>Vi?()=>{}:(Yd.add(e),()=>{Yd.delete(e)});function vn(e){return e?.features?.artifacts?.enabled===!0}function Dw(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!vn(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function UL(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Nw=["panel","seamless","detached"];function Bm(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Nw.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function _m(e){return!e||!vn(e)?!1:Bm(e)==="detached"}function Cl(e,t){if(!vn(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),UL(e),Dw(e,t);return}let n=t.features?.artifacts?.layout,o=Bm(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,d]of a){let p=l?.trim();p?e.style.setProperty(d,p):e.style.removeProperty(d)}Dw(e,t)}function wl(e,t){for(let l of Nw)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!vn(t))return;let n=t.features?.artifacts?.layout,o=Bm(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function Fw(e,t){return!t||!vn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var jL=new Set(["__proto__","prototype","constructor"]),qL=new Set(["collapsed","card","panel","inline"]),$w=new Set(["markdown","component"]),zL=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ns=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jd=e=>!jL.has(e),Dm=e=>typeof e=="string"&&qL.has(e),Fs=e=>Object.keys(e).length>0;function $o(e,t,n,o){e.push({path:t,code:n,message:o})}var VL="Ignored because this key is not part of the persisted preference schema.",Xd="Ignored an unsupported value.",KL="Expected collapsed, panel, or inline.",GL='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Uw={kind:"mode",message:Xd},Ki={kind:"string",message:"Expected a CSS length string."},gr={kind:"boolean"},YL={paneWidth:Ki,paneMaxWidth:Ki,paneMinWidth:Ki,expandedPanelWidth:Ki,resizableMinWidth:Ki,resizableMaxWidth:Ki,expandLauncherPanelWhenOpen:gr,resizable:gr},QL={kind:"object",message:"Expected a preference object.",children:{showToolCalls:gr,showReasoning:gr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Xd},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Xd},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Xd},expandable:gr,grouped:gr}},reasoningDisplay:{kind:"object",children:{expandable:gr,activePreview:gr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Uw,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Uw,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:$w,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:$w}}},filePreview:{kind:"object",children:{enabled:gr}},layout:{kind:"object",children:YL}}}}};function jw(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:$o(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:$o(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:$o(o,n,"invalid_value",t.message);case"mode":return Dm(e)?Fn(e):$o(o,n,"invalid_value",t.message);case"modeMap":{if(!Ns(e))return $o(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,l]of Object.entries(e)){let d=r?a:Ls(a);Jd(a)&&(r?r.has(a):zL.test(d))?Dm(l)?s[d]=Fn(l):$o(o,`${n}.${a}`,"invalid_value",KL):$o(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":GL)}return Fs(s)?s:void 0}case"object":{if(t.bareMode&&Dm(e))return Fn(e);if(!Ns(e))return $o(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!Jd(l)||!r.includes(l))&&$o(o,s(l),"unknown_key",VL);let a={};for(let l of r){let d=t.children[l],p=jw(e[l],d,s(l),o);if(d.deprecated&&e[l]!==void 0&&$o(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=Ns(m)&&Ns(p)?{...m,...p}:p}return Fs(a)?a:void 0}}}function qw(e){let t=[];return{preferences:(e===null?void 0:jw(e,QL,"",t))??{},issues:t}}function Gi(e){if(Array.isArray(e))return e.map(Gi);if(!Ns(e))return e;let t={};for(let[n,o]of Object.entries(e))Jd(n)&&o!==void 0&&(t[n]=Gi(o));return t}function zw(e,t){let n=Gi(e);for(let[o,r]of Object.entries(t)){if(!Jd(o)||r===void 0)continue;let s=n[o];n[o]=Ns(s)&&Ns(r)?zw(s,r):Gi(r)}return n}function XL(e){let t={},n;for(let r of e){let s=qw(r).preferences;n=Vw(n,s.artifacts?.display),t=zw(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function JL(e,t){if(t===void 0)return e===void 0?void 0:Gi(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...Fs(r)?{byMediaType:r}:{}};return Fs(s)?s:void 0}function Vw(e,t){if(t===void 0)return e===void 0?void 0:Gi(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=JL(n.files,t.files),a={...o?{default:o}:{},...Fs(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Fs(a)?a:void 0}function Kw(e={},t){let n=XL(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=Vw(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}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 Zd(e){let t=e.preferences;return!t||!Fs(t)?e:{...e,features:Kw(e.features??{},[t])}}function ZL(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function eI(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function tI(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function nI(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Nm(e,t){let o=(t.getComputedStyle(e).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 Gw(e,t,n,o,r,s,a=200){let l=ZL(r,200),d=nI(t,n,o,a);d=Math.max(l,d);let p=eI(s);return p!==null&&(d=Math.min(d,p)),tI(e,l,d)}var{setLoader:kN,load:oI,provide:PN,getSync:rI}=vt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var Yw=oI;var Qw=rI;var Fm=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},ep=new Fm;var Xw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sI=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Jw=(e,t,n)=>{if(!Xw(e)||!Xw(t)||sI.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=Jw(e[r],t[r],s)}return o};function tp(e,t){let n=Jw(e,t,"");return nl(n)}var Zw=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var iI=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},aI=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},np=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=iI(e),n=aI(t);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}},$m=e=>typeof e=="string"?e:e==null?"":String(e),Yi={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:$m(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=$m(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:$m(n.text)}}},ex=e=>Array.isArray(e)?e.map(t=>String(t)):[],op=e=>{let t=new Set(ex(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(ex(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?e.parsers.reduce((p,u)=>p||u?.({text:a,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let d={action:l,message:s.message};e.emit("action:detected",d);for(let p of e.handlers)if(p)try{let u=()=>{e.emit("action:resubmit",d)},m=p(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!m)continue;if(m.handled){let y=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:y,resubmit:m.resubmit}}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var lI=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},cI=e=>e.map(t=>({...t,streaming:!1})),dI=e=>e.map(t=>({...t,status:"complete"})),Um=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?lI(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?cI(n.messages):void 0,artifacts:n.artifacts?dI(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var pI=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},tx=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return pI(e)},uI=async(e,t)=>{let n=await tx(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await tx(`${e}\0${t}`)}`}};var nx=(e,t,n)=>{let o="",r="",s="",a=!1,l=!1,d=0,p=null,u=null,m=new Set,y=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},h=()=>{let A=y();if(!A)return p;try{return A.getItem(o)}catch{return a=!0,p}},C=(A,N)=>{if(l||A===p)return;let G=p;p=A,d+=1;let ae={previousToken:G,token:A,source:N,revision:d};for(let Y of m)Y(ae)},S=A=>{l||A.key!==null&&A.key!==o||C(A.key===null?null:A.newValue??null,"external")},x=(async()=>{let A=await uI(e,t);o=A.storageKey,r=A.leaseKey,s=A.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",S)})(),P=A=>new Promise(N=>setTimeout(N,A)),O=()=>{let A=y();if(!A)return null;try{let N=A.getItem(r);if(!N)return null;let G=JSON.parse(N);return typeof G?.expiresAt=="number"&&typeof G?.ownerNonce=="string"?G:null}catch{return null}},$=A=>{let N=y();if(N)try{O()?.ownerNonce===A&&N.removeItem(r)}catch{}},T=A=>new Promise(N=>{let G=setTimeout(ae,A);function ae(){clearTimeout(G),window.removeEventListener("storage",Y),N()}function Y(E){(E.key===null||E.key===r)&&ae()}window.addEventListener("storage",Y)}),R=async A=>{let N=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;Date.now()<G;){let ae=y();if(!ae)break;let Y=Date.now(),E=O();if(E&&E.expiresAt>Y&&E.ownerNonce!==N){await T(Math.min(E.expiresAt-Y,500));continue}try{ae.setItem(r,JSON.stringify({ownerNonce:N,expiresAt:Y+1e4}))}catch{a=!0;break}if(await P(20+Math.random()*40),O()?.ownerNonce!==N){await T(500);continue}u=N;try{return await A()}finally{u=null,$(N)}}return A()};return{ready:x,async get(){return await x,C(h(),"external"),p},async set(A){await x;let N=y();if(N)try{N.setItem(o,A)}catch{a=!0}C(A,"local")},async clear(){await x;let A=y();if(A)try{A.removeItem(o)}catch{a=!0}C(null,"local")},revision(){return d},subscribe(A){return m.add(A),()=>{m.delete(A)}},async withFirstInitLock(A){await x;let N=globalThis.navigator?.locks;return N?.request?N.request(s,()=>A()):y()?R(A):A()},matches(A,N,G){return A===e&&N===t&&G===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",S),u&&$(u)}}};var{setLoader:NN,load:gI}=vt({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var jm=gI;var qm=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},mr=e=>Object.freeze({...e}),ox=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),rx=e=>e?mr(e):null;function sx(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,a=!1,l=null,d=[],p=()=>{for(let T of d.splice(0))try{T()}catch(R){qm("renderHistoryView cleanup",R)}},u=(T,R)=>{for(let A of t){let N=A[T];if(N)try{let G=N(R);if(G)return G}catch(G){qm(T,G)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),y={header:T=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:mr(T.identityStatus),pendingAction:rx(T.pendingAction),copy:mr(T.copy),actions:Object.freeze({close:S.close,startNewConversation:S.startNewConversation}),defaultRenderer:T.defaultRenderer})):null,conversation:T=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:ox(T.conversation),active:T.active,pending:T.pending,open:T.open,requestDelete:T.requestDelete,defaultRenderer:T.defaultRenderer})):null,state:T=>a?u("renderHistoryState",Object.freeze({...m(),state:mr(T.state),identityStatus:mr(T.identityStatus),copy:mr(T.copy),...T.retry?{retry:T.retry}:{},...T.startNewConversation?{startNewConversation:T.startNewConversation}:{},defaultRenderer:T.defaultRenderer})):null},h=t.flatMap(T=>(T.railSections??[]).map(R=>({...R,placement:R.placement??"above-conversations",items:[],render:A=>R.render(Object.freeze({collapsed:A,presentation:e.getPresentation(),actions:S}))}))),C=e.createView({slots:y,renderDom:!1,onModelChange:()=>$(),railSections:h}),S=Object.freeze({...C.operations,close:e.close}),x=()=>(a=!0,C.setDomRenderEnabled(!0),C.element),P=T=>Object.freeze({conversations:Object.freeze(T.conversations.map(ox)),activeConversationId:T.activeConversationId,state:mr(T.state),pendingAction:rx(T.pendingAction),identityStatus:mr(T.identityStatus),nextCursor:T.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:mr(C.copy),actions:S,defaultRenderer:x,requestRender:()=>$(),onCleanup:R=>{d.push(R)}}),O=()=>{a=!1;let T=null;for(let A of t)if(A.renderHistoryView){try{T=A.renderHistoryView(P(C.getModel()))}catch(N){qm("renderHistoryView",N),T=null}if(T)break}let R=!T||T.contains(C.element);return a=R,C.setDomRenderEnabled(R),T??C.element};function $(){if(!(!s||o||r)){r=!0;try{p();let T=O();if(T===l)return;let R=l;l=T,e.onElementChanged(T,R)}finally{r=!1}}}return s=!0,$(),{view:C,get element(){return l??C.element},requestRender:$,dispose:()=>{o=!0,p()}}}var mI=null;function ix(){return mI}var fI=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),hI=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),zm=e=>hI.get(e)??"Conversation history is unavailable right now.";function yI(e){if(e instanceof yo)return e;if(e instanceof $e){let t=fI.get(e.code)??"unavailable";return new yo(t,zm(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new yo("unavailable",zm("unavailable"))}function ax(e){let t=()=>e.getClient?.()??e.client,n=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new yo("unsupported_scope",zm("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw yI(p)}},a=l=>{let d=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){d||(d=!0,l.commit(),await e.onActivationCommitted(l.session))},discard(){d||(d=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return t().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return t().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let d=await t().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(l,d){return s(d.context.scope,async()=>{let p=await t().getConversation(l,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),u=ov(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:Xa([],u),conversationRevision:p.conversationRevision??"",nextCursor:p.nextMessageCursor}})},async prepareOpen(l,d){return s(d.context.scope,async()=>a(await t().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>a(await t().prepareNewConversationSession()))},async delete(l,d){await s(d.context.scope,()=>t().deleteConversation(l,{scope:d.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>t().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var bI=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],lx={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."};function Vm(e){if(!e)return lx;let t={...lx};for(let n of bI){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var vI="button:not([disabled])";function rp(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=Q("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),a=Q("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=Q("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},Q("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),Q("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),Q("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,a));for(let p of[s,a])p.style.minHeight="44px",p.style.minWidth="88px",p.style.padding="0 16px",p.style.borderRadius="var(--persona-radius-md, 0.5rem)",p.style.cursor="pointer",p.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",a.style.border="none",a.style.background="var(--persona-danger, #b42318)",a.style.color="var(--persona-danger-fg, #ffffff)";let d=Q("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(p=>{let u=!1,m=h=>{u||(u=!0,d.removeEventListener("keydown",y,!0),d.remove(),t?.focus(),p(h))};function y(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),m(!1);return}if(h.key!=="Tab")return;let C=Array.from(l.querySelectorAll(vI));if(C.length===0)return;let S=C[0],x=C[C.length-1],P=document.activeElement;h.shiftKey&&(P===S||!l.contains(P))?(h.preventDefault(),x.focus()):!h.shiftKey&&P===x&&(h.preventDefault(),S.focus())}d.addEventListener("keydown",y,!0),d.addEventListener("pointerdown",h=>{h.target===d&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),e.host.appendChild(d),s.focus()})}import{parse as CI,STR as wI,OBJ as xI}from"partial-json";function SI(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function AI(e,t){if(!SI(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Km(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=CI(n,wI|xI),s=AI(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function MI(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Gm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Fo.get(e.component);if(!s){if(Wm.includes(e.component)){Qd().catch(()=>{});let l=M("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function EI(){let e=Km();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function cx(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function sp(e){let t=cx(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Ym(e){let t=cx(e);if(!t)return null;try{let n=JSON.parse(t);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:t}}}catch{}return null}var TI=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Qm(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:p=TI}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,y=document.createElement("div");y.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 S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,h.appendChild(S),y.appendChild(h);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-csat",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Satisfaction rating from 1 to 5");let P=[];for(let A=1;A<=5;A++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-star-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${p[A-1]}`),N.title=p[A-1],N.dataset.rating=String(A),N.innerHTML=`
36
+ `,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=St(s),d=n.querySelector("[data-role='launcher-title']");if(d){let D=a.title??"Chat Assistant";d.textContent=D,d.setAttribute("title",D)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let D=a.subtitle??"Here to help you get answers fast";p.textContent=D,p.setAttribute("title",D)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||l?u.style.display="none":u.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let D=a.agentIconSize??"40px";if(m.style.height=D,m.style.width=D,a.agentIconBackgroundColor?(m.style.backgroundColor=a.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",a.agentIconName){let T=parseFloat(D)||24,I=le(a.agentIconName,T*.6,"var(--persona-text-inverse, #ffffff)",1.5);I?(m.appendChild(I),m.style.display=""):(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let D=a.agentIconSize??"40px";y.style.height=D,y.style.width=D,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let h=n.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let D=a.callToActionIconSize??"32px";h.style.height=D,h.style.width=D,a.callToActionIconBackgroundColor?(h.style.backgroundColor=a.callToActionIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(h.style.color=a.callToActionIconColor,h.classList.remove("persona-text-persona-call-to-action")):(h.style.color="",h.classList.add("persona-text-persona-call-to-action"));let T=0;if(a.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=a.callToActionIconPadding,T=(parseFloat(a.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),a.callToActionIconHidden)h.style.display="none";else if(h.style.display=l?"none":"",h.innerHTML="",a.callToActionIconName){let I=parseFloat(D)||24,A=Math.max(I-T,8),_=le(a.callToActionIconName,A,"currentColor",1.5);_?h.appendChild(_):h.textContent=a.callToActionIconText??"\u2197"}else h.textContent=a.callToActionIconText??"\u2197"}let v=a.position&&zn[a.position]?zn[a.position]:zn["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",w="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-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?w:`${x} ${v}`,l||(n.style.zIndex=String(a.zIndex??rn));let k="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",O="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=a.border??k,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:O,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=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},ML="teaser-dismissed",Iw=new Set,Lw=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${ML}`},EL=(e,t)=>{if(Iw.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},TL=(e,t)=>{if(Iw.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},PL=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,kL=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||St(e??{})?null:t},Rw=(e,t)=>{let n=E("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,a=null,l=null,d=null,p=!1,u=!1,m=!1,y=!1,h=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,v=()=>{d!==null&&(clearTimeout(d),d=null)},x=()=>{!s||!p||(p=!1,s.hidden=!0)},w=J=>{v(),m=!0,x(),TL(Lw(o),J&&h())},k=J=>{!r||m||w(J==="user"&&p)},O=()=>{d=null,!(!s||m||y)&&(u=!0,p=!0,s.hidden=!1,!(PL()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},D=()=>{!r||!s||m||u||y||EL(Lw(o),h())||(v(),d=setTimeout(O,Math.max(0,r.delayMs??0)))},T=()=>{w(h()),t()},I=J=>{J.stopPropagation(),w(h())},_=Em(e,()=>{k("user"),t()}),K=()=>{v(),l?.removeEventListener("click",T),a?.removeEventListener("click",I),s?.remove(),s=null,l=null,a=null,p=!1},ie=()=>{l=G("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",T),a=G("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",I),s=G("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,_.element)},Z=()=>{let J=o.launcher?.position??"bottom-right",V=zn[J]??zn["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",_.element.style.position="";return}n.className=gn("persona-launcher-surface",V),n.setAttribute("data-teaser",J),n.style.zIndex=String(o.launcher?.zIndex??rn),_.element.style.position="static"},M=J=>{let V=kL(J);if(r=V,!V){K();return}s||ie(),l.textContent=V.text,a.hidden=V.dismissible===!1,a.setAttribute("aria-label",V.dismissLabel??"Dismiss message"),D()},B=J=>{o=J,_.update(J),M(J),Z()},H=(J,V="user")=>{y=J,J&&k(V)},R=()=>{K(),_.destroy(),n.remove()};return n.appendChild(_.element),e&&(M(e),Z()),{element:n,launcher:_,get teaser(){return s?{element:s,show:O,dismiss:w}:null},setPanelOpen:H,update:B,destroy:R}};var Hw=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Tw(e),s=kw(e,t),a={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,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},p={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:a,panelElements:s,transcript:l,header:d,composer:p,replaceHeader:y=>(d.element.replaceWith(y.header),d.element=y.header,d.iconHolder=y.iconHolder,d.headerTitle=y.headerTitle,d.headerSubtitle=y.headerSubtitle,d.closeButton=y.closeButton,d.closeButtonWrapper=y.closeButtonWrapper,d.clearChatButton=y.clearChatButton,d.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{p.footer.replaceWith(y),p.footer=y}}},Tm=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>Em(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Rw(e,n);return{instance:r,element:r.element}};var LL=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},IL=(e,t,n)=>`${LL(e)}plugin:${t}:${n}`,Ww=e=>{let t=new Map,n=!1,o=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=a=>IL(e(),r,a);return{get:a=>{let l=s(a),d=o();if(d)try{return d.getItem(l)}catch{n=!0}return t.get(l)??null},set:(a,l)=>{let d=s(a),p=o();if(p)try{p.setItem(d,l);return}catch{n=!0}t.set(d,l)},remove:a=>{let l=s(a);t.delete(l);let d=o();if(d)try{d.removeItem(l)}catch{n=!0}}}}};var _i=(e,t,n)=>{let o=n;for(let r of t){let s=E("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};import{ChevronDown as RL,ChevronUp as HL}from"lucide";var WL=["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"],OL="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",BL="persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none",_L=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Fd=(e,t)=>{let n=E("div",["persona-message-bubble",e,...WL].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},$d=e=>{let t=E("button",e.expandable?OL:BL);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},Pm=(e,t,n)=>{e.innerHTML="";let o=It(t?HL:RL,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},Ud=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=E("div","persona-flex persona-items-center");Pm(o,n.expanded,n.iconColor);let r=E("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),e.append(t,r),o},jd=e=>{let t=E("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();_L(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},qd=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&Pm(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},zd=(e,t,n)=>{let o=n.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),a=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let d=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");d&&Pm(d,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};var Di=new Set,DL=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
37
+ `):""},Ow=(e,t)=>{zd(e,t,{stateSet:Di,previewKind:"reasoning",iconColor:"currentColor"})},km=(e,t)=>{let n=e.reasoning,o=Fd("persona-reasoning-bubble",e.id);if(!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&Di.has(e.id),l=n.status!=="complete",d=DL(e,r.previewMaxLines??3),p=$d({expandable:s,expanded:a,bubbleType:"reasoning"}),u=E("div","persona-flex persona-flex-col persona-text-left"),m=E("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",h=t?.reasoning??{},v=String(n.startedAt??Date.now()),x=()=>{let R=E("span","");return R.setAttribute("data-tool-elapsed",v),R.textContent=Xc(n),R},w=h.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:y,previewText:d,isActive:l,config:t??{},elapsed:Xc(n),createElapsedElement:x});typeof w=="string"&&w.trim()?(m.textContent=w,u.appendChild(m)):w instanceof HTMLElement?u.appendChild(w):(m.textContent=y,u.appendChild(m));let k=E("span","persona-text-xs persona-text-persona-primary");k.textContent=Xb(n),u.appendChild(k);let O=r.loadingAnimation??"none",D=h.activeTextTemplate,T=h.completeTextTemplate,I=l?D:T,A=w instanceof HTMLElement,_=(R,J)=>{m.textContent="";let V=Jc(R,""),pe=0;for(let se of V){let ge=se.styles.length>0?(()=>{let Ie=E("span",se.styles.map(ye=>`persona-tool-text-${ye}`).join(" "));return m.appendChild(Ie),Ie})():m;if(se.isDuration&&l)ge.appendChild(x());else{let Ie=se.isDuration?Xc(n):se.text;J?pe=_i(ge,Ie,pe):ge.appendChild(document.createTextNode(Ie))}}};if(!A&&I)if(k.style.display="none",m.style.display="",l&&O!=="none"){let R=h.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),O==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${R}ms`),_(I,!1)):(m.classList.add(`persona-tool-loading-${O}`),m.style.setProperty("--persona-tool-anim-duration",`${R}ms`),O==="shimmer-color"&&(h.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor)),_(I,!0))}else _(I,!1);else if(!A&&l&&O!=="none"){m.style.display="";let R=h.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),O==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${R}ms`);else{m.classList.add(`persona-tool-loading-${O}`),m.style.setProperty("--persona-tool-anim-duration",`${R}ms`),O==="shimmer-color"&&(h.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor));let J=m.textContent||y;m.textContent="",_i(m,J,0)}n.status==="complete"&&(m.style.display="none")}else A||(n.status==="complete"?m.style.display="none":m.style.display="");if(r.iconName&&!A){let R=E("span","persona-reasoning-header-icon"),J=le(r.iconName,16,"currentColor",2);J&&(R.appendChild(J),p.appendChild(R))}let K="currentColor",ie=Ud(p,u,{expandable:s,expanded:a,iconColor:K,metaGap:!1}),Z=jd({bubble:o,previewKind:"reasoning",expanded:a,isActive:l,previewText:d,activePreview:r.activePreview,activeMinHeight:r.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:d,isActive:l,config:t??{}})});if(!s)return o.append(p,Z),o;let M=E("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");M.style.display=a?"":"none";let B=n.chunks.join(""),H=E("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return H.textContent=B||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),M.appendChild(H),qd({expanded:a,header:p,toggleIcon:ie,content:M,collapsedPreview:Z,iconColor:K}),o.append(p,Z,M),o};var Ni=new Set,Bw=e=>e.toggleTextColor||e.headerTextColor||"var(--persona-primary, #171717)",NL=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
38
+ `);let r=Yc(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
39
+ `):""},Lm=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},FL=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=n?.success===!1?n.error||"Tool failed":NL(e,o?.previewMaxLines??3),a=n?Zb(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",d=t?.toolCall??{},p=a;return r==="tool-name"?p=n.name?.trim()||a:r==="tool-preview"&&s&&(p=s),l&&d.activeTextTemplate?p=mg(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=mg(n,d.completeTextTemplate,p)),n.success===!1&&(p+=" \xB7 Failed"),{summary:p,previewText:s,isActive:l}},_w=(e,t,n)=>{zd(e,t,{stateSet:Ni,previewKind:"tool",iconColor:Bw(n?.toolCall??{})})},Im=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=Fd("persona-tool-bubble",e.id);if(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=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&Ni.has(e.id),{summary:d,previewText:p,isActive:u}=FL(e,t),m=$d({expandable:a,expanded:l,bubbleType:"tool"});o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let y=E("div","persona-flex persona-flex-col persona-text-left"),h=E("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(h.style.color=o.headerTextColor);let v=String(n.startedAt??Date.now()),x=()=>{let M=E("span","");return M.setAttribute("data-tool-elapsed",v),M.textContent=ja(n),M},w=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:t??{},elapsed:ja(n),createElapsedElement:x});typeof w=="string"&&w.trim()?(h.textContent=w,y.appendChild(h)):w instanceof HTMLElement?y.appendChild(w):(h.textContent=d,y.appendChild(h));let k=s.loadingAnimation??"none",O=o.activeTextTemplate,D=o.completeTextTemplate,T=u?O:D,I=w instanceof HTMLElement,A=(M,B)=>{h.textContent="";let H=n.name?.trim()||"tool",R=Jc(M,H),J=0;for(let V of R){let pe=V.styles.length>0?(()=>{let se=E("span",V.styles.map(ge=>`persona-tool-text-${ge}`).join(" "));return h.appendChild(se),se})():h;if(V.isDuration&&u)pe.appendChild(x());else{let se=V.isDuration?ja(n):V.text;B?J=_i(pe,se,J):pe.appendChild(document.createTextNode(se))}}};if(!I)if(u&&k!=="none"){let M=o.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),k==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${M}ms`),T&&A(T,!1);else if(h.classList.add(`persona-tool-loading-${k}`),h.style.setProperty("--persona-tool-anim-duration",`${M}ms`),k==="shimmer-color"&&(o.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),T)A(T,!0);else{let B=h.textContent||d;h.textContent="",_i(h,B,0)}}else T&&A(T,!1);let _=Bw(o),K=Ud(m,y,{expandable:a,expanded:l,iconColor:_,metaGap:!0}),ie=jd({bubble:r,previewKind:"tool",expanded:l,isActive:u,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:p,isActive:u,config:t??{}})});if(!a)return r.append(m,ie),r;let Z=E("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(Z.style.display=l?"":"none",o.contentBackgroundColor&&(Z.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(Z.style.color=o.contentTextColor),o.contentPaddingX&&(Z.style.paddingLeft=o.contentPaddingX,Z.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(Z.style.paddingTop=o.contentPaddingY,Z.style.paddingBottom=o.contentPaddingY),n.name){let M=E("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?M.style.color=o.contentTextColor:o.headerTextColor&&(M.style.color=o.headerTextColor),M.textContent=n.name,Z.appendChild(M)}if(n.args!==void 0){let M=E("div","persona-space-y-1"),B=E("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Arguments";let H=E("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");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",Lm(H,o),H.textContent=Yc(n.args),M.append(B,H),Z.appendChild(M)}if(n.chunks&&n.chunks.length){let M=E("div","persona-space-y-1"),B=E("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Activity";let H=E("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");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",Lm(H,o),H.textContent=n.chunks.join(""),M.append(B,H),Z.appendChild(M)}if(n.success===!1&&Z.appendChild(G("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),n.status==="complete"&&n.result!==void 0){let M=E("div","persona-space-y-1"),B=E("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Result";let H=E("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");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",Lm(H,o),H.textContent=Yc(n.result),M.append(B,H),Z.appendChild(M)}if(n.status==="complete"&&typeof n.duration=="number"){let M=E("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(M.style.color=o.contentTextColor),M.textContent=`Duration: ${n.duration}ms`,Z.appendChild(M)}return qd({expanded:l,header:m,toggleIcon:K,content:Z,collapsedPreview:ie,iconColor:_}),r.append(m,ie,Z),r};var{setLoader:fN,load:$L,provide:hN,getSync:UL}=ft({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var Dw=$L;var Nw=UL;var{setLoader:vN,load:jL}=ft({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var Rm=jL;var Hm=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},_o=new Hm;var Wm=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:EN,load:qL,provide:TN,getSync:zL}=ft({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),Fi=null,Vd=new Set,Fw=e=>{if(Fi)return Fi;Fi=e,e.initArtifactsUi({componentRegistry:_o});for(let o of Wm)_o.has(o)||_o.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Io();t?e.__provideMarkdownParsers(t):Oa(()=>{let o=Io();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>_c());let n=[...Vd];Vd.clear();for(let o of n)try{o()}catch{}return e};var Kd=()=>qL().then(Fw);var lr=()=>{if(Fi)return Fi;let e=zL();return e?Fw(e):null},Om=e=>Fi?()=>{}:(Vd.add(e),()=>{Vd.delete(e)});function bn(e){return e?.features?.artifacts?.enabled===!0}function $w(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!bn(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function VL(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Uw=["panel","seamless","detached"];function Bm(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Uw.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function _m(e){return!e||!bn(e)?!1:Bm(e)==="detached"}function yl(e,t){if(!bn(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),VL(e),$w(e,t);return}let n=t.features?.artifacts?.layout,o=Bm(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,d]of a){let p=l?.trim();p?e.style.setProperty(d,p):e.style.removeProperty(d)}$w(e,t)}function bl(e,t){for(let l of Uw)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!bn(t))return;let n=t.features?.artifacts?.layout,o=Bm(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function jw(e,t){return!t||!bn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var KL=new Set(["__proto__","prototype","constructor"]),GL=new Set(["collapsed","card","panel","inline"]),qw=new Set(["markdown","component"]),YL=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Rs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yd=e=>!KL.has(e),Dm=e=>typeof e=="string"&&GL.has(e),Hs=e=>Object.keys(e).length>0;function Do(e,t,n,o){e.push({path:t,code:n,message:o})}var QL="Ignored because this key is not part of the persisted preference schema.",Gd="Ignored an unsupported value.",XL="Expected collapsed, panel, or inline.",JL='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',zw={kind:"mode",message:Gd},$i={kind:"string",message:"Expected a CSS length string."},cr={kind:"boolean"},ZL={paneWidth:$i,paneMaxWidth:$i,paneMinWidth:$i,expandedPanelWidth:$i,resizableMinWidth:$i,resizableMaxWidth:$i,expandLauncherPanelWhenOpen:cr,resizable:cr},eI={kind:"object",message:"Expected a preference object.",children:{showToolCalls:cr,showReasoning:cr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Gd},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Gd},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Gd},expandable:cr,grouped:cr}},reasoningDisplay:{kind:"object",children:{expandable:cr,activePreview:cr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:zw,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:zw,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:qw,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:qw}}},filePreview:{kind:"object",children:{enabled:cr}},layout:{kind:"object",children:ZL}}}}};function Vw(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Do(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Do(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Do(o,n,"invalid_value",t.message);case"mode":return Dm(e)?Un(e):Do(o,n,"invalid_value",t.message);case"modeMap":{if(!Rs(e))return Do(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,l]of Object.entries(e)){let d=r?a:Ss(a);Yd(a)&&(r?r.has(a):YL.test(d))?Dm(l)?s[d]=Un(l):Do(o,`${n}.${a}`,"invalid_value",XL):Do(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":JL)}return Hs(s)?s:void 0}case"object":{if(t.bareMode&&Dm(e))return Un(e);if(!Rs(e))return Do(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!Yd(l)||!r.includes(l))&&Do(o,s(l),"unknown_key",QL);let a={};for(let l of r){let d=t.children[l],p=Vw(e[l],d,s(l),o);if(d.deprecated&&e[l]!==void 0&&Do(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=Rs(m)&&Rs(p)?{...m,...p}:p}return Hs(a)?a:void 0}}}function Kw(e){let t=[];return{preferences:(e===null?void 0:Vw(e,eI,"",t))??{},issues:t}}function Ui(e){if(Array.isArray(e))return e.map(Ui);if(!Rs(e))return e;let t={};for(let[n,o]of Object.entries(e))Yd(n)&&o!==void 0&&(t[n]=Ui(o));return t}function Gw(e,t){let n=Ui(e);for(let[o,r]of Object.entries(t)){if(!Yd(o)||r===void 0)continue;let s=n[o];n[o]=Rs(s)&&Rs(r)?Gw(s,r):Ui(r)}return n}function tI(e){let t={},n;for(let r of e){let s=Kw(r).preferences;n=Yw(n,s.artifacts?.display),t=Gw(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function nI(e,t){if(t===void 0)return e===void 0?void 0:Ui(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...Hs(r)?{byMediaType:r}:{}};return Hs(s)?s:void 0}function Yw(e,t){if(t===void 0)return e===void 0?void 0:Ui(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=nI(n.files,t.files),a={...o?{default:o}:{},...Hs(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Hs(a)?a:void 0}function Qw(e={},t){let n=tI(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=Yw(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}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 Qd(e){let t=e.preferences;return!t||!Hs(t)?e:{...e,features:Qw(e.features??{},[t])}}function oI(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function rI(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function sI(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function iI(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Nm(e,t){let o=(t.getComputedStyle(e).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 Xw(e,t,n,o,r,s,a=200){let l=oI(r,200),d=iI(t,n,o,a);d=Math.max(l,d);let p=rI(s);return p!==null&&(d=Math.min(d,p)),sI(e,l,d)}var{setLoader:WN,load:aI,provide:ON,getSync:lI}=ft({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var Jw=aI;var Zw=lI;var Fm=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Xd=new Fm;var ex=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cI=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),tx=(e,t,n)=>{if(!ex(e)||!ex(t)||cI.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=tx(e[r],t[r],s)}return o};function Jd(e,t){let n=tx(e,t,"");return Za(n)}var nx=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var dI=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},pI=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Zd=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=dI(e),n=pI(t);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}},$m=e=>typeof e=="string"?e:e==null?"":String(e),ji={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:$m(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=$m(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:$m(n.text)}}},ox=e=>Array.isArray(e)?e.map(t=>String(t)):[],ep=e=>{let t=new Set(ox(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(ox(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?e.parsers.reduce((p,u)=>p||u?.({text:a,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let d={action:l,message:s.message};e.emit("action:detected",d);for(let p of e.handlers)if(p)try{let u=()=>{e.emit("action:resubmit",d)},m=p(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!m)continue;if(m.handled){let y=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:y,resubmit:m.resubmit}}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var uI=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},gI=e=>e.map(t=>({...t,streaming:!1})),mI=e=>e.map(t=>({...t,status:"complete"})),Um=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?uI(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?gI(n.messages):void 0,artifacts:n.artifacts?mI(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var fI=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},rx=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return fI(e)},hI=async(e,t)=>{let n=await rx(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await rx(`${e}\0${t}`)}`}};var sx=(e,t,n)=>{let o="",r="",s="",a=!1,l=!1,d=0,p=null,u=null,m=new Set,y=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},h=()=>{let A=y();if(!A)return p;try{return A.getItem(o)}catch{return a=!0,p}},v=(A,_)=>{if(l||A===p)return;let K=p;p=A,d+=1;let ie={previousToken:K,token:A,source:_,revision:d};for(let Z of m)Z(ie)},x=A=>{l||A.key!==null&&A.key!==o||v(A.key===null?null:A.newValue??null,"external")},w=(async()=>{let A=await hI(e,t);o=A.storageKey,r=A.leaseKey,s=A.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",x)})(),k=A=>new Promise(_=>setTimeout(_,A)),O=()=>{let A=y();if(!A)return null;try{let _=A.getItem(r);if(!_)return null;let K=JSON.parse(_);return typeof K?.expiresAt=="number"&&typeof K?.ownerNonce=="string"?K:null}catch{return null}},D=A=>{let _=y();if(_)try{O()?.ownerNonce===A&&_.removeItem(r)}catch{}},T=A=>new Promise(_=>{let K=setTimeout(ie,A);function ie(){clearTimeout(K),window.removeEventListener("storage",Z),_()}function Z(M){(M.key===null||M.key===r)&&ie()}window.addEventListener("storage",Z)}),I=async A=>{let _=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,K=Date.now()+15e3;for(;Date.now()<K;){let ie=y();if(!ie)break;let Z=Date.now(),M=O();if(M&&M.expiresAt>Z&&M.ownerNonce!==_){await T(Math.min(M.expiresAt-Z,500));continue}try{ie.setItem(r,JSON.stringify({ownerNonce:_,expiresAt:Z+1e4}))}catch{a=!0;break}if(await k(20+Math.random()*40),O()?.ownerNonce!==_){await T(500);continue}u=_;try{return await A()}finally{u=null,D(_)}}return A()};return{ready:w,async get(){return await w,v(h(),"external"),p},async set(A){await w;let _=y();if(_)try{_.setItem(o,A)}catch{a=!0}v(A,"local")},async clear(){await w;let A=y();if(A)try{A.removeItem(o)}catch{a=!0}v(null,"local")},revision(){return d},subscribe(A){return m.add(A),()=>{m.delete(A)}},async withFirstInitLock(A){await w;let _=globalThis.navigator?.locks;return _?.request?_.request(s,()=>A()):y()?I(A):A()},matches(A,_,K){return A===e&&_===t&&K===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",x),u&&D(u)}}};var{setLoader:zN,load:yI}=ft({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var jm=yI;var qm=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},dr=e=>Object.freeze({...e}),ix=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),ax=e=>e?dr(e):null;function lx(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,a=!1,l=null,d=[],p=()=>{for(let T of d.splice(0))try{T()}catch(I){qm("renderHistoryView cleanup",I)}},u=(T,I)=>{for(let A of t){let _=A[T];if(_)try{let K=_(I);if(K)return K}catch(K){qm(T,K)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),y={header:T=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:dr(T.identityStatus),pendingAction:ax(T.pendingAction),copy:dr(T.copy),actions:Object.freeze({close:x.close,startNewConversation:x.startNewConversation}),defaultRenderer:T.defaultRenderer})):null,conversation:T=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:ix(T.conversation),active:T.active,pending:T.pending,open:T.open,requestDelete:T.requestDelete,defaultRenderer:T.defaultRenderer})):null,state:T=>a?u("renderHistoryState",Object.freeze({...m(),state:dr(T.state),identityStatus:dr(T.identityStatus),copy:dr(T.copy),...T.retry?{retry:T.retry}:{},...T.startNewConversation?{startNewConversation:T.startNewConversation}:{},defaultRenderer:T.defaultRenderer})):null},h=t.flatMap(T=>(T.railSections??[]).map(I=>({...I,placement:I.placement??"above-conversations",items:[],render:A=>I.render(Object.freeze({collapsed:A,presentation:e.getPresentation(),actions:x}))}))),v=e.createView({slots:y,renderDom:!1,onModelChange:()=>D(),railSections:h}),x=Object.freeze({...v.operations,close:e.close}),w=()=>(a=!0,v.setDomRenderEnabled(!0),v.element),k=T=>Object.freeze({conversations:Object.freeze(T.conversations.map(ix)),activeConversationId:T.activeConversationId,state:dr(T.state),pendingAction:ax(T.pendingAction),identityStatus:dr(T.identityStatus),nextCursor:T.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:dr(v.copy),actions:x,defaultRenderer:w,requestRender:()=>D(),onCleanup:I=>{d.push(I)}}),O=()=>{a=!1;let T=null;for(let A of t)if(A.renderHistoryView){try{T=A.renderHistoryView(k(v.getModel()))}catch(_){qm("renderHistoryView",_),T=null}if(T)break}let I=!T||T.contains(v.element);return a=I,v.setDomRenderEnabled(I),T??v.element};function D(){if(!(!s||o||r)){r=!0;try{p();let T=O();if(T===l)return;let I=l;l=T,e.onElementChanged(T,I)}finally{r=!1}}}return s=!0,D(),{view:v,get element(){return l??v.element},requestRender:D,dispose:()=>{o=!0,p()}}}var bI=null;function cx(){return bI}var vI=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),CI=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),zm=e=>CI.get(e)??"Conversation history is unavailable right now.";function wI(e){if(e instanceof fo)return e;if(e instanceof Ne){let t=vI.get(e.code)??"unavailable";return new fo(t,zm(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new fo("unavailable",zm("unavailable"))}function dx(e){let t=()=>e.getClient?.()??e.client,n=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new fo("unsupported_scope",zm("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw wI(p)}},a=l=>{let d=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){d||(d=!0,l.commit(),await e.onActivationCommitted(l.session))},discard(){d||(d=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return t().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return t().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let d=await t().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(l,d){return s(d.context.scope,async()=>{let p=await t().getConversation(l,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),u=av(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:Ka([],u),conversationRevision:p.conversationRevision??"",nextCursor:p.nextMessageCursor}})},async prepareOpen(l,d){return s(d.context.scope,async()=>a(await t().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>a(await t().prepareNewConversationSession()))},async delete(l,d){await s(d.context.scope,()=>t().deleteConversation(l,{scope:d.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>t().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var xI=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],px={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."};function Vm(e){if(!e)return px;let t={...px};for(let n of xI){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var SI="button:not([disabled])";function tp(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=G("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),a=G("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=G("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},G("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),G("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),G("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,a));for(let p of[s,a])p.style.minHeight="44px",p.style.minWidth="88px",p.style.padding="0 16px",p.style.borderRadius="var(--persona-radius-md, 0.5rem)",p.style.cursor="pointer",p.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",a.style.border="none",a.style.background="var(--persona-danger, #b42318)",a.style.color="var(--persona-danger-fg, #ffffff)";let d=G("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(p=>{let u=!1,m=h=>{u||(u=!0,d.removeEventListener("keydown",y,!0),d.remove(),t?.focus(),p(h))};function y(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),m(!1);return}if(h.key!=="Tab")return;let v=Array.from(l.querySelectorAll(SI));if(v.length===0)return;let x=v[0],w=v[v.length-1],k=document.activeElement;h.shiftKey&&(k===x||!l.contains(k))?(h.preventDefault(),w.focus()):!h.shiftKey&&k===w&&(h.preventDefault(),x.focus())}d.addEventListener("keydown",y,!0),d.addEventListener("pointerdown",h=>{h.target===d&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),e.host.appendChild(d),s.focus()})}import{parse as AI,STR as MI,OBJ as EI}from"partial-json";function TI(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function PI(e,t){if(!TI(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Km(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=AI(n,MI|EI),s=PI(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function kI(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Gm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=_o.get(e.component);if(!s){if(Wm.includes(e.component)){Kd().catch(()=>{});let l=E("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function LI(){let e=Km();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ux(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function np(e){let t=ux(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Ym(e){let t=ux(e);if(!t)return null;try{let n=JSON.parse(t);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:t}}}catch{}return null}var II=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Qm(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:p=II}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,y=document.createElement("div");y.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,h.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,h.appendChild(x),y.appendChild(h);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-csat",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let A=1;A<=5;A++){let _=document.createElement("button");_.type="button",_.className="persona-feedback-rating-btn persona-feedback-star-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${p[A-1]}`),_.title=p[A-1],_.dataset.rating=String(A),_.innerHTML=`
40
40
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
41
41
  <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>
42
42
  </svg>
43
- `,N.addEventListener("click",()=>{m=A,P.forEach((G,ae)=>{let Y=ae<A;G.classList.toggle("selected",Y),G.setAttribute("aria-checked",ae===A-1?"true":"false")})}),P.push(N),x.appendChild(N)}y.appendChild(x);let O=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",O=document.createElement("textarea"),O.className="persona-feedback-comment",O.placeholder=s,O.rows=3,O.setAttribute("aria-label","Additional comments"),A.appendChild(O),y.appendChild(A)}let $=document.createElement("div");$.className="persona-feedback-actions";let T=document.createElement("button");T.type="button",T.className="persona-feedback-btn persona-feedback-btn-skip",T.textContent=l,T.addEventListener("click",()=>{n?.(),u.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(m===null){x.classList.add("persona-feedback-shake"),setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let A=O?.value.trim()||void 0;await t(m,A),u.remove()}catch(A){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),$.appendChild(T),$.appendChild(R),y.appendChild($),u.appendChild(y),u}function Xm(e){let{onSubmit:t,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:a="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:p="Not likely",highLabel:u="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let y=null,h=document.createElement("div");h.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let S=document.createElement("h3");S.className="persona-feedback-title",S.textContent=o,C.appendChild(S);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,C.appendChild(x),h.appendChild(C);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-nps",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Likelihood rating from 0 to 10");let O=document.createElement("div");O.className="persona-feedback-labels";let $=document.createElement("span");$.className="persona-feedback-label-low",$.textContent=p;let T=document.createElement("span");T.className="persona-feedback-label-high",T.textContent=u,O.appendChild($),O.appendChild(T);let R=document.createElement("div");R.className="persona-feedback-numbers";let A=[];for(let E=0;E<=10;E++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-number-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`Rating ${E} out of 10`),B.textContent=String(E),B.dataset.rating=String(E),E<=6?B.classList.add("persona-feedback-detractor"):E<=8?B.classList.add("persona-feedback-passive"):B.classList.add("persona-feedback-promoter"),B.addEventListener("click",()=>{y=E,A.forEach((H,L)=>{H.classList.toggle("selected",L===E),H.setAttribute("aria-checked",L===E?"true":"false")})}),A.push(B),R.appendChild(B)}P.appendChild(O),P.appendChild(R),h.appendChild(P);let N=null;if(d){let E=document.createElement("div");E.className="persona-feedback-comment-container",N=document.createElement("textarea"),N.className="persona-feedback-comment",N.placeholder=s,N.rows=3,N.setAttribute("aria-label","Additional comments"),E.appendChild(N),h.appendChild(E)}let G=document.createElement("div");G.className="persona-feedback-actions";let ae=document.createElement("button");ae.type="button",ae.className="persona-feedback-btn persona-feedback-btn-skip",ae.textContent=l,ae.addEventListener("click",()=>{n?.(),m.remove()});let Y=document.createElement("button");return Y.type="button",Y.className="persona-feedback-btn persona-feedback-btn-submit",Y.textContent=a,Y.addEventListener("click",async()=>{if(y===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}Y.disabled=!0,Y.textContent="Submitting...";try{let E=N?.value.trim()||void 0;await t(y,E),m.remove()}catch(E){Y.disabled=!1,Y.textContent=a,console.error("[NPS Feedback] Failed to submit:",E)}}),G.appendChild(ae),G.appendChild(Y),h.appendChild(G),m.appendChild(h),m}var Qi="persona-chat-history",LI=30*1e3,II=641,Xi="data-persona-composer-reason",RI={"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 HI(e){if(!e)return[];let t=[],n=Array.from(e.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){t.push(r);continue}let s=RI[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function ip(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function WI(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function OI(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Jm=e=>!e||typeof e!="object"?{}:{...e},gx=e=>e.map(t=>({...t,streaming:!1})),mx=(e,t,n)=>{let o=e?.markdown?jc(e.markdown):null,r=rg(e?.sanitize);e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let s=!1,a=l=>{let d=l.text??"",p=l.message.rawContent??null;if(t){let y=t.process({text:d,raw:p??d,message:l.message,streaming:l.streaming});y!==null&&(d=y.text,y.persist||(l.message.__skipPersist=!0),y.resubmit&&!l.streaming&&n&&n())}let u=Oo()!==null,m;if(e?.postprocessMessage){let y=e.postprocessMessage({...l,text:d,raw:p??l.text??""});m=r?r(y):y}else if(o){let y=l.streaming?ub(d):d,h=o(y);m=r&&u?r(h):h}else m=Br(d);return m};return l=>{try{return a(l)}catch(d){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",d)),Br(l.text??"")}}};function fx(e){let t=M("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=pe(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=M("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var BI=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},_I=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:BI(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Zm=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=nl(t),r=()=>{Hv({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=Zd(o);let a=ep.getForInstance(o.plugins),l=OC(e),d=[],p=!1,u=Iw(()=>o),m=null,y=null,h=null,C=!1,S=null,x=i=>{m=i,i.initApprovalUi({webMcpToolTitle:Si});let c=i.createBuiltInApprovalPlugin();y=c.plugin,h=c.teardown},P=()=>{if(m)return m;let i=Bw();return i?(x(i),i):(Ow().then(c=>{C||m||(x(c),S?.())}).catch(()=>{}),null)},O=!1,$=!1,T=null,R=(i,c,g,f)=>{if(!i.querySelector("[data-tv-form]"))return;let b=Qw();if(b){b.enhanceWithForms(i,c,g,f);return}Yw().then(()=>{O||$||!T||($=!0,T())}).catch(()=>{})};o.components&&Fo.registerAll(o.components);let A=Zw(),G=o.persistState===!1?null:o.storageAdapter??Um(),ae=!!o.clientToken&&typeof o.reconnectStream!="function",Y={},E=null,B,H=new Promise(i=>{B=i}),L,ee=!1,K=i=>{if(o.onStateLoaded)try{let c=o.onStateLoaded(i);if(c&&typeof c=="object"&&"state"in c){let{state:g,open:f}=c;return f&&(ee=!0),g}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(G?.load)try{let i=G.load();if(i&&typeof i.then=="function")E=i.then(c=>K(c??{messages:[],metadata:{}}));else{let g=K(i??{messages:[],metadata:{}});g.metadata&&(Y=Jm(g.metadata)),g.messages?.length&&(o={...o,initialMessages:g.messages}),g.artifacts?.length&&(o={...o,initialArtifacts:g.artifacts,initialSelectedArtifactId:g.selectedArtifactId??null}),L=g.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=K({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}E||B();let ue=()=>Y,le=i=>{Y=i({...Y})??{},ti()},me=o.actionParsers&&o.actionParsers.length?o.actionParsers:[np],Re=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Yi.message,Yi.messageAndClick],He=op({parsers:me,handlers:Re,getSessionMetadata:ue,updateSessionMetadata:le,emit:A.emit,documentRef:typeof document<"u"?document:null});He.syncFromMetadata();let ve=o.launcher?.enabled??!0,Ge=o.launcher?.autoExpand??!1,be=o.autoFocusInput??!1,j=Ge,_e=ve,Fe=o.layout?.header?.layout,mt=!1,Ce=()=>zr(o),Ee=()=>ve||Ce(),he=Ce()?!1:ve?Ge:!0,Pe=!1,At=null,Yt=()=>{Pe=!0,At&&clearTimeout(At),At=setTimeout(()=>{Pe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Pe=!1)},1e4)},ft=mx(o,He,Yt),pn=o.features?.showReasoning??!0,zn=o.features?.showToolCalls??!0,an=o.features?.showEventStreamToggle??!1,Co=o.features?.scrollToBottom??{},Vn=o.features?.scrollBehavior??{},ro=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",wo=`${ro()}event-stream`,jo=null,Gr=o.features?.eventStream?.maxEvents??2e3,et=null,Pn=null,so=null,D=!1,X=null,v=!1,_=null,F=0,U=(i,c)=>{et?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},te=(i,c)=>{Pn?.processEvent(i,c),et?U(i,c):so&&(so.length>=Gr&&so.shift(),so.push({type:i,payload:c}))},re=()=>{et||!an||(so??(so=[]),Rm().then(i=>{if(D||et||!an)return;jo=new i.EventStreamStore(wo),et=new i.EventStreamBuffer(Gr,jo),Pn=Pn??new i.ThroughputTracker,jo.open().then(()=>et?.restore()).catch(g=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",g)});let c=so??[];so=null;for(let g of c)Pn?.processEvent(g.type,g.payload),U(g.type,g.payload)}).catch(()=>{}))};an&&re();let ie=!1,ce=null,Ut=()=>{},Oe=()=>{},Ot=()=>{},kt=()=>{},qo=()=>{},hr=()=>v||ie&&ce==="panel",jt={onCopy:i=>{A.emit("message:copy",i),k?.isClientTokenMode()&&k.submitMessageFeedback(i.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{A.emit("message:feedback",i),k?.isClientTokenMode()&&k.submitMessageFeedback(i.messageId,i.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(i)}},qt=o.statusIndicator??{},Cn=i=>i==="idle"?qt.idleText??$t.idle:i==="connecting"?qt.connectingText??$t.connecting:i==="connected"?qt.connectedText??$t.connected:i==="error"?qt.errorText??$t.error:i==="paused"?qt.pausedText??$t.paused:i==="resuming"?qt.resumingText??$t.resuming:$t[i];function Ml(i,c,g,f){if(!i.hasAttribute(Xi))if(f==="idle"&&g.idleLink){i.textContent="";let b=document.createElement("a");b.href=g.idleLink,b.target="_blank",b.rel="noopener noreferrer",b.textContent=c,b.style.color="inherit",b.style.textDecoration="none",i.appendChild(b)}else i.textContent=c}let Ln=Lw({config:o,showClose:Ee()}),{wrapper:Ke,panel:Se,pillRoot:Qt}=Ln.shell,De=Ln.panelElements,{container:ge,body:ne,messagesWrapper:Te,starterSuggestions:Cp,transcriptSuggestions:Ji,suggestions:yr,textarea:de,sendButton:Ae,composerForm:io,statusText:st,welcomeHost:wn,welcomeIconHolder:eS,greetingHost:In,introKicker:tS,introTitle:nS,introSubtitle:oS,closeButton:Ue,iconHolder:Pt,headerTitle:br,headerSubtitle:Yr,header:Me,footer:Ie,actionsRow:rS}=De,wp=De.leftActions,El=De.rightActions,xo=De.sendButtonWrapper,mf=De.setSendButtonMode,oe=De.micButton,Rn=De.micButtonWrapper,Mt=De.attachmentButton,xn=De.attachmentButtonWrapper,Ct=De.attachmentInput,Sn=De.attachmentPreviewsContainer;ge.classList.add("persona-relative"),ne.classList.add("persona-relative");let sS=12,Zi=()=>Co.label??"",iS=()=>Co.iconName??"arrow-down",aS=()=>Co.enabled!==!1,Hn=()=>Vn.mode??"anchor-top",vr=()=>Hn()==="follow"||Hn()==="anchor-top"&&ca,ea=()=>Vn.anchorTopOffset??16,lS=()=>Vn.restorePosition??"bottom",ff=()=>Vn.pauseOnInteraction===!0,hf=()=>Vn.showActivityWhilePinned!==!1,yf=()=>Vn.announce===!0,xp=()=>Vn.scrollbar??"on-scroll",_t=M("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");_t.type="button",_t.style.display="none",_t.setAttribute("data-persona-scroll-to-bottom","true");let ta=M("span","persona-flex persona-items-center"),Sp=M("span",""),Qr=M("span","");Qr.setAttribute("data-persona-scroll-to-bottom-count",""),Qr.style.display="none",_t.append(ta,Sp,Qr),ge.appendChild(_t);let Kn=M("div","persona-stream-anchor-spacer");Kn.setAttribute("aria-hidden","true"),Kn.setAttribute("data-persona-anchor-spacer",""),Kn.style.flexShrink="0",Kn.style.pointerEvents="none",Kn.style.height="0px",Kn.style.display="none",ne.appendChild(Kn);let zo=M("div","persona-sr-only");zo.setAttribute("aria-live","polite"),zo.setAttribute("aria-atomic","true"),zo.setAttribute("role","status"),zo.setAttribute("data-persona-live-region",""),Object.assign(zo.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"}),ge.appendChild(zo);let na=null,Tl=null,kl=i=>{!yf()||!i||(Tl=i,na===null&&(na=setTimeout(()=>{na=null,Tl&&yf()&&(zo.textContent=Tl),Tl=null},400)))},Pl="empty",Ll=0,Ap=()=>Ll||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,Xr=()=>{let c=Ie.style.display==="none"?0:Ie.offsetHeight;_t.style.bottom=`${c+Ap()+sS}px`};Xr();let Mp=()=>{Ks||(Ie.style.marginBottom=Ll>0?`${Ll}px`:"")},Il=()=>{let i=nm(o,Ce()),c=No(o),f=Ie.style.display==="none"?0:Ie.offsetHeight,b=c.anchor==="center"&&Pl==="empty"?il(c.anchorComposerTop)??il("44%"):null,w=b===null||Ce()?0:RC({columnHeight:ge.clientHeight,footerHeight:f,fraction:b});e.style.setProperty("--persona-composer-overlay-height",`${f}px`),e.style.setProperty("--persona-composer-lift",`${i==="overlay"?w:0}px`),Ll=i==="block"?w:0,Mp(),Xr()},bf=()=>{let i=!!Zi();_t.setAttribute("aria-label",Zi()||"Jump to latest"),_t.title=Zi(),_t.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),ta.innerHTML="";let c=pe(iS(),"14px","currentColor",2);c?(ta.appendChild(c),ta.style.display=""):ta.style.display="none",Sp.textContent=Zi(),Sp.style.display=i?"":"none"};bf();let Je=null,Bt=null,we=Tv(),cS=i=>{try{ge.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};we.subscribe(cS);let So=()=>{we.setText(de?.value??"")},Jr=()=>{we.setMentionRefs(Bt?.getMentionRefs()??[])},dS=i=>({id:i.id,name:i.file.name,mimeType:i.file.type,size:i.file.size,status:i.status,progress:i.progress,error:i.error}),vf=i=>{let c=Object.freeze(i.map(dS));we.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(g){console.error("[AgentWidget] attachments.onChange failed:",g)}Xp()};we.setSelectedModelId(o.composer?.selectedModelId);let oa=()=>o.composer?.modes??[],js=()=>eC(oa(),o.composer?.modeGroups);{let i=xd(o.composer?.defaultActiveModeIds??[],oa());i.length&&we.setActiveModeIds(i)}function Cf(i){if(we.getState().selectedModelId!==i){we.setSelectedModelId(i),Cr?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function Rl(i){we.setActiveModeIds(i),Vo?.render(i,js()),qs.forEach(c=>c.repaint()),Mo?.resolve(),oc(),ao()}function Ep(i){Rl(tC(we.getState().activeModeIds,i,oa(),o.composer?.modeGroups))}let Cr=null,Tp=null,Vo=null,qs=new Map,wr=null;function Ao(i){we.setQuote(i),wr?.render(we.getState().quote),ao(),uh()}let wf=!1;function kp(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!wf&&o.debug===!0&&(wf=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let xr=null;function zs(i){we.setPendingSubmission(i),xr?.render(we.getState().pendingSubmission),ao()}let pS=i=>{let c=qs.get(i);if(c)return c;let g=rC({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===i),getModes:()=>oa().filter(f=>f.groupId===i),getActiveIds:()=>we.getState().activeModeIds,onSelect:f=>Ep(f)});return qs.set(i,g),g},uS=()=>{let i=[],c=we.getState().activeModeIds,g=new Set;if(oa().forEach((f,b)=>{if(wd(f.groupId,o.composer?.modeGroups)){let w=f.groupId;if(g.has(w))return;g.add(w);let W=pS(w);W.action.order=Yg(b),W.action.label=o.composer?.modeGroups?.find(z=>z.id===w)?.label??w,i.push(W.action);return}i.push({id:Jv(f.id),kind:"button",placement:"start",order:Yg(b),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:c.includes(f.id),onSelect:()=>Ep(f.id)})}),o.composer?.models?.length&&!a.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!Cr||Tp!==f)&&(Tp=f,Cr=Qv({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>we.getState().selectedModelId,onSelect:b=>Cf(b),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Cr.action)}return i},Pp=null,xf=a.find(i=>i.renderHeader);if(xf?.renderHeader){let i=xf.renderHeader({config:o,defaultRenderer:()=>{let c=Vr({config:o,showClose:Ee()});return Di(ge,c,o),c.header},onClose:()=>ut(!1,"user")});if(i){let c=Me;c&&(c.replaceWith(i),Me=i,Ln.header.element=i)}}let Sf=()=>{X&&(ne.style.display="none",Ie.parentNode?.insertBefore(X.element,Ie),X.update())},Lp=()=>{if(!et){re();return}if(v=!0,X?Sf():Rm().then(c=>{X||!v||!et||(X=c.createEventStreamView({buffer:et,getFullHistory:()=>et.getAllFromStore(),onClose:()=>Vs(),config:o,plugins:a,getThroughput:()=>Pn?.getMetric()??{status:"idle"},renderIconByName:pe}),Sf())}).catch(()=>{Vs()}),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${yn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(g=>g&&tt.classList.add(g))}let i=()=>{if(!v)return;let c=Date.now();c-F>=200&&(X?.update(),F=c),_=requestAnimationFrame(i)};F=0,_=requestAnimationFrame(i),Vt(),A.emit("eventStream:opened",{timestamp:Date.now()})},Vs=()=>{if(v){if(v=!1,X&&X.element.remove(),ne.style.display="",tt){tt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&tt.classList.remove(c))}_!==null&&(cancelAnimationFrame(_),_=null),Vt(),A.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(an){let i=o.features?.eventStream?.classNames,c="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"+(i?.toggleButton?" "+i.toggleButton:"");tt=M("button",c),tt.style.width="28px",tt.style.height="28px",tt.style.color=yn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let g=Wt(dx,"18px","currentColor",1.5);g&&tt.appendChild(g);let f=De.clearChatButtonWrapper,b=De.closeButtonWrapper,w=f||b;w&&w.parentNode===Me?Me.insertBefore(tt,w):Me.appendChild(tt),tt.addEventListener("click",()=>{v?Vs():Lp()})}let Af=i=>{let c=o.attachments;if(!c?.enabled)return;let g=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!g){g=M("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),g.setAttribute("data-persona-composer-attachment-previews",""),g.style.display="none";let b=i.querySelector("[data-persona-composer-form]");b?.parentNode?b.parentNode.insertBefore(g,b):i.insertBefore(g,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let b=M("input");b.type="file",b.setAttribute("data-persona-composer-attachment-input",""),b.accept=(c.allowedTypes??pr).join(","),b.multiple=(c.maxFiles??4)>1,b.style.display="none",b.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(b)}},Ks=!1,Mf=i=>{let c=a.find(b=>b.renderComposer);if(!c?.renderComposer)return null;let g=o.composer,f=p?k.isStreaming():!1;return c.renderComposer({config:o,defaultRenderer:i,requestRender:()=>Dy(),storage:u(c.id),onSubmit:b=>{!k||k.isStreaming()||Lc(b.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{Pr()||Ct?.click()},models:g?.models,selectedModelId:we.getState().selectedModelId??g?.selectedModelId,onModelChange:b=>Cf(b),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Pp?.()}:void 0})},Ef=Mf(()=>Fi({config:o}).footer);Ef&&(Ln.replaceComposer(Ef),Ie=Ln.composer.footer,Ks=!0);let nt=null,gS=i=>{io=i.form,de=i.input,xo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Ae=i.sendButton),i.micButton&&(oe=i.micButton,Rn=i.micButton.parentElement),i.found.status&&(st=i.found.status),i.found.suggestions&&(yr=i.found.suggestions),i.attachmentButton&&(Mt=i.attachmentButton,xn=i.attachmentButton.parentElement),Ct=i.attachmentInput??null,Sn=i.attachmentPreviews??null,i.found.actionsRow&&(rS=i.found.actionsRow),wp=i.found.actionsStart,El=i.found.actionsEnd};function Ip(){let i=de;if(!i)return;let c=o.composer?.inputAttributes,g=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;ud(i,c),g&&i.setAttribute("aria-label",g),pd(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:ol(i)}),Dv(i,dd(o.composer?.maxLines,Ce()?5:3))}let Tf=i=>{nt=Pv(i,{debug:o.debug===!0}),nt&&gS(nt),Ip()};Af(Ie),Tf(Ie),So();let ra=jr(o,Ce());ra&&(Te.style.maxWidth=ra,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",In.style.maxWidth=ra,In.style.marginLeft="auto",In.style.marginRight="auto",In.style.width="100%",Cp.style.maxWidth=ra,Ji.style.maxWidth=ra,Ji.style.marginLeft="auto",Ji.style.marginRight="auto",Ji.style.width="100%");let kf=()=>{let i=jr(o,Ce());if(!(!i||Ce()))for(let c of[io,yr,Sn,st])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};kf();let Pf=()=>{!o.attachments?.enabled||!Ct||!Sn||(Je?Je.remountPreviews(Sn):(Je=Ii.fromConfig(o.attachments,vf),Je.setPreviewsContainer(Sn)),nt?.addListener(Ct,"change",i=>{let c=i.target;Je?.handleFileSelect(c.files),c.value=""}),ge.querySelector(".persona-attachment-drop-overlay")||ge.appendChild(fx(o.attachments.dropOverlay)))};Pf();let mS=()=>Bt?.prefetch(),Lf=()=>{if(!o.contextMentions?.enabled||!de)return;let i=nt?.header??null,c=i?Gg(i):void 0;if(Bt=AC({config:o,textarea:de,anchor:io??de,getMessages:()=>k.getMessages(),liveRegionHost:ge,chipRow:c}),Bt&&!c){let g=de;g.parentElement?.insertBefore(Bt.contextRow,g)}};Lf();let Mo=null,fS={getState:()=>we.getState(),getValue:()=>de?.value??"",setValue:i=>{de&&(de.value=i,de.dispatchEvent(new Event("input",{bubbles:!0})),So())},submit:()=>{mC(nt?.form??null)},openAttachmentPicker:()=>{Pr()||Ct?.click()},toggleVoice:()=>{Pp?.()},requestRender:()=>Mo?.resolve()},hS=()=>{let i=[];return(Bt?.affordanceButtons??[]).forEach((g,f)=>{i.push({id:`core:mention-${f}`,placement:"start",order:_o.mention+f,element:g,managed:!0})}),xn&&i.push({id:"core:attachment",placement:"start",order:_o.attachment,element:xn}),Rn&&i.push({id:"core:mic",placement:"end",order:_o.mic,element:Rn}),xo&&i.push({id:"core:send",placement:"end",order:_o.send,element:xo}),i},If=()=>{Mo?.destroy(),Mo=Kv({getBindings:()=>nt,collect:()=>({builtIns:hS(),configActions:[...uS(),...o.composer?.actions??[]],plugins:a,contributionContext:{config:o,getState:()=>we.getState(),requestRender:()=>Mo?.resolve()},debug:o.debug===!0}),actionContext:fS,getState:()=>we.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),Mo.resolve()};If();let Rp=()=>{if(Vo?.destroy(),Vo=null,!js().length)return;let i=nt?.header;i&&(Vo=Xv({row:Gg(i),onRemove:c=>Ep(c),initialIds:we.getState().activeModeIds}),Vo.render(we.getState().activeModeIds,js()))};Rp();let Rf=()=>{wr?.destroy(),wr=null,xr?.destroy(),xr=null;let i=nt?.header;i&&(wr=sC({onDismiss:()=>Ao(void 0)}),i.appendChild(wr.element),wr.render(we.getState().quote),kp()==="defer-one"&&(xr=iC({onEdit:()=>qA(),onRemove:()=>zs(void 0)}),i.appendChild(xr.element),xr.render(we.getState().pendingSubmission)))};Rf();let Hp=uC(),yS=()=>{let i=nt?.header?.querySelector(Kg);if(i)return i.childElementCount>0;let c=we.getState();return c.mentionRefs.length>0||xd(c.activeModeIds,js()).length>0},Hf=()=>!1;function ao(){let i=we.getState(),c=Hp.observe(gC(de),i.text);Ie.toggleAttribute("data-persona-composer-compact",pC({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:yS(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0,dictationActive:Hf()}))}function Wf(){o.composer?.layout==="single-row"&&!Ce()?Ie.setAttribute("data-persona-composer-layout","single-row"):Ie.removeAttribute("data-persona-composer-layout")}Wf(),we.subscribe(()=>{Mo?.sync(),Xp(),tc(),ao(),uh()}),tc();let Of=!1,bS=i=>{if(Of||o.debug!==!0)return;let c=["messages","composer"].filter(g=>i[g]);c.length&&(Of=!0,console.warn(`[persona] layout.slots.${c.join(" and layout.slots.")} ${c.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let i=o.layout?.slots??{};bS(i);let c=f=>{switch(f){case"body-top":return ne.querySelector("[data-persona-intro-card]");case"messages":return Te;case"footer-top":return yr;case"composer":return io;case"footer-bottom":return st;default:return null}},g=(f,b)=>{switch(f){case"header-left":case"header-center":case"header-right":if(f==="header-left")Me.insertBefore(b,Me.firstChild);else if(f==="header-right")Me.appendChild(b);else{let w=Me.querySelector(".persona-flex-col");w?w.parentNode?.insertBefore(b,w.nextSibling):Me.appendChild(b)}break;case"body-top":{let w=ne.querySelector("[data-persona-intro-card]");w?w.replaceWith(b):ne.insertBefore(b,ne.firstChild);break}case"body-bottom":ne.appendChild(b);break;case"footer-top":yr.replaceWith(b);break;case"footer-bottom":st.replaceWith(b);break;default:break}};for(let[f,b]of Object.entries(i))if(b)try{let w=b({config:o,defaultContent:()=>c(f)});w&&g(f,w)}catch(w){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${f}":`,w)}})();let Bf=i=>{let g=i.target.closest('button[data-expand-header="true"]');if(!g)return;let f=g.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!f)return;let b=f.getAttribute("data-message-id");if(!b)return;let w=g.getAttribute("data-bubble-type");if(w==="reasoning")qi.has(b)?qi.delete(b):qi.add(b),Rw(b,f);else if(w==="tool")zi.has(b)?zi.delete(b):zi.add(b),Ww(b,f,o);else if(w==="approval"&&m){let z=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",q=m.approvalDetailsExpansionState.get(b)??z;m.approvalDetailsExpansionState.set(b,!q),m.updateApprovalDetailsUI(b,f,o)}Dt.delete(b)};Te.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Bf(i))}),Te.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Bf(i))}),Te.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let g=Te.getRootNode(),f=typeof g.getSelection=="function"?g.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let b=f.toString(),w=BC(b);!w||w===b||(c.setData("text/plain",w),i.preventDefault())});let Wp=new Map,_f=null,Df="idle",vS={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},CS=(i,c)=>{let{icon:g,label:f}=vS[c];i.setAttribute("aria-label",f),i.title=f,i.setAttribute("aria-pressed",c==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",c!=="idle"),i.classList.toggle("persona-message-action-loading",c==="loading");let b=pe(g,14,"currentColor",2);b&&(i.innerHTML="",i.appendChild(b))},Nf=()=>{Te.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let f=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;CS(c,f&&f===_f?Df:"idle")})};Te.addEventListener("click",i=>{let g=i.target.closest(".persona-message-action-btn[data-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest("[data-actions-for]");if(!f)return;let b=f.getAttribute("data-actions-for");if(!b)return;let w=g.getAttribute("data-action");if(w==="copy"){let z=k.getMessages().find(q=>q.id===b);if(z&&jt.onCopy){let q=z.content||"";navigator.clipboard.writeText(q).then(()=>{g.classList.add("persona-message-action-success");let V=Wt(px,14,"currentColor",2);V&&(g.innerHTML="",g.appendChild(V)),setTimeout(()=>{g.classList.remove("persona-message-action-success");let J=Wt(ux,14,"currentColor",2);J&&(g.innerHTML="",g.appendChild(J))},2e3)}).catch(V=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",V)}),jt.onCopy(z)}}else if(w==="read-aloud")k.toggleReadAloud(b);else if(w==="upvote"||w==="downvote"){let z=(Wp.get(b)??null)===w,q=w==="upvote"?"thumbs-up":"thumbs-down";if(z){Wp.delete(b),g.classList.remove("persona-message-action-active");let V=pe(q,14,"currentColor",2);V&&(g.innerHTML="",g.appendChild(V))}else{let V=w==="upvote"?"downvote":"upvote",J=f.querySelector(`[data-action="${V}"]`);if(J){J.classList.remove("persona-message-action-active");let gt=pe(V==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);gt&&(J.innerHTML="",J.appendChild(gt))}Wp.set(b,w),g.classList.add("persona-message-action-active");let se=pe(q,14,"currentColor",2);se&&(se.setAttribute("fill","currentColor"),g.innerHTML="",g.appendChild(se)),g.classList.remove("persona-message-action-pop"),g.offsetWidth,g.classList.add("persona-message-action-pop");let Xe=k.getMessages().find(dt=>dt.id===b);Xe&&jt.onFeedback&&jt.onFeedback({type:w,messageId:Xe.id,message:Xe})}}else if(w==="regenerate")Hl?.regenerate(b);else if(w==="edit")Hl?.edit(b);else if(w==="quote")Hl?.quote(b);else if(w?.startsWith(Nd)){let W=w.slice(Nd.length),z=o.messageActions?.custom?.find(V=>V.id===W),q=k.getMessages().find(V=>V.id===b);if(!z||!q)return;try{z.onSelect(q)}catch(V){console.error(`[AgentWidget] messageActions.custom "${W}" onSelect failed:`,V)}}});let Hl=null;Te.addEventListener("click",i=>{let g=i.target.closest("button[data-approval-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest(".persona-approval-bubble");if(!f)return;let b=f.getAttribute("data-message-id");if(!b)return;let w=g.getAttribute("data-approval-action");if(!w)return;let W=w==="approve"?"approved":"denied",q=k.getMessages().find(J=>J.id===b);if(!q?.approval)return;let V=f.querySelector("[data-approval-buttons]");V&&V.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),q.approval.toolType==="webmcp"?k.resolveWebMcpApproval(b,W):k.resolveApproval(q.approval,W)});let qe=null,Ff=!1,sa=null,Zr=()=>{},ia="none",Wl=null,Gn={artifacts:[],selectedId:null},Ko=!1,lo=!1,aa=!1,Gs=!1,$f=()=>Gs||Gn.artifacts.some(i=>cr(o.features?.artifacts,i)==="panel"),Ol=()=>Gn.artifacts.length>0&&!Ko&&$f(),ct={current:null},Op=(i,c)=>{let g=k.getArtifactById(c),f=g?.markdown,b=g?.title||"artifact",w=g?.file,W=g?.artifactType??"markdown";if(!f){let V=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(V){let se=k.getMessages().find(fe=>fe.id===V);if(se?.rawContent)try{let fe=JSON.parse(se.rawContent);f=fe?.props?.markdown,b=fe?.props?.title||b,fe?.props?.file&&typeof fe.props.file=="object"&&(w=fe.props.file),!g&&typeof fe?.props?.artifactType=="string"&&(W=fe.props.artifactType)}catch{}}}return{markdown:f,title:b,file:w,artifactType:W}};Te.addEventListener("click",i=>{let g=i.target.closest("[data-download-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-download-artifact");if(!f||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:f})===!0)return;let{markdown:w,title:W,file:z}=Op(g,f);if(!w)return;let q=ur();q&&q.triggerArtifactDownload(q.downloadInfoFor({title:W,markdown:w,file:z}))}),Te.addEventListener("click",i=>{let g=i.target.closest("[data-artifact-custom-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-artifact-custom-action");if(!f)return;let b=g.closest("[data-artifact-inline]"),w=b?null:g.closest("[data-open-artifact]"),W=b?b.getAttribute("data-artifact-inline"):w?.getAttribute("data-open-artifact")??null,q=(b?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(dt=>dt.id===f);if(!q)return;let{markdown:V,title:J,file:se,artifactType:fe}=Op(g,W??""),Xe={artifactId:W,title:J,artifactType:fe,markdown:V,file:se};try{Promise.resolve(q.onClick(Xe)).catch(()=>{})}catch{}}),Te.addEventListener("click",i=>{let g=i.target.closest("[data-copy-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-copy-artifact");if(!f)return;let b=k.getArtifactById(f),w=ur();if(!w)return;let W="";if(b)W=w.artifactCopyText(b);else{let{markdown:z,file:q,artifactType:V}=Op(g,f);V==="markdown"&&(W=w.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:z??"",...q?{file:q}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let z=Wt(px,16,"currentColor",2);z&&(g.replaceChildren(z),setTimeout(()=>{let q=Wt(ux,16,"currentColor",2);q&&g.replaceChildren(q)},1500))}).catch(()=>{})}),Te.addEventListener("click",i=>{let g=i.target.closest("[data-expand-artifact-inline]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-expand-artifact-inline");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(Ko=!1,Gs=!0,lo=!0,aa=!0,k.selectArtifact(f),co())}),Te.addEventListener("click",i=>{let c=i.target;if(c.closest("[data-download-artifact]")||c.closest("[data-artifact-custom-action]"))return;let g=c.closest("[data-open-artifact]");if(!g)return;let f=g.getAttribute("data-open-artifact");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(i.preventDefault(),i.stopPropagation(),Ko=!1,Gs=!0,k.selectArtifact(f),co())}),Te.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let c=i.target;!c.hasAttribute("data-open-artifact")&&!c.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),c.click())});let Ys=De.composerOverlay,Qs=(i,c,g)=>{let f=c.trim();if(!f||!ct.current)return;let b=i.getAttribute("data-tool-call-id")??"",w=g.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:b,answer:f,answers:g.structured,values:g.values??(g.source==="multi"?f.split(", "):[f]),isFreeText:w,source:g.source},bubbles:!0,composed:!0})),Hs(Ys,b);let W=ct.current.getMessages().find(z=>z.toolCall?.id===b);W?.agentMetadata?.awaitingLocalTool?ct.current.resolveAskUserQuestion(W,g.structured??f):ct.current.sendMessage(f)},es=i=>{let c=ct.current;if(!c)return;let g=i.getAttribute("data-tool-call-id")??"",f=c.getMessages().find(b=>b.toolCall?.id===g);f&&c.persistAskUserQuestionProgress(f,{answers:Yc(i,f),currentIndex:no(i)})},Uf=i=>Object.entries(i).map(([c,g])=>`${c}: ${Array.isArray(g)?g.join(", "):g}`).join(" | "),Bp=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=no(i),g=Mi(i);if(c>=g-1)return;let f=ct.current?.getMessages().find(b=>b.toolCall?.id===i.getAttribute("data-tool-call-id"));f&&(Qc(i,f,o,c+1),es(i))};Ys.addEventListener("click",i=>{let g=i.target.closest("[data-ask-user-action]");if(!g)return;let f=g.closest("[data-persona-ask-sheet-for]");if(!f)return;let b=g.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),b==="dismiss"){let w=f.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:w},bubbles:!0,composed:!0})),Hs(Ys,w);let W=ct.current?.getMessages().find(z=>z.toolCall?.id===w);W?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(W),ct.current?.resolveAskUserQuestion(W,"(dismissed)"));return}if(b==="pick"){let w=g.getAttribute("data-option-label");if(!w)return;let W=f.getAttribute("data-multi-select")==="true",z=Nr(f);if(z&&W){let q=Rs(f)[no(f)],V=new Set(Array.isArray(q)?q:[]);V.has(w)?V.delete(w):V.add(w),Fr(f,Array.from(V)),es(f);return}if(z){Fr(f,w),es(f),Bp(f);return}if(W){let q=g.getAttribute("aria-pressed")==="true";g.setAttribute("aria-pressed",q?"false":"true"),g.classList.toggle("persona-ask-pill-selected",!q);let V=f.querySelector('[data-ask-user-action="submit-multi"]');V&&(V.disabled=pg(f).length===0);return}Qs(f,w,{source:"pick",values:[w]});return}if(b==="submit-multi"){let w=pg(f);if(w.length===0)return;Qs(f,w.join(", "),{source:"multi",values:w});return}if(b==="open-free-text"){let w=f.querySelector('[data-ask-free-text-row="true"]');w&&(w.classList.remove("persona-hidden"),w.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(b==="focus-free-text"){f.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(b==="submit-free-text"){let W=f.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!W.trim())return;if(Nr(f)){Fr(f,W.trim()),es(f),Bp(f);return}Qs(f,W,{source:"free-text"});return}if(b==="next"||b==="back"){if(!ct.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=ct.current.getMessages().find(se=>se.toolCall?.id===w);if(!W)return;let q=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(q){let se=Rs(f)[no(f)];(typeof se!="string"||se!==q)&&Fr(f,q)}let V=b==="next"?1:-1,J=no(f)+V;Qc(f,W,o,J),es(f);return}if(b==="submit-all"){if(!ct.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=ct.current.getMessages().find(se=>se.toolCall?.id===w);if(!W)return;let q=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";q&&Fr(f,q);let V=Yc(f,W);ct.current.persistAskUserQuestionProgress(W,{answers:V,currentIndex:no(f)});let J=Uf(V);Qs(f,J||"(submitted)",{source:"submit-all",structured:V});return}if(b==="skip"){if(!ct.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=ct.current.getMessages().find(fe=>fe.toolCall?.id===w);if(!W)return;let z=Nr(f),q=no(f),V=Mi(f),J=q>=V-1;if(!z){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:w},bubbles:!0,composed:!0})),Hs(Ys,w),W.agentMetadata?.awaitingLocalTool&&(ct.current.markAskUserQuestionResolved(W),ct.current.resolveAskUserQuestion(W,"(dismissed)"));return}Fr(f,"");let se=f.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),J){let fe=Yc(f,W),Xe=Uf(fe);Qs(f,Xe||"(skipped)",{source:"submit-all",structured:fe});return}Qc(f,W,o,q+1),es(f);return}}),Ys.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let g=i.target;if(!g.matches?.('[data-ask-free-text-input="true"]'))return;let f=g.closest("[data-persona-ask-sheet-for]");if(!f)return;i.preventDefault();let b=g.value;if(b.trim()){if(Nr(f)){Fr(f,b.trim()),es(f),Bp(f);return}Qs(f,b,{source:"free-text"})}});let jf=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let c=i.target;if(c?.tagName==="INPUT"||c?.tagName==="TEXTAREA"||c?.isContentEditable)return;let g=Ys.querySelector("[data-persona-ask-sheet-for]");if(!g||g.getAttribute("data-ask-layout")!=="rows"||g.getAttribute("data-multi-select")==="true")return;let f=Number(i.key),w=g.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[f-1];w&&(i.preventDefault(),w.click())};document.addEventListener("keydown",jf);let Eo=null,wt=null,la=null,Bl=null,_l=()=>{},qf=!1,Dl="",Nl="";function _p(){Bl?.(),Bl=null}let wS=()=>{let i=ci&&Cs?.isConnected?Cs:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},zf=()=>{if(!Eo||!wt)return;let i=e.classList.contains("persona-artifact-welded-split"),c=e.ownerDocument.defaultView??window,g=c.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||g){wt.style.removeProperty("position"),wt.style.removeProperty("left"),wt.style.removeProperty("top"),wt.style.removeProperty("bottom"),wt.style.removeProperty("width"),wt.style.removeProperty("z-index");return}let f=Eo.firstElementChild;if(!f||f===wt)return;let b=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${b}px`,wt.style.zIndex="5";let w=Nm(Eo,c),W=f.offsetWidth+w/2-b/2;wt.style.left=`${Math.max(0,W)}px`},Fl=()=>{},xS=()=>{let i=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,g=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>g?!1:ve||Tt(o)},$l=()=>!vn(o)||!Ol()||e.classList.contains("persona-artifact-narrow-host")||xS()||(e.ownerDocument.defaultView??window).innerWidth<II?"none":_m(o)?"detached":"welded",co=()=>{if(!qe||!vn(o))return;Cl(e,o),wl(e,o),Fl();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=Se.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let g=Ol();qe.setVisible(g),qe.update(Gn),Ko?(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),lo=!1,aa=!1):Gn.artifacts.length>0&&$f()?(qe.element.classList.remove("persona-hidden"),qe.setMobileOpen(!0)):(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),lo=!1,aa=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(qe.setExpandToggleVisible(f),qe.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),qe.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),qe.setCustomActions(o.features?.artifacts?.toolbarActions??[]),qe.setTabFade(o.features?.artifacts?.layout?.tabFade),qe.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!aa&&(lo=!1),lo!==qf){let w=qe.element;lo?(Dl=w.style.width,Nl=w.style.maxWidth,w.style.removeProperty("width"),w.style.removeProperty("max-width")):(Dl&&(w.style.width=Dl),Nl&&(w.style.maxWidth=Nl),Dl="",Nl=""),qf=lo}e.classList.toggle("persona-artifact-expanded",lo),qe.setExpanded(lo);let b=$l();b!==ia&&(ia=b,Zr()),_l()};if(vn(o)){Se.style.position="relative";let i=M("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=M("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(ge),Eo=c,c.appendChild(i),Se.appendChild(c);let g=b=>{Ff||qe||(qe=b.createArtifactPane(o,{onSelect:w=>ct.current?.selectArtifact(w),onDismiss:()=>{Ko=!0,co()},onToggleExpand:()=>{let w=!lo,W=Gn.selectedId??Gn.artifacts[Gn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:W,expanded:w})!==!0&&(lo=w,w||(aa=!1),co())}}),qe.element.classList.add("persona-hidden"),c.appendChild(qe.element),qe.backdrop&&Se.appendChild(qe.backdrop),_l(),co())},f=ur();f?g(f):(Om(()=>{let b=ur();b&&g(b)}),Qd().catch(()=>{})),_l=()=>{if(!Eo||!qe)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){la?.(),la=null,_p(),wt&&(wt.remove(),wt=null),qe.element.style.removeProperty("width"),qe.element.style.removeProperty("maxWidth");return}if(!wt){let w=M("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");w.setAttribute("role","separator"),w.setAttribute("aria-orientation","vertical"),w.setAttribute("aria-label","Resize artifacts panel"),w.tabIndex=0;let W=e.ownerDocument,z=W.defaultView??window,q=V=>{if(!qe||V.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||z.innerWidth<=640)return;V.preventDefault(),_p();let J=V.clientX,se=qe.element.getBoundingClientRect().width,fe=o.features?.artifacts?.layout,Xe=gt=>{let Xt=Eo.getBoundingClientRect().width,Ft=e.classList.contains("persona-artifact-welded-split"),Rt=Nm(Eo,z),ln=Ft?0:w.getBoundingClientRect().width||6,Ze=se-(gt.clientX-J),cn=Gw(Ze,Xt,Rt,ln,fe?.resizableMinWidth,fe?.resizableMaxWidth,wS());qe.element.style.width=`${cn}px`,qe.element.style.maxWidth="none",zf()},dt=()=>{W.removeEventListener("pointermove",Xe),W.removeEventListener("pointerup",dt),W.removeEventListener("pointercancel",dt),Bl=null;try{w.releasePointerCapture(V.pointerId)}catch{}};Bl=dt,W.addEventListener("pointermove",Xe),W.addEventListener("pointerup",dt),W.addEventListener("pointercancel",dt);try{w.setPointerCapture(V.pointerId)}catch{}};w.addEventListener("pointerdown",q),wt=w,Eo.insertBefore(w,qe.element),la=()=>{w.removeEventListener("pointerdown",q)}}if(wt){let w=Ol();wt.classList.toggle("persona-hidden",!w),zf()}},Fl=()=>{if(!ve||!qe||(o.launcher?.sidebarMode??!1)||Tt(o)&&Un(o).reveal==="emerge")return;let w=e.ownerDocument.defaultView??window,W=o.launcher?.mobileFullscreen??!0,z=o.launcher?.mobileBreakpoint??640;if(W&&w.innerWidth<=z||!Fw(o,ve))return;let q=o.launcher?.width??o.launcherWidth??oo,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Ol()?(Se.style.width=V,Se.style.maxWidth=V):(Se.style.width=q,Se.style.maxWidth=q)},typeof ResizeObserver<"u"&&(sa=new ResizeObserver(()=>{co()}),sa.observe(Se))}else Se.appendChild(ge);Ce()&&Qt&&(De.peekBanner&&Qt.appendChild(De.peekBanner),Qt.appendChild(Ie)),e.appendChild(Ke),Qt&&e.appendChild(Qt);let Dp=()=>{if(Ce()){Se.style.width="100%",Se.style.maxWidth="100%";let Ne=o.launcher?.composerBar??{},ht=Ke.dataset.state==="expanded",ot=Ne.expandedSize??"anchored";if(!(ht&&ot!=="fullscreen")){ge.style.background="",ge.style.border="",ge.style.borderRadius="",ge.style.overflow="",ge.style.boxShadow="";return}let yt=o.theme?.components?.panel,lr=Os(o),Jt=(Ts,Bc)=>Ts==null||Ts===""?Bc:hn(lr,Ts)??Ts,to="1px solid var(--persona-border)",bt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ju="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ge.style.background="var(--persona-surface, #ffffff)",ge.style.border=Jt(yt?.border,to),ge.style.borderRadius=Jt(yt?.borderRadius,Ju),ge.style.boxShadow=Jt(yt?.shadow,bt),ge.style.overflow="hidden";return}let i=Tt(o),c=o.launcher?.sidebarMode??!1,g=i||c||(o.launcher?.fullHeight??!1),f=o.launcher?.enabled===!1,b=o.launcher?.detachedPanel===!0,w=o.theme?.components?.panel,W=Os(o),z=(Ne,ht)=>Ne==null||Ne===""?ht:hn(W,Ne)??Ne,q=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,J=o.launcher?.mobileBreakpoint??640,se=q.innerWidth<=J,fe=V&&se&&ve,Xe=i&&V&&se,dt=o.launcher?.position??"bottom-left",gt=dt==="bottom-left"||dt==="top-left",Xt=o.launcher?.zIndex??sn,Ft="var(--persona-panel-border, 1px solid var(--persona-border))",Rt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",ln="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ze=b&&!fe&&!Xe;Ze?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let cn=Ze?Ft:c||fe?"none":Ft,Ro=Ze?Rt:fe?"none":c?gt?"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))":f?"none":Rt;i&&!fe&&!Ze&&(Ro="none",cn="none");let ar=Ze?ln:c||fe?"0":ln,Ho=z(w?.border,cn),Ci=z(w?.shadow,Ro),Es=z(w?.borderRadius,ar),I=$l(),ke=I==="detached",We=I==="welded";e.classList.toggle("persona-artifact-detached-split",ke),e.classList.toggle("persona-artifact-welded-split",We);let xe="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)))))",lt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&vn(o)&&_m(o)&&f&&!i;e.classList.toggle("persona-artifact-chat-flush",lt);let Le=ke||lt?"none":Ci,go=ke?Ft:We?"none":Ho,Et=ke?ln:Es;lt&&(go="none",Et="0");let on=w?.borderRadius!=null&&w.borderRadius!=="",Gt=lt&&!on?"0":Es,Ht=ne.scrollTop;e.style.cssText="",Ke.style.cssText="",Se.style.cssText="",ge.style.cssText="",ne.style.cssText="",Ks||(Ie.style.cssText=""),v&&(ne.style.display="none"),(g||f)&&(e.style.minWidth="0");let Be=()=>{if(Ht<=0)return;(ne.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ne.scrollTop===Ht)return;let ht=ne.scrollHeight-ne.clientHeight;ht<=0||(ne.scrollTop=Math.min(Ht,ht))})};if(fe){Ke.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"),Ke.style.cssText=`
43
+ `,_.addEventListener("click",()=>{m=A,k.forEach((K,ie)=>{let Z=ie<A;K.classList.toggle("selected",Z),K.setAttribute("aria-checked",ie===A-1?"true":"false")})}),k.push(_),w.appendChild(_)}y.appendChild(w);let O=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",O=document.createElement("textarea"),O.className="persona-feedback-comment",O.placeholder=s,O.rows=3,O.setAttribute("aria-label","Additional comments"),A.appendChild(O),y.appendChild(A)}let D=document.createElement("div");D.className="persona-feedback-actions";let T=document.createElement("button");T.type="button",T.className="persona-feedback-btn persona-feedback-btn-skip",T.textContent=l,T.addEventListener("click",()=>{n?.(),u.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=a,I.addEventListener("click",async()=>{if(m===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let A=O?.value.trim()||void 0;await t(m,A),u.remove()}catch(A){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),D.appendChild(T),D.appendChild(I),y.appendChild(D),u.appendChild(y),u}function Xm(e){let{onSubmit:t,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:a="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:p="Not likely",highLabel:u="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let y=null,h=document.createElement("div");h.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,v.appendChild(x);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=r,v.appendChild(w),h.appendChild(v);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let O=document.createElement("div");O.className="persona-feedback-labels";let D=document.createElement("span");D.className="persona-feedback-label-low",D.textContent=p;let T=document.createElement("span");T.className="persona-feedback-label-high",T.textContent=u,O.appendChild(D),O.appendChild(T);let I=document.createElement("div");I.className="persona-feedback-numbers";let A=[];for(let M=0;M<=10;M++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-number-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`Rating ${M} out of 10`),B.textContent=String(M),B.dataset.rating=String(M),M<=6?B.classList.add("persona-feedback-detractor"):M<=8?B.classList.add("persona-feedback-passive"):B.classList.add("persona-feedback-promoter"),B.addEventListener("click",()=>{y=M,A.forEach((H,R)=>{H.classList.toggle("selected",R===M),H.setAttribute("aria-checked",R===M?"true":"false")})}),A.push(B),I.appendChild(B)}k.appendChild(O),k.appendChild(I),h.appendChild(k);let _=null;if(d){let M=document.createElement("div");M.className="persona-feedback-comment-container",_=document.createElement("textarea"),_.className="persona-feedback-comment",_.placeholder=s,_.rows=3,_.setAttribute("aria-label","Additional comments"),M.appendChild(_),h.appendChild(M)}let K=document.createElement("div");K.className="persona-feedback-actions";let ie=document.createElement("button");ie.type="button",ie.className="persona-feedback-btn persona-feedback-btn-skip",ie.textContent=l,ie.addEventListener("click",()=>{n?.(),m.remove()});let Z=document.createElement("button");return Z.type="button",Z.className="persona-feedback-btn persona-feedback-btn-submit",Z.textContent=a,Z.addEventListener("click",async()=>{if(y===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}Z.disabled=!0,Z.textContent="Submitting...";try{let M=_?.value.trim()||void 0;await t(y,M),m.remove()}catch(M){Z.disabled=!1,Z.textContent=a,console.error("[NPS Feedback] Failed to submit:",M)}}),K.appendChild(ie),K.appendChild(Z),h.appendChild(K),m.appendChild(h),m}var qi="persona-chat-history",WI=30*1e3,OI=641,zi="data-persona-composer-reason",BI={"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 _I(e){if(!e)return[];let t=[],n=Array.from(e.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){t.push(r);continue}let s=BI[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function op(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function DI(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function NI(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Jm=e=>!e||typeof e!="object"?{}:{...e},hx=e=>e.map(t=>({...t,streaming:!1})),yx=(e,t,n)=>{let o=e?.markdown?Fc(e.markdown):null,r=rg(e?.sanitize);e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let s=!1,a=l=>{let d=l.text??"",p=l.message.rawContent??null;if(t){let y=t.process({text:d,raw:p??d,message:l.message,streaming:l.streaming});y!==null&&(d=y.text,y.persist||(l.message.__skipPersist=!0),y.resubmit&&!l.streaming&&n&&n())}let u=Io()!==null,m;if(e?.postprocessMessage){let y=e.postprocessMessage({...l,text:d,raw:p??l.text??""});m=r?r(y):y}else if(o){let y=l.streaming?hb(d):d,h=o(y);m=r&&u?r(h):h}else m=Ir(d);return m};return l=>{try{return a(l)}catch(d){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",d)),Ir(l.text??"")}}};function bx(e){let t=E("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=le(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=E("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var FI=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},$I=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:FI(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Zm=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Za(t),r=()=>{Bv({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=Qd(o);let a=Xd.getForInstance(o.plugins),l=DC(e),d=[],p=!1,u=Ww(()=>o),m=null,y=null,h=null,v=!1,x=null,w=i=>{m=i,i.initApprovalUi({webMcpToolTitle:yi});let c=i.createBuiltInApprovalPlugin();y=c.plugin,h=c.teardown},k=()=>{if(m)return m;let i=Nw();return i?(w(i),i):(Dw().then(c=>{v||m||(w(c),x?.())}).catch(()=>{}),null)},O=!1,D=!1,T=null,I=(i,c,g,f)=>{if(!i.querySelector("[data-tv-form]"))return;let b=Zw();if(b){b.enhanceWithForms(i,c,g,f);return}Jw().then(()=>{O||D||!T||(D=!0,T())}).catch(()=>{})};o.components&&_o.registerAll(o.components);let A=nx(),K=o.persistState===!1?null:o.storageAdapter??Um(),ie=!!o.clientToken&&typeof o.reconnectStream!="function",Z={},M=null,B,H=new Promise(i=>{B=i}),R,J=!1,V=i=>{if(o.onStateLoaded)try{let c=o.onStateLoaded(i);if(c&&typeof c=="object"&&"state"in c){let{state:g,open:f}=c;return f&&(J=!0),g}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(K?.load)try{let i=K.load();if(i&&typeof i.then=="function")M=i.then(c=>V(c??{messages:[],metadata:{}}));else{let g=V(i??{messages:[],metadata:{}});g.metadata&&(Z=Jm(g.metadata)),g.messages?.length&&(o={...o,initialMessages:g.messages}),g.artifacts?.length&&(o={...o,initialArtifacts:g.artifacts,initialSelectedArtifactId:g.selectedArtifactId??null}),R=g.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=V({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}M||B();let pe=()=>Z,se=i=>{Z=i({...Z})??{},Ys()},ge=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zd],Ie=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ji.message,ji.messageAndClick],ye=ep({parsers:ge,handlers:Ie,getSessionMetadata:pe,updateSessionMetadata:se,emit:A.emit,documentRef:typeof document<"u"?document:null});ye.syncFromMetadata();let ce=o.launcher?.enabled??!0,Je=o.launcher?.autoExpand??!1,fe=o.autoFocusInput??!1,F=Je,Oe=ce,Ue=o.layout?.header?.layout,Bt=!1,be=()=>Fr(o),Be=()=>ce||be(),ve=be()?!1:ce?Je:!0,xe=!1,bt=null,Rt=()=>{xe=!0,bt&&clearTimeout(bt),bt=setTimeout(()=>{xe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),xe=!1)},1e4)},ut=yx(o,ye,Rt),vn=o.features?.showReasoning??!0,q=o.features?.showToolCalls??!0,S=o.features?.showEventStreamToggle??!1,N=o.features?.scrollToBottom??{},z=o.features?.scrollBehavior??{},Y=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",he=`${Y()}event-stream`,Te=null,ke=o.features?.eventStream?.maxEvents??2e3,He=null,rt=null,Ke=null,je=!1,ht=null,Gt=!1,Ht=null,sn=0,Cn=(i,c)=>{He?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},yp=(i,c)=>{rt?.processEvent(i,c),He?Cn(i,c):Ke&&(Ke.length>=ke&&Ke.shift(),Ke.push({type:i,payload:c}))},xl=()=>{He||!S||(Ke??(Ke=[]),Rm().then(i=>{if(je||He||!S)return;Te=new i.EventStreamStore(he),He=new i.EventStreamBuffer(ke,Te),rt=rt??new i.ThroughputTracker,Te.open().then(()=>He?.restore()).catch(g=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",g)});let c=Ke??[];Ke=null;for(let g of c)rt?.processEvent(g.type,g.payload),Cn(g.type,g.payload)}).catch(()=>{}))};S&&xl();let At=!1,_t=null,bp=()=>{},Fo=()=>{},mf=()=>{},ff=()=>{},vp=()=>{},oS=()=>Gt||At&&_t==="panel",Os={onCopy:i=>{A.emit("message:copy",i),P?.isClientTokenMode()&&P.submitMessageFeedback(i.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{A.emit("message:feedback",i),P?.isClientTokenMode()&&P.submitMessageFeedback(i.messageId,i.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(i)}},Bs=o.statusIndicator??{},hf=i=>i==="idle"?Bs.idleText??qt.idle:i==="connecting"?Bs.connectingText??qt.connecting:i==="connected"?Bs.connectedText??qt.connected:i==="error"?Bs.errorText??qt.error:i==="paused"?Bs.pausedText??qt.paused:i==="resuming"?Bs.resumingText??qt.resuming:qt[i];function Sl(i,c,g,f){if(!i.hasAttribute(zi))if(f==="idle"&&g.idleLink){i.textContent="";let b=document.createElement("a");b.href=g.idleLink,b.target="_blank",b.rel="noopener noreferrer",b.textContent=c,b.style.color="inherit",b.style.textDecoration="none",i.appendChild(b)}else i.textContent=c}let Hn=Hw({config:o,showClose:Be()}),{wrapper:Ge,panel:Se,pillRoot:Yt}=Hn.shell,_e=Hn.panelElements,{container:de,body:te,messagesWrapper:Pe,starterSuggestions:Cp,transcriptSuggestions:Vi,suggestions:ur,textarea:ae,sendButton:Me,composerForm:oo,statusText:st,welcomeHost:wn,welcomeIconHolder:rS,greetingHost:Wn,introKicker:sS,introTitle:iS,introSubtitle:aS,closeButton:Fe,iconHolder:Mt,headerTitle:gr,headerSubtitle:jr,header:Ee,footer:Le,actionsRow:lS}=_e,wp=_e.leftActions,Al=_e.rightActions,bo=_e.sendButtonWrapper,yf=_e.setSendButtonMode,ne=_e.micButton,On=_e.micButtonWrapper,xt=_e.attachmentButton,xn=_e.attachmentButtonWrapper,yt=_e.attachmentInput,Sn=_e.attachmentPreviewsContainer;de.classList.add("persona-relative"),te.classList.add("persona-relative");let cS=12,Ki=()=>N.label??"",dS=()=>N.iconName??"arrow-down",pS=()=>N.enabled!==!1,Bn=()=>z.mode??"anchor-top",mr=()=>Bn()==="follow"||Bn()==="anchor-top"&&oa,Gi=()=>z.anchorTopOffset??16,uS=()=>z.restorePosition??"bottom",bf=()=>z.pauseOnInteraction===!0,vf=()=>z.showActivityWhilePinned!==!1,Cf=()=>z.announce===!0,xp=()=>z.scrollbar??"on-scroll",Dt=E("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");Dt.type="button",Dt.style.display="none",Dt.setAttribute("data-persona-scroll-to-bottom","true");let Yi=E("span","persona-flex persona-items-center"),Sp=E("span",""),qr=E("span","");qr.setAttribute("data-persona-scroll-to-bottom-count",""),qr.style.display="none",Dt.append(Yi,Sp,qr),de.appendChild(Dt);let Kn=E("div","persona-stream-anchor-spacer");Kn.setAttribute("aria-hidden","true"),Kn.setAttribute("data-persona-anchor-spacer",""),Kn.style.flexShrink="0",Kn.style.pointerEvents="none",Kn.style.height="0px",Kn.style.display="none",te.appendChild(Kn);let $o=E("div","persona-sr-only");$o.setAttribute("aria-live","polite"),$o.setAttribute("aria-atomic","true"),$o.setAttribute("role","status"),$o.setAttribute("data-persona-live-region",""),Object.assign($o.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"}),de.appendChild($o);let Qi=null,Ml=null,El=i=>{!Cf()||!i||(Ml=i,Qi===null&&(Qi=setTimeout(()=>{Qi=null,Ml&&Cf()&&($o.textContent=Ml),Ml=null},400)))},Tl="empty",Pl=0,Ap=()=>Pl||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,zr=()=>{let c=Le.style.display==="none"?0:Le.offsetHeight;Dt.style.bottom=`${c+Ap()+cS}px`};zr();let Mp=()=>{$s||(Le.style.marginBottom=Pl>0?`${Pl}px`:"")},kl=()=>{let i=nm(o,be()),c=Bo(o),f=Le.style.display==="none"?0:Le.offsetHeight,b=c.anchor==="center"&&Tl==="empty"?ol(c.anchorComposerTop)??ol("44%"):null,C=b===null||be()?0:OC({columnHeight:de.clientHeight,footerHeight:f,fraction:b});e.style.setProperty("--persona-composer-overlay-height",`${f}px`),e.style.setProperty("--persona-composer-lift",`${i==="overlay"?C:0}px`),Pl=i==="block"?C:0,Mp(),zr()},wf=()=>{let i=!!Ki();Dt.setAttribute("aria-label",Ki()||"Jump to latest"),Dt.title=Ki(),Dt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Yi.innerHTML="";let c=le(dS(),"14px","currentColor",2);c?(Yi.appendChild(c),Yi.style.display=""):Yi.style.display="none",Sp.textContent=Ki(),Sp.style.display=i?"":"none"};wf();let Ze=null,Wt=null,Ce=Lv(),gS=i=>{try{de.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};Ce.subscribe(gS);let vo=()=>{Ce.setText(ae?.value??"")},Vr=()=>{Ce.setMentionRefs(Wt?.getMentionRefs()??[])},mS=i=>({id:i.id,name:i.file.name,mimeType:i.file.type,size:i.file.size,status:i.status,progress:i.progress,error:i.error}),xf=i=>{let c=Object.freeze(i.map(mS));Ce.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(g){console.error("[AgentWidget] attachments.onChange failed:",g)}Jp()};Ce.setSelectedModelId(o.composer?.selectedModelId);let Xi=()=>o.composer?.modes??[],_s=()=>oC(Xi(),o.composer?.modeGroups);{let i=vd(o.composer?.defaultActiveModeIds??[],Xi());i.length&&Ce.setActiveModeIds(i)}function Sf(i){if(Ce.getState().selectedModelId!==i){Ce.setSelectedModelId(i),fr?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function Ll(i){Ce.setActiveModeIds(i),Uo?.render(i,_s()),Ds.forEach(c=>c.repaint()),wo?.resolve(),tc(),ro()}function Ep(i){Ll(rC(Ce.getState().activeModeIds,i,Xi(),o.composer?.modeGroups))}let fr=null,Tp=null,Uo=null,Ds=new Map,hr=null;function Co(i){Ce.setQuote(i),hr?.render(Ce.getState().quote),ro(),fh()}let Af=!1;function Pp(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!Af&&o.debug===!0&&(Af=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let yr=null;function Ns(i){Ce.setPendingSubmission(i),yr?.render(Ce.getState().pendingSubmission),ro()}let fS=i=>{let c=Ds.get(i);if(c)return c;let g=aC({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===i),getModes:()=>Xi().filter(f=>f.groupId===i),getActiveIds:()=>Ce.getState().activeModeIds,onSelect:f=>Ep(f)});return Ds.set(i,g),g},hS=()=>{let i=[],c=Ce.getState().activeModeIds,g=new Set;if(Xi().forEach((f,b)=>{if(bd(f.groupId,o.composer?.modeGroups)){let C=f.groupId;if(g.has(C))return;g.add(C);let W=fS(C);W.action.order=Yg(b),W.action.label=o.composer?.modeGroups?.find(U=>U.id===C)?.label??C,i.push(W.action);return}i.push({id:tC(f.id),kind:"button",placement:"start",order:Yg(b),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:c.includes(f.id),onSelect:()=>Ep(f.id)})}),o.composer?.models?.length&&!a.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!fr||Tp!==f)&&(Tp=f,fr=Zv({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Ce.getState().selectedModelId,onSelect:b=>Sf(b),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(fr.action)}return i},kp=null,Mf=a.find(i=>i.renderHeader);if(Mf?.renderHeader){let i=Mf.renderHeader({config:o,defaultRenderer:()=>{let c=$r({config:o,showClose:Be()});return Ri(de,c,o),c.header},onClose:()=>gt(!1,"user")});if(i){let c=Ee;c&&(c.replaceWith(i),Ee=i,Hn.header.element=i)}}let Ef=()=>{ht&&(te.style.display="none",Le.parentNode?.insertBefore(ht.element,Le),ht.update())},Lp=()=>{if(!He){xl();return}if(Gt=!0,ht?Ef():Rm().then(c=>{ht||!Gt||!He||(ht=c.createEventStreamView({buffer:He,getFullHistory:()=>He.getAllFromStore(),onClose:()=>Fs(),config:o,plugins:a,getThroughput:()=>rt?.getMetric()??{status:"idle"},renderIconByName:le}),Ef())}).catch(()=>{Fs()}),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${hn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(g=>g&&tt.classList.add(g))}let i=()=>{if(!Gt)return;let c=Date.now();c-sn>=200&&(ht?.update(),sn=c),Ht=requestAnimationFrame(i)};sn=0,Ht=requestAnimationFrame(i),Vt(),A.emit("eventStream:opened",{timestamp:Date.now()})},Fs=()=>{if(Gt){if(Gt=!1,ht&&ht.element.remove(),te.style.display="",tt){tt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&tt.classList.remove(c))}Ht!==null&&(cancelAnimationFrame(Ht),Ht=null),Vt(),A.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(S){let i=o.features?.eventStream?.classNames,c="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"+(i?.toggleButton?" "+i.toggleButton:"");tt=E("button",c),tt.style.width="28px",tt.style.height="28px",tt.style.color=hn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let g=It(gx,"18px","currentColor",1.5);g&&tt.appendChild(g);let f=_e.clearChatButtonWrapper,b=_e.closeButtonWrapper,C=f||b;C&&C.parentNode===Ee?Ee.insertBefore(tt,C):Ee.appendChild(tt),tt.addEventListener("click",()=>{Gt?Fs():Lp()})}let Tf=i=>{let c=o.attachments;if(!c?.enabled)return;let g=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!g){g=E("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),g.setAttribute("data-persona-composer-attachment-previews",""),g.style.display="none";let b=i.querySelector("[data-persona-composer-form]");b?.parentNode?b.parentNode.insertBefore(g,b):i.insertBefore(g,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let b=E("input");b.type="file",b.setAttribute("data-persona-composer-attachment-input",""),b.accept=(c.allowedTypes??ar).join(","),b.multiple=(c.maxFiles??4)>1,b.style.display="none",b.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(b)}},$s=!1,Pf=i=>{let c=a.find(b=>b.renderComposer);if(!c?.renderComposer)return null;let g=o.composer,f=p?P.isStreaming():!1;return c.renderComposer({config:o,defaultRenderer:i,requestRender:()=>$y(),storage:u(c.id),onSubmit:b=>{!P||P.isStreaming()||Pc(b.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{Mo()||yt?.click()},models:g?.models,selectedModelId:Ce.getState().selectedModelId??g?.selectedModelId,onModelChange:b=>Sf(b),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{kp?.()}:void 0})},kf=Pf(()=>Wi({config:o}).footer);kf&&(Hn.replaceComposer(kf),Le=Hn.composer.footer,$s=!0);let nt=null,yS=i=>{oo=i.form,ae=i.input,bo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Me=i.sendButton),i.micButton&&(ne=i.micButton,On=i.micButton.parentElement),i.found.status&&(st=i.found.status),i.found.suggestions&&(ur=i.found.suggestions),i.attachmentButton&&(xt=i.attachmentButton,xn=i.attachmentButton.parentElement),yt=i.attachmentInput??null,Sn=i.attachmentPreviews??null,i.found.actionsRow&&(lS=i.found.actionsRow),wp=i.found.actionsStart,Al=i.found.actionsEnd};function Ip(){let i=ae;if(!i)return;let c=o.composer?.inputAttributes,g=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;cd(i,c),g&&i.setAttribute("aria-label",g),ld(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:el(i)}),$v(i,ad(o.composer?.maxLines,be()?5:3))}let Lf=i=>{nt=Rv(i,{debug:o.debug===!0}),nt&&yS(nt),Ip()};Tf(Le),Lf(Le),vo();let Ji=Dr(o,be());Ji&&(Pe.style.maxWidth=Ji,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%",Wn.style.maxWidth=Ji,Wn.style.marginLeft="auto",Wn.style.marginRight="auto",Wn.style.width="100%",Cp.style.maxWidth=Ji,Vi.style.maxWidth=Ji,Vi.style.marginLeft="auto",Vi.style.marginRight="auto",Vi.style.width="100%");let If=()=>{let i=Dr(o,be());if(!(!i||be()))for(let c of[oo,ur,Sn,st])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};If();let Rf=()=>{!o.attachments?.enabled||!yt||!Sn||(Ze?Ze.remountPreviews(Sn):(Ze=Mi.fromConfig(o.attachments,xf),Ze.setPreviewsContainer(Sn)),nt?.addListener(yt,"change",i=>{let c=i.target;Ze?.handleFileSelect(c.files),c.value=""}),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(bx(o.attachments.dropOverlay)))};Rf();let bS=()=>Wt?.prefetch(),Hf=()=>{if(!o.contextMentions?.enabled||!ae)return;let i=nt?.header??null,c=i?Gg(i):void 0;if(Wt=TC({config:o,textarea:ae,anchor:oo??ae,getMessages:()=>P.getMessages(),liveRegionHost:de,chipRow:c}),Wt&&!c){let g=ae;g.parentElement?.insertBefore(Wt.contextRow,g)}};Hf();let wo=null,vS={getState:()=>Ce.getState(),getValue:()=>ae?.value??"",setValue:i=>{ae&&(ae.value=i,ae.dispatchEvent(new Event("input",{bubbles:!0})),vo())},submit:()=>{yC(nt?.form??null)},openAttachmentPicker:()=>{Mo()||yt?.click()},toggleVoice:()=>{kp?.()},requestRender:()=>wo?.resolve()},CS=()=>{let i=[];return(Wt?.affordanceButtons??[]).forEach((g,f)=>{i.push({id:`core:mention-${f}`,placement:"start",order:Wo.mention+f,element:g,managed:!0})}),xn&&i.push({id:"core:attachment",placement:"start",order:Wo.attachment,element:xn}),On&&i.push({id:"core:mic",placement:"end",order:Wo.mic,element:On}),bo&&i.push({id:"core:send",placement:"end",order:Wo.send,element:bo}),i},Wf=()=>{wo?.destroy(),wo=Qv({getBindings:()=>nt,collect:()=>({builtIns:CS(),configActions:[...hS(),...o.composer?.actions??[]],plugins:a,contributionContext:{config:o,getState:()=>Ce.getState(),requestRender:()=>wo?.resolve()},debug:o.debug===!0}),actionContext:vS,getState:()=>Ce.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),wo.resolve()};Wf();let Rp=()=>{if(Uo?.destroy(),Uo=null,!_s().length)return;let i=nt?.header;i&&(Uo=eC({row:Gg(i),onRemove:c=>Ep(c),initialIds:Ce.getState().activeModeIds}),Uo.render(Ce.getState().activeModeIds,_s()))};Rp();let Of=()=>{hr?.destroy(),hr=null,yr?.destroy(),yr=null;let i=nt?.header;i&&(hr=lC({onDismiss:()=>Co(void 0)}),i.appendChild(hr.element),hr.render(Ce.getState().quote),Pp()==="defer-one"&&(yr=cC({onEdit:()=>GA(),onRemove:()=>Ns(void 0)}),i.appendChild(yr.element),yr.render(Ce.getState().pendingSubmission)))};Of();let Hp=fC(),wS=()=>{let i=nt?.header?.querySelector(Kg);if(i)return i.childElementCount>0;let c=Ce.getState();return c.mentionRefs.length>0||vd(c.activeModeIds,_s()).length>0},Bf=()=>!1;function ro(){let i=Ce.getState(),c=Hp.observe(hC(ae),i.text);Le.toggleAttribute("data-persona-composer-compact",mC({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:wS(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0,dictationActive:Bf()}))}function _f(){o.composer?.layout==="single-row"&&!be()?Le.setAttribute("data-persona-composer-layout","single-row"):Le.removeAttribute("data-persona-composer-layout")}_f(),Ce.subscribe(()=>{wo?.sync(),Jp(),Zl(),ro(),fh()}),Zl();let Df=!1,xS=i=>{if(Df||o.debug!==!0)return;let c=["messages","composer"].filter(g=>i[g]);c.length&&(Df=!0,console.warn(`[persona] layout.slots.${c.join(" and layout.slots.")} ${c.length>1?"are":"is"} deprecated and unsupported: the renderer never runs. Use the message render hooks for the transcript and the renderComposer plugin hook for the composer.`))};(()=>{let i=o.layout?.slots??{};xS(i);let c=f=>{switch(f){case"body-top":return te.querySelector("[data-persona-intro-card]");case"messages":return Pe;case"footer-top":return ur;case"composer":return oo;case"footer-bottom":return st;default:return null}},g=(f,b)=>{switch(f){case"header-left":case"header-center":case"header-right":if(f==="header-left")Ee.insertBefore(b,Ee.firstChild);else if(f==="header-right")Ee.appendChild(b);else{let C=Ee.querySelector(".persona-flex-col");C?C.parentNode?.insertBefore(b,C.nextSibling):Ee.appendChild(b)}break;case"body-top":{let C=te.querySelector("[data-persona-intro-card]");C?C.replaceWith(b):te.insertBefore(b,te.firstChild);break}case"body-bottom":te.appendChild(b);break;case"footer-top":ur.replaceWith(b);break;case"footer-bottom":st.replaceWith(b);break;default:break}};for(let[f,b]of Object.entries(i))if(b)try{let C=b({config:o,defaultContent:()=>c(f)});C&&g(f,C)}catch(C){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${f}":`,C)}})();let Nf=i=>{let g=i.target.closest('button[data-expand-header="true"]');if(!g)return;let f=g.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!f)return;let b=f.getAttribute("data-message-id");if(!b)return;let C=g.getAttribute("data-bubble-type");if(C==="reasoning")Di.has(b)?Di.delete(b):Di.add(b),Ow(b,f);else if(C==="tool")Ni.has(b)?Ni.delete(b):Ni.add(b),_w(b,f,o);else if(C==="approval"&&m){let U=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",$=m.approvalDetailsExpansionState.get(b)??U;m.approvalDetailsExpansionState.set(b,!$),m.updateApprovalDetailsUI(b,f,o)}Nt.delete(b)};Pe.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Nf(i))}),Pe.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Nf(i))}),Pe.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let g=Pe.getRootNode(),f=typeof g.getSelection=="function"?g.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let b=f.toString(),C=NC(b);!C||C===b||(c.setData("text/plain",C),i.preventDefault())});let Wp=new Map,Ff=null,$f="idle",SS={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},AS=(i,c)=>{let{icon:g,label:f}=SS[c];i.setAttribute("aria-label",f),i.title=f,i.setAttribute("aria-pressed",c==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",c!=="idle"),i.classList.toggle("persona-message-action-loading",c==="loading");let b=le(g,14,"currentColor",2);b&&(i.innerHTML="",i.appendChild(b))},Uf=()=>{Pe.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let f=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;AS(c,f&&f===Ff?$f:"idle")})};Pe.addEventListener("click",i=>{let g=i.target.closest(".persona-message-action-btn[data-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest("[data-actions-for]");if(!f)return;let b=f.getAttribute("data-actions-for");if(!b)return;let C=g.getAttribute("data-action");if(C==="copy"){let U=P.getMessages().find($=>$.id===b);if(U&&Os.onCopy){let $=U.content||"";navigator.clipboard.writeText($).then(()=>{g.classList.add("persona-message-action-success");let j=It(mx,14,"currentColor",2);j&&(g.innerHTML="",g.appendChild(j)),setTimeout(()=>{g.classList.remove("persona-message-action-success");let Q=It(fx,14,"currentColor",2);Q&&(g.innerHTML="",g.appendChild(Q))},2e3)}).catch(j=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",j)}),Os.onCopy(U)}}else if(C==="read-aloud")P.toggleReadAloud(b);else if(C==="upvote"||C==="downvote"){let U=(Wp.get(b)??null)===C,$=C==="upvote"?"thumbs-up":"thumbs-down";if(U){Wp.delete(b),g.classList.remove("persona-message-action-active");let j=le($,14,"currentColor",2);j&&(g.innerHTML="",g.appendChild(j))}else{let j=C==="upvote"?"downvote":"upvote",Q=f.querySelector(`[data-action="${j}"]`);if(Q){Q.classList.remove("persona-message-action-active");let mt=le(j==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);mt&&(Q.innerHTML="",Q.appendChild(mt))}Wp.set(b,C),g.classList.add("persona-message-action-active");let oe=le($,14,"currentColor",2);oe&&(oe.setAttribute("fill","currentColor"),g.innerHTML="",g.appendChild(oe)),g.classList.remove("persona-message-action-pop"),g.offsetWidth,g.classList.add("persona-message-action-pop");let Xe=P.getMessages().find(dt=>dt.id===b);Xe&&Os.onFeedback&&Os.onFeedback({type:C,messageId:Xe.id,message:Xe})}}else if(C==="regenerate")Il?.regenerate(b);else if(C==="edit")Il?.edit(b);else if(C==="quote")Il?.quote(b);else if(C?.startsWith(Bd)){let W=C.slice(Bd.length),U=o.messageActions?.custom?.find(j=>j.id===W),$=P.getMessages().find(j=>j.id===b);if(!U||!$)return;try{U.onSelect($)}catch(j){console.error(`[AgentWidget] messageActions.custom "${W}" onSelect failed:`,j)}}});let Il=null;Pe.addEventListener("click",i=>{let g=i.target.closest("button[data-approval-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest(".persona-approval-bubble");if(!f)return;let b=f.getAttribute("data-message-id");if(!b)return;let C=g.getAttribute("data-approval-action");if(!C)return;let W=C==="approve"?"approved":"denied",$=P.getMessages().find(Q=>Q.id===b);if(!$?.approval)return;let j=f.querySelector("[data-approval-buttons]");j&&j.querySelectorAll("button").forEach(oe=>{oe.disabled=!0,oe.style.opacity="0.5",oe.style.cursor="not-allowed"}),$.approval.toolType==="webmcp"?P.resolveWebMcpApproval(b,W):P.resolveApproval($.approval,W)});let qe=null,jf=!1,Zi=null,Kr=()=>{},ea="none",Rl=null,Gn={artifacts:[],selectedId:null},jo=!1,so=!1,ta=!1,Us=!1,qf=()=>Us||Gn.artifacts.some(i=>sr(o.features?.artifacts,i)==="panel"),Hl=()=>Gn.artifacts.length>0&&!jo&&qf(),ct={current:null},Op=(i,c)=>{let g=P.getArtifactById(c),f=g?.markdown,b=g?.title||"artifact",C=g?.file,W=g?.artifactType??"markdown";if(!f){let j=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(j){let oe=P.getMessages().find(ue=>ue.id===j);if(oe?.rawContent)try{let ue=JSON.parse(oe.rawContent);f=ue?.props?.markdown,b=ue?.props?.title||b,ue?.props?.file&&typeof ue.props.file=="object"&&(C=ue.props.file),!g&&typeof ue?.props?.artifactType=="string"&&(W=ue.props.artifactType)}catch{}}}return{markdown:f,title:b,file:C,artifactType:W}};Pe.addEventListener("click",i=>{let g=i.target.closest("[data-download-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-download-artifact");if(!f||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:f})===!0)return;let{markdown:C,title:W,file:U}=Op(g,f);if(!C)return;let $=lr();$&&$.triggerArtifactDownload($.downloadInfoFor({title:W,markdown:C,file:U}))}),Pe.addEventListener("click",i=>{let g=i.target.closest("[data-artifact-custom-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-artifact-custom-action");if(!f)return;let b=g.closest("[data-artifact-inline]"),C=b?null:g.closest("[data-open-artifact]"),W=b?b.getAttribute("data-artifact-inline"):C?.getAttribute("data-open-artifact")??null,$=(b?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(dt=>dt.id===f);if(!$)return;let{markdown:j,title:Q,file:oe,artifactType:ue}=Op(g,W??""),Xe={artifactId:W,title:Q,artifactType:ue,markdown:j,file:oe};try{Promise.resolve($.onClick(Xe)).catch(()=>{})}catch{}}),Pe.addEventListener("click",i=>{let g=i.target.closest("[data-copy-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-copy-artifact");if(!f)return;let b=P.getArtifactById(f),C=lr();if(!C)return;let W="";if(b)W=C.artifactCopyText(b);else{let{markdown:U,file:$,artifactType:j}=Op(g,f);j==="markdown"&&(W=C.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:U??"",...$?{file:$}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let U=It(mx,16,"currentColor",2);U&&(g.replaceChildren(U),setTimeout(()=>{let $=It(fx,16,"currentColor",2);$&&g.replaceChildren($)},1500))}).catch(()=>{})}),Pe.addEventListener("click",i=>{let g=i.target.closest("[data-expand-artifact-inline]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-expand-artifact-inline");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(jo=!1,Us=!0,so=!0,ta=!0,P.selectArtifact(f),io())}),Pe.addEventListener("click",i=>{let c=i.target;if(c.closest("[data-download-artifact]")||c.closest("[data-artifact-custom-action]"))return;let g=c.closest("[data-open-artifact]");if(!g)return;let f=g.getAttribute("data-open-artifact");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(i.preventDefault(),i.stopPropagation(),jo=!1,Us=!0,P.selectArtifact(f),io())}),Pe.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let c=i.target;!c.hasAttribute("data-open-artifact")&&!c.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),c.click())});let js=_e.composerOverlay,qs=(i,c,g)=>{let f=c.trim();if(!f||!ct.current)return;let b=i.getAttribute("data-tool-call-id")??"",C=g.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:b,answer:f,answers:g.structured,values:g.values??(g.source==="multi"?f.split(", "):[f]),isFreeText:C,source:g.source},bubbles:!0,composed:!0})),Es(js,b);let W=ct.current.getMessages().find(U=>U.toolCall?.id===b);W?.agentMetadata?.awaitingLocalTool?ct.current.resolveAskUserQuestion(W,g.structured??f):ct.current.sendMessage(f)},Gr=i=>{let c=ct.current;if(!c)return;let g=i.getAttribute("data-tool-call-id")??"",f=c.getMessages().find(b=>b.toolCall?.id===g);f&&c.persistAskUserQuestionProgress(f,{answers:Vc(i,f),currentIndex:to(i)})},zf=i=>Object.entries(i).map(([c,g])=>`${c}: ${Array.isArray(g)?g.join(", "):g}`).join(" | "),Bp=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=to(i),g=vi(i);if(c>=g-1)return;let f=ct.current?.getMessages().find(b=>b.toolCall?.id===i.getAttribute("data-tool-call-id"));f&&(Kc(i,f,o,c+1),Gr(i))};js.addEventListener("click",i=>{let g=i.target.closest("[data-ask-user-action]");if(!g)return;let f=g.closest("[data-persona-ask-sheet-for]");if(!f)return;let b=g.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),b==="dismiss"){let C=f.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:C},bubbles:!0,composed:!0})),Es(js,C);let W=ct.current?.getMessages().find(U=>U.toolCall?.id===C);W?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(W),ct.current?.resolveAskUserQuestion(W,"(dismissed)"));return}if(b==="pick"){let C=g.getAttribute("data-option-label");if(!C)return;let W=f.getAttribute("data-multi-select")==="true",U=Wr(f);if(U&&W){let $=Ms(f)[to(f)],j=new Set(Array.isArray($)?$:[]);j.has(C)?j.delete(C):j.add(C),Or(f,Array.from(j)),Gr(f);return}if(U){Or(f,C),Gr(f),Bp(f);return}if(W){let $=g.getAttribute("aria-pressed")==="true";g.setAttribute("aria-pressed",$?"false":"true"),g.classList.toggle("persona-ask-pill-selected",!$);let j=f.querySelector('[data-ask-user-action="submit-multi"]');j&&(j.disabled=pg(f).length===0);return}qs(f,C,{source:"pick",values:[C]});return}if(b==="submit-multi"){let C=pg(f);if(C.length===0)return;qs(f,C.join(", "),{source:"multi",values:C});return}if(b==="open-free-text"){let C=f.querySelector('[data-ask-free-text-row="true"]');C&&(C.classList.remove("persona-hidden"),C.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(b==="focus-free-text"){f.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(b==="submit-free-text"){let W=f.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!W.trim())return;if(Wr(f)){Or(f,W.trim()),Gr(f),Bp(f);return}qs(f,W,{source:"free-text"});return}if(b==="next"||b==="back"){if(!ct.current)return;let C=f.getAttribute("data-tool-call-id")??"",W=ct.current.getMessages().find(oe=>oe.toolCall?.id===C);if(!W)return;let $=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if($){let oe=Ms(f)[to(f)];(typeof oe!="string"||oe!==$)&&Or(f,$)}let j=b==="next"?1:-1,Q=to(f)+j;Kc(f,W,o,Q),Gr(f);return}if(b==="submit-all"){if(!ct.current)return;let C=f.getAttribute("data-tool-call-id")??"",W=ct.current.getMessages().find(oe=>oe.toolCall?.id===C);if(!W)return;let $=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";$&&Or(f,$);let j=Vc(f,W);ct.current.persistAskUserQuestionProgress(W,{answers:j,currentIndex:to(f)});let Q=zf(j);qs(f,Q||"(submitted)",{source:"submit-all",structured:j});return}if(b==="skip"){if(!ct.current)return;let C=f.getAttribute("data-tool-call-id")??"",W=ct.current.getMessages().find(ue=>ue.toolCall?.id===C);if(!W)return;let U=Wr(f),$=to(f),j=vi(f),Q=$>=j-1;if(!U){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:C},bubbles:!0,composed:!0})),Es(js,C),W.agentMetadata?.awaitingLocalTool&&(ct.current.markAskUserQuestionResolved(W),ct.current.resolveAskUserQuestion(W,"(dismissed)"));return}Or(f,"");let oe=f.querySelector('[data-ask-free-text-input="true"]');if(oe&&(oe.value=""),Q){let ue=Vc(f,W),Xe=zf(ue);qs(f,Xe||"(skipped)",{source:"submit-all",structured:ue});return}Kc(f,W,o,$+1),Gr(f);return}}),js.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let g=i.target;if(!g.matches?.('[data-ask-free-text-input="true"]'))return;let f=g.closest("[data-persona-ask-sheet-for]");if(!f)return;i.preventDefault();let b=g.value;if(b.trim()){if(Wr(f)){Or(f,b.trim()),Gr(f),Bp(f);return}qs(f,b,{source:"free-text"})}});let Vf=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let c=i.target;if(c?.tagName==="INPUT"||c?.tagName==="TEXTAREA"||c?.isContentEditable)return;let g=js.querySelector("[data-persona-ask-sheet-for]");if(!g||g.getAttribute("data-ask-layout")!=="rows"||g.getAttribute("data-multi-select")==="true")return;let f=Number(i.key),C=g.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[f-1];C&&(i.preventDefault(),C.click())};document.addEventListener("keydown",Vf);let xo=null,vt=null,na=null,Wl=null,Ol=()=>{},Kf=!1,Bl="",_l="";function _p(){Wl?.(),Wl=null}let MS=()=>{let i=oi&&ms?.isConnected?ms:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},Gf=()=>{if(!xo||!vt)return;let i=e.classList.contains("persona-artifact-welded-split"),c=e.ownerDocument.defaultView??window,g=c.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||g){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 f=xo.firstElementChild;if(!f||f===vt)return;let b=10;vt.style.position="absolute",vt.style.top="0",vt.style.bottom="0",vt.style.width=`${b}px`,vt.style.zIndex="5";let C=Nm(xo,c),W=f.offsetWidth+C/2-b/2;vt.style.left=`${Math.max(0,W)}px`},Dl=()=>{},ES=()=>{let i=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,g=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>g?!1:ce||St(o)},Nl=()=>!bn(o)||!Hl()||e.classList.contains("persona-artifact-narrow-host")||ES()||(e.ownerDocument.defaultView??window).innerWidth<OI?"none":_m(o)?"detached":"welded",io=()=>{if(!qe||!bn(o))return;yl(e,o),bl(e,o),Dl();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=Se.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let g=Hl();qe.setVisible(g),qe.update(Gn),jo?(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),so=!1,ta=!1):Gn.artifacts.length>0&&qf()?(qe.element.classList.remove("persona-hidden"),qe.setMobileOpen(!0)):(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),so=!1,ta=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(qe.setExpandToggleVisible(f),qe.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),qe.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),qe.setCustomActions(o.features?.artifacts?.toolbarActions??[]),qe.setTabFade(o.features?.artifacts?.layout?.tabFade),qe.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!ta&&(so=!1),so!==Kf){let C=qe.element;so?(Bl=C.style.width,_l=C.style.maxWidth,C.style.removeProperty("width"),C.style.removeProperty("max-width")):(Bl&&(C.style.width=Bl),_l&&(C.style.maxWidth=_l),Bl="",_l=""),Kf=so}e.classList.toggle("persona-artifact-expanded",so),qe.setExpanded(so);let b=Nl();b!==ea&&(ea=b,Kr()),Ol()};if(bn(o)){Se.style.position="relative";let i=E("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=E("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(de),xo=c,c.appendChild(i),Se.appendChild(c);let g=b=>{jf||qe||(qe=b.createArtifactPane(o,{onSelect:C=>ct.current?.selectArtifact(C),onDismiss:()=>{jo=!0,io()},onToggleExpand:()=>{let C=!so,W=Gn.selectedId??Gn.artifacts[Gn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:W,expanded:C})!==!0&&(so=C,C||(ta=!1),io())}}),qe.element.classList.add("persona-hidden"),c.appendChild(qe.element),qe.backdrop&&Se.appendChild(qe.backdrop),Ol(),io())},f=lr();f?g(f):(Om(()=>{let b=lr();b&&g(b)}),Kd().catch(()=>{})),Ol=()=>{if(!xo||!qe)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){na?.(),na=null,_p(),vt&&(vt.remove(),vt=null),qe.element.style.removeProperty("width"),qe.element.style.removeProperty("maxWidth");return}if(!vt){let C=E("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");C.setAttribute("role","separator"),C.setAttribute("aria-orientation","vertical"),C.setAttribute("aria-label","Resize artifacts panel"),C.tabIndex=0;let W=e.ownerDocument,U=W.defaultView??window,$=j=>{if(!qe||j.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||U.innerWidth<=640)return;j.preventDefault(),_p();let Q=j.clientX,oe=qe.element.getBoundingClientRect().width,ue=o.features?.artifacts?.layout,Xe=mt=>{let Qt=xo.getBoundingClientRect().width,$t=e.classList.contains("persona-artifact-welded-split"),Pt=Nm(xo,U),an=$t?0:C.getBoundingClientRect().width||6,et=oe-(mt.clientX-Q),ln=Xw(et,Qt,Pt,an,ue?.resizableMinWidth,ue?.resizableMaxWidth,MS());qe.element.style.width=`${ln}px`,qe.element.style.maxWidth="none",Gf()},dt=()=>{W.removeEventListener("pointermove",Xe),W.removeEventListener("pointerup",dt),W.removeEventListener("pointercancel",dt),Wl=null;try{C.releasePointerCapture(j.pointerId)}catch{}};Wl=dt,W.addEventListener("pointermove",Xe),W.addEventListener("pointerup",dt),W.addEventListener("pointercancel",dt);try{C.setPointerCapture(j.pointerId)}catch{}};C.addEventListener("pointerdown",$),vt=C,xo.insertBefore(C,qe.element),na=()=>{C.removeEventListener("pointerdown",$)}}if(vt){let C=Hl();vt.classList.toggle("persona-hidden",!C),Gf()}},Dl=()=>{if(!ce||!qe||(o.launcher?.sidebarMode??!1)||St(o)&&qn(o).reveal==="emerge")return;let C=e.ownerDocument.defaultView??window,W=o.launcher?.mobileFullscreen??!0,U=o.launcher?.mobileBreakpoint??640;if(W&&C.innerWidth<=U||!jw(o,ce))return;let $=o.launcher?.width??o.launcherWidth??no,j=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Hl()?(Se.style.width=j,Se.style.maxWidth=j):(Se.style.width=$,Se.style.maxWidth=$)},typeof ResizeObserver<"u"&&(Zi=new ResizeObserver(()=>{io()}),Zi.observe(Se))}else Se.appendChild(de);be()&&Yt&&(_e.peekBanner&&Yt.appendChild(_e.peekBanner),Yt.appendChild(Le)),e.appendChild(Ge),Yt&&e.appendChild(Yt);let Dp=()=>{if(be()){Se.style.width="100%",Se.style.maxWidth="100%";let De=o.launcher?.composerBar??{},we=Ge.dataset.state==="expanded",dn=De.expandedSize??"anchored";if(!(we&&dn!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let Pn=o.theme?.components?.panel,kn=Ps(o),at=(Ot,Ln)=>Ot==null||Ot===""?Ln:fn(kn,Ot)??Ot,pt="1px solid var(--persona-border)",We="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",rr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=at(Pn?.border,pt),de.style.borderRadius=at(Pn?.borderRadius,rr),de.style.boxShadow=at(Pn?.shadow,We),de.style.overflow="hidden";return}let i=St(o),c=o.launcher?.sidebarMode??!1,g=i||c||(o.launcher?.fullHeight??!1),f=o.launcher?.enabled===!1,b=o.launcher?.detachedPanel===!0,C=o.theme?.components?.panel,W=Ps(o),U=(De,we)=>De==null||De===""?we:fn(W,De)??De,$=e.ownerDocument.defaultView??window,j=o.launcher?.mobileFullscreen??!0,Q=o.launcher?.mobileBreakpoint??640,oe=$.innerWidth<=Q,ue=j&&oe&&ce,Xe=i&&j&&oe,dt=o.launcher?.position??"bottom-left",mt=dt==="bottom-left"||dt==="top-left",Qt=o.launcher?.zIndex??rn,$t="var(--persona-panel-border, 1px solid var(--persona-border))",Pt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",an="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",et=b&&!ue&&!Xe;et?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let ln=et?$t:c||ue?"none":$t,ko=et?Pt:ue?"none":c?mt?"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))":f?"none":Pt;i&&!ue&&!et&&(ko="none",ln="none");let or=et?an:c||ue?"0":an,co=U(C?.border,ln),La=U(C?.shadow,ko),Cs=U(C?.borderRadius,or),po=Nl(),tn=po==="detached",uo=po==="welded";e.classList.toggle("persona-artifact-detached-split",tn),e.classList.toggle("persona-artifact-welded-split",uo);let mi="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)))))",Ae=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&bn(o)&&_m(o)&&f&&!i;e.classList.toggle("persona-artifact-chat-flush",Ae);let re=tn||Ae?"none":La,kt=tn?$t:uo?"none":co,Ut=tn?an:Cs;Ae&&(kt="none",Ut="0");let nn=C?.borderRadius!=null&&C.borderRadius!=="",jt=Ae&&!nn?"0":Cs,Kt=te.scrollTop;e.style.cssText="",Ge.style.cssText="",Se.style.cssText="",de.style.cssText="",te.style.cssText="",$s||(Le.style.cssText=""),Gt&&(te.style.display="none"),(g||f)&&(e.style.minWidth="0");let Lt=()=>{if(Kt<=0)return;(te.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(te.scrollTop===Kt)return;let we=te.scrollHeight-te.clientHeight;we<=0||(te.scrollTop=Math.min(Kt,we))})};if(ue){Ge.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"),Ge.style.cssText=`
44
44
  position: fixed !important;
45
45
  inset: 0 !important;
46
46
  width: 100% !important;
@@ -50,7 +50,7 @@ _Details: ${n.message}_`:o}var Ig=e=>({isError:!0,content:[{type:"text",text:e}]
50
50
  padding: 0 !important;
51
51
  display: flex !important;
52
52
  flex-direction: column !important;
53
- z-index: ${Xt} !important;
53
+ z-index: ${Qt} !important;
54
54
  background-color: var(--persona-surface, #ffffff) !important;
55
55
  `,Se.style.cssText=`
56
56
  position: relative !important;
@@ -65,7 +65,7 @@ _Details: ${n.message}_`:o}var Ig=e=>({isError:!0,content:[{type:"text",text:e}]
65
65
  padding: 0 !important;
66
66
  box-shadow: none !important;
67
67
  border-radius: 0 !important;
68
- `,ge.style.cssText=`
68
+ `,de.style.cssText=`
69
69
  display: flex !important;
70
70
  flex-direction: column !important;
71
71
  flex: 1 1 0% !important;
@@ -76,32 +76,32 @@ _Details: ${n.message}_`:o}var Ig=e=>({isError:!0,content:[{type:"text",text:e}]
76
76
  overflow: hidden !important;
77
77
  border-radius: 0 !important;
78
78
  border: none !important;
79
- `,ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.overflowY="auto",Ie.style.flexShrink="0",Mp(),mt=!0,Be();return}let je=o?.launcher?.width??o?.launcherWidth??oo;if(!c&&!i)f&&g?(Se.style.width="100%",Se.style.maxWidth="100%"):(Se.style.width=je,Se.style.maxWidth=je);else if(i)if(Un(o).reveal==="emerge"&&!b){let ht=Un(o).width;Se.style.width=ht,Se.style.maxWidth=ht}else Se.style.width="100%",Se.style.maxWidth="100%";if(Fl(),Se.style.boxShadow=Le,Se.style.borderRadius=Gt,ke?Se.style.border="none":We&&(Se.style.border=Ho),ge.style.border=go,ge.style.borderRadius=Et,ge.style.boxShadow=ke&&!lt?xe:"",lt&&(ge.style.background="transparent",ne.style.background="transparent",Ie.style.background="transparent",Ie.style.borderTop="none"),We){let Ne=o.features?.artifacts?.layout;Wl=Ne?.unifiedSplitOuterRadius?.trim()||Ne?.paneBorderRadius?.trim()||Es}else Wl=null;if(i&&!fe&&!Ze&&!ke&&!We&&w?.border===void 0&&(ge.style.border="none",Un(o).side==="right"?ge.style.borderLeft="1px solid var(--persona-border)":ge.style.borderRight="1px solid var(--persona-border)"),i&&!fe&&We&&w?.border===void 0&&(Un(o).side==="right"?Se.style.borderLeft="1px solid var(--persona-border)":Se.style.borderRight="1px solid var(--persona-border)"),g&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",f&&(e.style.width="100%"),Ke.style.display="flex",Ke.style.flexDirection="column",Ke.style.flex="1 1 0%",Ke.style.minHeight="0",Ke.style.maxHeight="100%",Ke.style.height="100%",f&&(Ke.style.overflow="hidden"),Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.height="100%",ke||(Se.style.overflow="hidden"),ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.overflow="hidden",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.overflowY="auto",Ie.style.flexShrink="0"),f&&(Ze||ke||lt)&&!i&&(lt||(Ke.style.padding="var(--persona-panel-inset)"),Ke.style.background="var(--persona-panel-canvas-bg)"),Ke.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"),!c&&!f&&!i&&(jn[dt]??jn["bottom-right"]).split(" ").forEach(ht=>Ke.classList.add(ht)),c){let Ne=o.launcher?.sidebarWidth??"420px";b?Ke.style.cssText=`
79
+ `,te.style.flex="1 1 0%",te.style.minHeight="0",te.style.overflowY="auto",Le.style.flexShrink="0",Mp(),Bt=!0,Lt();return}let Re=o?.launcher?.width??o?.launcherWidth??no;if(!c&&!i)f&&g?(Se.style.width="100%",Se.style.maxWidth="100%"):(Se.style.width=Re,Se.style.maxWidth=Re);else if(i)if(qn(o).reveal==="emerge"&&!b){let we=qn(o).width;Se.style.width=we,Se.style.maxWidth=we}else Se.style.width="100%",Se.style.maxWidth="100%";if(Dl(),Se.style.boxShadow=re,Se.style.borderRadius=jt,tn?Se.style.border="none":uo&&(Se.style.border=co),de.style.border=kt,de.style.borderRadius=Ut,de.style.boxShadow=tn&&!Ae?mi:"",Ae&&(de.style.background="transparent",te.style.background="transparent",Le.style.background="transparent",Le.style.borderTop="none"),uo){let De=o.features?.artifacts?.layout;Rl=De?.unifiedSplitOuterRadius?.trim()||De?.paneBorderRadius?.trim()||Cs}else Rl=null;if(i&&!ue&&!et&&!tn&&!uo&&C?.border===void 0&&(de.style.border="none",qn(o).side==="right"?de.style.borderLeft="1px solid var(--persona-border)":de.style.borderRight="1px solid var(--persona-border)"),i&&!ue&&uo&&C?.border===void 0&&(qn(o).side==="right"?Se.style.borderLeft="1px solid var(--persona-border)":Se.style.borderRight="1px solid var(--persona-border)"),g&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",f&&(e.style.width="100%"),Ge.style.display="flex",Ge.style.flexDirection="column",Ge.style.flex="1 1 0%",Ge.style.minHeight="0",Ge.style.maxHeight="100%",Ge.style.height="100%",f&&(Ge.style.overflow="hidden"),Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.height="100%",tn||(Se.style.overflow="hidden"),de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.overflow="hidden",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.overflowY="auto",Le.style.flexShrink="0"),f&&(et||tn||Ae)&&!i&&(Ae||(Ge.style.padding="var(--persona-panel-inset)"),Ge.style.background="var(--persona-panel-canvas-bg)"),Ge.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"),!c&&!f&&!i&&(zn[dt]??zn["bottom-right"]).split(" ").forEach(we=>Ge.classList.add(we)),c){let De=o.launcher?.sidebarWidth??"420px";b?Ge.style.cssText=`
80
80
  position: fixed !important;
81
81
  top: var(--persona-panel-inset) !important;
82
82
  bottom: var(--persona-panel-inset) !important;
83
- width: ${Ne} !important;
83
+ width: ${De} !important;
84
84
  height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
85
85
  max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
86
86
  margin: 0 !important;
87
87
  padding: 0 !important;
88
88
  display: flex !important;
89
89
  flex-direction: column !important;
90
- z-index: ${Xt} !important;
91
- ${gt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
92
- `:Ke.style.cssText=`
90
+ z-index: ${Qt} !important;
91
+ ${mt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
92
+ `:Ge.style.cssText=`
93
93
  position: fixed !important;
94
94
  top: 0 !important;
95
95
  bottom: 0 !important;
96
- width: ${Ne} !important;
96
+ width: ${De} !important;
97
97
  height: 100vh !important;
98
98
  max-height: 100vh !important;
99
99
  margin: 0 !important;
100
100
  padding: 0 !important;
101
101
  display: flex !important;
102
102
  flex-direction: column !important;
103
- z-index: ${Xt} !important;
104
- ${gt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
103
+ z-index: ${Qt} !important;
104
+ ${mt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
105
105
  `,Se.style.cssText=`
106
106
  position: relative !important;
107
107
  display: flex !important;
@@ -113,10 +113,10 @@ _Details: ${n.message}_`:o}var Ig=e=>({isError:!0,content:[{type:"text",text:e}]
113
113
  min-height: 0 !important;
114
114
  margin: 0 !important;
115
115
  padding: 0 !important;
116
- box-shadow: ${Le} !important;
117
- border-radius: ${Gt} !important;
118
- ${ke?"border: none !important;":We?`border: ${Ho} !important;`:""}
119
- `,Se.style.setProperty("width","100%","important"),Se.style.setProperty("max-width","100%","important"),ge.style.cssText=`
116
+ box-shadow: ${re} !important;
117
+ border-radius: ${jt} !important;
118
+ ${tn?"border: none !important;":uo?`border: ${co} !important;`:""}
119
+ `,Se.style.setProperty("width","100%","important"),Se.style.setProperty("max-width","100%","important"),de.style.cssText=`
120
120
  display: flex !important;
121
121
  flex-direction: column !important;
122
122
  flex: 1 1 0% !important;
@@ -125,32 +125,32 @@ _Details: ${n.message}_`:o}var Ig=e=>({isError:!0,content:[{type:"text",text:e}]
125
125
  min-height: 0 !important;
126
126
  max-height: 100% !important;
127
127
  overflow: hidden !important;
128
- border-radius: ${Et} !important;
129
- border: ${go} !important;
130
- ${ke&&!lt?`box-shadow: ${xe} !important;`:""}
131
- ${lt?"background: transparent !important;":""}
132
- `,Ks||(Ie.style.cssText=`
128
+ border-radius: ${Ut} !important;
129
+ border: ${kt} !important;
130
+ ${tn&&!Ae?`box-shadow: ${mi} !important;`:""}
131
+ ${Ae?"background: transparent !important;":""}
132
+ `,$s||(Le.style.cssText=`
133
133
  flex-shrink: 0 !important;
134
134
  border-top: none !important;
135
135
  padding: 8px 16px 12px 16px !important;
136
- ${lt?"background: transparent !important;":""}
137
- `)}if(!f&&!i){let Ne="max-height: -moz-available !important; max-height: stretch !important;",ht=c?"":"padding-top: 1.25em !important;",ot=c?"":`z-index: ${o.launcher?.zIndex??sn} !important;`;Ke.style.cssText+=Ne+ht+ot}Mp(),Be()},Np=()=>{e.style.setProperty("--persona-content-max-width",jr(o,Ce()))},Vf=!1,Kf=()=>{let i=nm(o,Ce());Ce()&&o.composer?.placement&&o.debug===!0&&!Vf&&(Vf=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=No(o);e.setAttribute("data-persona-composer-placement",i),e.setAttribute("data-persona-conversation-state",Pl),e.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",c.composerGap??Td),Il()},Gf=()=>{if(Ce())return;let i=Tt(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!ve)return;let f=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640;if(b&&f.innerWidth<=w)return;let W=f.innerHeight,z=64,q=o.launcher?.heightOffset??0,V=Math.max(200,W-z),J=Math.min(640,V);Se.style.height=`${Math.max(200,J-q)}px`};Dp(),Oi(e,o),Cl(e,o),wl(e,o),Np(),Kf(),Zr=()=>{Dp(),Gf(),Oi(e,o),Cl(e,o),wl(e,o),Np(),Kf(),Wl?e.style.setProperty("--persona-artifact-welded-outer-radius",Wl):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Oe(),Ut()};let ye=[];ye.push(()=>{Ff=!0}),ye.push(()=>{d.forEach(i=>i()),l.destroy()}),ye.push(()=>{document.removeEventListener("keydown",jf)}),ye.push(()=>{na!==null&&clearTimeout(na)});let To=null,ko=null;ye.push(()=>{To?.(),To=null,ko?.(),ko=null}),sa&&ye.push(()=>{sa?.disconnect(),sa=null}),ye.push(()=>{la?.(),la=null,_p(),wt&&(wt.remove(),wt=null),qe?.element.style.removeProperty("width"),qe?.element.style.removeProperty("maxWidth"),qe?.destroy()}),an&&ye.push(()=>{D=!0,so=null,_!==null&&(cancelAnimationFrame(_),_=null),X?.destroy(),X=null,et?.destroy(),et=null,jo=null});let ts=null,Yf=()=>{ts&&(ts(),ts=null),o.colorScheme==="auto"&&(ts=sl(()=>{Oi(e,o)}))};Yf(),ye.push(()=>{ts&&(ts(),ts=null)}),ye.push(()=>{C=!0,h?.()}),ye.push(()=>{O=!0});let Qf=!1;ye.push(()=>{Qf=!0});let Fp=(i,c)=>{let g=dl(i,c);return g||!XC.includes(i)?g:(ZC().then(f=>{if(Qf)return;Hd(f.wipe),Hd(f.glyphCycle);let b=dl(i,c);b&&gl(b,e)}).catch(()=>{}),null)},Ul=o.features?.streamAnimation;if(Ul?.type&&Ul.type!=="none"){let i=Fp(Ul.type,Ul.plugins);i&&gl(i,e),ye.push(()=>JC(e))}let Go=hl(yr),Xf=hl(Cp),Jf=hl(Ji),ns=[Go,Xf,Jf];ye.push(()=>{ns.forEach(i=>i.destroy())});let os=null,k,rs=null,Zf=!1,eh=0,th=null,nh=i=>i.reduce((c,g)=>g.role==="user"?c+1:c,0),oh=i=>{for(let c=i.length-1;c>=0;c--)if(Ei(i[c]))return i[c].id??null;return null},rh=!1,SS=()=>{rh||o.debug!==!0||(rh=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},sh=!1,ih=!1,ah=(i,c)=>{sh||o.debug!==!0||!c.enabled||c.expose||Zf||ih&&(k.isStreaming()||i.some(Ei)||(sh=!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.")))},Xs=i=>{if(!k)return;let c=i??k.getMessages(),g=V=>{V.render([],k,de,c)},f=V=>{ns.forEach(J=>{J!==V&&g(J)})};rs&&(nh(c)>eh||oh(c)!==th)&&(rs=null);let b=$r(o);ah(c,b);let w=b.enabled?gg(c):null,W=rs??w,z=rs?"host":"agent";if(W){let V=o.suggestions?.followUps,J=V?.placement??(V?"auto":"composer"),fe=(J==="auto"?Ce()?"composer":"after-message":J)==="after-message"?Jf:Go;f(fe),fe.render(W,k,de,c,o.suggestionChipsConfig,{source:z,surface:"followUp",variant:V?.variant??"chip",behavior:V?.behavior??"send",overflow:V?.overflow??"wrap",maxItems:V?.maxItems??4,config:o,plugins:a,submitPrompt:Pc});return}if(c.some(V=>V.role==="user")){ns.forEach(g);return}let q=o.suggestions?.starters;if(q){let V=Ds(No(o),c),J=q.placement??"auto",se=J==="auto"?V?"welcome":"composer":J;if(se==="welcome"&&!V){SS(),ns.forEach(g);return}let fe=se==="welcome"?Xf:Go;f(fe),fe.render(q.items??o.suggestionChips,k,de,c,o.suggestionChipsConfig,{surface:"starter",variant:q.variant??"card",behavior:q.behavior??"send",overflow:q.overflow??"wrap",maxItems:q.maxItems??4,config:o,plugins:a,submitPrompt:Pc});return}f(Go),Go.render(o.suggestionChips,k,de,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a,submitPrompt:Pc})},lh=()=>{rs&&(rs=null,Xs())},AS=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){lh();return}let g=k?k.getMessages():[];rs=c,Zf=!0,eh=nh(g),th=oh(g),Xs(g)},Wn=!1,Dt=NC(),Js=new Map,ss=new Map,Sr=new Map,is=null,Ar=null;function as(){if(!is)return;let i=is;is=null,Ar?.destroy(),Ar=null,Dt.delete(i),ge.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),k&&Yn(Te,k.getMessages(),ft)}let ls=0,MS=Oo()!==null,On=qC(),Bn=0,Mr=null,An=!1,jl=!1,Er=0,zt=null,cs=null,$p=!1,Zs=!1,ds=null,ca=!0,ql=!1,ei=null,zl=!1,ps=()=>{zl=!0,PS()},Up=null,ES=4,Yo=24,TS=80,kS=1e3,Qo=null,ch=()=>{e.setAttribute("data-persona-scrollbar",xp()),xp()!=="on-scroll"&&(Qo!==null&&clearTimeout(Qo),Qo=null,ne.removeAttribute("data-persona-scrollbar-visible"))},PS=()=>{xp()==="on-scroll"&&(ne.setAttribute("data-persona-scrollbar-visible",""),Qo!==null&&clearTimeout(Qo),Qo=setTimeout(()=>{Qo=null,Bs(ne,Yo)&&ne.removeAttribute("data-persona-scrollbar-visible")},kS))};ch(),ye.push(()=>{Qo!==null&&clearTimeout(Qo)});let jp=new Map,ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Hf=()=>ze.active,ao();let dh=o.voiceRecognition?.autoResume??!1,Xo=i=>{A.emit("voice:state",{active:ze.active,source:i,timestamp:Date.now()})},po=()=>{le(i=>({...i,voiceState:{active:ze.active,timestamp:Date.now(),manuallyDeactivated:ze.manuallyDeactivated}}))},LS=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Jm(Y.voiceState),c=!!i.active,g=Number(i.timestamp??0);ze.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-g<LI&&setTimeout(()=>{ze.active||(ze.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?k.toggleVoice().then(()=>{ze.active=k.isVoiceActive(),Xo("restore"),k.isVoiceActive()&&bi()}):Rc("restore"))},1e3)},IS=()=>k?gx(k.getMessages()).filter(i=>!i.__skipPersist):[],Vl=null,ph=(i,c)=>{typeof console<"u"&&console.error(i,c)},Kl=(i,c)=>{let g=()=>{try{let W=i();return!W||typeof W.then!="function"?null:Promise.resolve(W).catch(z=>{ph(c,z)})}catch(W){return ph(c,W),null}},f=Vl,b=f?f.then(()=>g()??void 0):g();if(!b)return;let w=b.finally(()=>{Vl===w&&(Vl=null)});Vl=w};function ti(i){if(!G?.save)return;let c=i?gx(i):k?IS():[],g=ae&&k?.getResumableHandle();g&&(Y={...Y,durableResume:{executionId:g.executionId,after:g.lastEventId}});let f={messages:c,metadata:Y,artifacts:Gn.artifacts,selectedArtifactId:Gn.selectedId,...us?{draft:us}:{}};Kl(()=>G.save(f),"[AgentWidget] Failed to persist state:")}let us,Gl=()=>!G?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,da=dC({write:()=>{if(!Gl())return;let i=we.getState(),c=lC({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Du(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(us)&&(us=c,ti())}});function uh(){Gl()&&da.schedule()}function qp(){da.flush()}function gh(i){if(!Gl())return;let c=cC(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(g=>g.id),modelIds:(o.composer?.models??[]).map(g=>g.id),modes:o.composer?.modes??[]});c&&(us=i,de&&!de.value&&(de.value=c.text,de.dispatchEvent(new Event("input",{bubbles:!0})),So()),c.selectedModelId&&(we.setSelectedModelId(c.selectedModelId),Cr?.repaint()),Rl(c.activeModeIds??[]),c.quote&&Ao(c.quote),da.cancel())}function Yl(){da.cancel(),us&&(us=void 0,Gl()&&ti())}let ni=null,mh=()=>Ke.querySelector("#persona-scroll-container")||ne,oi=()=>{ni!==null&&(cancelAnimationFrame(ni),ni=null),An=!1},fh=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),jl=!1,oi()},RS=()=>Wn&&Vp()&&(Hn()!=="anchor-top"||hf()),zp=()=>{let i=Zi()||"Jump to latest",c=RS();_t.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Er>0?(Qr.textContent=String(Er),Qr.style.display="",_t.setAttribute("aria-label",`${i} (${Er} new)`)):(Qr.textContent="",Qr.style.display="none",_t.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},hh=()=>{Er!==0&&(Er=0,zp())},HS=()=>{let i=zt?.spacerHeight??0;return i<=0?Bs(ne,Yo):Zl(i)-ne.scrollTop-ne.clientHeight<=Yo},Vp=()=>vr()?!On.isFollowing():!HS(),Kp=()=>!!k&&k.getMessages().length>0,Vt=()=>{if(!aS()||hr()){_t.parentNode&&_t.remove(),_t.style.display="none";return}_t.parentNode!==ge&&ge.appendChild(_t),Xr();let c=Do(ne)>0&&Vp()&&Kp();c?zp():hh(),_t.style.display=c?"":"none"},pa=()=>{On.pause()&&(fh(),Vt())},Mn=()=>{On.resume(),hh(),Vt()},Tr=(i=!1)=>{vr()&&Kp()&&On.isFollowing()&&(!i&&!Wn||(Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),jl=!0,Mr=requestAnimationFrame(()=>{Mr=null,jl=!1,On.isFollowing()&&WS(mh(),i?220:140)})))},yh=(i,c,g,f=()=>!0)=>{let b=i.scrollTop,w=c(),W=w-b;if(oi(),Math.abs(W)<1){An=!0,i.scrollTop=w,Bn=i.scrollTop,An=!1;return}let z=performance.now();An=!0;let q=J=>1-Math.pow(1-J,3),V=J=>{if(!f()){oi();return}let se=c();se!==w&&(w=se,W=w-b);let fe=J-z,Xe=Math.min(fe/g,1),dt=q(Xe),gt=b+W*dt;i.scrollTop=gt,Bn=i.scrollTop,Xe<1?ni=requestAnimationFrame(V):(i.scrollTop=w,Bn=i.scrollTop,ni=null,An=!1)};ni=requestAnimationFrame(V)},WS=(i,c=500)=>{let g=Do(i)-i.scrollTop;if(Math.abs(g)<1){Bn=i.scrollTop;return}if(Math.abs(g)>=TS){oi(),An=!0,i.scrollTop=Do(i),Bn=i.scrollTop,An=!1;return}yh(i,()=>Do(i),c,()=>On.isFollowing())},Ql=()=>{if(!Kp()){Vt();return}let i=mh();An=!0,i.scrollTop=Do(i),Bn=i.scrollTop,An=!1,Vt()},gs=i=>{let c=0,g=i;for(;g&&g!==ne;)c+=g.offsetTop,g=g.offsetParent;return c},OS=()=>{let i=ne.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ne.ownerDocument.getSelection()},Xl=()=>KC(OS(),ne),Gp=()=>{if(lS()!=="last-user-turn")return!1;let i=k?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(w=>w.role==="user");if(!c)return!1;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=ne.querySelector(`[data-message-id="${g}"]`);if(!f)return!1;let b=Math.min(Math.max(0,gs(f)-ea()),Do(ne));return An=!0,ne.scrollTop=b,Bn=ne.scrollTop,An=!1,Hn()==="follow"&&!Bs(ne,Yo)&&On.pause(),Vt(),!0},Jl=i=>{let c=Math.max(0,Math.round(i));Kn.style.height=`${c}px`,Kn.style.display=c>0?"":"none",zt&&(zt.spacerHeight=Math.max(0,i))},Zl=i=>{let c=parseFloat(getComputedStyle(ne).paddingBottom)||0,g=0;for(let b of Array.from(ne.children)){if(b===Kn||b.offsetHeight===0)continue;let w=gs(b)+b.offsetHeight;w>g&&(g=w)}let f=ne.scrollHeight-i;return g>0?Math.min(g+c,f):f},BS=()=>{if(!zt||zt.spacerHeight<=0)return;let i=Zl(zt.spacerHeight),c=Math.max(0,Math.round(ne.scrollTop)+ne.clientHeight-i+Yo);c<zt.spacerHeight&&(Jl(c),Vt())},uo=()=>{cs!==null&&(cancelAnimationFrame(cs),cs=null),oi(),zt=null,Kn.style.height="0px",Kn.style.display="none"},bh=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Yp=i=>ne.querySelector(`[data-message-id="${bh(i)}"]`),vh=i=>{cs!==null&&cancelAnimationFrame(cs),cs=requestAnimationFrame(()=>{cs=null;let c=bh(i),g=ne.querySelector(`[data-message-id="${c}"]`);if(!g)return;let f=gs(g),b=zt?.spacerHeight??0,w=Zl(b),{targetScrollTop:W,spacerHeight:z}=sm({anchorOffsetTop:f,topOffset:ea(),viewportHeight:ne.clientHeight,contentHeight:w,slack:Yo});zt={initialSpacerHeight:z,contentHeightAtAnchor:w,spacerHeight:z},Jl(z),yh(ne,()=>g.isConnected?Math.max(0,gs(g)-ea()):W,220)})},En=()=>{if(Hn()!=="anchor-top"||!zt||!ei)return;let i=Yp(ei);if(!i)return;oi();let c=zt.spacerHeight,g=Zl(c),{targetScrollTop:f,spacerHeight:b}=sm({anchorOffsetTop:gs(i),topOffset:ea(),viewportHeight:ne.clientHeight,contentHeight:g,slack:Yo});zt={initialSpacerHeight:b,contentHeightAtAnchor:g,spacerHeight:b},Jl(b),An=!0,ne.scrollTop=f,Bn=ne.scrollTop,An=!1,Vt()},_S=()=>{if(vr()){if(!On.isFollowing()||Bs(ne,1))return;Tr(!Wn);return}if(zt&&zt.initialSpacerHeight>0){let i=ne.scrollHeight-zt.spacerHeight,c=GC({initialSpacerHeight:zt.initialSpacerHeight,contentHeightAtAnchor:zt.contentHeightAtAnchor,currentContentHeight:i});c!==zt.spacerHeight&&Jl(c)}Vt()},DS=i=>{let c=Hn();c==="follow"?(Mn(),Tr(!0)):c==="anchor-top"&&(ca=!1,ql=!0,zl=!1,ei=i,vh(i))},NS=()=>{if(Hn()==="anchor-top"){if(ql){ca=!1;return}ca=!0,uo(),Mn(),Tr(!0)}},FS=96,$S=i=>{if(ds===null)return!0;let c=Yp(ds),g=Yp(i);if(!c||!g)return!0;let f=gs(g)-gs(c);return ea()+f>ne.clientHeight-FS},US=i=>{if(Hn()!=="anchor-top"||!ql||zl||Xl())return;let c=ds===null;for(let g of i){if(!c){g.id===ds&&(c=!0);continue}if(jC(g)){if(g.id===ei||!$S(g.id))return;ei=g.id,vh(g.id);return}}},jS=i=>{let c=new Map;i.forEach(g=>{let f=jp.get(g.id);c.set(g.id,{streaming:g.streaming,role:g.role}),!f&&g.role==="assistant"&&(A.emit("assistant:message",g),!Zs&&(Hn()!=="anchor-top"||hf())&&Vp()&&(Er+=1,zp(),Vt(),kl(Er===1?"1 new message below.":`${Er} new messages below.`))),g.role==="assistant"&&f?.streaming&&g.streaming===!1&&A.emit("assistant:complete",g),g.variant==="approval"&&g.approval&&(f?g.approval.status!=="pending"&&A.emit("approval:resolved",{approval:g.approval,decision:g.approval.status}):A.emit("approval:requested",{approval:g.approval,message:g}))}),jp.clear(),c.forEach((g,f)=>{jp.set(f,g)})},ua=(i,c)=>{let g=c==="user"?"user":"assistant",f=o.layout?.messages?.[g],b=f?.width??"content",w=f?.maxWidth??(b==="full"?"100%":void 0);i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${c}`,`persona-message-width-${b}`),i.classList.toggle("persona-justify-end",c==="user"),i.setAttribute("data-message-role",c),i.setAttribute("data-message-width",b),w?i.style.setProperty("--persona-message-row-max-width",w):i.style.removeProperty("--persona-message-row-max-width")},Jo=(i,c)=>{let g=document.createElement("div");return g.className="persona-flex",g.id=`wrapper-${i}`,g.setAttribute("data-wrapper-id",i),ua(g,c),g},qS=(i,c,g)=>{let f=document.createElement("div"),w=(()=>{let I=a.find(ke=>ke.renderLoadingIndicator);if(I?.renderLoadingIndicator)return I.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),W=(I,ke)=>ke==null?!1:typeof ke=="string"?(I.textContent=ke,!0):(I.appendChild(ke),!0),z=new Set,q=new Map,V=new Set,J=a.some(I=>I.renderAskUserQuestion),se=[],fe=[],Xe=o.enableComponentStreaming!==!1,dt=o.approval!==!1,gt=[],Xt=o.messageActions,Ft=Xt?.showRegenerate===!0&&Xt.enabled!==!1&&ct.current?.isStreaming()!==!0?hv(c):null,Rt=Xt?.showEdit===!0&&Xt.enabled!==!1,ln=Xt?.showQuote===!0&&Xt.enabled!==!1,Ze=null,cn=o.features?.reasoningDisplay?.completedVisibility,Ro=I=>cn==="removed"?!0:cn==="removed-when-short"?Gb(I,o.features?.reasoningDisplay?.shortThinkThreshold):!1,ar=o.features?.toolCallDisplay?.completedVisibility==="removed";if(c.forEach(I=>{if(I.variant==="reasoning"&&I.reasoning?.status==="complete"&&Ro(I.reasoning)||ar&&I.variant==="tool"&&I.toolCall?.status==="complete")return;if(z.add(I.id),q.set(I.id,I.role),is===I.id&&Ar){let Be=Jo(I.id,I.role);Be.setAttribute("data-persona-message-edit-stub","true"),Be.setAttribute("data-preserve-runtime","true"),f.appendChild(Be),Ze={messageId:I.id,element:Ar.element};return}let ke=J&&_r(I),We=dt&&I.variant==="approval"&&!!I.approval,xe=!ke&&I.role==="assistant"&&!I.variant&&Xe&&sp(I);!We&&Sr.has(I.id)&&(i.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime"),Sr.delete(I.id)),!xe&&ss.has(I.id)&&(i.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime"),ss.delete(I.id));let Kt=_r(I)?`:${I.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${I.agentMetadata?.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",dn={canRegenerate:Ft===I.id,canEdit:Rt&&Mg(I),canQuote:ln&&!I.variant&&(I.content?.trim().length??0)>0},lt=`${dn.canRegenerate?"r":""}${dn.canEdit?"e":""}${dn.canQuote?"q":""}`,Le=DC(I,ls)+Kt+`:${lt}`,go=ke||We||xe?null:FC(Dt,I.id,Le);if(go){f.appendChild(go.cloneNode(!0)),_r(I)&&I.toolCall?.id&&I.agentMetadata?.awaitingLocalTool===!0&&!I.agentMetadata?.askUserQuestionAnswered&&(V.add(I.toolCall.id),qa(I,o,De.composerOverlay));return}let Et=null,on=a.find(Be=>!!(I.variant==="reasoning"&&Be.renderReasoning||I.variant==="tool"&&Be.renderToolCall||!I.variant&&Be.renderMessage)),Gt=o.layout?.messages;if(_r(I)&&I.agentMetadata?.askUserQuestionAnswered===!0){Js.delete(I.id),i.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ei(I)&&$r(o).enabled)return;if(_r(I)&&o.features?.askUserQuestion?.enabled!==!1){let Be=a.find(Nn=>typeof Nn.renderAskUserQuestion=="function");if(Be&&ct.current){let Nn=Js.get(I.id),je=Nn!==Le,Ne=null;if(je){let{payload:pt,complete:yt}=Dr(I),lr=I.id,Jt=()=>ct.current?.getMessages().find(to=>to.id===lr);Ne=Be.renderAskUserQuestion({message:I,payload:pt,complete:yt,resolve:to=>{let bt=Jt();bt&&ct.current?.resolveAskUserQuestion(bt,to)},dismiss:()=>{let to=Jt();to?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(to),ct.current?.resolveAskUserQuestion(to,"(dismissed)"))},config:o})}let ht=Nn!=null;if(je&&Ne===null&&!ht){I.agentMetadata?.awaitingLocalTool===!0&&!I.agentMetadata?.askUserQuestionAnswered&&(V.add(I.toolCall.id),qa(I,o,De.composerOverlay));return}let ot=Jo(I.id,I.role);ot.setAttribute("data-ask-plugin-stub","true"),ot.setAttribute("data-preserve-runtime","true"),f.appendChild(ot),se.push({messageId:I.id,fingerprint:Le,bubble:Ne});return}else{I.agentMetadata?.awaitingLocalTool===!0&&!I.agentMetadata?.askUserQuestionAnswered&&(V.add(I.toolCall.id),qa(I,o,De.composerOverlay));return}}else if(We){let Be=P();if(!Be){f.appendChild(Jo(I.id,I.role));return}let Nn=a.find(ot=>typeof ot.renderApproval=="function")??y,Ne=Sr.get(I.id)!==Le,ht=null;if(Ne&&Nn?.renderApproval){let ot=I.id,pt=(yt,lr)=>{let Jt=ct.current?.getMessages().find(to=>to.id===ot);Jt?.approval&&(Jt.approval.toolType==="webmcp"?ct.current?.resolveWebMcpApproval(Jt.id,yt):ct.current?.resolveApproval(Jt.approval,yt,lr))};ht=Nn.renderApproval({message:I,defaultRenderer:()=>Be.createApprovalBubble(I,o),config:o,approve:yt=>pt("approved",yt),deny:yt=>pt("denied",yt)})}if(Ne&&ht===null)i.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime"),Sr.delete(I.id),Et=Be.createApprovalBubble(I,o);else{let ot=Jo(I.id,I.role);ot.setAttribute("data-approval-plugin-stub","true"),ot.setAttribute("data-preserve-runtime","true"),f.appendChild(ot),gt.push({messageId:I.id,fingerprint:Le,bubble:ht});return}}else if(on)if(I.variant==="reasoning"&&I.reasoning&&on.renderReasoning){if(!pn)return;Et=on.renderReasoning({message:I,defaultRenderer:()=>Pm(I,o),config:o})}else if(I.variant==="tool"&&I.toolCall&&on.renderToolCall){if(!zn)return;Et=on.renderToolCall({message:I,defaultRenderer:()=>Im(I,o),config:o})}else on.renderMessage&&(Et=on.renderMessage({message:I,defaultRenderer:()=>{let Be=vl(I,g,Gt,o.messageActions,jt,{loadingIndicatorRenderer:w,widgetConfig:o,actionEligibility:dn});return I.role!=="user"&&R(Be,I,o,k),Be},config:o}));if(!Et&&xe){let Be=Ym(I);if(Be){let Nn=ss.get(I.id),je=Nn!==Le,Ne=o.wrapComponentDirectiveInBubble!==!1&&Fo.getOptions(Be.component)?.bubbleChrome!==!1,ht=null;if(je){let ot=Gm(Be,{config:o,message:I,transform:g});if(ot&&Be.component==="PersonaArtifactInline"){let pt=ot.hasAttribute("data-artifact-inline")?ot:ot.querySelector("[data-artifact-inline]"),yt=pt?.getAttribute("data-artifact-inline")??"",lr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(yt):yt,Jt=yt?i.querySelector(`#wrapper-${I.id}`)?.querySelector(`[data-artifact-inline="${lr}"]`)??null:null;pt&&Jt&&Jt!==pt&&ur()?.hasLiveInlineArtifactBlock(Jt)&&(pt===ot?ot=Jt:pt.replaceWith(Jt))}if(ot)if(Ne){let pt=document.createElement("div");if(pt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),pt.id=`bubble-${I.id}`,pt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let yt=document.createElement("div");yt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",yt.innerHTML=g({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),pt.appendChild(yt)}pt.appendChild(ot),ht=pt}else{let pt=document.createElement("div");if(pt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",pt.id=`bubble-${I.id}`,pt.setAttribute("data-message-id",I.id),pt.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let yt=document.createElement("div");yt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",yt.innerHTML=g({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),pt.appendChild(yt)}pt.appendChild(ot),ht=pt}}if(ht||Nn!=null){let ot=Jo(I.id,I.role);ot.setAttribute("data-component-directive-stub","true"),ot.setAttribute("data-preserve-runtime","true"),f.appendChild(ot),fe.push({messageId:I.id,fingerprint:Le,bubble:ht});return}}}if(!Et)if(I.variant==="reasoning"&&I.reasoning){if(!pn)return;Et=Pm(I,o)}else if(I.variant==="tool"&&I.toolCall){if(!zn)return;Et=Im(I,o)}else if(I.variant==="approval"&&I.approval){if(o.approval===!1)return;let Be=P();if(!Be)return;Et=Be.createApprovalBubble(I,o)}else{let Be=o.layout?.messages;Be?.renderUserMessage&&I.role==="user"?Et=Be.renderUserMessage({message:I,config:o,streaming:!!I.streaming}):Be?.renderAssistantMessage&&I.role==="assistant"?Et=Be.renderAssistantMessage({message:I,config:o,streaming:!!I.streaming}):Et=vl(I,g,Be,o.messageActions,jt,{loadingIndicatorRenderer:w,widgetConfig:o,actionEligibility:dn}),I.role!=="user"&&Et&&R(Et,I,o,k)}let Ht=Jo(I.id,I.role);Ht.appendChild(Et),$C(Dt,I.id,Le,Ht),f.appendChild(Ht)}),De.composerOverlay&&De.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ke=>{let We=ke.getAttribute("data-persona-ask-sheet-for");We&&!V.has(We)&&Hs(De.composerOverlay,We)}),o.features?.toolCallDisplay?.grouped){let I=[],ke=[],We=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(xe=>{if(xe.variant==="tool"&&xe.toolCall&&zn){if(ar&&xe.toolCall.status==="complete")return;ke.push(xe);return}xe.variant==="reasoning"&&(!pn||xe.reasoning?.status==="complete"&&Ro(xe.reasoning))||((ke.length>1||We&&ke.length>0)&&I.push(ke),ke=[])}),(ke.length>1||We&&ke.length>0)&&I.push(ke),I.forEach(xe=>{let Kt=xe.map(Gt=>Array.from(f.children).find(Ht=>Ht instanceof HTMLElement&&Ht.getAttribute("data-wrapper-id")===Gt.id)).filter(Gt=>!!Gt);if(Kt.length<(We?1:2))return;let dn=Jo(`tool-group-${xe[0].id}`,"assistant");dn.setAttribute("data-persona-tool-group-row","true");let lt=document.createElement("div");lt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",lt.setAttribute("data-persona-tool-group","true");let Le=document.createElement("div");Le.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",Le.id=`tool-group-summary-${xe[0].id}`;let go=`Called ${xe.length} ${xe.length===1?"tool":"tools"}`,Et=o.toolCall?.renderGroupedSummary?.({messages:xe,toolCalls:xe.map(Gt=>Gt.toolCall).filter(Gt=>!!Gt),defaultSummary:go,config:o});W(Le,Et)||(Le.textContent=go);let on=document.createElement("div");on.className="persona-tool-group-stack persona-flex persona-flex-col",on.id=`tool-group-stack-${xe[0].id}`,on.setAttribute("data-persona-tool-group-stack","true"),lt.appendChild(Le),We||lt.appendChild(on),dn.appendChild(lt),Kt[0].before(dn),Kt.forEach((Gt,Ht)=>{if(We){Gt.remove();return}Gt.style.setProperty("--persona-message-row-max-width","100%");let Be=document.createElement("div");Be.className="persona-tool-group-item persona-relative",Be.setAttribute("data-persona-tool-group-item","true"),Ht<Kt.length-1&&Be.setAttribute("data-persona-tool-group-connector","true"),Be.appendChild(Gt),on.appendChild(Be)})})}UC(Dt,z);let Ho=c.some(I=>I.role==="assistant"&&I.streaming),Ci=c[c.length-1],Es=Ci?.role==="assistant"&&!Ci.streaming&&Ci.variant!=="approval";if(Wn&&c.some(I=>I.role==="user")&&!Ho&&!Es){let I={config:o,streaming:!0,location:"standalone",defaultRenderer:$i},ke=a.find(xe=>xe.renderLoadingIndicator),We=null;if(ke?.renderLoadingIndicator&&(We=ke.renderLoadingIndicator(I)),We===null&&o.loadingIndicator?.render&&(We=o.loadingIndicator.render(I)),We===null&&(We=$i()),We){let xe=document.createElement("div"),Kt=o.loadingIndicator?.showBubble!==!1,dn=o.layout?.messages?.layout??"bubble";xe.className=Kt?bl("assistant",dn).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),xe.setAttribute("data-typing-indicator","true"),Kt&&(xe.style.color="var(--persona-message-assistant-text, var(--persona-text))",dn!=="flat"&&(xe.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",xe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),xe.appendChild(We);let lt=Jo("typing-indicator","assistant");lt.appendChild(xe),f.appendChild(lt)}}if(!Wn&&c.length>0){let I=c[c.length-1],ke={config:o,lastMessage:I,messageCount:c.length},We=a.find(Kt=>Kt.renderIdleIndicator),xe=null;if(We?.renderIdleIndicator&&(xe=We.renderIdleIndicator(ke)),xe===null&&o.loadingIndicator?.renderIdle&&(xe=o.loadingIndicator.renderIdle(ke)),xe){let Kt=document.createElement("div"),dn=o.loadingIndicator?.showBubble!==!1;Kt.className=dn?["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(" "),Kt.setAttribute("data-idle-indicator","true"),Kt.appendChild(xe);let lt=Jo("idle-indicator","assistant");lt.appendChild(Kt),f.appendChild(lt)}}if(hb(f),Id(i,f),sg(i),Ze){let{messageId:I,element:ke}=Ze,We=i.querySelector(`#wrapper-${I}`);We&&ke.parentElement!==We&&(ua(We,q.get(I)??"user"),We.replaceChildren(ke))}if(se.length>0)for(let{messageId:I,fingerprint:ke,bubble:We}of se){let xe=i.querySelector(`#wrapper-${I}`);xe&&(ua(xe,q.get(I)??"assistant"),We!==null&&(xe.replaceChildren(We),xe.setAttribute("data-bubble-fp",ke),Js.set(I,ke)))}if(Js.size>0)for(let I of Js.keys())z.has(I)||Js.delete(I);if(fe.length>0)for(let{messageId:I,fingerprint:ke,bubble:We}of fe){let xe=i.querySelector(`#wrapper-${I}`);xe&&(ua(xe,q.get(I)??"assistant"),We!==null&&(xe.replaceChildren(We),xe.setAttribute("data-bubble-fp",ke),ss.set(I,ke)))}if(ss.size>0)for(let I of ss.keys())z.has(I)||ss.delete(I);if(gt.length>0)for(let{messageId:I,fingerprint:ke,bubble:We}of gt){let xe=i.querySelector(`#wrapper-${I}`);xe&&(ua(xe,q.get(I)??"assistant"),We!==null&&(xe.replaceChildren(We),xe.setAttribute("data-bubble-fp",ke),Sr.set(I,ke)))}if(Sr.size>0)for(let I of Sr.keys())z.has(I)||Sr.delete(I)},Qp=!1,ec=()=>{Qp||(Qp=!0,eg().catch(()=>{Qp=!1}))},Yn=(i,c,g)=>{c.length>0&&ec(),qS(i,c,g),Nf()},ga=null,zS=()=>{if(ga)return;let i=g=>{let f=g.composedPath();f.includes(Ke)||Qt&&f.includes(Qt)||ut(!1,"user")};ga=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},Ch=()=>{if(!ga)return;(e.ownerDocument??document).removeEventListener("pointerdown",ga,!0),ga=null};ye.push(()=>Ch());let ma=null,VS=()=>{if(ma)return;let i=g=>{g.key==="Escape"&&(g.isComposing||ut(!1,"user"))};ma=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},wh=()=>{if(!ma)return;(e.ownerDocument??document).removeEventListener("keydown",ma,!0),ma=null};ye.push(()=>wh());let fa=!1,xh=new Set,KS=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},ri=()=>{if(!Ce())return;let i=De.peekBanner,c=De.peekTextNode;if(!i||!c)return;if(he){i.classList.remove("persona-pill-peek--visible");return}let g=k?.getMessages()??[],f;for(let Ft=g.length-1;Ft>=0;Ft--){let Rt=g[Ft];if(Rt.role==="assistant"&&Rt.content){f=Rt;break}}if(!f){i.classList.remove("persona-pill-peek--visible");return}let b=f.content,w=!!f.streaming,W=KS(),z=Rd(W),q=z.type!=="none"?Fp(z.type,W?.plugins):null,V=q?.isAnimating?.(f)===!0,J=q!==null&&(w||V);J&&q&&!xh.has(q.name)&&(gl(q,e),xh.add(q.name));let se=J&&q?.containerClass?q.containerClass:null,fe=c.dataset.personaPeekStreamClass??null;fe&&fe!==se&&(c.classList.remove(fe),delete c.dataset.personaPeekStreamClass),se&&fe!==se&&(c.classList.add(se),c.dataset.personaPeekStreamClass=se),J?(c.style.setProperty("--persona-stream-step",`${z.speed}ms`),c.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let Xe=J?Wd(b,z.buffer,q,f,w):b;if(J&&z.placeholder==="skeleton"&&w&&(!Xe||!Xe.trim())){let Ft=document.createElement("div"),Rt=ul();Rt.classList.add("persona-pill-peek__skeleton"),Ft.appendChild(Rt),Id(c,Ft)}else{let Ft=Math.max(0,Xe.length-100),Rt=Xe.length>100?Xe.slice(-100):Xe,ln=Br(Rt);if(!J||!q){let Ze=Xe.length>100?`\u2026${Rt}`:Rt;c.textContent!==Ze&&(c.textContent=Ze)}else{let Ze=ln;(q.wrap==="char"||q.wrap==="word")&&(Ze=pl(ln,q.wrap,`peek-${f.id}`,{skipTags:q.skipTags,startIndex:Ft}));let cn=document.createElement("div");if(cn.innerHTML=Ze,q.useCaret&&Rt.length>0){let Ro=Od(),ar=cn.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ho=ar[ar.length-1];Ho?.parentNode?Ho.parentNode.insertBefore(Ro,Ho.nextSibling):cn.appendChild(Ro)}Id(c,cn),q.onAfterRender?.({container:c,bubble:i,messageId:f.id,message:f,speed:z.speed,duration:z.duration})}}let Xt=Wn||fa;i.classList.toggle("persona-pill-peek--visible",Xt)};if(Ce()){let i=De.peekBanner;if(i){let f=b=>{b.preventDefault(),b.stopPropagation(),ut(!0,"user")};i.addEventListener("pointerdown",f),ye.push(()=>{i.removeEventListener("pointerdown",f)})}let c=()=>{fa||(fa=!0,ri())},g=()=>{fa&&(fa=!1,ri())};Se.addEventListener("pointerenter",c),Se.addEventListener("pointerleave",g),ye.push(()=>{Se.removeEventListener("pointerenter",c),Se.removeEventListener("pointerleave",g)}),Qt&&(Qt.addEventListener("pointerenter",c),Qt.addEventListener("pointerleave",g),ye.push(()=>{Qt.removeEventListener("pointerenter",c),Qt.removeEventListener("pointerleave",g)}))}let GS=i=>{let c=o.launcher?.composerBar??{},g=c.expandedSize??"anchored",f=c.bottomOffset??"16px",b=c.collapsedMaxWidth,w=c.expandedMaxWidth??"880px",W=c.expandedTopOffset??"5vh",z=c.modalMaxWidth??"880px",q=c.modalMaxHeight??"min(90vh, 800px)",V="calc(100vw - 32px)",J="var(--persona-pill-area-height, 80px)",se=Ke.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",Qt){let fe=Qt.style;fe.bottom=f,fe.width=b??""}if(i&&g!=="fullscreen"){if(g==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=z,se.maxWidth=V,se.maxHeight=q,se.height=q;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${f} + ${J})`,se.top=W,se.width=w,se.maxWidth=V}},ha=()=>{if(he&&ec(),!Ee())return;if(Ce()){let V=(o.launcher?.composerBar??{}).expandedSize??"anchored",J=he?"expanded":"collapsed";Ke.dataset.state=J,Ke.dataset.expandedSize=V,Qt&&(Qt.dataset.state=J,Qt.dataset.expandedSize=V),Ke.style.removeProperty("display"),Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),GS(he),ge.style.display=he?"flex":"none",Zr(),he?(zS(),VS()):(Ch(),wh()),ri();return}let i=Tt(o),c=e.ownerDocument.defaultView??window,g=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,b=c.innerWidth<=g,w=f&&b&&ve,W=Un(o).reveal;he?(Ke.style.removeProperty("display"),Ke.style.display=i?"flex":"",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0"),Se.classList.add("persona-scale-100","persona-opacity-100"),Lt?(Lt.setPanelOpen(!0),Lt.element.style.display="none"):gn&&(gn.style.display="none")):(i?i&&(W==="overlay"||W==="push")&&!w?(Ke.style.removeProperty("display"),Ke.style.display="flex",Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ke.style.setProperty("display","none","important"),Ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ke.style.display="",Ke.classList.add("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100"),Se.classList.add("persona-scale-95","persona-opacity-0")),Lt?(Lt.setPanelOpen(!1),Lt.element.style.display=i?"none":""):gn&&(gn.style.display=i?"none":""))},ut=(i,c="user")=>{if(!Ee()||he===i)return;let g=he;he=i,ha();let f=(()=>{let w=o.launcher?.sidebarMode??!1,W=e.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,q=o.launcher?.mobileBreakpoint??640,V=W.innerWidth<=q,J=Tt(o)&&z&&V,se=Ce()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return w||z&&V&&ve||J||se})();if(he&&f){if(!To){let w=e.getRootNode(),W=w instanceof ShadowRoot?w.host:e.closest(".persona-host");W&&(To=lm(W,o.launcher?.zIndex??sn))}ko||(ko=cm(e.ownerDocument))}else he||(To?.(),To=null,ko?.(),ko=null);he&&(Ha(),Gp()||(Hn()==="follow"?Tr(!0):Ql()));let b={open:he,source:c,timestamp:Date.now()};he&&!g?A.emit("widget:opened",b):!he&&g&&A.emit("widget:closed",b),A.emit("widget:state",{open:he,launcherEnabled:ve,voiceActive:ze.active,streaming:k.isStreaming()})},kr={inputDisabled:!1,sendDisabled:!1},Pr=()=>kr.inputDisabled,ms=()=>kr.inputDisabled||kr.sendDisabled,YS=()=>(kr.inputDisabled?kr.inputReason:void 0)??(kr.sendDisabled?kr.sendReason:void 0);function Xp(){if(!Ae)return;if(we.getState().phase==="streaming"){Ae.disabled=!1;return}let i=Je?!Je.isReady():!1;Ae.disabled=ms()||i}function tc(){if(!xo)return;let i=we.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;xo.toggleAttribute("data-persona-send-hidden",c)}function QS(){let i=YS();if(Ce()){let c=io??Ie;i?c.setAttribute("title",i):c.removeAttribute("title"),Ie.toggleAttribute(Xi,!!i);return}if(i){st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.setAttribute(Xi,""),st.textContent=i;return}if(st.hasAttribute(Xi)&&(st.removeAttribute("role"),st.removeAttribute("aria-live"),st.removeAttribute(Xi),p)){let c=k.getStatus();Ml(st,Cn(c),o.statusIndicator??{},c)}}function Jp(){let i=Ng(o.composer?.inputDisabled),c=Ng(o.composer?.sendDisabled);kr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},we.setInputDisabled(i.disabled),we.setSendDisabled(c.disabled);let g=we.getState().phase==="streaming",f=i.disabled,b=g||f;de&&(de instanceof HTMLTextAreaElement?de.disabled=f:de.setAttribute("contenteditable",f?"false":"true"),de.setAttribute("aria-disabled",f?"true":"false")),Mt&&(Mt.disabled=f),Ct&&(Ct.disabled=f);for(let w of Bt?.affordanceButtons??[])w.querySelectorAll("button").forEach(W=>{W.disabled=f});oe&&(oe.disabled=b),ns.forEach(w=>{w.elements.forEach(W=>{W.toggleAttribute("data-disabled",b),W instanceof HTMLButtonElement||W.setAttribute("aria-disabled",b?"true":"false")}),w.buttons.forEach(W=>{W.disabled=b})}),ou.forEach(w=>{w.toggleAttribute("data-disabled",b),w instanceof HTMLButtonElement?w.disabled=b:w.setAttribute("aria-disabled",b?"true":"false"),w.querySelectorAll("button").forEach(W=>{W.disabled=b})}),Ie.dataset.personaComposerStreaming=g?"true":"false",Ie.dataset.personaComposerInputDisabled=f?"true":"false",Ie.dataset.personaComposerSendDisabled=ms()?"true":"false",Ie.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(w=>{(w instanceof HTMLButtonElement||w instanceof HTMLInputElement||w instanceof HTMLTextAreaElement||w instanceof HTMLSelectElement)&&(w.disabled=g)}),Xp(),QS()}let ya=i=>{we.setStreaming(i),mf(i?"stop":"send"),Jp()},fs=()=>{ze.active||de&&de.focus()};A.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>fs(),200)});let hs=null,ba=!1,Zp=!wn.hidden,Lr=null,eu=!E,nc=null;ye.push(()=>{nc?.cancel(),nc=null});let XS=i=>{let c=xw(i);if(c===Pl)return;Pl=c,e.setAttribute("data-persona-conversation-state",c);let g=Ap();Il(),eu&&(nc?.cancel(),nc=Cw(Ie,c==="active"?g:Ap(),c==="active"?"drop":"rise")),En()},Sh=null,Ah,Mh=null,si=null,tu=!1,va=i=>{let c=No(o),g=`${c.variant}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(g!==Sh||c.icon!==Ah)&&(Sh=g,Ah=c.icon,$d({host:wn,iconHolder:eS,kicker:tS,title:nS,subtitle:oS,starterSuggestions:Cp},c));let f=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;f!==Mh&&(Mh=f,Ud(In,c.message,o));let b=i??(k?k.getMessages():o.initialMessages);XS(b);let w=ba,W=!w&&Ds(c,b),z=W!==Zp;if(Zp=W,si){Lr?.cancel(),Lr=null,w!==tu&&(tu=w,w?wm(ne,wn,null):Cm(ne,wn,si)),Ui(ne,wn,!w);return}if(z&&!W&&!w&&c.dismiss==="on-first-message"&&eu){Lr=vw(wn,V=>{Lr===V&&(Lr=null),!Zp&&!si&&(Ui(ne,wn,!1),En()),V?.cancel()});return}if(Lr){if(!W&&!w)return;Lr.cancel(),Lr=null}let q=!wn.hidden;Ui(ne,wn,W),!W&&q&&En()},nu=[],ou=[],ru=!1,Eh=null,Th,kh=()=>{ou.length=0;let i=nu.splice(0,nu.length);for(let c of i)try{c()}catch(g){console.warn("[persona] renderWelcome cleanup threw",g)}};ye.push(kh);let JS=(i,c)=>{let g=pm(i,c);if(!g)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),M("span");let f=o.suggestions?.starters,b=um({item:{...g,behavior:g.behavior??f?.behavior??"send"},index:c,surface:"starter",source:"config",variant:f?.variant??"card",streaming:p?k.isStreaming():!1,config:o,plugins:a,chipsConfig:o.suggestionChipsConfig,session:k,getTextarea:()=>de,eventTarget:wn,submitPrompt:Pc});return ou.push(b),b},su=()=>{if(ru)return;ru=!0;let i=No(o);Eh=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,Th=i.icon;try{kh(),wm(ne,wn,si),si=null,tu=!1;let c=k?k.getMessages():o.initialMessages,g=Ds(i,c),f=0,b=null;for(let w of a)if(w.renderWelcome&&(b=w.renderWelcome({config:i,variant:i.variant,visible:g,defaultRenderer:()=>wn,sendMessage:W=>{if(!k||k.isStreaming())return;let z=W.trim();z&&k.sendMessage(z)},requestRender:()=>su(),renderStarter:W=>JS(W,f++),storage:u(w.id),onCleanup:W=>{nu.push(W)}}),b))break;b&&b!==wn&&(si=b,Cm(ne,wn,b))}finally{ru=!1}va()},ZS=()=>{let i=No(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Eh&&i.icon===Th||su()},oc=()=>{va(),Ks||(de.placeholder=oC(we.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!k?.isStreaming()&&(Ae.textContent=o.copy?.sendButtonLabel??"Send")),de.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',de.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},eA=!!o.setStoredConversationId,ii=i=>le(c=>{let g={...c};return delete g[i],g}),rc=i=>{let c=Y[i];return typeof c=="string"?c:null},Ph=()=>{let i=Y.durableResume;if(!i||typeof i!="object")return null;let c=i;return typeof c.executionId=="string"&&c.executionId.length>0&&typeof c.after=="string"&&c.after.length>0?{executionId:c.executionId,after:c.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>rc("sessionId"),setStoredSessionId:i=>{le(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ii("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>rc("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{le(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ii("conversationId"))});let Lh=()=>o.clientToken??null,Ih=i=>nx(i,ro(),o.persistState===!1),Rh=Lh(),Zo=Rh?Ih(Rh):null,er={...Zo?{visitorStore:Zo}:{},historyBootstrapReady:H,getStoredMessageCursor:()=>rc("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){ii("historyMessageCursor");return}le(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=Y.pendingDisplayProjections;if(!i||typeof i!="object")return null;let c=i;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(g=>typeof g=="string")}},setPendingDisplayProjections:i=>{if(!i){ii("pendingDisplayProjections");return}le(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:Ph,setStoredResumableHandle:i=>{if(!i){ii("durableResume");return}le(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>ae&&Ph()!==null,...eA?{}:{getStoredConversationRevision:()=>rc("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){ii("conversationRevision");return}le(c=>({...c,conversationRevision:i}))}}};if(ae){let i=o.onExecutionState,c=e.ownerDocument.defaultView,g=!1,f=()=>g=!0,b=()=>g=!1;c?.addEventListener("pagehide",f),c?.addEventListener("pageshow",b),ye.push(()=>{c?.removeEventListener("pagehide",f),c?.removeEventListener("pageshow",b)}),o={...o,reconnectStream:o.reconnectStream??(w=>k.getClient().reconnectClientTokenStream(w)),onExecutionState:w=>{(w||!g)&&er.setStoredResumableHandle?.(w?{executionId:w.executionId,after:w.lastEventId}:null),i?.(w)}}}let tA=()=>{let i=Lh();if(i&&Zo?.matches(i,ro(),o.persistState===!1)||!i&&!Zo)return;Zo?.destroy(),Zo=i?Ih(i):null;let c={...er};Zo?c.visitorStore=Zo:delete c.visitorStore,er=c,k.setHistoryInternals(er)},ys=null,nA=()=>{ys==null&&(ys=setInterval(()=>{let i=Te.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(ys),ys=null;return}let c=Date.now();i.forEach(g=>{let f=Number(g.getAttribute("data-tool-elapsed"));f&&(g.textContent=Zc(c-f))})},100))},iu=(i,c)=>{if(Object.is(i,c))return!0;if(i===null||c===null||typeof i!="object"||typeof c!="object")return!1;if(Array.isArray(i)||Array.isArray(c))return!Array.isArray(i)||!Array.isArray(c)||i.length!==c.length?!1:i.every((W,z)=>iu(W,c[z]));let g=i,f=c,b=Object.keys(g),w=Object.keys(f);return b.length===w.length&&b.every(W=>Object.prototype.hasOwnProperty.call(f,W)&&iu(g[W],f[W]))},Hh=i=>{let{content:c,rawContent:g,llmContent:f,...b}=i;return b},au=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!sp(i),oA=(i,c,g)=>{if(i.length!==c.length)return!1;let f=i[g.index],b=c[g.index];return!f||!b||f.id!==g.id||b.id!==g.id?!1:(!Object.is(f.content,b.content)||!Object.is(f.rawContent,b.rawContent)||!Object.is(f.llmContent,b.llmContent))&&au(f)&&au(b)&&iu(Hh(f),Hh(b))},lu=null,ai=null,bs=null,tr=null,cu=null,rA=i=>{if(!ae)return ti(i);cu=i,queueMicrotask(()=>{cu===i&&(cu=null,ti(i))})},sc=i=>{lu=i;let c,g;ai=null;for(let b=i.length-1;b>=0;b-=1){let w=i[b];if(!c&&w.role==="user"&&(c=w),!g&&w.role==="assistant"&&(g=w),!ai&&au(w)&&(ai={index:b,id:w.id}),c&&g&&ai)break}Yn(Te,i,ft),ur()?.updateInlineArtifactBlocks(Te,Gn.artifacts,{suppressTransition:Wn}),nA(),va(i),Xs(i),Tr(!Wn),jS(i),i.length===0&&(uo(),ca=!0,ql=!1,ei=null,zl=!1),!$p||Zs?($p=!0,ds=c?.id??null,Up=g?.id??null):c&&c.id!==ds?(ds=c.id,DS(c.id)):g&&g.id!==Up&&NS(),g&&(Up=g.id),US(i);let f=ze.lastUserMessageId;c&&c.id!==f&&(ze.lastUserMessageId=c.id,A.emit("user:message",c)),ze.lastUserMessageWasVoice=!!c?.viaVoice,rA(i),ri()},du=()=>{tr!==null&&(cancelAnimationFrame(tr),tr=null);let i=bs;bs=null,i&&sc(i)},Wh=()=>{tr!==null&&cancelAnimationFrame(tr),tr=null,bs=null},sA=i=>{let c=bs??lu;if(Wn&&c&&ai&&oA(c,i,ai)){bs=i,tr===null&&(tr=requestAnimationFrame(()=>{tr=null;let g=bs;bs=null,g&&sc(g)}));return}if(i.length===0){Wh(),sc(i);return}du(),sc(i)};k=new Za(o,{onMessagesChanged(i){sA(i)},onStatusChanged(i){let c=o.statusIndicator??{};Ml(st,(f=>f==="idle"?c.idleText??$t.idle:f==="connecting"?c.connectingText??$t.connecting:f==="connected"?c.connectedText??$t.connected:f==="error"?c.errorText??$t.error:f==="paused"?c.pausedText??$t.paused:f==="resuming"?c.resumingText??$t.resuming:$t[f])(i),c,i),qo()},onStreamingChanged(i){i||(k?.getMessages().length===0?Wh():du()),Wn=i,ya(i),qo(),k&&Yn(Te,k.getMessages(),ft),i||(Tr(!0),BS(),ih=!0,k&&ah(k.getMessages(),$r(o))),Vt(),kl(i?"Responding\u2026":"Response complete."),ri()},onVoiceStatusChanged(i){if(A.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":ir(),bi();break;case"processing":ir(),aM();break;case"speaking":ir(),lM();break;default:i==="idle"&&k.isBargeInActive()?(ir(),bi(),oe?.setAttribute("aria-label","End voice session")):(ze.active=!1,ir(),Xo("system"),po());break}},onArtifactsState(i){Gn=i,i.artifacts.length===0&&(Gs=!1),ur()?.updateInlineArtifactBlocks(Te,i.artifacts,{suppressTransition:Wn}),co(),ti()},onHistoryStateChanged(i){Ot(i)},onHistoryNotice(i){kt(i)},onReconnect(i){let{executionId:c,lastEventId:g}=i.handle;i.phase==="paused"?A.emit("stream:paused",{executionId:c,after:g}):i.phase==="resuming"?A.emit("stream:resuming",{executionId:c,after:g,attempt:i.attempt??1}):A.emit("stream:resumed",{executionId:c,after:g})}},er),ct.current=k,ye.push(()=>k.cancel()),ye.push(()=>{k.destroy(),Zo?.destroy()});let pu=null;if(k.onReadAloudChange((i,c)=>{_f=i,Df=c,Nf();let g=i??pu;i&&(pu=i);let f=g?k.getMessages().find(b=>b.id===g)??null:null;A.emit("message:read-aloud",{messageId:g,message:f,state:c,timestamp:Date.now()}),c==="idle"&&(pu=null)}),p=!0,$p=!0,o.voiceRecognition?.provider?.type==="runtype")try{k.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let iA=720,aA=250,Qe=Vm(o.features?.history?.copy),_n=null,uu=!1,it=null,ic=null,ac="conversation",gu=null,un=null,Po=null,lc=k.getHistoryState(),mu=null,Ca=0,fu=null,cc=null,dc=null,hu=`persona-history-${Math.random().toString(36).slice(2,8)}`,yu=()=>o.features?.history?.enabled===!0,Lo=()=>yu()&&!!_n&&!uu,Oh=()=>{let i=k.getStatus();return Wn||i==="paused"||i==="resuming"},bu=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",g=_n?.capabilities.scopes;return!g||g.includes(c)?c:g[0]??c},li=()=>ic?.scope??bu(),Bh=()=>k.getClientSession()?.targetId??null,_h=i=>`${i.state}:${"reason"in i?i.reason:""}`,lA=i=>{let c=_h(i);c!==mu&&(mu=c,A.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},pc=i=>{i&&(zo.textContent="",zo.textContent=i)},Dh=null,Nh=null,cA=()=>{if(!yu())return null;let i=ix();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(Dh!==c&&(Dh=c,Nh=c()),Nh):k.isClientTokenMode()?ax({client:k.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:g=>k.bindActivatedSession(g),getClient:()=>k.getClient()}):null},Fh=()=>{cc?.(),cc=null,dc?.(),dc=null,uu=!1,_n=cA();let i={...er};_n?i.historyProvider=_n:delete i.historyProvider,er=i,k.setHistoryInternals(er),_n&&(cc=_n.subscribeAvailability?.(c=>{uu=!c,c||Tn({restoreFocus:!1}),Rr()})??null,dc=_n.subscribeIdentityStatus(c=>lA(c)),mu=_h(_n.getIdentityStatus()))},vu=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!ve||Tt(o)))return"panel";let c=Eo??ge;return(c.getBoundingClientRect().width||c.clientWidth)>=iA?"rail":"panel"},Qn=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},uc="data-persona-history-suppressed",Dn=null,Ir=null,vs=null,wa=null,Cu=null,$h="",Uh=()=>Me===Cu?$h:o.layout?.showHeader===!1?"none":"",dA=()=>ce==="panel"&&!!vs&&wa===vs.element&&o.layout?.showHeader!==!1&&Uh()!=="none",pA=()=>{for(let i of Array.from(Me.children))i!==Dn&&i.setAttribute(uc,"")},uA=()=>{for(let i of Array.from(ge.querySelectorAll(`[${uc}]`)))i.removeAttribute(uc)},gA=()=>{let i=vs;if(!i)return;if(Array.from(Me.children).some(f=>f!==Dn&&!f.hasAttribute(uc))){Ir&&Ir!==Me&&(Ir.style.removeProperty("min-height"),Ir=null);let f=Me.offsetHeight;f>0&&(Me.style.minHeight=`${f}px`,Ir=Me)}Dn||(Dn=M("div","persona-history-header-host")),i.setHeaderPlacement("external");let g=i.getHeaderElement();g.parentNode!==Dn&&Dn.replaceChildren(g),Dn.parentNode!==Me&&Me.appendChild(Dn),pA()},jh=()=>{Ir&&(Ir.style.removeProperty("min-height"),Ir=null),Dn&&(vs?.setHeaderPlacement("inline"),Dn.remove(),Dn=null,uA())},gc=null,wu=()=>{if(gc){if(ne.style.display="none",Qn(ne,!0),Ie.hidden=!0,Qn(Ie,!0),dA()){gA(),Me.style.display=Uh(),Qn(Me,!1);return}jh(),Me.style.display="none",Qn(Me,!0)}};Ut=wu;let mA=i=>{let c=ne.style.display,g=Ie.hidden,f=Ie,b=Me,w=Me.style.display;Cu=b,$h=w,gc=()=>{gc=null,jh(),Cu=null,ne.style.display=c,Qn(ne,!1),f.hidden=g,Qn(f,!1),Ie!==f&&(Ie.hidden=!1,Qn(Ie,!1)),b.style.display=w,Qn(b,!1),Me!==b&&(Me.style.display=o.layout?.showHeader===!1?"none":"",Qn(Me,!1))},Ie.parentNode?.insertBefore(i,Ie),wu()},ci=null,Cs=null,xa=null,di=null,qh=()=>[Me,De.closeButtonWrapper,De.clearChatButtonWrapper,ne,Ie],fA=52,mc=()=>o.features?.history?.rail?.collapsible!==!1,pi=()=>o.features?.history?.rail?.side==="right"?"right":"left",xu=200,Su=400,Au=i=>Math.min(Su,Math.max(xu,Math.round(i))),hA=()=>o.features?.history?.rail?.resizable===!0,Sa,yA=()=>{if(Sa===void 0&&(Sa=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${ro()}rail-width`));i&&(Sa=i)}catch{}return Sa},Aa=()=>Au(yA()??o.features?.history?.rail?.width??260),bA=i=>{if(Sa=i,o.persistState!==!1)try{window.localStorage.setItem(`${ro()}rail-width`,String(i))}catch{}},fc=()=>mc()&&o.features?.history?.rail?.collapsedBehavior==="overlay",Nt=!1,zh=i=>{let c=M("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},vA=()=>{let i=o.features?.history?.rail?.brand;if(!i)return;let c=!1,g;return f=>{if(i.render)try{return i.render({collapsed:f})??null}catch(b){return c||(c=!0,console.warn("[persona] history rail brand threw",b)),null}return g===void 0&&(i.iconUrl?g=zh(i.iconUrl):g=i.icon?pe(i.icon,20):null),g?g.cloneNode(!0):null}},CA=()=>o.features?.history?.rail?.sections?.map(i=>{let c=!1,g=f=>{c||(c=!0,console.warn("[persona] history rail section threw",i.id,f))};return{id:i.id,title:i.title,placement:i.placement??"above-conversations",items:i.items.map(f=>{let b;return{id:f.id,label:f.label,badge:f.badge,iconNode:()=>{if(b!==void 0)return b;try{f.renderIcon?b=f.renderIcon()??null:f.iconUrl?b=zh(f.iconUrl):b=f.icon?pe(f.icon,20):null}catch(w){g(w),b=null}return b},onSelect:()=>{try{f.onSelect()}catch(w){g(w)}}}})}})??[],wA=i=>{let c=CA();for(let g of i)c.some(f=>f.id===g.id)?console.warn("[persona] duplicate history rail section id",g.id):c.push(g);return c.length?c:void 0},Ma=null,Vh=()=>`${ro()}rail-collapsed`,Mu=()=>{if(Ma===null&&(Ma=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(Vh());i&&(Ma=i==="1")}catch{}return Ma},Eu=i=>{if(Ma=i,o.persistState!==!1)try{window.localStorage.setItem(Vh(),i?"1":"0")}catch{}},Ea=()=>ce==="rail"&&mc()&&!fc()&&Mu(),Tu=()=>{},Kh=()=>{if(fc()){Tu();return}Eu(!Mu()),it?.view.setCollapsed(Ea()),Oe(),En()},ku=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!Pd(i)?null:{combo:i,hint:Ld(i),aria:al(i)}},Gh=()=>{d.forEach(c=>c()),d=[];let i=ku();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>ie&&ce==="rail"&&mc()||gi(),run:()=>fc()?Tu():Kh()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&d.push(l.register({id:`header-action-${c.id}`,combo:c.shortcut,run:()=>{let g=e.querySelector(`[data-persona-header-action="${c.id}"]`);g?g.click():o.layout?.header?.onAction?.(c.id)}}));for(let c of a)for(let g of c.shortcuts??[])d.push(l.register({...g,id:`${c.id}:${g.id}`}))};Gh();let xA=300,hc="var(--persona-history-overlay-margin,8px)",Xn=null,nr=null,yc=0,or=null,ui=null,ws=!1,Pu=0,Yh=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,gi=()=>Lo()&&fc()&&(ce??vu())==="rail",SA=()=>ie&&!Nt,Ta=()=>{ui!==null&&clearTimeout(ui),ui=null},AA=()=>{jm().catch(()=>{})},Qh=()=>{Ta(),Nt&&(ui=setTimeout(()=>{ui=null,!(ws||!Nt)&&(or?.contains(document.activeElement)||Tn({restoreFocus:!1}))},xA))},MA=(i,c)=>{let g=or?.getBoundingClientRect();if(!g)return!1;let f=Xn?.getBoundingClientRect(),b=f?Math.min(f.top,g.top):g.top;return i>=g.left&&i<=g.right&&c>=b&&c<=g.bottom||!!f&&i>=f.left&&i<=f.right&&c>=f.top&&c<=f.bottom},Lu=i=>{Nt&&(ws=MA(i.clientX,i.clientY),ws?Ta():ui===null&&Qh())},Xh=i=>{ie||!gi()||(Nt=!0,Pa({invoker:Xn,keyboard:i?.keyboard===!0}).then(()=>{ie?!ws&&document.activeElement!==Xn&&Tn():Nt=!1}))},Jh=()=>{let i=wa?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",Nt?Qe.expandLabel:Qe.collapseLabel),i.setAttribute("aria-expanded",Nt?"false":"true"))},Zh=()=>{Eu(!1);let i=it;if(!Nt||!i){Pa({invoker:Xn});return}let c=document.activeElement===Xn;Nt=!1,bc(),i.element.remove(),Ru(i.element),Jh(),c&&Cc(),En(),Rr()},EA=()=>{Eu(!0),Tn()};Tu=()=>{!ie||Nt?Zh():EA()};let TA=()=>{let i=ku(),c=_s({ariaLabel:Qe.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":hu,...i?{"aria-keyshortcuts":i.aria}:{}}}),g=c.button;g.addEventListener("mouseenter",()=>{ws=!0,Ta(),!(Yh()||Date.now()<Pu)&&Xh()}),g.addEventListener("mouseleave",()=>{ws=!1,Pu=0,Qh()}),g.addEventListener("focus",()=>{ie||AA()}),g.addEventListener("click",f=>{Lo()&&(f.detail!==0&&Yh()&&!ie?Xh():Zh())}),Xn=g,nr=c.wrapper},ka=()=>{if(nr&&!nr.isConnected&&(nr=null,Xn=null),!gi()){nr?.remove(),nr=null,Xn=null;return}Xn||TA();let i=nr,c=Xn;if(!i||!c)return;let g=pi()!=="right"?Me.firstChild:null;(g??Me.lastChild)!==i&&Me.insertBefore(i,g),i.style.display=SA()||yc>0?"none":"",c.setAttribute("aria-label",Qe.expandLabel),c.setAttribute("aria-expanded",ie?"true":"false"),or&&Oe()},ey=i=>{if(!Nt)return;let c=i.target;c instanceof Node&&(or?.contains(c)||nr?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||Tn({restoreFocus:!1}))};document.addEventListener("pointerdown",ey,!0),ye.push(()=>{document.removeEventListener("pointerdown",ey,!0),document.removeEventListener("pointermove",Lu),mi?.(),Ta()});let Iu=null,mi=null,ty=16,ny=i=>{bA(Au(i)),Oe(),En()},kA=()=>{let i=M("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(xu)),i.setAttribute("aria-valuemax",String(Su)),i.addEventListener("pointerdown",c=>{let g=Cs;if(!g||c.button!==0)return;c.preventDefault(),mi?.();let f=c.clientX,b=g.getBoundingClientRect().width||Aa(),w=pi()==="right"?-1:1,W=b,z=e.ownerDocument;g.style.transition="none";let q=J=>{W=Au(b+w*(J.clientX-f)),g.style.flex=`0 0 ${W}px`,i.setAttribute("aria-valuenow",String(W))},V=()=>{mi=null,z.removeEventListener("pointermove",q),z.removeEventListener("pointerup",V),z.removeEventListener("pointercancel",V),g.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}ny(W)};mi=V,z.addEventListener("pointermove",q),z.addEventListener("pointerup",V),z.addEventListener("pointercancel",V);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let g=pi()==="right"?-ty:ty,f=Aa(),b=c.key==="ArrowRight"?f+g:c.key==="ArrowLeft"?f-g:c.key==="Home"?xu:c.key==="End"?Su:null;b!==null&&(c.preventDefault(),ny(b))}),i},PA=(i,c)=>{if(!hA()||Ea()){mi?.(),Iu?.remove();return}let g=Iu??kA();Iu=g,g.setAttribute("aria-label",Qe.resizeLabel),g.setAttribute("aria-valuenow",String(Aa())),g.nextElementSibling!==c&&i.insertBefore(g,c)};Oe=()=>{it?.view.setRailSide(pi());let i=pi()==="right",c=or;if(c){let z=Xn?Xn.getBoundingClientRect().bottom-ge.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(z))}px + ${hc})`,c.style.width=`${Aa()}px`,c.style.left=i?"":hc,c.style.right=i?hc:""}let g=Cs,f=ci,b=xa;if(!g||!f||!b)return;g.style.flex=`0 0 ${Ea()?fA:Aa()}px`;let w="1px solid var(--persona-divider,#e5e7eb)";g.style.borderRight=i?"":w,g.style.borderLeft=i?w:"";let W=i?b:g;f.firstElementChild!==W&&f.append(W,i?g:b),PA(f,i?g:b)};let oy=i=>{if(di&&Cs){di.replaceWith(i),di=null,Oe();return}let c=M("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let g=M("div","persona-history-rail-conversation");g.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let f=M("div","persona-history-rail-host");f.style.cssText="display:flex;min-height:0;overflow:hidden",ge.insertBefore(c,Me.parentNode===ge?Me:ne);for(let b of qh())b?.parentNode===ge&&g.appendChild(b);c.append(f,g),f.appendChild(i),ci=c,Cs=f,xa=g,Oe()},LA=()=>{if(ci)return;let i=M("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",di=i,oy(i),En()},ry=()=>{di&&(bc(),En())},IA=i=>{let c=M("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${hc};display:flex;overflow:hidden;z-index:${Ri-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,ge.style.position="relative",ge.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",Lu),or=c,Oe(),Jh()},bc=()=>{gc?.(),or&&(ws&&(Pu=Date.now()+150),document.removeEventListener("pointermove",Lu),or.remove(),or=null);let i=ci;if(i){mi?.();for(let c of qh())c&&i.contains(c)&&ge.insertBefore(c,i);i.remove(),ci=null,Cs=null,xa=null,di=null}},sy=i=>{wa=i,i.id=hu,i.style.flex="1 1 auto",i.style.minHeight="0"},Ru=i=>{sy(i),(ce!=="rail"||Nt)&&ry(),ce!=="rail"?mA(i):Nt?IA(i):oy(i)},vc=()=>{if(ka(),hy(),!ie||!it)return;let i=vu();if(i===ce)return;let c=document.activeElement,g=c instanceof HTMLElement&&(it.element.contains(c)||Dn?.contains(c)===!0)?c:null;bc(),it.element.remove(),it.view.setHeaderPlacement("inline"),ce=i,it.view.setPresentation(i),it.view.setCollapsed(Ea()),it.requestRender(),it.element.isConnected||Ru(it.element),g?.isConnected?g.focus():Cc(),Vt(),En(),Rr()},iy=(i,c)=>Dn?.querySelector(c)??i.querySelector(c),Cc=()=>{let i=it?.element??wa;if(!i)return;let c=iy(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let g=iy(i,".persona-history-title")??i;g.tabIndex=-1,g.focus()},Pa=async i=>{if(!Lo()||ie)return;let c=_n;if(!c)return;if(!Nt&&gi()&&Mu()){ka();return}wc();let g=++Ca;ac=i?.returnSurface??"conversation",gu=i?.invoker??un;let f=gi()&&!Nt;f&&(yc+=1,ka(),LA());let b;try{b=await jm()}catch{pc(Qe.openHistoryLabel),f&&(yc-=1,g===Ca&&(ry(),ka()));return}if(f&&(yc-=1),g!==Ca||ie)return;ic={scope:bu()},ce=vu(),ie=!0;let w=ce==="panel"&&o.layout?.showHeader!==!1&&Me.style.display!=="none"?"external":"inline",W=o.features?.history?.rowAvatar,z=ku(),q=z?{hint:z.hint,aria:z.aria}:null,V={provider:c,context:ic,targetId:Bh(),presentation:ce,collapsible:mc(),collapsed:Ea(),railSide:pi(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:vA(),onToggleCollapse:Kh,...q?{collapseShortcut:q}:{},headerPlacement:w,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:W===!1?!1:typeof W=="string"?W:o.launcher?.iconUrl,activeConversationId:k.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:J=>Wu(J,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:J=>xs(J),attachTooltip:tn,onStartNew:()=>Ou({focusComposer:!0}),onClose:()=>Tn(),onRequestDeleteConversation:J=>fy(J),onRequestClearHistory:()=>_A(),...c.resetDevice?{onRequestResetIdentity:()=>DA()}:{}};it=sx({plugins:a,config:o,getPresentation:()=>ce??"panel",getReturnSurface:()=>ac,close:()=>Tn(),createView:({slots:J,renderDom:se,onModelChange:fe,railSections:Xe})=>(vs=b.createHistoryView({...V,railSections:wA(Xe),slots:J,renderDom:se,onModelChange:fe,onAnnounce:pc}),vs),onElementChanged:(J,se)=>{if(!se?.isConnected)return Ru(J);sy(J),se.replaceWith(J),wu()}}),it.view.setNewConversationRequired(lc.recovery==="new_conversation_required"),i?.focus!==!1&&(ce!=="rail"||i?.keyboard===!0)&&Cc(),Vt(),En(),Rr(),A.emit("history:opened",{presentation:ce,returnSurface:ac,timestamp:Date.now()})},wc=()=>{},Tn=i=>{if(!ie)return;Ca+=1;let c=ac,g=gu,f=it,b=i?.restoreFocus!==!1;ie=!1;let w=!1,W=null,z=()=>{if(!w){if(w=!0,wc=()=>{},W!==null&&clearTimeout(W),Nt=!1,Ta(),bc(),f?.dispose(),f?.view.destroy(),f?.element.remove(),it===f&&(it=null,vs=null,wa=null,ce=null,ic=null,gu=null),Vt(),En(),Rr(),b){let V=g??un;V?.isConnected?V.focus():fs()}A.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},q=f&&f.element===f.view.element?f.view.playExit():null;if(!q){z();return}wc=z,W=setTimeout(z,aA),q.then(z)},ay=i=>{if(!(i.key!=="Escape"||!ie||!it)){if(ce==="rail"){let c=i.target;if(!(c instanceof Node)||!(it.element.contains(c)||Nt&&nr?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Tn()}};ge.addEventListener("keydown",ay),ye.push(()=>ge.removeEventListener("keydown",ay));let xc=null,ly=!1,La=()=>{if(!br)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&xc?.trim()||null;br.textContent=c??o.launcher?.title??"Chat Assistant";let g=br.closest(".persona-combo-btn");if(!g)return;let f=!i||k.getActiveConversationId()!==null;g.setAttribute("data-persona-menu-locked",f?"false":"true"),g.setAttribute("aria-haspopup",f?"true":"false"),f||g.setAttribute("aria-expanded","false"),g.style.cursor=f?"pointer":"default";let b=g.querySelector("svg");b&&(b.style.display=f?"":"none")},RA=i=>{i!==xc&&(xc=i,La())},xs=i=>{ly=i?.starred===!0,RA(i&&i.title.trim()||null),La()};La(),ge.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,g=k.getActiveConversationId();g&&(c==="delete"?fy(g):c==="star"&&k.canUpdateConversations()&&Bu(g,{starred:!ly}).catch(()=>{}))});let Sc=0,HA=250,Ac=null,Mc=()=>{Ac&&clearTimeout(Ac),Ac=null};ye.push(Mc);let cy=()=>{Mc();let i=hs;i&&(ba=!0,i.hidden=!1,Te.style.display="none",va())},Ec=()=>{Sc+=1,Mc(),hs&&(hs.remove(),hs=null,ba=!1,Te.style.removeProperty("display"),Qn(Ie,!1),va())},WA=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Te.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Hu=(i,c)=>Q("div",{className:mn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),dy=()=>Q("div",{className:"persona-conversation-loading-body"},Hu("58%",!1),Hu("72%",!0),Hu("44%",!1)),py=i=>{hs?.remove(),hs=i,i.hidden=!ba,ne.insertBefore(i,Te),Mc(),ba||(Ac=setTimeout(cy,HA)),Qn(Ie,!0)},OA=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:dy},c=null,g=a.find(f=>f.renderLoadingIndicator);g?.renderLoadingIndicator&&(c=g.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),py(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Qe.openConversationLoadingLabel}},c??dy()))},BA=i=>{let c=()=>{Wu(i,{focusComposer:!0}).catch(()=>{})},g=Lo()?()=>{Ec(),Pa()}:void 0,f=(z,q)=>{let V=Q("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:z});return V.addEventListener("click",q),V},b=()=>Q("div",{className:"persona-conversation-loading-error-body"},Q("p",{className:"persona-conversation-loading-error-title",text:Qe.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},f(Qe.openConversationRetryLabel,c),g?f(Qe.openConversationBackLabel,g):null)),w=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Qe.openConversationErrorTitle,retryLabel:Qe.openConversationRetryLabel,backLabel:Qe.openConversationBackLabel}),retry:c,...g?{back:g}:{},defaultRenderer:b}),W=null;for(let z of a)if(z.renderHistoryOpenError){try{W=z.renderHistoryOpenError(w)}catch(q){console.warn("[persona] renderHistoryOpenError threw",q),W=null}if(W)break}py(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},W??b())),cy()};A.on("history:closed",()=>{hs&&Qn(Ie,!0)});let Wu=async(i,{focusComposer:c=!1}={})=>{let g=li(),f=!!it;it?.view.setActiveConversationId(i),Ec();let b=Sc;OA(),ie&&(ce==="panel"||Nt)&&Tn({restoreFocus:!1}),Zs=!0;try{await k.openConversation(i,{scope:g})}catch(w){throw b===Sc&&BA(i),w}finally{Zs=!1}b===Sc&&(Ec(),Dt.clear(),uo(),Mn(),Gp()||Ql(),WA(),rr(),f||xs(null),A.emit("history:conversationOpened",{conversationId:i,title:xc,scope:g,timestamp:Date.now()}),c&&fs())},Ou=async({focusComposer:i=!1}={})=>{Ec(),await k.startNewConversation({scope:li()}),xs(null),Dt.clear(),uo(),Mn(),Ql(),rr();let c=k.getActiveConversationId();it?.view.setActiveConversationId(c),A.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),ie&&(ce==="panel"||Nt)&&Tn({restoreFocus:!1}),i&&fs()},Bu=async(i,c)=>{let g=await k.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return it?.view.applyConversationSummary(g),!it&&i===k.getActiveConversationId()&&xs(g),g},uy=async i=>{let c=li(),g=k.getActiveConversationId()===i;await k.deleteConversation(i,{scope:c}),it?.view.removeConversationSummary(i),g&&(xs(null),Dt.clear(),uo(),Mn(),rr()),A.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:g,timestamp:Date.now()})},gy=async i=>{let c=i?.scope??li(),g=i?.allTargets?null:i?.targetId??Bh(),f=await k.clearConversationHistory({...g?{targetId:g}:{},scope:c});return xs(null),Dt.clear(),uo(),Mn(),rr(),A.emit("history:cleared",{deleted:f.deleted,scope:c,targetId:g,timestamp:Date.now()}),f},my=async()=>{if(!_n?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await k.resetHistoryDevice()).remoteRevocationConfirmed}finally{xs(null),k.clearArtifacts(),Dt.clear(),lu=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),Y={},He.syncFromMetadata(),G?.clear&&Kl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),uo(),Mn(),rr(),Tn({restoreFocus:!1}),fs(),he||Lt?.launcher.element.focus()}return pc(i?Qe.identityResetNotice:Qe.identityResetUnconfirmedNotice),A.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},_u=()=>Eo?Se:ge,fy=async i=>await rp({host:_u(),title:Qe.deleteConversationConfirmTitle,description:Qe.deleteConversationConfirm,confirmLabel:Qe.deleteConversationConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await uy(i),"deleted"):"cancelled",_A=async()=>{let i=li()==="verified-user";return await rp({host:_u(),title:Qe.clearHistoryConfirmTitle,description:i?Qe.clearHistoryVerifiedConfirm:Qe.clearHistoryConfirm,confirmLabel:Qe.clearHistoryConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await gy(),"cleared"):"cancelled"},DA=async()=>{if(!await rp({host:_u(),title:Qe.resetIdentityConfirmTitle,description:Qe.resetIdentityConfirm,confirmLabel:Qe.resetIdentityConfirmLabel,cancelLabel:Qe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await my();return{outcome:"reset",remoteRevocationConfirmed:c}},Jn=M("button","persona-history-earlier");Jn.type="button",Jn.textContent=Qe.showEarlierMessagesLabel,Jn.setAttribute("data-persona-history-earlier",""),Object.assign(Jn.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let rr=()=>{if(!(Lo()&&!!lc.nextMessageCursor&&!!k.getActiveConversationId())){Jn.remove();return}Jn.textContent=Qe.showEarlierMessagesLabel,Jn.parentNode!==ne&&ne.insertBefore(Jn,ne.firstChild)};Jn.addEventListener("click",()=>{let i=k.getActiveConversationId(),c=lc.nextMessageCursor;if(!i||!c||Jn.disabled)return;Jn.disabled=!0;let g=ne.scrollHeight,f=ne.scrollTop;k.loadOlderMessages(i,c,{scope:li()}).then(()=>{ne.scrollTop=f+(ne.scrollHeight-g),En()}).catch(()=>{}).finally(()=>{Jn.disabled=!1,rr()})});let NA=()=>{let i=_s({ariaLabel:Qe.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return i.button.addEventListener("click",c=>{if(!(!Lo()||Oh())){if(ie){Tn();return}Pa({invoker:i.button,keyboard:c.detail===0})}}),i},hy=()=>{if(!Lo()){Po?.remove(),un=null,Po=null;return}if(Po&&!Po.isConnected&&(un=null,Po=null),!un&&Me){let f=NA();un=f.button,Po=f.wrapper;let b=De.clearChatButtonWrapper||De.closeButtonWrapper;b?.parentNode&&Me.contains(b)?b.parentNode.insertBefore(Po,b):Me.appendChild(Po)}if(!un||!Po)return;let i=gi()||ie&&ce==="rail";if(Po.style.display=i?"none":"",i){document.activeElement===un&&Cc();return}let c=Oh();un.disabled=c,un.setAttribute("aria-disabled",c?"true":"false");let g=c?Qe.openHistoryBusyLabel:Qe.openHistoryLabel;un.setAttribute("aria-label",g),(o.features?.history?.presentation??"panel")==="panel"?(un.removeAttribute("aria-expanded"),un.removeAttribute("aria-controls")):(un.setAttribute("aria-expanded",ie?"true":"false"),un.setAttribute("aria-controls",hu))},Tc=!1,FA=()=>{let i=De.clearChatButton;if(i){if(Lo()){Tc||(fu=i.getAttribute("aria-label")??"",Tc=!0),i.setAttribute("aria-label",Qe.newConversationLabel),i.removeAttribute("title");return}Tc&&(Tc=!1,fu&&i.setAttribute("aria-label",fu))}},Rr=()=>{Qe=Vm(o.features?.history?.copy),hy(),ka(),FA(),rr()};qo=Rr,Ot=i=>{lc=i,it?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),ya(i.sendBlocked||Wn),rr()},kt=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(Dt.clear(),uo(),Mn()),pc(i.message),it?.view.refresh()},Fh(),Rr(),ye.push(()=>{cc?.(),dc?.(),Ca+=1,wc(),it?.dispose(),it?.view.destroy(),it=null}),o.clientToken&&k.initClientSession().then(()=>{if(Lo())return k.reconcileBootConversation({scope:bu()})}).then(()=>{rr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(an||o.onSSEEvent)&&k.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),te(i,c)});let yy=()=>{let i=o.resume??(ae?er.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&k.resumeFromHandle(i)};E?E.then(i=>{if(i){if(i.metadata&&(Y=Jm(i.metadata),He.syncFromMetadata()),i.messages?.length){Zs=!0;try{k.hydrateMessages(i.messages)}finally{Zs=!1}ec()}i.artifacts?.length&&k.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),gh(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{eu=!0,B(),yy()}):(gh(L),yy());let $A=()=>{!Ce()||he||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ut(!0,"auto")},UA=(i,c)=>i?c?{refs:[...i.refs,...c.refs],finalize:async()=>{let[g,f]=await Promise.allSettled([i.finalize(),c.finalize()]),b=[];return g.status==="fulfilled"?b.push(g.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",g.reason),f.status==="fulfilled"?b.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),_I(b)}}:i:c,Du=()=>{let c=de.getInlineMessageFields?.();return c&&c.contentSegments.some(f=>f.kind==="mention")?c.contentSegments:void 0},sr=!1,Ss=null,kc=()=>{de.value="",de.style.height="auto",So(),Ra()},Nu="data-persona-composer-notice",fi=null;function jA(i){kl(i),!(Ce()||!st)&&(st.hasAttribute(Xi)||(st.setAttribute(Nu,""),st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.textContent=i,fi&&clearTimeout(fi),fi=setTimeout(()=>{if(fi=null,!!st?.hasAttribute(Nu)&&(st.removeAttribute(Nu),st.removeAttribute("role"),st.removeAttribute("aria-live"),p)){let c=k.getStatus();Ml(st,Cn(c),o.statusIndicator??{},c)}},4e3)))}function qA(){let i=we.getState().pendingSubmission;i&&(zs(void 0),de&&(de.value=i.text,de.dispatchEvent(new Event("input",{bubbles:!0})),So()),i.options.selectedModelId&&(we.setSelectedModelId(i.options.selectedModelId),Cr?.repaint()),i.options.activeModeIds?.length&&Rl(i.options.activeModeIds),i.options.quote&&Ao(i.options.quote),de?.focus())}let zA=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},by=(i={})=>{let c=(i.overrideText??de?.value??"").trim();return i.resolveInlineCommand&&c?(Bt?.takeInlineCommand(c)??Promise.resolve(null)).then(g=>vy(i,c,g)):vy(i,c,null)},vy=(i,c,g)=>{if(g?.kind==="action"){kc(),Bt?.clear(),Jr();return}let f=g?.kind==="server"?g.mentions:null,b=g?.kind==="prompt"?g.sendText:c,w=i.pending?.contentParts,W=(Je?.hasAttachments()??!1)||(w?.length??0)>0;if(!hC({text:b,hasAttachments:W,attachmentsReady:Je?.isReady()??!0,hasMentions:Bt?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:Pr(),sendDisabled:ms()}))return;let z=k.isStreaming()?kp():"block";if(z==="defer-one"&&!i.pending){if(we.getState().pendingSubmission){jA("One message is already queued. Edit or remove it first.");return}VA({intent:i,sendText:b,serverMentions:f});return}let q={text:b,mentionRefs:[...Bt?.getMentionRefs()??[],...f?.refs??[]],contentSegments:g?.kind==="prompt"?void 0:Du(),options:{...we.getState().selectedModelId&&{selectedModelId:we.getState().selectedModelId},...we.getState().activeModeIds.length>0&&{activeModeIds:[...we.getState().activeModeIds]},...we.getState().quote&&{quote:{...we.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(q.options={...i.pending.options},q.contentSegments=i.pending.contentSegments,q.mentionRefs=[...i.pending.mentionRefs],q.viaVoice=i.pending.viaVoice);let V=()=>{if(w?.length)return[...w];if(!Je?.hasAttachments())return;let gt=[...Je.getContentParts()];return q.text&&gt.push(ho(q.text)),gt};q.contentParts=V();let J=()=>{as(),$A();let gt=Bt?.collectForSubmit()??null,Xt=UA(gt,f),Ft=V();i.consumeDraft!==!1&&kc();let Rt={selectedModelId:q.options.selectedModelId,activeModeIds:q.options.activeModeIds},ln=z==="interrupt";ln&&k.cancel(),k.sendMessage(q.text,{contentParts:Ft,mentions:Xt??void 0,contentSegments:q.contentSegments,viaVoice:q.viaVoice,composerOptions:Rt,...q.options.quote&&{quote:q.options.quote},...ln&&{interrupt:!0}}),Je?.hasAttachments()&&Je.clearAttachments(),gt&&Bt?.clear(),Jr();let Ze=we.getState().activeModeIds,cn=nC(Ze,o.composer?.modes);cn.length!==Ze.length&&Rl(cn),we.getState().quote&&Ao(void 0),Yl(),Hp.release(),ao()},se=o.composer?.onBeforeSend;if(!se){J();return}let fe=new AbortController;Ss=fe;let Xe=gt=>{if(Ss=null,gt.status==="error"){zA(gt.error);return}gt.status==="proceed"&&J()},dt=yC(se,q,fe.signal);if(!(dt instanceof Promise)){Xe(dt);return}return we.setPreparing(!0),dt.then(Xe).finally(()=>we.setPreparing(!1))};function VA(i){let c=we.getState(),g=Je?.hasAttachments()??!1,f=g?[...Je.getContentParts()]:[];g&&i.sendText&&f.push(ho(i.sendText));let b=Qg({text:i.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Bt?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Du(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});zs(b),i.intent.consumeDraft!==!1&&kc(),g&&Je.clearAttachments(),Bt?.clear(),Jr(),c.quote&&Ao(void 0),Yl(),Hp.release(),ao(),kl("Message queued. It sends when the response finishes.")}function KA(){let i=we.getState().pendingSubmission;i&&(zs(void 0),Lc(i.text,{consumeDraft:!1,pending:i}))}function GA(i){if(o.messageActions?.showEdit!==!0)return;let c=k.getMessages().find(g=>g.id===i);!c||!Mg(c)||is!==i&&(as(),is=i,Ar=aC({messageId:i,initialText:c.content,onSave:g=>YA(i,g),onCancel:()=>as()}),Dt.delete(i),Yn(Te,k.getMessages(),ft),Ar.focus())}function YA(i,c){let g=Ar;if(is=null,Ar=null,g?.destroy(),Dt.delete(i),!k.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){Yn(Te,k.getMessages(),ft);return}En()}function QA(i){if(k.isStreaming())return;let c=Ag(k.getMessages(),i);c&&(as(),k.resubmitFrom(c,{reason:"retry"})&&En())}Hl={regenerate:QA,edit:GA,quote:i=>{let g=k.getMessages().find(f=>f.id===i)?.content?.trim();g&&(Ao({text:g,messageId:i}),de?.focus())}};let Ia=async i=>{if(!sr){sr=!0;try{await by({resolveInlineCommand:!0,...i})}finally{sr=!1}}};function Pc(i){ms()||(kc(),Lc(i,{consumeDraft:!1}))}let Lc=(i,c)=>{if(sr)return;sr=!0;let g=()=>{sr=!1};try{let f=by({...c,overrideText:i});f instanceof Promise?f.finally(g):g()}catch(f){throw g(),f}},XA=i=>{if(i.preventDefault(),k.isStreaming()){k.cancel(),Pn?.reset(),X?.update();return}sr||Ia()},JA=()=>o.features?.composerHistory!==!1,Fu={...rm},$u=!1,Ra=()=>{Fu={...rm}},ZA=()=>k.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),eM=i=>{if(!de)return;$u=!0,de.value=i,de.dispatchEvent(new Event("input",{bubbles:!0})),$u=!1;let c=de.value.length;de.setSelectionRange(c,c)},tM=i=>{$u||(i.isComposing||Bt?.handleInput(i.inputType??void 0),Ra())},nM=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:ol(de)}),oM=i=>{if(de&&!Pr()&&!(!i.isComposing&&Bt?.handleKeydown(i))){if(JA()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let c=de.selectionStart===0&&de.selectionEnd===0,g=_C({direction:i.key==="ArrowUp"?"up":"down",history:ZA(),currentValue:de.value,atStart:c,state:Fu});if(Fu=g.state,g.handled){i.preventDefault(),g.value!==void 0&&eM(g.value);return}}if(Fv(i,nM())){if(k.isStreaming()){if(i.preventDefault(),kp()==="block"||sr||ms())return;Ra(),Ia();return}if(sr){i.preventDefault();return}if(ms()){i.preventDefault();return}Ra(),i.preventDefault(),Ae.click()}}},Cy=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(ge)){if(Ss){Ss.abort(),Ss=null,i.preventDefault(),i.stopImmediatePropagation();return}k.isStreaming()&&(k.cancel(),Pn?.reset(),X?.update(),Ra(),i.preventDefault(),i.stopImmediatePropagation())}},rM=async i=>{if(o.attachments?.enabled!==!0||!Je||Pr())return;let c=HI(i.clipboardData);c.length!==0&&(i.preventDefault(),await Je.handleFiles(c))},Zn=null,Io=!1,hi=null,xt=null,Uu=()=>o.voiceRecognition?.completionBehavior==="review";function As(i){oe?.setAttribute("data-state",i),i==="recording"?iM():Vu()}let wy="--persona-voice-level",ju=.5,yi=null,qu=-1,Ic=0,xy=()=>{let i=[],c=Rn??oe?.parentElement??null;return c&&i.push(c),Ie&&i.push(Ie),i},zu=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==qu){qu=c;for(let g of xy())g.style.setProperty(wy,String(c))}},sM=()=>{qu=-1,Ic=0;for(let i of xy())i.style.removeProperty(wy)};function iM(){if(yi!==null)return;if(typeof requestAnimationFrame!="function"){zu(p?k.getVoiceLevel()??ju:ju);return}let i=()=>{yi=requestAnimationFrame(i);let c=p?k.getVoiceLevel():null;if(c===null){zu(ju);return}Ic+=(c-Ic)*.3,zu(Ic)};yi=requestAnimationFrame(i)}function Vu(){yi!==null&&(cancelAnimationFrame(yi),yi=null),sM()}let Sy=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Rc=(i="user")=>{if(Io||k.isStreaming())return;let c=Sy();if(!c)return;Zn=new c;let g=o.voiceRecognition??{},f=g.pauseDuration??2e3;Zn.continuous=g.provider?.browser?.continuous??!0,Zn.interimResults=!0,Zn.lang=g.provider?.browser?.language??"en-US";let b=de.value;Zn.onresult=w=>{let W="",z="";for(let V=0;V<w.results.length;V++){let J=w.results[V],se=J[0].transcript;J.isFinal?W+=se+" ":z=se}let q=b+W+z;de.value=q,So(),hi&&clearTimeout(hi),(W||z)&&(hi=window.setTimeout(()=>{if(de.value.trim()&&Zn&&Io){if(Hr(),Uu())return;Ia({viaVoice:!0})}},f))},Zn.onerror=w=>{w.error!=="no-speech"&&Hr()},Zn.onend=()=>{if(Io){let w=de.value.trim();!Uu()&&w&&w!==b.trim()&&Ia({viaVoice:!0}),Hr()}};try{if(Zn.start(),Io=!0,ze.active=!0,i!=="system"&&(ze.manuallyDeactivated=!1),Xo(i),po(),ao(),oe){let w=o.voiceRecognition??{};xt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:w.iconName??"mic",iconSize:parseFloat(w.iconSize??"")||fn};let W=w.recordingBackgroundColor,z=w.recordingIconColor,q=w.recordingBorderColor;if(oe.classList.add("persona-voice-recording"),As("recording"),oe.style.backgroundColor=W??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=z??"var(--persona-voice-recording-indicator, #ffffff)",z){let V=oe.querySelector("svg");V&&V.setAttribute("stroke",z)}q&&(oe.style.borderColor=q),oe.setAttribute("aria-label","Stop voice recognition")}}catch{Hr("system")}},Hr=(i="user")=>{if(Io){if(Io=!1,hi&&(clearTimeout(hi),hi=null),Zn){try{Zn.stop()}catch{}Zn=null}if(ze.active=!1,Xo(i),po(),ao(),oe){if(oe.classList.remove("persona-voice-recording"),As("idle"),xt){oe.style.backgroundColor=xt.backgroundColor,oe.style.color=xt.color,oe.style.borderColor=xt.borderColor;let c=oe.querySelector("svg");c&&c.setAttribute("stroke",xt.color||"currentColor"),xt=null}oe.setAttribute("aria-label","Start voice recognition")}}},Ku=()=>{if(!oe||xt)return;let i=o.voiceRecognition??{};xt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||fn}},Gu=(i,c)=>{if(!oe)return;let g=oe.querySelector("svg");g&&g.remove();let f=xt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||fn),b=pe(i,f,c,1.5);b&&oe.appendChild(b)},Hc=()=>{oe&&oe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},bi=()=>{if(!oe)return;Ku();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,g=i.recordingIconColor,f=i.recordingBorderColor;if(Hc(),oe.classList.add("persona-voice-recording"),As("recording"),oe.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=g??"var(--persona-voice-recording-indicator, #ffffff)",g){let b=oe.querySelector("svg");b&&b.setAttribute("stroke",g)}f&&(oe.style.borderColor=f),oe.setAttribute("aria-label","Stop voice recognition")},aM=()=>{if(!oe)return;Ku();let i=o.voiceRecognition??{},c=k.getVoiceInterruptionMode(),g=i.processingIconName??"loader",f=i.processingIconColor??xt?.color??"",b=i.processingBackgroundColor??xt?.backgroundColor??"",w=i.processingBorderColor??xt?.borderColor??"";Hc(),oe.classList.add("persona-voice-processing"),As("processing"),oe.style.backgroundColor=b,oe.style.borderColor=w;let W=f||"currentColor";oe.style.color=W,Gu(g,W),oe.setAttribute("aria-label","Processing voice input"),c==="none"&&(oe.style.cursor="default")},lM=()=>{if(!oe)return;Ku();let i=o.voiceRecognition??{},c=k.getVoiceInterruptionMode(),g=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",f=i.speakingIconName??g,b=i.speakingIconColor??(c==="barge-in"?i.recordingIconColor??xt?.color??"":xt?.color??""),w=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":xt?.backgroundColor??""),W=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":xt?.borderColor??"");Hc(),oe.classList.add("persona-voice-speaking"),As("speaking"),oe.style.backgroundColor=w,oe.style.borderColor=W;let z=b||"currentColor";oe.style.color=z,Gu(f,z);let q=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";oe.setAttribute("aria-label",q),c==="none"&&(oe.style.cursor="default"),c==="barge-in"&&oe.classList.add("persona-voice-recording")},ir=()=>{oe&&(Hc(),As("idle"),xt&&(oe.style.backgroundColor=xt.backgroundColor??"",oe.style.color=xt.color??"",oe.style.borderColor=xt.borderColor??"",Gu(xt.iconName,xt.color||"currentColor"),xt=null),oe.style.cursor="",oe.setAttribute("aria-label","Start voice recognition"))},Yu=()=>{if(!Pr()){if(o.voiceRecognition?.provider?.type==="runtype"){let i=k.getVoiceStatus(),c=k.getVoiceInterruptionMode();if(c==="none"&&(i==="processing"||i==="speaking"))return;if(c==="cancel"&&(i==="processing"||i==="speaking")){k.stopVoicePlayback();return}if(k.isBargeInActive()){k.stopVoicePlayback(),k.deactivateBargeIn().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,po(),Xo("user"),ir()});return}k.toggleVoice().then(()=>{ze.active=k.isVoiceActive(),ze.manuallyDeactivated=!k.isVoiceActive(),po(),Xo("user"),k.isVoiceActive()?bi():ir()});return}if(Io){let i=de.value.trim();ze.manuallyDeactivated=!0,po(),Hr("user"),i&&!Uu()&&Ia()}else ze.manuallyDeactivated=!1,po(),Rc("user")}};Pp=Yu,oe&&ye.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(k.isVoiceActive()&&k.toggleVoice(),ir()):Hr("system")});let cM=A.on("assistant:complete",()=>{we.getState().pendingSubmission&&setTimeout(()=>{k.isStreaming()||KA()},0)});ye.push(cM);let dM=A.on("assistant:complete",()=>{dh&&(ze.active||ze.manuallyDeactivated||dh==="assistant"&&!ze.lastUserMessageWasVoice||setTimeout(()=>{!ze.active&&!ze.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?k.toggleVoice().then(()=>{ze.active=k.isVoiceActive(),Xo("auto"),k.isVoiceActive()&&bi()}):Rc("auto"))},600))});ye.push(dM);let pM=A.on("action:resubmit",()=>{setTimeout(()=>{k&&!k.isStreaming()&&k.continueConversation()},100)});ye.push(pM);let Ay=()=>{ut(!he,"user")},Lt=null,gn=null;if(ve&&!Ce()){let{instance:i,element:c}=Tm({config:o,plugins:a,onToggle:Ay});Lt=i,i||(gn=c)}Lt?e.appendChild(Lt.element):gn&&e.appendChild(gn),ha(),Xs(),oc(),su(),ya(k.isStreaming()),Gp()||(Hn()==="follow"?Tr(!0):Ql()),LS(),be&&(!ve||Ce()?setTimeout(()=>fs(),0):he&&setTimeout(()=>fs(),200));let Ms=null,My=()=>{Ms&&(Ms.disconnect(),Ms.observe(Ie),Ms.observe(ge))},Ha=()=>{if(Ce()){Xr(),ha();return}let i=Tt(o),c=o.launcher?.sidebarMode??!1,g=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640,w=g.innerWidth<=b,W=f&&w&&ve;try{if(W){Zr(),ia=$l();return}let z=!1;mt&&(mt=!1,Zr(),z=!0);let q=$l();if(!z&&q!==ia&&(Zr(),z=!0),ia=q,z&&_l(),!ve&&!i){Se.style.height="",Se.style.width="";return}if(!c&&!i){let J=o?.launcher?.width??o?.launcherWidth??oo;Se.style.width=J,Se.style.maxWidth=J}Fl(),Gf()}finally{if(Xr(),Il(),ha(),he&&ve){let q=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),V=o.launcher?.sidebarMode??!1,J=o.launcher?.mobileFullscreen??!0,se=Tt(o)&&J&&q,fe=V||J&&q&&ve||se;if(fe&&!ko){let Xe=e.getRootNode(),dt=Xe instanceof ShadowRoot?Xe.host:e.closest(".persona-host");dt&&!To&&(To=lm(dt,o.launcher?.zIndex??sn)),ko=cm(e.ownerDocument)}else fe||(To?.(),To=null,ko?.(),ko=null)}}};Ha();let Wc=e.ownerDocument.defaultView??window;if(Wc.addEventListener("resize",Ha),ye.push(()=>Wc.removeEventListener("resize",Ha)),typeof ResizeObserver<"u"){Ms=new ResizeObserver(()=>{Il()}),My(),ye.push(()=>{Ms?.disconnect(),Ms=null});let i=new ResizeObserver(()=>{vc()});i.observe(ge),ye.push(()=>i.disconnect())}Wc.addEventListener("resize",vc),ye.push(()=>Wc.removeEventListener("resize",vc)),Bn=ne.scrollTop;let Ey=Do(ne),Ty=()=>{let i=ne.scrollTop,c=Do(ne),g=c<Ey;if(Ey=c,!vr()){Bn=i,Vt();return}let{action:f,nextLastScrollTop:b}=zC({following:On.isFollowing(),currentScrollTop:i,lastScrollTop:Bn,nearBottom:Bs(ne,Yo),userScrollThreshold:ES,isAutoScrolling:An||jl||g,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Bn=b,f==="resume"){Xl()||Mn();return}f==="pause"&&pa()};if(ne.addEventListener("scroll",Ty,{passive:!0}),ye.push(()=>ne.removeEventListener("scroll",Ty)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{_S(),sg(Te)});i.observe(Te),i.observe(ne),ye.push(()=>i.disconnect())}let ky=()=>{vr()&&On.isFollowing()&&Xl()&&pa()},Py=ne.ownerDocument;Py.addEventListener("selectionchange",ky),ye.push(()=>{Py.removeEventListener("selectionchange",ky)});let uM=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Ly=i=>{uM.has(i.key)&&(ps(),ff()&&vr()&&On.isFollowing()&&pa())},Iy=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(ps(),ff()&&vr()&&On.isFollowing()&&pa())};ne.addEventListener("keydown",Ly),ne.addEventListener("focusin",Iy),ye.push(()=>{ne.removeEventListener("keydown",Ly),ne.removeEventListener("focusin",Iy)});let Ry=i=>{if(i.deltaY!==0&&ps(),!vr())return;let c=VC({following:On.isFollowing(),deltaY:i.deltaY,nearBottom:Bs(ne,Yo),resumeWhenNearBottom:!0});c==="pause"?pa():c==="resume"&&!Xl()&&Mn()};ne.addEventListener("wheel",Ry,{passive:!0}),ne.addEventListener("touchmove",ps,{passive:!0}),ne.addEventListener("pointerdown",ps,{passive:!0}),ye.push(()=>{ne.removeEventListener("touchmove",ps),ne.removeEventListener("pointerdown",ps)}),ye.push(()=>ne.removeEventListener("wheel",Ry)),_t.addEventListener("click",()=>{uo(),ne.scrollTop=ne.scrollHeight,Bn=ne.scrollTop,Mn(),Tr(!0),Vt()}),ye.push(()=>_t.remove()),ye.push(()=>{fh(),uo()});let Hy=()=>{Ue&&(os&&(Ue.removeEventListener("click",os),os=null),Ee()?(Ue.style.display="",os=()=>{ut(!1,"user")},Ue.addEventListener("click",os)):Ue.style.display="none")};Hy(),(()=>{let{clearChatButton:i}=De;i&&i.addEventListener("click",()=>{if(Lo()){Ou({focusComposer:!0}).catch(g=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",g)});return}k.clearMessages(),Dt.clear(),Mn(),Hs(De.composerOverlay);try{localStorage.removeItem(Qi),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Qi}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Qi)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 c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),G?.clear&&Kl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),Y={},He.syncFromMetadata(),Je?.clearAttachments(),Yl(),zs(void 0),Ao(void 0),as(),et?.clear(),Pn?.reset(),X?.update()})})();let Wy=[["keydown",oM],["input",tM],["input",So],["input",Jr],["keyup",Jr],["paste",rM],["focus",mS]],Oy=i=>{if(i)for(let[c,g]of Wy)nt?.addListener(i,c,g)},gM=i=>{if(i)for(let[c,g]of Wy)nt?.removeListener(i,c,g)},By=()=>{nt&&(nt.addListener(nt.form,"submit",XA),nt.addListener(nt.footer,"click",Jr),Oy(de),oe&&nt.addListener(oe,"click",Yu))};By();let _y=()=>{Bt?.onComposerSwap((i,c)=>{gM(c),de=i,nt&&(nt.input=i),Oy(i),Ip(),Jp(),So()})};_y();let Qu=!1;function Dy(){if(!Qu){Qu=!0;try{let i=de?.value??"",c=Ie.ownerDocument??document,g=de?c.activeElement===de:!1;Vu(),nt?.destroy(),nt=null,Bt?.destroy(),Bt=null;let f=null,b=()=>(f=Ce()?Dd({config:o}):Fi({config:o}),f.footer),w=Mf(b)??b();Ln.replaceComposer(w),Ie=Ln.composer.footer;let W=f!==null&&w===f.footer;Ks=!W,mf=W?f.setSendButtonMode:()=>{},Af(Ie),Tf(Ie),kf(),Pf(),Lf(),_y(),If(),Rp(),Rf(),By();let z=ns.indexOf(Go);Go.destroy(),Go=hl(yr),z>=0&&(ns[z]=Go),de&&(de.value=i),So(),Jr(),oc(),Xs(),ya(k.isStreaming()),ze.active&&As("recording"),Zr(),My(),Xr(),ao(),tc(),g&&de?.focus()}finally{Qu=!1}}}let Wa=e.ownerDocument??document;Wa.addEventListener("keydown",Cy,!0);let Ny=()=>{qp()},Fy=()=>{Wa.visibilityState==="hidden"&&qp()};typeof window<"u"&&(window.addEventListener("pagehide",Ny),Wa.addEventListener("visibilitychange",Fy),ye.push(()=>{window.removeEventListener("pagehide",Ny),Wa.removeEventListener("visibilitychange",Fy)}));let $y="persona-attachment-drop-active",Oa=0,Xu=()=>{Oa=0,ge.classList.remove($y)},vi=()=>o.attachments?.enabled===!0&&Je!==null&&!Pr(),Uy=i=>{!ip(i.dataTransfer)||!vi()||(Oa++,Oa===1&&ge.classList.add($y))},jy=i=>{!ip(i.dataTransfer)||!vi()||(Oa--,Oa<=0&&Xu())},qy=i=>{!ip(i.dataTransfer)||!vi()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},zy=i=>{if(!ip(i.dataTransfer)||!vi())return;i.preventDefault(),i.stopPropagation(),Xu();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&Je.handleFiles(c)},Wr=!0;ge.addEventListener("dragenter",Uy,Wr),ge.addEventListener("dragleave",jy,Wr),e.addEventListener("dragover",qy,Wr),e.addEventListener("drop",zy,Wr);let Oc=e.ownerDocument,Vy=i=>{vi()&&i.preventDefault()},Ky=i=>{vi()&&i.preventDefault()};Oc.addEventListener("dragover",Vy),Oc.addEventListener("drop",Ky),ye.push(()=>{nt?.destroy(),nt=null,Vu(),Mo?.destroy(),Mo=null,Vo?.destroy(),Vo=null,wr?.destroy(),wr=null,xr?.destroy(),xr=null,Cr=null,Tp=null,qp(),da.destroy(),fi&&clearTimeout(fi),as(),Ss?.abort(),Ss=null,Je?.destroy(),Je=null,we.destroy(),Wa.removeEventListener("keydown",Cy,!0),Bt?.destroy()}),ye.push(()=>{ge.removeEventListener("dragenter",Uy,Wr),ge.removeEventListener("dragleave",jy,Wr),e.removeEventListener("dragover",qy,Wr),e.removeEventListener("drop",zy,Wr),Oc.removeEventListener("dragover",Vy),Oc.removeEventListener("drop",Ky),Xu()}),ye.push(()=>{k.cancel()}),Lt?ye.push(()=>{Lt?.destroy()}):gn&&ye.push(()=>{gn?.remove()});let It={update(i){let c=o.toolCall,g=o.messageActions,f=o.layout?.messages,b=o.colorScheme,w=o.loadingIndicator,W=o.iterationDisplay,z=o.features?.showReasoning,q=o.features?.showToolCalls,V=o.features?.toolCallDisplay,J=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type,fe=o.features?.history?.enabled===!0,Xe=o.features?.history?.provider,dt=o.getIdentityProof,gt=o.clientToken,Xt=o.contextMentions;o=tp({...o,features:s},i),s=o.features,o=Zd(o),r(),Dp(),Oi(e,o),Cl(e,o),wl(e,o),Oe(),co(),o.colorScheme!==b&&Yf();let Ft=ep.getForInstance(o.plugins);a.length=0,a.push(...Ft),Gh(),ve=o.launcher?.enabled??!0,Ge=o.launcher?.autoExpand??!1,pn=o.features?.showReasoning??!0,zn=o.features?.showToolCalls??!0,Co=o.features?.scrollToBottom??{};let Rt=Hn();Vn=o.features?.scrollBehavior??{},Rt!==Hn()&&(uo(),Mn()),ch(),bf(),Vt();let ln=an;if(an=o.features?.showEventStreamToggle??!1,an&&!ln){if(et||(re(),k.setSSEEventCallback((Z,Ve)=>{o.onSSEEvent?.(Z,Ve),te(Z,Ve)})),!tt&&Me){let Z=o.features?.eventStream?.classNames,Ve="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"+(Z?.toggleButton?" "+Z.toggleButton:"");tt=M("button",Ve),tt.style.width="28px",tt.style.height="28px",tt.style.color=yn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Ye=Wt(dx,"18px","currentColor",1.5);Ye&&tt.appendChild(Ye);let rt=De.clearChatButtonWrapper,St=De.closeButtonWrapper,rn=rt||St;rn&&rn.parentNode===Me?Me.insertBefore(tt,rn):Me.appendChild(tt),tt.addEventListener("click",()=>{v?Vs():Lp()})}}else!an&&ln&&(Vs(),tt&&(tt.remove(),tt=null),et?.clear(),jo?.destroy(),et=null,jo=null,Pn?.reset(),Pn=null,so=null);if(o.launcher?.enabled===!1&&Lt&&(Lt.destroy(),Lt=null),o.launcher?.enabled===!1&&gn&&(gn.remove(),gn=null),o.launcher?.enabled!==!1&&!Lt&&!gn){let{instance:Z,element:Ve}=Tm({config:o,plugins:a,onToggle:Ay});Lt=Z,Z||(gn=Ve),e.appendChild(Ve)}Lt&&Lt.update(o),La(),Yr&&o.launcher?.subtitle!==void 0&&(Yr.textContent=o.launcher.subtitle);let Ze=o.layout?.header;if(Ze?.layout!==Fe&&Me){let Z=Ze?yl(o,Ze,{showClose:Ee(),onClose:()=>ut(!1,"user")}):Vr({config:o,showClose:Ee(),onClose:()=>ut(!1,"user")});Ln.replaceHeader(Z),Me=Ln.header.element,Pt=Ln.header.iconHolder,br=Ln.header.headerTitle,Yr=Ln.header.headerSubtitle,Ue=Ln.header.closeButton,Fe=Ze?.layout,La()}else if(Ze){if(Pt&&(Pt.style.display=Ze.showIcon===!1?"none":""),br&&(br.style.display=Ze.showTitle===!1?"none":""),Yr&&(Yr.style.display=Ze.showSubtitle===!1?"none":""),Ue){let Z=Ee()&&Ze.showCloseButton!==!1;Ue.style.display=Z?"":"none"}if(De.clearChatButtonWrapper){let Z=Ze.showClearChat;if(Z!==void 0){De.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:Ve}=De;Ve&&!Ve.classList.contains("persona-absolute")&&(Z?Ve.classList.remove("persona-ml-auto"):Ve.classList.add("persona-ml-auto"))}}}let Ro=o.layout?.showHeader!==!1;Me&&(Me.style.display=Ro?"":"none");let ar=o.layout?.showFooter!==!1;Ie&&(Ie.style.display=ar?"":"none"),Xr(),Vt(),ve!==_e?ve?ut(Ge,"auto"):(he=!0,ha()):Ge!==j&&ut(Ge,"auto"),j=Ge,_e=ve,Ha(),Hy();let Es=JSON.stringify(o.toolCall)!==JSON.stringify(c),I=JSON.stringify(o.messageActions)!==JSON.stringify(g),ke=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),We=o.loadingIndicator?.render!==w?.render||o.loadingIndicator?.renderIdle!==w?.renderIdle||o.loadingIndicator?.showBubble!==w?.showBubble,xe=o.iterationDisplay!==W,Kt=(o.features?.showReasoning??!0)!==(z??!0)||(o.features?.showToolCalls??!0)!==(q??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(V)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(J);(Es||I||ke||We||xe||Kt)&&k&&(ls++,Yn(Te,k.getMessages(),ft));let lt=o.features?.streamAnimation?.type;if(lt!==se&&lt&&lt!=="none"){let Z=Fp(lt,o.features?.streamAnimation?.plugins);Z&&gl(Z,e)}let Le=o.launcher??{},go=Le.headerIconHidden??!1,Et=o.layout?.header?.showIcon,on=go||Et===!1,Gt=Le.headerIconName,Ht=Le.headerIconSize??"48px";if(Pt){let Z=Me,Ve=Z?.querySelector(".persona-flex-col");if(on)Pt.style.display="none",Z&&Ve&&!Z.contains(Ve)&&Z.insertBefore(Ve,Z.firstChild);else{if(Pt.style.display="",Pt.style.height=Ht,Pt.style.width=Ht,Z&&Ve&&(Z.contains(Pt)?Pt.nextSibling!==Ve&&(Pt.remove(),Z.insertBefore(Pt,Ve)):Z.insertBefore(Pt,Ve)),Gt){let rt=parseFloat(Ht)||24,St=pe(Gt,rt*.6,"currentColor",1);St?Pt.replaceChildren(St):Pt.textContent=Le.agentIconText??"\u{1F4AC}"}else if(Le.iconUrl){let rt=Pt.querySelector("img");if(rt)rt.src=Le.iconUrl,rt.style.height=Ht,rt.style.width=Ht;else{let St=document.createElement("img");St.src=Le.iconUrl,St.alt="",St.className="persona-rounded-xl persona-object-cover",St.style.height=Ht,St.style.width=Ht,Pt.replaceChildren(St)}}else{let rt=Pt.querySelector("svg"),St=Pt.querySelector("img");(rt||St)&&Pt.replaceChildren(),Pt.textContent=Le.agentIconText??"\u{1F4AC}"}let Ye=Pt.querySelector("img");Ye&&(Ye.style.height=Ht,Ye.style.width=Ht)}}let Be=o.layout?.header?.showTitle,Nn=o.layout?.header?.showSubtitle;if(br&&(br.style.display=Be===!1?"none":""),Yr&&(Yr.style.display=Nn===!1?"none":""),Ue){let Z=Ee()&&o.layout?.header?.showCloseButton!==!1;if(Ue.style.display=Z?"":"none",!Ce()){let Zt=Le.closeButtonSize??"";Ue.style.height=Zt,Ue.style.width=Zt,Ue.style.minWidth=Zt,Ue.style.minHeight=Zt}let Ve=Le.closeButtonPlacement??"inline",{closeButtonWrapper:Ye}=De,rt=Ve==="top-right",St=Ye?.classList.contains("persona-absolute");if(Ye&&rt!==St)if(Ye.remove(),rt){Ye.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Zt=xa??ge;Zt.style.position="relative",Zt.appendChild(Ye)}else{let Zt=Le.clearChat?.placement??"inline",en=Le.clearChat?.enabled??!0;Ye.className=en&&Zt==="inline"?"":"persona-ml-auto",Me&&Me.appendChild(Ye)}if(Ue.style.color=Le.closeButtonColor||yn.actionIconColor,Le.closeButtonBackgroundColor?(Ue.style.backgroundColor=Le.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),Le.closeButtonBorderWidth||Le.closeButtonBorderColor){let Zt=Le.closeButtonBorderWidth||"0px",en=Le.closeButtonBorderColor||"transparent";Ue.style.border=`${Zt} solid ${en}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");Le.closeButtonBorderRadius?(Ue.style.borderRadius=Le.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),Le.closeButtonPaddingX?(Ue.style.paddingLeft=Le.closeButtonPaddingX,Ue.style.paddingRight=Le.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),Le.closeButtonPaddingY?(Ue.style.paddingTop=Le.closeButtonPaddingY,Ue.style.paddingBottom=Le.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom=""),Bd(Ue,Le.closeButtonIconName??"x",{iconSize:Ce()?Sm:void 0,iconText:Le.closeButtonIconText??"\xD7"});let rn=Le.closeButtonTooltipText??"Close chat",mo=Le.closeButtonShowTooltip??!0;Ue.setAttribute("aria-label",rn),Ye&&tn({anchor:Ue,trigger:Ye,text:()=>Ue?.getAttribute("aria-label")??rn,enabled:mo})}let{clearChatButton:je,clearChatButtonWrapper:Ne}=De;if(je){let Z=Le.clearChat??{},Ve=Z.enabled??!0,Ye=o.layout?.header?.showClearChat,rt=Ye!==void 0?Ye:Ve,St=Z.placement??"inline";if(Ne){Ne.style.display=rt?"":"none";let{closeButtonWrapper:rn}=De;!Ce()&&rn&&!rn.classList.contains("persona-absolute")&&(rt?rn.classList.remove("persona-ml-auto"):rn.classList.add("persona-ml-auto"));let mo=St==="top-right",Zt=Ne.classList.contains("persona-absolute");if(!Ce()&&mo!==Zt&&rt){if(Ne.remove(),mo){Ne.className="persona-absolute persona-top-4 persona-z-50",Ne.style.right="48px";let Wo=xa??ge;Wo.style.position="relative",Wo.appendChild(Ne)}else{Ne.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ne.style.right="";let Wo=De.closeButtonWrapper;Me&&Wo&&Wo.parentElement===Me?Me.insertBefore(Ne,Wo):Me&&Me.appendChild(Ne)}let en=De.closeButtonWrapper;en&&!en.classList.contains("persona-absolute")&&(mo?en.classList.add("persona-ml-auto"):en.classList.remove("persona-ml-auto"))}}if(rt){if(!Ce()){let en=Z.size??"";je.style.height=en,je.style.width=en,je.style.minWidth=en,je.style.minHeight=en}let rn=Z.iconColor??"";if(je.style.color=rn||yn.actionIconColor,Bd(je,Z.iconName??"refresh-cw",{iconSize:Ce()?Am:void 0}),Z.backgroundColor?(je.style.backgroundColor=Z.backgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let en=Z.borderWidth||"0px",Wo=Z.borderColor||"transparent";je.style.border=`${en} solid ${Wo}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");Z.borderRadius?(je.style.borderRadius=Z.borderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),Z.paddingX?(je.style.paddingLeft=Z.paddingX,je.style.paddingRight=Z.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),Z.paddingY?(je.style.paddingTop=Z.paddingY,je.style.paddingBottom=Z.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let mo=Z.tooltipText??"Clear chat",Zt=Z.showTooltip??!0;je.setAttribute("aria-label",mo),Ne&&tn({anchor:je,trigger:Ne,text:()=>je?.getAttribute("aria-label")??mo,enabled:Zt})}}let ht=o.actionParsers&&o.actionParsers.length?o.actionParsers:[np],ot=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Yi.message,Yi.messageAndClick];He=op({parsers:ht,handlers:ot,getSessionMetadata:ue,updateSessionMetadata:le,emit:A.emit,documentRef:typeof document<"u"?document:null}),ft=mx(o,He,Yt),tA(),k.updateConfig(o),(o.features?.history?.enabled===!0!==fe||o.features?.history?.provider!==Xe||o.getIdentityProof!==dt||o.clientToken!==gt)&&(Tn({restoreFocus:!1}),Fh()),Rr(),vc(),Yn(Te,k.getMessages(),ft),Xs(),oc(),ZS(),ya(k.isStreaming()),Xt!==o.contextMentions&&Dy();let pt=o.voiceRecognition?.enabled===!0,yt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),lr=o.voiceRecognition?.provider?.type==="runtype";if(pt&&(yt||lr))if(!oe||!Rn){let Z=Wi(o);if(Z){oe=Z.button,Rn=Z.wrapper;let Ve=xo&&xo.parentElement===El?xo:null;El?El.insertBefore(Rn,Ve):io?.appendChild(Rn),nt&&(nt.micButton=oe),nt?.addListener(oe,"click",Yu),oe.disabled=k.isStreaming()}}else{let Z=o.voiceRecognition??{},Ve=o.sendButton??{},Ye=Z.iconName??"mic",rt=Z.iconSize,St=parseFloat(rt??"")||fn;oe.classList.add($n),oe.classList.toggle(bo,!rt),oe.style.width=rt??"",oe.style.height=rt??"",oe.style.minWidth=rt??"",oe.style.minHeight=rt??"";let rn=Z.iconColor??Ve.textColor;oe.innerHTML="";let mo=pe(Ye,St,rn||"currentColor",1.5);mo?oe.appendChild(mo):oe.textContent="\u{1F3A4}";let Zt=Z.backgroundColor??Ve.backgroundColor;Zt?oe.style.backgroundColor=Zt:oe.style.backgroundColor="",rn?oe.style.color=rn:oe.style.color="var(--persona-text, #111827)",Z.borderWidth?(oe.style.borderWidth=Z.borderWidth,oe.style.borderStyle="solid"):(oe.style.borderWidth="",oe.style.borderStyle=""),Z.borderColor?oe.style.borderColor=Z.borderColor:oe.style.borderColor="",Z.paddingX?(oe.style.paddingLeft=Z.paddingX,oe.style.paddingRight=Z.paddingX):(oe.style.paddingLeft="",oe.style.paddingRight=""),Z.paddingY?(oe.style.paddingTop=Z.paddingY,oe.style.paddingBottom=Z.paddingY):(oe.style.paddingTop="",oe.style.paddingBottom="");let en=Z.tooltipText??"Start voice recognition",Wo=Z.showTooltip??!1;oe.setAttribute("aria-label",en),Rn&&tn({anchor:oe,trigger:Rn,text:()=>oe?.getAttribute("aria-label")??en,enabled:Wo}),Rn.style.display="",oe.disabled=k.isStreaming()}else oe&&Rn&&(Rn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?k.isVoiceActive()&&k.toggleVoice():Io&&Hr());if(o.attachments?.enabled===!0){if(!xn||!Mt){let Z=o.attachments??{};Sn||(Sn=M("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Sn.style.display="none",(de.parentElement??io).insertBefore(Sn,de)),Ct||(Ct=document.createElement("input"),Ct.type="file",Ct.accept=(Z.allowedTypes??pr).join(","),Ct.multiple=(Z.maxFiles??4)>1,Ct.style.display="none",Ct.setAttribute("aria-label","Attach files"),(de.parentElement??io).insertBefore(Ct,de)),xn=M("div","persona-send-button-wrapper"),Mt=M("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${$n} ${bo}`),Mt.type="button",Mt.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let Ve=Z.buttonIconName??"paperclip";Mt.style.fontSize="18px",Mt.style.lineHeight="1";let Ye=pe(Ve,fn,"currentColor",1.5);Ye?Mt.appendChild(Ye):Mt.textContent="\u{1F4CE}",Mt.addEventListener("click",St=>{St.preventDefault(),Ct?.click()}),xn.appendChild(Mt);let rt=Z.buttonTooltipText??"Attach file";tn({anchor:Mt,trigger:xn,text:()=>Mt?.getAttribute("aria-label")??rt}),wp?wp.append(xn):io.appendChild(xn),nt&&(nt.attachmentButton=Mt,nt.attachmentInput=Ct??void 0,nt.attachmentPreviews=Sn??void 0),!Je&&Ct&&Sn&&(Je=Ii.fromConfig(Z,vf),Je.setPreviewsContainer(Sn),nt?.addListener(Ct,"change",async()=>{Je&&Ct?.files&&(await Je.handleFileSelect(Ct.files),Ct.value="")}))}else{xn.style.display="";let Z=o.attachments??{};Ct&&(Ct.accept=(Z.allowedTypes??pr).join(","),Ct.multiple=(Z.maxFiles??4)>1),Je&&Je.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles,adapter:Z.adapter})}if(ge.querySelector(".persona-attachment-drop-overlay")?.remove(),ge.appendChild(fx(o.attachments?.dropOverlay)),Mt){let Z=o.attachments??{},Ve=Z.buttonTooltipText??"Attach file";Mt.setAttribute("aria-label",Ve),Mt.textContent="";let Ye=pe(Z.buttonIconName??"paperclip",fn,"currentColor",1.5);Ye?Mt.appendChild(Ye):Mt.textContent="\u{1F4CE}",xn&&tn({anchor:Mt,trigger:xn,text:()=>Mt?.getAttribute("aria-label")??Ve})}}else xn&&(xn.style.display="none"),Je&&Je.clearAttachments(),ge.querySelector(".persona-attachment-drop-overlay")?.remove();let bt=o.sendButton??{},Ju=bt.useIcon??!1,Ts=bt.iconText??"\u2191",Bc=bt.iconName,Gy=bt.tooltipText??"Send message",hM=bt.showTooltip??!1,Ba=bt.size,yM=parseFloat(Ba??"")||$g,_c=bt.backgroundColor,_a=bt.textColor;if(Ju){if(Ae.style.width=Ba??"",Ae.style.height=Ba??"",Ae.style.minWidth=Ba??"",Ae.style.minHeight=Ba??"",Ae.style.fontSize="18px",Ae.style.lineHeight="1",_a?Ae.style.color=_a:Ae.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!k.isStreaming())if(Ae.innerHTML="",Bc){let Z=parseFloat(bt.iconSize??"")||Math.round(yM*.5),Ve=_a?.trim()||"currentColor",Ye=bt.iconStrokeWidth??2,rt=pe(Bc,Z,Ve,Ye),St=pe(bt.stopIconName??"square",Z,Ve,Ye);rt&&St?Ae.appendChild(Ug(rt,St)):rt?Ae.appendChild(rt):Ae.textContent=Ts}else Ae.textContent=Ts;Ae.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${$n}`,_c?(Ae.style.backgroundColor=_c,Ae.classList.remove("persona-bg-persona-primary")):(Ae.style.backgroundColor="",Ae.classList.add("persona-bg-persona-primary"))}else Ae.textContent=o.copy?.sendButtonLabel??"Send",Ae.style.width="",Ae.style.height="",Ae.style.minWidth="",Ae.style.minHeight="",Ae.style.fontSize="",Ae.style.lineHeight="",Ae.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",_c?(Ae.style.backgroundColor=_c,Ae.classList.remove("persona-bg-persona-accent")):Ae.classList.add("persona-bg-persona-accent"),_a?Ae.style.color=_a:Ae.classList.add("persona-text-white");bt.borderWidth?(Ae.style.borderWidth=bt.borderWidth,Ae.style.borderStyle="solid"):(Ae.style.borderWidth="",Ae.style.borderStyle=""),bt.borderColor?Ae.style.borderColor=bt.borderColor:Ae.style.borderColor="",bt.paddingX?(Ae.style.paddingLeft=bt.paddingX,Ae.style.paddingRight=bt.paddingX):(Ae.style.paddingLeft="",Ae.style.paddingRight=""),bt.paddingY?(Ae.style.paddingTop=bt.paddingY,Ae.style.paddingBottom=bt.paddingY):(Ae.style.paddingTop="",Ae.style.paddingBottom=""),k.isStreaming()||Ae.setAttribute("aria-label",Gy),tc(),xo&&tn({anchor:Ae,trigger:xo,text:()=>Ae.getAttribute("aria-label")??Gy,enabled:hM}),Wf();let Yy=xd(we.getState().activeModeIds,o.composer?.modes);we.setActiveModeIds(Yy),js().length>0!==!!Vo&&Rp(),Vo?.render(Yy,js());for(let Z of[...qs.keys()])wd(Z,o.composer?.modeGroups)||qs.delete(Z);qs.forEach(Z=>Z.repaint()),Cr?.repaint(),Mo?.resolve();let Dc=jr(o,Ce());if(Np(),Dc){Te.style.maxWidth=Dc,Te.style.marginLeft="auto",Te.style.marginRight="auto",Te.style.width="100%",In.style.maxWidth=Dc,In.style.marginLeft="auto",In.style.marginRight="auto",In.style.width="100%";for(let Z of[io,yr,Sn,st])Z&&(Z.style.maxWidth=Dc,Z.style.marginLeft="auto",Z.style.marginRight="auto",Z.style.width="100%")}else{Te.style.maxWidth="",Te.style.marginLeft="",Te.style.marginRight="",Te.style.width="",In.style.maxWidth="",In.style.marginLeft="",In.style.marginRight="",In.style.width="";for(let Z of[io,yr,Sn,st])Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight="",Z.style.width="")}let Or=o.statusIndicator??{},bM=Or.visible??!0;if(st.style.display=bM?"":"none",k){let Z=k.getStatus();Ml(st,(Ye=>Ye==="idle"?Or.idleText??$t.idle:Ye==="connecting"?Or.connectingText??$t.connecting:Ye==="connected"?Or.connectedText??$t.connected:Ye==="error"?Or.errorText??$t.error:$t[Ye])(Z),Or,Z)}st.classList.remove("persona-text-left","persona-text-center","persona-text-right");let vM=Or.align==="left"?"persona-text-left":Or.align==="center"?"persona-text-center":"persona-text-right";st.classList.add(vM),Ip(),Jp(),ao(),Ut()},open(){Ee()&&ut(!0,"api")},close(){Ee()&&ut(!1,"api")},toggle(){Ee()&&ut(!he,"api")},reconnect(){k.reconnectNow()},clearChat(){Ko=!1,k.clearMessages(),Dt.clear(),Mn();try{localStorage.removeItem(Qi),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Qi}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Qi)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),G?.clear&&Kl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),Y={},He.syncFromMetadata(),Je?.clearAttachments(),Yl(),zs(void 0),Ao(void 0),as(),et?.clear(),Pn?.reset(),X?.update()},setMessage(i){return!de||k.isStreaming()||Pr()?!1:(!he&&Ee()&&ut(!0,"system"),de.value=i,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(k.isStreaming()||ms())return!1;let c=i?.trim()||de.value.trim();return c?(!he&&Ee()&&ut(!0,"system"),de.value="",de.style.height="auto",So(),Lc(c,{consumeDraft:!1}),!0):!1},getComposerState(){return we.getState()},setQuote(i){let c=i?.text?.trim();c&&Ao({...i,text:c})},clearQuote(){Ao(void 0)},startVoiceRecognition(){return k.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(k.isVoiceActive()||(!he&&Ee()&&ut(!0,"system"),ze.manuallyDeactivated=!1,po(),k.toggleVoice().then(()=>{ze.active=k.isVoiceActive(),Xo("user"),k.isVoiceActive()&&bi()})),!0):Io?!0:Sy()?(!he&&Ee()&&ut(!0,"system"),ze.manuallyDeactivated=!1,po(),Rc("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?k.isVoiceActive()?(k.toggleVoice().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,po(),Xo("user"),ir()}),!0):!1:Io?(ze.manuallyDeactivated=!0,po(),Hr("user"),!0):!1},injectMessage(i){return!he&&Ee()&&ut(!0,"system"),k.injectMessage(i)},injectAssistantMessage(i){!he&&Ee()&&ut(!0,"system");let c=k.injectAssistantMessage(i);return Pe&&(Pe=!1,At&&(clearTimeout(At),At=null),setTimeout(()=>{k&&!k.isStreaming()&&k.continueConversation()},100)),c},injectUserMessage(i){return!he&&Ee()&&ut(!0,"system"),k.injectUserMessage(i)},injectSystemMessage(i){return!he&&Ee()&&ut(!0,"system"),k.injectSystemMessage(i)},injectMessageBatch(i){return!he&&Ee()&&ut(!0,"system"),k.injectMessageBatch(i)},injectComponentDirective(i){return!he&&Ee()&&ut(!0,"system"),k.injectComponentDirective(i)},injectTestMessage(i){!he&&Ee()&&ut(!0,"system"),k.injectTestEvent(i)},async connectStream(i,c){return k.connectStream(i,c)},__pushEventStreamEvent(i){an&&(re(),te(i.type,i.payload))},showEventStream(){an&&Lp()},hideEventStream(){v&&Vs()},isEventStreamVisible(){return v},listConversations(i){return k.listConversations(i)},getActiveConversationId(){return k.getActiveConversationId()},openConversation(i,c){return Wu(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return Ou({focusComposer:i?.focus===!0})},deleteConversation(i){return uy(i)},renameConversation(i,c){return Bu(i,{title:c})},setConversationStarred(i,c){return Bu(i,{starred:c})},clearConversationHistory(i){return gy(i)},resetHistoryIdentity(){return my()},getHistoryIdentityStatus(){return _n?_n.getIdentityStatus():yu()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return Pa({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){Tn(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return ie},showArtifacts(){vn(o)&&(Ko=!1,Gs=!0,co(),qe?.setMobileOpen(!0))},hideArtifacts(){vn(o)&&(Ko=!0,co())},upsertArtifact(i){return vn(o)?(cr(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Ko=!1,Gs=!0),k.upsertArtifact(i)):null},selectArtifact(i){vn(o)&&k.selectArtifact(i)},clearArtifacts(){vn(o)&&k.clearArtifacts()},getArtifacts(){return k?.getArtifacts()??[]},getSelectedArtifactId(){return k?.getSelectedArtifactId()??null},focusInput(){return ve&&!he&&!Ce()||!de?!1:(de.focus(),!0)},async resolveApproval(i,c,g){let b=k.getMessages().find(w=>w.variant==="approval"&&w.approval?.id===i);if(!b?.approval)throw new Error(`Approval not found: ${i}`);if(b.approval.toolType==="webmcp"){k.resolveWebMcpApproval(b.id,c);return}return k.resolveApproval(b.approval,c,g)},setFollowUpSuggestions(i){AS(i)},clearFollowUpSuggestions(){lh()},getMessages(){return k.getMessages()},getStatus(){return k.getStatus()},getPersistentMetadata(){return{...Y}},updatePersistentMetadata(i){le(i)},on(i,c){return A.on(i,c)},off(i,c){A.off(i,c)},isOpen(){return Ee()&&he},isVoiceActive(){return ze.active},toggleReadAloud(i){k.toggleReadAloud(i)},stopReadAloud(){k.stopSpeaking()},getReadAloudState(i){return k.getReadAloudState(i)},onReadAloudChange(i){return k.onReadAloudChange(i)},getState(){return{open:Ee()&&he,launcherEnabled:ve,voiceActive:ze.active,streaming:k.isStreaming()}},showCSATFeedback(i){!he&&Ee()&&ut(!0,"system");let c=Te.querySelector(".persona-feedback-container");c&&c.remove();let g=Qm({onSubmit:async(f,b)=>{k.isClientTokenMode()&&await k.submitCSATFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});Te.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!he&&Ee()&&ut(!0,"system");let c=Te.querySelector(".persona-feedback-container");c&&c.remove();let g=Xm({onSubmit:async(f,b)=>{k.isClientTokenMode()&&await k.submitNPSFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});Te.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,c){return k.submitCSATFeedback(i,c)},async submitNPSFeedback(i,c){return k.submitNPSFeedback(i,c)},destroy(){du(),ys!=null&&(clearInterval(ys),ys=null),ye.forEach(i=>i()),Ke.remove(),Qt?.remove(),Lt?.destroy(),gn?.remove(),os&&Ue.removeEventListener("click",os)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:It,getMessages:It.getMessages,getStatus:It.getStatus,getMetadata:It.getPersistentMetadata,updateMetadata:It.updatePersistentMetadata,clearHistory:()=>It.clearChat(),setVoiceActive:g=>g?It.startVoiceRecognition():It.stopVoiceRecognition()};window.AgentWidgetBrowser=c,ye.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),c=V=>{let J=V.detail;(!J?.instanceId||J.instanceId===i)&&It.focusInput()};if(window.addEventListener("persona:focusInput",c),ye.push(()=>{window.removeEventListener("persona:focusInput",c)}),an){let V=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===i)&&It.showEventStream()},J=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===i)&&It.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",J),ye.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",J)})}let g=V=>{let J=V.detail;(!J?.instanceId||J.instanceId===i)&&It.showHistory()},f=V=>{let J=V.detail;(!J?.instanceId||J.instanceId===i)&&It.hideHistory()};window.addEventListener("persona:showHistory",g),window.addEventListener("persona:hideHistory",f),ye.push(()=>{window.removeEventListener("persona:showHistory",g),window.removeEventListener("persona:hideHistory",f)});let b=V=>{let J=V.detail;(!J?.instanceId||J.instanceId===i)&&It.showArtifacts()},w=V=>{let J=V.detail;(!J?.instanceId||J.instanceId===i)&&It.hideArtifacts()},W=V=>{let J=V.detail;J?.instanceId&&J.instanceId!==i||J?.artifact&&It.upsertArtifact(J.artifact)},z=V=>{let J=V.detail;J?.instanceId&&J.instanceId!==i||typeof J?.id=="string"&&It.selectArtifact(J.id)},q=V=>{let J=V.detail;(!J?.instanceId||J.instanceId===i)&&It.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",w),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",z),window.addEventListener("persona:clearArtifacts",q),ye.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",w),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",z),window.removeEventListener("persona:clearArtifacts",q)})}let eo=WI(o.persistState);if(eo&&Ee()){let i=OI(eo.storage),c=`${eo.keyPrefix}widget-open`,g=`${eo.keyPrefix}widget-voice`,f=`${eo.keyPrefix}widget-voice-mode`;if(i){let b=eo.persist?.openState&&i.getItem(c)==="true",w=eo.persist?.voiceState&&i.getItem(g)==="true",W=eo.persist?.voiceState&&i.getItem(f)==="true";if(b&&(Lt?.setPanelOpen(!0,"auto"),setTimeout(()=>{It.open(),setTimeout(()=>{if(w||W)It.startVoiceRecognition();else if(eo.persist?.focusInput){let z=e.querySelector("textarea");z&&z.focus()}},100)},0)),eo.persist?.openState&&(A.on("widget:opened",()=>{i.setItem(c,"true")}),A.on("widget:closed",()=>{i.setItem(c,"false")})),eo.persist?.voiceState&&(A.on("voice:state",z=>{i.setItem(g,z.active?"true":"false")}),A.on("user:message",z=>{i.setItem(f,z.viaVoice?"true":"false")})),eo.clearOnChatClear){let z=()=>{i.removeItem(c),i.removeItem(g),i.removeItem(f)},q=()=>z();window.addEventListener("persona:clear-chat",q),ye.push(()=>{window.removeEventListener("persona:clear-chat",q)})}}}if(ee&&Ee()&&(Lt?.setPanelOpen(!0,"auto"),setTimeout(()=>{It.open()},0)),ri(),!MS){let i=Na(()=>{k&&(ls++,Dt.clear(),Yn(Te,k.getMessages(),ft))});ye.push(i)}S=()=>{k&&(ls++,Dt.clear(),Yn(Te,k.getMessages(),ft))},k.getMessages().length>0&&ec(),T=()=>{k&&(ls++,Dt.clear(),Yn(Te,k.getMessages(),ft))};let mM=nb(()=>{k&&(ls++,Dt.clear(),Yn(Te,k.getMessages(),ft))});ye.push(mM);let fM=Om(()=>{k&&(ls++,Dt.clear(),Yn(Te,k.getMessages(),ft),ur()?.updateInlineArtifactBlocks(Te,Gn.artifacts,{suppressTransition:!0}),co())});return ye.push(fM),It};var hx=(e,t)=>{let n=e.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,t*parseFloat(r[1])/100):420},DI=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},NI=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},FI=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.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."+(t.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 ${t.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.")},yx=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},of=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},bx=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",of(e)},ef=e=>{e.style.transition=""},tf=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},nf=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ap=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},$I=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},UI=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},jI=e=>{let t=Os(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:hn(t,r)??r;return{inset:o(n?.inset,Sd),canvasBackground:o(n?.canvasBackground,Ad)}},vx=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},qI=(e,t,n,o,r,s,a,l)=>{let d=Un(s),p=d.reveal==="push",u=l!=null,m=l?.inset??"",y=l?.canvasBackground??"";$I(e,t,n,o,p),UI(e,t,n,o,d.side,p),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=d.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",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 h=e.ownerDocument.defaultView,C=s?.launcher?.mobileFullscreen??!0,S=s?.launcher?.mobileBreakpoint??640,x=h!=null?h.innerWidth<=S:!1;if(C&&x&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),tf(t),ef(o),bx(o),nf(n),ap(r,o),vx(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.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??sn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),bx(o),DI(o,d.maxHeight),vx(o,u&&a,m,y),d.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",tf(t),ef(o),nf(n),ap(r,o);let O=d.animate?"transform 180ms ease":"none",$=d.side==="right"?"translateX(100%)":"translateX(-100%)",T=a?"translateX(0)":$;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=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=O,o.style.transform=T,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ef(o),of(o),ap(r,o);let O=hx(d.width,e.clientWidth),$=Math.max(0,e.clientWidth),T=d.animate?"margin-left 180ms ease":"none",R=d.side==="right"?a?-O:0:a?0:-O;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${$+O}px`,t.style.transition=T,t.style.marginLeft=`${R}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${$}px`,n.style.maxWidth=`${$}px`,n.style.minWidth=`${$}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",tf(t),of(o),nf(n),ap(r,o);let O=d.reveal==="emerge";O?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let $=a?d.width:"0px",T=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",R=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${$}`,o.style.width=$,o.style.maxWidth=$,o.style.minWidth=$,o.style.minHeight="0",NI(o,d.maxHeight),o.style.overflow=O||R?"hidden":"visible",o.style.transition=T,O){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let A=u?`calc(${hx(d.width,e.clientWidth)}px - (2 * ${m}))`:d.width;r.style.width=A,r.style.minWidth=A,r.style.maxWidth=A,r.style.boxSizing="border-box"}}},zI=(e,t)=>{let n=e.ownerDocument.createElement("div");return yx(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){yx(n,o)},destroy(){n.remove()}}},VI=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.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=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),p=n.createElement("aside"),u=n.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",p.appendChild(u),o.insertBefore(a,e),d.appendChild(e);let y=null,h=()=>{y?.disconnect(),y=null},C=null,S=()=>{C=t?.launcher?.detachedPanel===!0?jI(t):null};S();let x=()=>{qI(a,l,d,p,u,t,m,C)},P=null,O=()=>{P?.(),P=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(P=sl(()=>{S(),x()}))},$=()=>{h(),Un(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{x()}),y.observe(a)))},T=!1,R=()=>{x(),$(),m&&!T&&a.dataset.personaDockMobileFullscreen!=="true"&&(T=!0,FI(a,Un(t)))},A=a.ownerDocument.defaultView,N=()=>{R()};return A?.addEventListener("resize",N),Un(t).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),R(),O(),{mode:"docked",host:u,shell:a,syncWidgetState(G){let ae=G.launcherEnabled?G.open:!0;m!==ae&&(m=ae,R())},updateConfig(G){t=G,(t?.launcher?.enabled??!0)===!1&&(m=!0),S(),R(),O()},destroy(){A?.removeEventListener("resize",N),P?.(),P=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},lp=(e,t)=>Tt(t)?VI(e,t):zI(e,t);var KI=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Cx=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},cp=[],GI=()=>[...cp],wx=e=>{let t=KI(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=lp(t,r),a,l=[],d=(x,P)=>{let $=!(P?.launcher?.enabled??!0)||Tt(P),T=o.createElement("div");if(T.setAttribute("data-persona-root","true"),$&&(T.style.height="100%",T.style.display="flex",T.style.flexDirection="column",T.style.flex="1",T.style.minHeight="0",T.style.minWidth="0"),n){let R=x.attachShadow({mode:"open"});R.appendChild(T),Cx(R,o)}else x.appendChild(T),Cx(x,o);return t.id&&T.setAttribute("data-persona-instance",t.id),T},p=()=>{s.syncWidgetState(a.getState())},u=()=>{l.forEach(x=>x()),l=[a.on("widget:opened",p),a.on("widget:closed",p)],p()},m=()=>{let x=d(s.host,r);a=Zm(x,r,{debugTools:e.debugTools}),u()},y=()=>{l.forEach(x=>x()),l=[],a.destroy()};m(),e.onChatReady?.();let h=x=>{y(),s.destroy(),s=lp(t,x),r=x,m()},C={update(x){let P=tp(r??{},x),O=Tt(r),$=Tt(P),T=zr(r),R=zr(P);if(O!==$||T!==R){h(P);return}r=P,s.updateConfig(r),a.update(x),p()},destroy(){y(),s.destroy();let x=cp.indexOf(S);x!==-1&&cp.splice(x,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},S=new Proxy(C,{get(x,P,O){if(P==="host")return s.host;if(P in x)return Reflect.get(x,P,O);let $=a[P];return typeof $=="function"?$.bind(a):$}});return cp.push(S),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=S),S};var Ex=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),YI=new Set(["button","a","input","select","textarea","details","summary"]),QI=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),rf=/\b(product|card|item|listing|result)\b/i,af=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,XI=3e3,JI=100;function Tx(e){let t=typeof e.className=="string"?e.className:"";if(rf.test(t)||e.id&&rf.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&rf.test(o.value))return!0}return!1}function kx(e){return af.test((e.textContent??"").trim())}function Px(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function ZI(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function xx(e){let t=e.match(af);return t?t[0]:null}function Sx(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function eR(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var tR="commerce-card",nR="result-card";function Ax(e){return!Tx(e)||!kx(e)||!Px(e)&&!ZI(e)?0:5200}function Mx(e){return!Tx(e)||kx(e)||!Px(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Lx=[{id:tR,scoreElement(e){return Ax(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||af.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Ax(e)===0)return null;let{title:n,href:o}=Sx(e),r=xx((e.textContent??"").trim())??xx(t.text)??"",s=eR(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
138
- `)}},{id:nR,scoreElement(e){return Mx(e)},formatSummary(e,t){if(Mx(e)===0)return null;let{title:n,href:o}=Sx(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
139
- `)}}];function oR(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function rR(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,l=t.mode??"structured",d=t.maxCandidates??Math.max(500,n*10),p=e.rules??Lx;return l==="simple"&&e.rules&&e.rules.length>0?(oR(),p=[]):l==="simple"&&(p=[]),{mode:l,maxElements:n,maxCandidates:d,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:p}}function sf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var sR=["data-testid","data-product","data-action","data-id","data-name","data-type"];function iR(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||YI.has(t)||n&&QI.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Ix(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function aR(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let l=e.getAttribute("name");l&&(t.name=l);let d=e.getAttribute("role");d&&(t.role=d);for(let p=0;p<e.attributes.length;p++){let u=e.attributes[p];u.name.startsWith("data-")&&(t[u.name]=u.value)}return t}function Rx(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${sf(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of sR){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${sf(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(a=>sf(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let l=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(l>=0){let d=`${r}:nth-of-type(${l+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function lR(e){return e==="static"?JI:XI}function Hx(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Rx(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:iR(e),attributes:aR(e)}}function cR(e,t,n,o){let r=lR(t.interactivity),s=null;for(let a of n){let l=a.scoreElement(e,t,o);l>0&&(r+=l,a.formatSummary&&!s&&(s=a))}return{score:r,formattingRule:s}}function dR(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function pR(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=a.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let p=l,u=p.tagName.toLowerCase();if(Ex.has(u)){l=a.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){l=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Ix(p)){l=a.nextNode();continue}let m=Hx(p,e.maxTextLength),y=m.text.length>0,h=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(x=>x==="role");if(!y&&!h){l=a.nextNode();continue}if(o.has(m.selector)){l=a.nextNode();continue}o.add(m.selector);let{score:C,formattingRule:S}=cR(p,m,e.rules,n);r.push({el:p,domIndex:s,enriched:m,score:C,formattingRule:S}),s+=1}l=a.nextNode()}r.sort((p,u)=>{let m=p.enriched.interactivity==="static"?1:0,y=u.enriched.interactivity==="static"?1:0;return m!==y?m-y:u.score!==p.score?u.score-p.score:p.domIndex-u.domIndex});let d=[];for(let p of r){if(d.length>=e.maxElements)break;dR(d,p)||d.push(p)}return d.sort((p,u)=>{let m=p.enriched.interactivity==="static"?1:0,y=u.enriched.interactivity==="static"?1:0;return m!==y?m-y:m===1&&u.score!==p.score?u.score-p.score:p.domIndex-u.domIndex}),d.map(p=>{let u;if(p.formattingRule?.formatSummary){let y=p.formattingRule.formatSummary(p.el,p.enriched,n);y&&(u=y)}let m={...p.enriched};return u&&(m.formattedSummary=u),m})}function uR(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,p=d.tagName.toLowerCase();if(Ex.has(p)){s=r.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Ix(d)){s=r.nextNode();continue}let u=Hx(d,e.maxTextLength),m=u.text.length>0,y=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(h=>h==="role");if(!m&&!y){s=r.nextNode();continue}o.has(u.selector)||(o.add(u.selector),n.push(u))}s=r.nextNode()}let a=[],l=[];for(let d of n)d.interactivity!=="static"?a.push(d):l.push(d);return[...a,...l].slice(0,e.maxElements)}function gR(e={}){let t=rR(e),n=t.root??document.body;return n?t.mode==="simple"?uR(t,n):pR(t,n):[]}var dp=100;function mR(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);s.length>0&&o.push(`Structured summaries:
136
+ ${Ae?"background: transparent !important;":""}
137
+ `)}if(!f&&!i){let De="max-height: -moz-available !important; max-height: stretch !important;",we=c?"":"padding-top: 1.25em !important;",dn=c?"":`z-index: ${o.launcher?.zIndex??rn} !important;`;Ge.style.cssText+=De+we+dn}Mp(),Lt()},Np=()=>{e.style.setProperty("--persona-content-max-width",Dr(o,be()))},Yf=!1,Qf=()=>{let i=nm(o,be());be()&&o.composer?.placement&&o.debug===!0&&!Yf&&(Yf=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=Bo(o);e.setAttribute("data-persona-composer-placement",i),e.setAttribute("data-persona-conversation-state",Tl),e.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",c.composerGap??Ad),kl()},Xf=()=>{if(be())return;let i=St(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!ce)return;let f=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,C=o.launcher?.mobileBreakpoint??640;if(b&&f.innerWidth<=C)return;let W=f.innerHeight,U=64,$=o.launcher?.heightOffset??0,j=Math.max(200,W-U),Q=Math.min(640,j);Se.style.height=`${Math.max(200,Q-$)}px`};Dp(),ki(e,o),yl(e,o),bl(e,o),Np(),Qf(),Kr=()=>{Dp(),Xf(),ki(e,o),yl(e,o),bl(e,o),Np(),Qf(),Rl?e.style.setProperty("--persona-artifact-welded-outer-radius",Rl):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Fo(),bp()};let me=[];me.push(()=>{jf=!0}),me.push(()=>{d.forEach(i=>i()),l.destroy()}),me.push(()=>{document.removeEventListener("keydown",Vf)}),me.push(()=>{Qi!==null&&clearTimeout(Qi)});let So=null,Ao=null;me.push(()=>{So?.(),So=null,Ao?.(),Ao=null}),Zi&&me.push(()=>{Zi?.disconnect(),Zi=null}),me.push(()=>{na?.(),na=null,_p(),vt&&(vt.remove(),vt=null),qe?.element.style.removeProperty("width"),qe?.element.style.removeProperty("maxWidth"),qe?.destroy()}),S&&me.push(()=>{je=!0,Ke=null,Ht!==null&&(cancelAnimationFrame(Ht),Ht=null),ht?.destroy(),ht=null,He?.destroy(),He=null,Te=null});let Yr=null,Jf=()=>{Yr&&(Yr(),Yr=null),o.colorScheme==="auto"&&(Yr=nl(()=>{ki(e,o)}))};Jf(),me.push(()=>{Yr&&(Yr(),Yr=null)}),me.push(()=>{v=!0,h?.()}),me.push(()=>{O=!0});let Zf=!1;me.push(()=>{Zf=!0});let Fp=(i,c)=>{let g=al(i,c);return g||!ew.includes(i)?g:(nw().then(f=>{if(Zf)return;Ld(f.wipe),Ld(f.glyphCycle);let b=al(i,c);b&&dl(b,e)}).catch(()=>{}),null)},Fl=o.features?.streamAnimation;if(Fl?.type&&Fl.type!=="none"){let i=Fp(Fl.type,Fl.plugins);i&&dl(i,e),me.push(()=>tw(e))}let qo=gl(ur),eh=gl(Cp),th=gl(Vi),Qr=[qo,eh,th];me.push(()=>{Qr.forEach(i=>i.destroy())});let Xr=null,P,Jr=null,nh=!1,oh=0,rh=null,sh=i=>i.reduce((c,g)=>g.role==="user"?c+1:c,0),ih=i=>{for(let c=i.length-1;c>=0;c--)if(Ci(i[c]))return i[c].id??null;return null},ah=!1,TS=()=>{ah||o.debug!==!0||(ah=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},lh=!1,ch=!1,dh=(i,c)=>{lh||o.debug!==!0||!c.enabled||c.expose||nh||ch&&(P.isStreaming()||i.some(Ci)||(lh=!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.")))},zs=i=>{if(!P)return;let c=i??P.getMessages(),g=j=>{j.render([],P,ae,c)},f=j=>{Qr.forEach(Q=>{Q!==j&&g(Q)})};Jr&&(sh(c)>oh||ih(c)!==rh)&&(Jr=null);let b=Br(o);dh(c,b);let C=b.enabled?gg(c):null,W=Jr??C,U=Jr?"host":"agent";if(W){let j=o.suggestions?.followUps,Q=j?.placement??(j?"auto":"composer"),ue=(Q==="auto"?be()?"composer":"after-message":Q)==="after-message"?th:qo;f(ue),ue.render(W,P,ae,c,o.suggestionChipsConfig,{source:U,surface:"followUp",variant:j?.variant??"chip",behavior:j?.behavior??"send",overflow:j?.overflow??"wrap",maxItems:j?.maxItems??4,config:o,plugins:a,submitPrompt:Tc});return}if(c.some(j=>j.role==="user")){Qr.forEach(g);return}let $=o.suggestions?.starters;if($){let j=Is(Bo(o),c),Q=$.placement??"auto",oe=Q==="auto"?j?"welcome":"composer":Q;if(oe==="welcome"&&!j){TS(),Qr.forEach(g);return}let ue=oe==="welcome"?eh:qo;f(ue),ue.render($.items??o.suggestionChips,P,ae,c,o.suggestionChipsConfig,{surface:"starter",variant:$.variant??"card",behavior:$.behavior??"send",overflow:$.overflow??"wrap",maxItems:$.maxItems??4,config:o,plugins:a,submitPrompt:Tc});return}f(qo),qo.render(o.suggestionChips,P,ae,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a,submitPrompt:Tc})},ph=()=>{Jr&&(Jr=null,zs())},PS=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){ph();return}let g=P?P.getMessages():[];Jr=c,nh=!0,oh=sh(g),rh=ih(g),zs(g)},_n=!1,Nt=UC(),Vs=new Map,Zr=new Map,br=new Map,es=null,vr=null;function ts(){if(!es)return;let i=es;es=null,vr?.destroy(),vr=null,Nt.delete(i),de.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),P&&Yn(Pe,P.getMessages(),ut)}let ns=0,kS=Io()!==null,Dn=KC(),Nn=0,Cr=null,An=!1,$l=!1,wr=0,zt=null,os=null,$p=!1,Ks=!1,rs=null,oa=!0,Ul=!1,Gs=null,jl=!1,ss=()=>{jl=!0,HS()},Up=null,LS=4,zo=24,IS=80,RS=1e3,Vo=null,uh=()=>{e.setAttribute("data-persona-scrollbar",xp()),xp()!=="on-scroll"&&(Vo!==null&&clearTimeout(Vo),Vo=null,te.removeAttribute("data-persona-scrollbar-visible"))},HS=()=>{xp()==="on-scroll"&&(te.setAttribute("data-persona-scrollbar-visible",""),Vo!==null&&clearTimeout(Vo),Vo=setTimeout(()=>{Vo=null,ks(te,zo)&&te.removeAttribute("data-persona-scrollbar-visible")},RS))};uh(),me.push(()=>{Vo!==null&&clearTimeout(Vo)});let jp=new Map,ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Bf=()=>ze.active,ro();let gh=o.voiceRecognition?.autoResume??!1,Ko=i=>{A.emit("voice:state",{active:ze.active,source:i,timestamp:Date.now()})},ao=()=>{se(i=>({...i,voiceState:{active:ze.active,timestamp:Date.now(),manuallyDeactivated:ze.manuallyDeactivated}}))},WS=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Jm(Z.voiceState),c=!!i.active,g=Number(i.timestamp??0);ze.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-g<WI&&setTimeout(()=>{ze.active||(ze.manuallyDeactivated=!1,In(o.voiceRecognition?.provider)?P.toggleVoice().then(()=>{ze.active=P.isVoiceActive(),Ko("restore"),P.isVoiceActive()&&ui()}):Lc("restore"))},1e3)},OS=()=>P?hx(P.getMessages()).filter(i=>!i.__skipPersist):[],ql=null,mh=(i,c)=>{typeof console<"u"&&console.error(i,c)},zl=(i,c)=>{let g=()=>{try{let W=i();return!W||typeof W.then!="function"?null:Promise.resolve(W).catch(U=>{mh(c,U)})}catch(W){return mh(c,W),null}},f=ql,b=f?f.then(()=>g()??void 0):g();if(!b)return;let C=b.finally(()=>{ql===C&&(ql=null)});ql=C};function Ys(i){if(!K?.save)return;let c=i?hx(i):P?OS():[],g=ie&&P?.getResumableHandle();g&&(Z={...Z,durableResume:{executionId:g.executionId,after:g.lastEventId}});let f={messages:c,metadata:Z,artifacts:Gn.artifacts,selectedArtifactId:Gn.selectedId,...is?{draft:is}:{}};zl(()=>K.save(f),"[AgentWidget] Failed to persist state:")}let is,Vl=()=>!K?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,ra=gC({write:()=>{if(!Vl())return;let i=Ce.getState(),c=pC({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Nu(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(is)&&(is=c,Ys())}});function fh(){Vl()&&ra.schedule()}function qp(){ra.flush()}function hh(i){if(!Vl())return;let c=uC(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(g=>g.id),modelIds:(o.composer?.models??[]).map(g=>g.id),modes:o.composer?.modes??[]});c&&(is=i,ae&&!ae.value&&(ae.value=c.text,ae.dispatchEvent(new Event("input",{bubbles:!0})),vo()),c.selectedModelId&&(Ce.setSelectedModelId(c.selectedModelId),fr?.repaint()),Ll(c.activeModeIds??[]),c.quote&&Co(c.quote),ra.cancel())}function Kl(){ra.cancel(),is&&(is=void 0,Vl()&&Ys())}let Qs=null,yh=()=>Ge.querySelector("#persona-scroll-container")||te,Xs=()=>{Qs!==null&&(cancelAnimationFrame(Qs),Qs=null),An=!1},bh=()=>{Cr!==null&&(cancelAnimationFrame(Cr),Cr=null),$l=!1,Xs()},BS=()=>_n&&Vp()&&(Bn()!=="anchor-top"||vf()),zp=()=>{let i=Ki()||"Jump to latest",c=BS();Dt.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),wr>0?(qr.textContent=String(wr),qr.style.display="",Dt.setAttribute("aria-label",`${i} (${wr} new)`)):(qr.textContent="",qr.style.display="none",Dt.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},vh=()=>{wr!==0&&(wr=0,zp())},_S=()=>{let i=zt?.spacerHeight??0;return i<=0?ks(te,zo):Xl(i)-te.scrollTop-te.clientHeight<=zo},Vp=()=>mr()?!Dn.isFollowing():!_S(),Kp=()=>!!P&&P.getMessages().length>0,Vt=()=>{if(!pS()||oS()){Dt.parentNode&&Dt.remove(),Dt.style.display="none";return}Dt.parentNode!==de&&de.appendChild(Dt),zr();let c=Oo(te)>0&&Vp()&&Kp();c?zp():vh(),Dt.style.display=c?"":"none"},sa=()=>{Dn.pause()&&(bh(),Vt())},Mn=()=>{Dn.resume(),vh(),Vt()},xr=(i=!1)=>{mr()&&Kp()&&Dn.isFollowing()&&(!i&&!_n||(Cr!==null&&(cancelAnimationFrame(Cr),Cr=null),$l=!0,Cr=requestAnimationFrame(()=>{Cr=null,$l=!1,Dn.isFollowing()&&DS(yh(),i?220:140)})))},Ch=(i,c,g,f=()=>!0)=>{let b=i.scrollTop,C=c(),W=C-b;if(Xs(),Math.abs(W)<1){An=!0,i.scrollTop=C,Nn=i.scrollTop,An=!1;return}let U=performance.now();An=!0;let $=Q=>1-Math.pow(1-Q,3),j=Q=>{if(!f()){Xs();return}let oe=c();oe!==C&&(C=oe,W=C-b);let ue=Q-U,Xe=Math.min(ue/g,1),dt=$(Xe),mt=b+W*dt;i.scrollTop=mt,Nn=i.scrollTop,Xe<1?Qs=requestAnimationFrame(j):(i.scrollTop=C,Nn=i.scrollTop,Qs=null,An=!1)};Qs=requestAnimationFrame(j)},DS=(i,c=500)=>{let g=Oo(i)-i.scrollTop;if(Math.abs(g)<1){Nn=i.scrollTop;return}if(Math.abs(g)>=IS){Xs(),An=!0,i.scrollTop=Oo(i),Nn=i.scrollTop,An=!1;return}Ch(i,()=>Oo(i),c,()=>Dn.isFollowing())},Gl=()=>{if(!Kp()){Vt();return}let i=yh();An=!0,i.scrollTop=Oo(i),Nn=i.scrollTop,An=!1,Vt()},as=i=>{let c=0,g=i;for(;g&&g!==te;)c+=g.offsetTop,g=g.offsetParent;return c},NS=()=>{let i=te.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??te.ownerDocument.getSelection()},Yl=()=>QC(NS(),te),Gp=()=>{if(uS()!=="last-user-turn")return!1;let i=P?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(C=>C.role==="user");if(!c)return!1;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=te.querySelector(`[data-message-id="${g}"]`);if(!f)return!1;let b=Math.min(Math.max(0,as(f)-Gi()),Oo(te));return An=!0,te.scrollTop=b,Nn=te.scrollTop,An=!1,Bn()==="follow"&&!ks(te,zo)&&Dn.pause(),Vt(),!0},Ql=i=>{let c=Math.max(0,Math.round(i));Kn.style.height=`${c}px`,Kn.style.display=c>0?"":"none",zt&&(zt.spacerHeight=Math.max(0,i))},Xl=i=>{let c=parseFloat(getComputedStyle(te).paddingBottom)||0,g=0;for(let b of Array.from(te.children)){if(b===Kn||b.offsetHeight===0)continue;let C=as(b)+b.offsetHeight;C>g&&(g=C)}let f=te.scrollHeight-i;return g>0?Math.min(g+c,f):f},FS=()=>{if(!zt||zt.spacerHeight<=0)return;let i=Xl(zt.spacerHeight),c=Math.max(0,Math.round(te.scrollTop)+te.clientHeight-i+zo);c<zt.spacerHeight&&(Ql(c),Vt())},lo=()=>{os!==null&&(cancelAnimationFrame(os),os=null),Xs(),zt=null,Kn.style.height="0px",Kn.style.display="none"},wh=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Yp=i=>te.querySelector(`[data-message-id="${wh(i)}"]`),xh=i=>{os!==null&&cancelAnimationFrame(os),os=requestAnimationFrame(()=>{os=null;let c=wh(i),g=te.querySelector(`[data-message-id="${c}"]`);if(!g)return;let f=as(g),b=zt?.spacerHeight??0,C=Xl(b),{targetScrollTop:W,spacerHeight:U}=sm({anchorOffsetTop:f,topOffset:Gi(),viewportHeight:te.clientHeight,contentHeight:C,slack:zo});zt={initialSpacerHeight:U,contentHeightAtAnchor:C,spacerHeight:U},Ql(U),Ch(te,()=>g.isConnected?Math.max(0,as(g)-Gi()):W,220)})},En=()=>{if(Bn()!=="anchor-top"||!zt||!Gs)return;let i=Yp(Gs);if(!i)return;Xs();let c=zt.spacerHeight,g=Xl(c),{targetScrollTop:f,spacerHeight:b}=sm({anchorOffsetTop:as(i),topOffset:Gi(),viewportHeight:te.clientHeight,contentHeight:g,slack:zo});zt={initialSpacerHeight:b,contentHeightAtAnchor:g,spacerHeight:b},Ql(b),An=!0,te.scrollTop=f,Nn=te.scrollTop,An=!1,Vt()},$S=()=>{if(mr()){if(!Dn.isFollowing()||ks(te,1))return;xr(!_n);return}if(zt&&zt.initialSpacerHeight>0){let i=te.scrollHeight-zt.spacerHeight,c=XC({initialSpacerHeight:zt.initialSpacerHeight,contentHeightAtAnchor:zt.contentHeightAtAnchor,currentContentHeight:i});c!==zt.spacerHeight&&Ql(c)}Vt()},US=i=>{let c=Bn();c==="follow"?(Mn(),xr(!0)):c==="anchor-top"&&(oa=!1,Ul=!0,jl=!1,Gs=i,xh(i))},jS=()=>{if(Bn()==="anchor-top"){if(Ul){oa=!1;return}oa=!0,lo(),Mn(),xr(!0)}},qS=96,zS=i=>{if(rs===null)return!0;let c=Yp(rs),g=Yp(i);if(!c||!g)return!0;let f=as(g)-as(c);return Gi()+f>te.clientHeight-qS},VS=i=>{if(Bn()!=="anchor-top"||!Ul||jl||Yl())return;let c=rs===null;for(let g of i){if(!c){g.id===rs&&(c=!0);continue}if(VC(g)){if(g.id===Gs||!zS(g.id))return;Gs=g.id,xh(g.id);return}}},KS=i=>{let c=new Map;i.forEach(g=>{let f=jp.get(g.id);c.set(g.id,{streaming:g.streaming,role:g.role}),!f&&g.role==="assistant"&&(A.emit("assistant:message",g),!Ks&&(Bn()!=="anchor-top"||vf())&&Vp()&&(wr+=1,zp(),Vt(),El(wr===1?"1 new message below.":`${wr} new messages below.`))),g.role==="assistant"&&f?.streaming&&g.streaming===!1&&A.emit("assistant:complete",g),g.variant==="approval"&&g.approval&&(f?g.approval.status!=="pending"&&A.emit("approval:resolved",{approval:g.approval,decision:g.approval.status}):A.emit("approval:requested",{approval:g.approval,message:g}))}),jp.clear(),c.forEach((g,f)=>{jp.set(f,g)})},ia=(i,c)=>{let g=c==="user"?"user":"assistant",f=o.layout?.messages?.[g],b=f?.width??"content",C=f?.maxWidth??(b==="full"?"100%":void 0);i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${c}`,`persona-message-width-${b}`),i.classList.toggle("persona-justify-end",c==="user"),i.setAttribute("data-message-role",c),i.setAttribute("data-message-width",b),C?i.style.setProperty("--persona-message-row-max-width",C):i.style.removeProperty("--persona-message-row-max-width")},Go=(i,c)=>{let g=document.createElement("div");return g.className="persona-flex",g.id=`wrapper-${i}`,g.setAttribute("data-wrapper-id",i),ia(g,c),g},GS=(i,c,g)=>{let f=document.createElement("div"),C=(()=>{let L=a.find($e=>$e.renderLoadingIndicator);if(L?.renderLoadingIndicator)return L.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),W=(L,$e)=>$e==null?!1:typeof $e=="string"?(L.textContent=$e,!0):(L.appendChild($e),!0),U=new Set,$=new Map,j=new Set,Q=a.some(L=>L.renderAskUserQuestion),oe=[],ue=[],Xe=o.enableComponentStreaming!==!1,dt=o.approval!==!1,mt=[],Qt=o.messageActions,$t=Qt?.showRegenerate===!0&&Qt.enabled!==!1&&ct.current?.isStreaming()!==!0?Cv(c):null,Pt=Qt?.showEdit===!0&&Qt.enabled!==!1,an=Qt?.showQuote===!0&&Qt.enabled!==!1,et=null,ln=o.features?.reasoningDisplay?.completedVisibility,ko=L=>ln==="removed"?!0:ln==="removed-when-short"?Jb(L,o.features?.reasoningDisplay?.shortThinkThreshold):!1,or=o.features?.toolCallDisplay?.completedVisibility==="removed",co=L=>L.variant==="reasoning"&&L.reasoning?.status==="complete"?ko(L.reasoning):or&&L.variant==="tool"&&L.toolCall?.status==="complete";if(c.forEach(L=>{if(co(L))return;if(U.add(L.id),$.set(L.id,L.role),es===L.id&&vr){let we=Go(L.id,L.role);we.setAttribute("data-persona-message-edit-stub","true"),we.setAttribute("data-preserve-runtime","true"),f.appendChild(we),et={messageId:L.id,element:vr.element};return}let $e=Q&&Rr(L),Ae=dt&&L.variant==="approval"&&!!L.approval,re=!$e&&L.role==="assistant"&&!L.variant&&Xe&&np(L);!Ae&&br.has(L.id)&&(i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),br.delete(L.id)),!re&&Zr.has(L.id)&&(i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),Zr.delete(L.id));let kt=Rr(L)?`:${L.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${L.agentMetadata?.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ut={canRegenerate:$t===L.id,canEdit:Pt&&Mg(L),canQuote:an&&!L.variant&&(L.content?.trim().length??0)>0},nn=`${Ut.canRegenerate?"r":""}${Ut.canEdit?"e":""}${Ut.canQuote?"q":""}`,jt=$C(L,ns)+kt+`:${nn}`,Kt=$e||Ae||re?null:jC(Nt,L.id,jt);if(Kt){f.appendChild(Kt.cloneNode(!0)),Rr(L)&&L.toolCall?.id&&L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(j.add(L.toolCall.id),Fa(L,o,_e.composerOverlay));return}let Lt=null,cn=a.find(we=>!!(L.variant==="reasoning"&&we.renderReasoning||L.variant==="tool"&&we.renderToolCall||!L.variant&&we.renderMessage)),Re=o.layout?.messages;if(Rr(L)&&L.agentMetadata?.askUserQuestionAnswered===!0){Vs.delete(L.id),i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ci(L)&&Br(o).enabled)return;if(Rr(L)&&o.features?.askUserQuestion?.enabled!==!1){let we=a.find(dn=>typeof dn.renderAskUserQuestion=="function");if(we&&ct.current){let dn=Vs.get(L.id),kr=dn!==jt,Pn=null;if(kr){let{payload:pt,complete:We}=Hr(L),rr=L.id,Ot=()=>ct.current?.getMessages().find(Ln=>Ln.id===rr);Pn=we.renderAskUserQuestion({message:L,payload:pt,complete:We,resolve:Ln=>{let Ia=Ot();Ia&&ct.current?.resolveAskUserQuestion(Ia,Ln)},dismiss:()=>{let Ln=Ot();Ln?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(Ln),ct.current?.resolveAskUserQuestion(Ln,"(dismissed)"))},config:o})}let kn=dn!=null;if(kr&&Pn===null&&!kn){L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(j.add(L.toolCall.id),Fa(L,o,_e.composerOverlay));return}let at=Go(L.id,L.role);at.setAttribute("data-ask-plugin-stub","true"),at.setAttribute("data-preserve-runtime","true"),f.appendChild(at),oe.push({messageId:L.id,fingerprint:jt,bubble:Pn});return}else{L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(j.add(L.toolCall.id),Fa(L,o,_e.composerOverlay));return}}else if(Ae){let we=k();if(!we){f.appendChild(Go(L.id,L.role));return}let dn=a.find(at=>typeof at.renderApproval=="function")??y,Pn=br.get(L.id)!==jt,kn=null;if(Pn&&dn?.renderApproval){let at=L.id,pt=(We,rr)=>{let Ot=ct.current?.getMessages().find(Ln=>Ln.id===at);Ot?.approval&&(Ot.approval.toolType==="webmcp"?ct.current?.resolveWebMcpApproval(Ot.id,We):ct.current?.resolveApproval(Ot.approval,We,rr))};kn=dn.renderApproval({message:L,defaultRenderer:()=>we.createApprovalBubble(L,o),config:o,approve:We=>pt("approved",We),deny:We=>pt("denied",We)})}if(Pn&&kn===null)i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),br.delete(L.id),Lt=we.createApprovalBubble(L,o);else{let at=Go(L.id,L.role);at.setAttribute("data-approval-plugin-stub","true"),at.setAttribute("data-preserve-runtime","true"),f.appendChild(at),mt.push({messageId:L.id,fingerprint:jt,bubble:kn});return}}else if(cn)if(L.variant==="reasoning"&&L.reasoning&&cn.renderReasoning){if(!vn)return;Lt=cn.renderReasoning({message:L,defaultRenderer:()=>km(L,o),config:o})}else if(L.variant==="tool"&&L.toolCall&&cn.renderToolCall){if(!q)return;Lt=cn.renderToolCall({message:L,defaultRenderer:()=>Im(L,o),config:o})}else cn.renderMessage&&(Lt=cn.renderMessage({message:L,defaultRenderer:()=>{let we=hl(L,g,Re,o.messageActions,Os,{loadingIndicatorRenderer:C,widgetConfig:o,actionEligibility:Ut});return L.role!=="user"&&I(we,L,o,P),we},config:o}));if(!Lt&&re){let we=Ym(L);if(we){let dn=Zr.get(L.id),kr=dn!==jt,Pn=o.wrapComponentDirectiveInBubble!==!1&&_o.getOptions(we.component)?.bubbleChrome!==!1,kn=null;if(kr){let at=Gm(we,{config:o,message:L,transform:g});if(at&&we.component==="PersonaArtifactInline"){let pt=at.hasAttribute("data-artifact-inline")?at:at.querySelector("[data-artifact-inline]"),We=pt?.getAttribute("data-artifact-inline")??"",rr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(We):We,Ot=We?i.querySelector(`#wrapper-${L.id}`)?.querySelector(`[data-artifact-inline="${rr}"]`)??null:null;pt&&Ot&&Ot!==pt&&lr()?.hasLiveInlineArtifactBlock(Ot)&&(pt===at?at=Ot:pt.replaceWith(Ot))}if(at)if(Pn){let pt=document.createElement("div");if(pt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),pt.id=`bubble-${L.id}`,pt.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let We=document.createElement("div");We.className="persona-mb-3 persona-text-sm persona-leading-relaxed",We.innerHTML=g({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),pt.appendChild(We)}pt.appendChild(at),kn=pt}else{let pt=document.createElement("div");if(pt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",pt.id=`bubble-${L.id}`,pt.setAttribute("data-message-id",L.id),pt.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let We=document.createElement("div");We.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",We.innerHTML=g({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),pt.appendChild(We)}pt.appendChild(at),kn=pt}}if(kn||dn!=null){let at=Go(L.id,L.role);at.setAttribute("data-component-directive-stub","true"),at.setAttribute("data-preserve-runtime","true"),f.appendChild(at),ue.push({messageId:L.id,fingerprint:jt,bubble:kn});return}}}if(!Lt)if(L.variant==="reasoning"&&L.reasoning){if(!vn)return;Lt=km(L,o)}else if(L.variant==="tool"&&L.toolCall){if(!q)return;Lt=Im(L,o)}else if(L.variant==="approval"&&L.approval){if(o.approval===!1)return;let we=k();if(!we)return;Lt=we.createApprovalBubble(L,o)}else{let we=o.layout?.messages;we?.renderUserMessage&&L.role==="user"?Lt=we.renderUserMessage({message:L,config:o,streaming:!!L.streaming}):we?.renderAssistantMessage&&L.role==="assistant"?Lt=we.renderAssistantMessage({message:L,config:o,streaming:!!L.streaming}):Lt=hl(L,g,we,o.messageActions,Os,{loadingIndicatorRenderer:C,widgetConfig:o,actionEligibility:Ut}),L.role!=="user"&&Lt&&I(Lt,L,o,P)}let De=Go(L.id,L.role);De.appendChild(Lt),qC(Nt,L.id,jt,De),f.appendChild(De)}),_e.composerOverlay&&_e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach($e=>{let Ae=$e.getAttribute("data-persona-ask-sheet-for");Ae&&!j.has(Ae)&&Es(_e.composerOverlay,Ae)}),o.features?.toolCallDisplay?.grouped){let L=[],$e=[],Ae=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(re=>{if(re.variant==="tool"&&re.toolCall&&q){if(or&&re.toolCall.status==="complete")return;$e.push(re);return}re.variant==="reasoning"&&(!vn||re.reasoning?.status==="complete"&&ko(re.reasoning))||(($e.length>1||Ae&&$e.length>0)&&L.push($e),$e=[])}),($e.length>1||Ae&&$e.length>0)&&L.push($e),L.forEach(re=>{let kt=re.map(Re=>Array.from(f.children).find(De=>De instanceof HTMLElement&&De.getAttribute("data-wrapper-id")===Re.id)).filter(Re=>!!Re);if(kt.length<(Ae?1:2))return;let Ut=Go(`tool-group-${re[0].id}`,"assistant");Ut.setAttribute("data-persona-tool-group-row","true");let nn=document.createElement("div");nn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",nn.setAttribute("data-persona-tool-group","true");let jt=document.createElement("div");jt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",jt.id=`tool-group-summary-${re[0].id}`;let Kt=`Called ${re.length} ${re.length===1?"tool":"tools"}`,Lt=o.toolCall?.renderGroupedSummary?.({messages:re,toolCalls:re.map(Re=>Re.toolCall).filter(Re=>!!Re),defaultSummary:Kt,config:o});W(jt,Lt)||(jt.textContent=Kt);let cn=document.createElement("div");cn.className="persona-tool-group-stack persona-flex persona-flex-col",cn.id=`tool-group-stack-${re[0].id}`,cn.setAttribute("data-persona-tool-group-stack","true"),nn.appendChild(jt),Ae||nn.appendChild(cn),Ut.appendChild(nn),kt[0].before(Ut),kt.forEach((Re,De)=>{if(Ae){Re.remove();return}Re.style.setProperty("--persona-message-row-max-width","100%");let we=document.createElement("div");we.className="persona-tool-group-item persona-relative",we.setAttribute("data-persona-tool-group-item","true"),De<kt.length-1&&we.setAttribute("data-persona-tool-group-connector","true"),we.appendChild(Re),cn.appendChild(we)})})}zC(Nt,U);let La=L=>L.variant==="tool"&&!q||L.variant==="reasoning"&&!vn||co(L),Cs=c.some(L=>L.role==="assistant"&&L.streaming&&!La(L)),po=c.length-1;for(;po>=0&&La(c[po]);)po--;let tn=po>=0?c[po]:void 0,uo=po<c.length-1,mi=tn?.role==="assistant"&&!tn.streaming&&tn.variant!=="approval"&&!uo;if(_n&&c.some(L=>L.role==="user")&&!Cs&&!mi){let L={config:o,streaming:!0,location:"standalone",defaultRenderer:Oi},$e=a.find(re=>re.renderLoadingIndicator),Ae=null;if($e?.renderLoadingIndicator&&(Ae=$e.renderLoadingIndicator(L)),Ae===null&&o.loadingIndicator?.render&&(Ae=o.loadingIndicator.render(L)),Ae===null&&(Ae=Oi()),Ae){let re=document.createElement("div"),kt=o.loadingIndicator?.showBubble!==!1,Ut=o.layout?.messages?.layout??"bubble";re.className=kt?fl("assistant",Ut).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),re.setAttribute("data-typing-indicator","true"),kt&&(re.style.color="var(--persona-message-assistant-text, var(--persona-text))",Ut!=="flat"&&(re.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",re.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),re.appendChild(Ae);let nn=Go("typing-indicator","assistant");nn.appendChild(re),f.appendChild(nn)}}if(!_n&&c.length>0){let L=c[c.length-1],$e={config:o,lastMessage:L,messageCount:c.length},Ae=a.find(kt=>kt.renderIdleIndicator),re=null;if(Ae?.renderIdleIndicator&&(re=Ae.renderIdleIndicator($e)),re===null&&o.loadingIndicator?.renderIdle&&(re=o.loadingIndicator.renderIdle($e)),re){let kt=document.createElement("div"),Ut=o.loadingIndicator?.showBubble!==!1;kt.className=Ut?["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(" "),kt.setAttribute("data-idle-indicator","true"),kt.appendChild(re);let nn=Go("idle-indicator","assistant");nn.appendChild(kt),f.appendChild(nn)}}if(Cb(f),Pd(i,f),sg(i),et){let{messageId:L,element:$e}=et,Ae=i.querySelector(`#wrapper-${L}`);Ae&&$e.parentElement!==Ae&&(ia(Ae,$.get(L)??"user"),Ae.replaceChildren($e))}if(oe.length>0)for(let{messageId:L,fingerprint:$e,bubble:Ae}of oe){let re=i.querySelector(`#wrapper-${L}`);re&&(ia(re,$.get(L)??"assistant"),Ae!==null&&(re.replaceChildren(Ae),re.setAttribute("data-bubble-fp",$e),Vs.set(L,$e)))}if(Vs.size>0)for(let L of Vs.keys())U.has(L)||Vs.delete(L);if(ue.length>0)for(let{messageId:L,fingerprint:$e,bubble:Ae}of ue){let re=i.querySelector(`#wrapper-${L}`);re&&(ia(re,$.get(L)??"assistant"),Ae!==null&&(re.replaceChildren(Ae),re.setAttribute("data-bubble-fp",$e),Zr.set(L,$e)))}if(Zr.size>0)for(let L of Zr.keys())U.has(L)||Zr.delete(L);if(mt.length>0)for(let{messageId:L,fingerprint:$e,bubble:Ae}of mt){let re=i.querySelector(`#wrapper-${L}`);re&&(ia(re,$.get(L)??"assistant"),Ae!==null&&(re.replaceChildren(Ae),re.setAttribute("data-bubble-fp",$e),br.set(L,$e)))}if(br.size>0)for(let L of br.keys())U.has(L)||br.delete(L)},Qp=!1,Jl=()=>{Qp||(Qp=!0,eg().catch(()=>{Qp=!1}))},Yn=(i,c,g)=>{c.length>0&&Jl(),GS(i,c,g),Uf()},aa=null,YS=()=>{if(aa)return;let i=g=>{let f=g.composedPath();f.includes(Ge)||Yt&&f.includes(Yt)||gt(!1,"user")};aa=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},Sh=()=>{if(!aa)return;(e.ownerDocument??document).removeEventListener("pointerdown",aa,!0),aa=null};me.push(()=>Sh());let la=null,QS=()=>{if(la)return;let i=g=>{g.key==="Escape"&&(g.isComposing||gt(!1,"user"))};la=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Ah=()=>{if(!la)return;(e.ownerDocument??document).removeEventListener("keydown",la,!0),la=null};me.push(()=>Ah());let ca=!1,Mh=new Set,XS=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Js=()=>{if(!be())return;let i=_e.peekBanner,c=_e.peekTextNode;if(!i||!c)return;if(ve){i.classList.remove("persona-pill-peek--visible");return}let g=P?.getMessages()??[],f;for(let $t=g.length-1;$t>=0;$t--){let Pt=g[$t];if(Pt.role==="assistant"&&Pt.content){f=Pt;break}}if(!f){i.classList.remove("persona-pill-peek--visible");return}let b=f.content,C=!!f.streaming,W=XS(),U=kd(W),$=U.type!=="none"?Fp(U.type,W?.plugins):null,j=$?.isAnimating?.(f)===!0,Q=$!==null&&(C||j);Q&&$&&!Mh.has($.name)&&(dl($,e),Mh.add($.name));let oe=Q&&$?.containerClass?$.containerClass:null,ue=c.dataset.personaPeekStreamClass??null;ue&&ue!==oe&&(c.classList.remove(ue),delete c.dataset.personaPeekStreamClass),oe&&ue!==oe&&(c.classList.add(oe),c.dataset.personaPeekStreamClass=oe),Q?(c.style.setProperty("--persona-stream-step",`${U.speed}ms`),c.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let Xe=Q?Id(b,U.buffer,$,f,C):b;if(Q&&U.placeholder==="skeleton"&&C&&(!Xe||!Xe.trim())){let $t=document.createElement("div"),Pt=cl();Pt.classList.add("persona-pill-peek__skeleton"),$t.appendChild(Pt),Pd(c,$t)}else{let $t=Math.max(0,Xe.length-100),Pt=Xe.length>100?Xe.slice(-100):Xe,an=Ir(Pt);if(!Q||!$){let et=Xe.length>100?`\u2026${Pt}`:Pt;c.textContent!==et&&(c.textContent=et)}else{let et=an;($.wrap==="char"||$.wrap==="word")&&(et=ll(an,$.wrap,`peek-${f.id}`,{skipTags:$.skipTags,startIndex:$t}));let ln=document.createElement("div");if(ln.innerHTML=et,$.useCaret&&Pt.length>0){let ko=Rd(),or=ln.querySelectorAll(".persona-stream-char, .persona-stream-word"),co=or[or.length-1];co?.parentNode?co.parentNode.insertBefore(ko,co.nextSibling):ln.appendChild(ko)}Pd(c,ln),$.onAfterRender?.({container:c,bubble:i,messageId:f.id,message:f,speed:U.speed,duration:U.duration})}}let Qt=_n||ca;i.classList.toggle("persona-pill-peek--visible",Qt)};if(be()){let i=_e.peekBanner;if(i){let f=b=>{b.preventDefault(),b.stopPropagation(),gt(!0,"user")};i.addEventListener("pointerdown",f),me.push(()=>{i.removeEventListener("pointerdown",f)})}let c=()=>{ca||(ca=!0,Js())},g=()=>{ca&&(ca=!1,Js())};Se.addEventListener("pointerenter",c),Se.addEventListener("pointerleave",g),me.push(()=>{Se.removeEventListener("pointerenter",c),Se.removeEventListener("pointerleave",g)}),Yt&&(Yt.addEventListener("pointerenter",c),Yt.addEventListener("pointerleave",g),me.push(()=>{Yt.removeEventListener("pointerenter",c),Yt.removeEventListener("pointerleave",g)}))}let JS=i=>{let c=o.launcher?.composerBar??{},g=c.expandedSize??"anchored",f=c.bottomOffset??"16px",b=c.collapsedMaxWidth,C=c.expandedMaxWidth??"880px",W=c.expandedTopOffset??"5vh",U=c.modalMaxWidth??"880px",$=c.modalMaxHeight??"min(90vh, 800px)",j="calc(100vw - 32px)",Q="var(--persona-pill-area-height, 80px)",oe=Ge.style;if(oe.left="",oe.right="",oe.top="",oe.bottom="",oe.transform="",oe.width="",oe.maxWidth="",oe.height="",oe.maxHeight="",Yt){let ue=Yt.style;ue.bottom=f,ue.width=b??""}if(i&&g!=="fullscreen"){if(g==="modal"){oe.top="50%",oe.left="50%",oe.transform="translate(-50%, -50%)",oe.bottom="auto",oe.right="auto",oe.width=U,oe.maxWidth=j,oe.maxHeight=$,oe.height=$;return}oe.left="50%",oe.transform="translateX(-50%)",oe.bottom=`calc(${f} + ${Q})`,oe.top=W,oe.width=C,oe.maxWidth=j}},da=()=>{if(ve&&Jl(),!Be())return;if(be()){let j=(o.launcher?.composerBar??{}).expandedSize??"anchored",Q=ve?"expanded":"collapsed";Ge.dataset.state=Q,Ge.dataset.expandedSize=j,Yt&&(Yt.dataset.state=Q,Yt.dataset.expandedSize=j),Ge.style.removeProperty("display"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),JS(ve),de.style.display=ve?"flex":"none",Kr(),ve?(YS(),QS()):(Sh(),Ah()),Js();return}let i=St(o),c=e.ownerDocument.defaultView??window,g=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,b=c.innerWidth<=g,C=f&&b&&ce,W=qn(o).reveal;ve?(Ge.style.removeProperty("display"),Ge.style.display=i?"flex":"",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0"),Se.classList.add("persona-scale-100","persona-opacity-100"),Et?(Et.setPanelOpen(!0),Et.element.style.display="none"):un&&(un.style.display="none")):(i?i&&(W==="overlay"||W==="push")&&!C?(Ge.style.removeProperty("display"),Ge.style.display="flex",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ge.style.setProperty("display","none","important"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ge.style.display="",Ge.classList.add("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100"),Se.classList.add("persona-scale-95","persona-opacity-0")),Et?(Et.setPanelOpen(!1),Et.element.style.display=i?"none":""):un&&(un.style.display=i?"none":""))},gt=(i,c="user")=>{if(!Be()||ve===i)return;let g=ve;ve=i,da();let f=(()=>{let C=o.launcher?.sidebarMode??!1,W=e.ownerDocument.defaultView??window,U=o.launcher?.mobileFullscreen??!0,$=o.launcher?.mobileBreakpoint??640,j=W.innerWidth<=$,Q=St(o)&&U&&j,oe=be()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return C||U&&j&&ce||Q||oe})();if(ve&&f){if(!So){let C=e.getRootNode(),W=C instanceof ShadowRoot?C.host:e.closest(".persona-host");W&&(So=lm(W,o.launcher?.zIndex??rn))}Ao||(Ao=cm(e.ownerDocument))}else ve||(So?.(),So=null,Ao?.(),Ao=null);ve&&(Ta(),Gp()||(Bn()==="follow"?xr(!0):Gl()));let b={open:ve,source:c,timestamp:Date.now()};ve&&!g?A.emit("widget:opened",b):!ve&&g&&A.emit("widget:closed",b),A.emit("widget:state",{open:ve,launcherEnabled:ce,voiceActive:ze.active,streaming:P.isStreaming()})},Sr={inputDisabled:!1,sendDisabled:!1},Mo=()=>Sr.inputDisabled,Xp=()=>In(o.voiceRecognition?.provider)&&!!P&&(P.isBargeInActive()||["listening","processing","speaking"].includes(P.getVoiceStatus())),ls=()=>Sr.inputDisabled||Sr.sendDisabled,ZS=()=>(Sr.inputDisabled?Sr.inputReason:void 0)??(Sr.sendDisabled?Sr.sendReason:void 0);function Jp(){if(!Me)return;if(Ce.getState().phase==="streaming"){Me.disabled=!1;return}let i=Ze?!Ze.isReady():!1;Me.disabled=ls()||i}function Zl(){if(!bo)return;let i=Ce.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;bo.toggleAttribute("data-persona-send-hidden",c)}function eA(){let i=ZS();if(be()){let c=oo??Le;i?c.setAttribute("title",i):c.removeAttribute("title"),Le.toggleAttribute(zi,!!i);return}if(i){st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.setAttribute(zi,""),st.textContent=i;return}if(st.hasAttribute(zi)&&(st.removeAttribute("role"),st.removeAttribute("aria-live"),st.removeAttribute(zi),p)){let c=P.getStatus();Sl(st,hf(c),o.statusIndicator??{},c)}}function Zp(){let i=Ng(o.composer?.inputDisabled),c=Ng(o.composer?.sendDisabled);Sr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},Ce.setInputDisabled(i.disabled),Ce.setSendDisabled(c.disabled);let g=Ce.getState().phase==="streaming",f=i.disabled,b=g||f;ae&&(ae instanceof HTMLTextAreaElement?ae.disabled=f:ae.setAttribute("contenteditable",f?"false":"true"),ae.setAttribute("aria-disabled",f?"true":"false")),xt&&(xt.disabled=f),yt&&(yt.disabled=f);for(let C of Wt?.affordanceButtons??[])C.querySelectorAll("button").forEach(W=>{W.disabled=f});ne&&(ne.disabled=f||g&&!Xp()),Qr.forEach(C=>{C.elements.forEach(W=>{W.toggleAttribute("data-disabled",b),W instanceof HTMLButtonElement||W.setAttribute("aria-disabled",b?"true":"false")}),C.buttons.forEach(W=>{W.disabled=b})}),ru.forEach(C=>{C.toggleAttribute("data-disabled",b),C instanceof HTMLButtonElement?C.disabled=b:C.setAttribute("aria-disabled",b?"true":"false"),C.querySelectorAll("button").forEach(W=>{W.disabled=b})}),Le.dataset.personaComposerStreaming=g?"true":"false",Le.dataset.personaComposerInputDisabled=f?"true":"false",Le.dataset.personaComposerSendDisabled=ls()?"true":"false",Le.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(C=>{(C instanceof HTMLButtonElement||C instanceof HTMLInputElement||C instanceof HTMLTextAreaElement||C instanceof HTMLSelectElement)&&(C.disabled=g)}),Jp(),eA()}let pa=i=>{Ce.setStreaming(i),yf(i?"stop":"send"),Zp()},cs=()=>{ze.active||ae&&ae.focus()};A.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>cs(),200)});let ds=null,ua=!1,eu=!wn.hidden,Ar=null,tu=!M,ec=null;me.push(()=>{ec?.cancel(),ec=null});let tA=i=>{let c=Mw(i);if(c===Tl)return;Tl=c,e.setAttribute("data-persona-conversation-state",c);let g=Ap();kl(),tu&&(ec?.cancel(),ec=Sw(Le,c==="active"?g:Ap(),c==="active"?"drop":"rise")),En()},Eh=null,Th,Ph=null,Zs=null,nu=!1,ga=i=>{let c=Bo(o),g=`${c.variant}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(g!==Eh||c.icon!==Th)&&(Eh=g,Th=c.icon,Dd({host:wn,iconHolder:rS,kicker:sS,title:iS,subtitle:aS,starterSuggestions:Cp},c));let f=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;f!==Ph&&(Ph=f,Nd(Wn,c.message,o));let b=i??(P?P.getMessages():o.initialMessages);tA(b);let C=ua,W=!C&&Is(c,b),U=W!==eu;if(eu=W,Zs){Ar?.cancel(),Ar=null,C!==nu&&(nu=C,C?wm(te,wn,null):Cm(te,wn,Zs)),Bi(te,wn,!C);return}if(U&&!W&&!C&&c.dismiss==="on-first-message"&&tu){Ar=xw(wn,j=>{Ar===j&&(Ar=null),!eu&&!Zs&&(Bi(te,wn,!1),En()),j?.cancel()});return}if(Ar){if(!W&&!C)return;Ar.cancel(),Ar=null}let $=!wn.hidden;Bi(te,wn,W),!W&&$&&En()},ou=[],ru=[],su=!1,kh=null,Lh,Ih=()=>{ru.length=0;let i=ou.splice(0,ou.length);for(let c of i)try{c()}catch(g){console.warn("[persona] renderWelcome cleanup threw",g)}};me.push(Ih);let nA=(i,c)=>{let g=pm(i,c);if(!g)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),E("span");let f=o.suggestions?.starters,b=um({item:{...g,behavior:g.behavior??f?.behavior??"send"},index:c,surface:"starter",source:"config",variant:f?.variant??"card",streaming:p?P.isStreaming():!1,config:o,plugins:a,chipsConfig:o.suggestionChipsConfig,session:P,getTextarea:()=>ae,eventTarget:wn,submitPrompt:Tc});return ru.push(b),b},iu=()=>{if(su)return;su=!0;let i=Bo(o);kh=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,Lh=i.icon;try{Ih(),wm(te,wn,Zs),Zs=null,nu=!1;let c=P?P.getMessages():o.initialMessages,g=Is(i,c),f=0,b=null;for(let C of a)if(C.renderWelcome&&(b=C.renderWelcome({config:i,variant:i.variant,visible:g,defaultRenderer:()=>wn,sendMessage:W=>{if(!P||P.isStreaming())return;let U=W.trim();U&&P.sendMessage(U)},requestRender:()=>iu(),renderStarter:W=>nA(W,f++),storage:u(C.id),onCleanup:W=>{ou.push(W)}}),b))break;b&&b!==wn&&(Zs=b,Cm(te,wn,b))}finally{su=!1}ga()},oA=()=>{let i=Bo(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===kh&&i.icon===Lh||iu()},tc=()=>{ga(),$s||(ae.placeholder=iC(Ce.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!P?.isStreaming()&&(Me.textContent=o.copy?.sendButtonLabel??"Send")),ae.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ae.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},rA=!!o.setStoredConversationId,ei=i=>se(c=>{let g={...c};return delete g[i],g}),nc=i=>{let c=Z[i];return typeof c=="string"?c:null},Rh=()=>{let i=Z.durableResume;if(!i||typeof i!="object")return null;let c=i;return typeof c.executionId=="string"&&c.executionId.length>0&&typeof c.after=="string"&&c.after.length>0?{executionId:c.executionId,after:c.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>nc("sessionId"),setStoredSessionId:i=>{se(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ei("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>nc("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{se(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ei("conversationId"))});let Hh=()=>o.clientToken??null,Wh=i=>sx(i,Y(),o.persistState===!1),Oh=Hh(),Yo=Oh?Wh(Oh):null,Qo={...Yo?{visitorStore:Yo}:{},historyBootstrapReady:H,getStoredMessageCursor:()=>nc("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){ei("historyMessageCursor");return}se(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=Z.pendingDisplayProjections;if(!i||typeof i!="object")return null;let c=i;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(g=>typeof g=="string")}},setPendingDisplayProjections:i=>{if(!i){ei("pendingDisplayProjections");return}se(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:Rh,setStoredResumableHandle:i=>{if(!i){ei("durableResume");return}se(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>ie&&Rh()!==null,...rA?{}:{getStoredConversationRevision:()=>nc("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){ei("conversationRevision");return}se(c=>({...c,conversationRevision:i}))}}};if(ie){let i=o.onExecutionState,c=e.ownerDocument.defaultView,g=!1,f=()=>g=!0,b=()=>g=!1;c?.addEventListener("pagehide",f),c?.addEventListener("pageshow",b),me.push(()=>{c?.removeEventListener("pagehide",f),c?.removeEventListener("pageshow",b)}),o={...o,reconnectStream:o.reconnectStream??(C=>P.getClient().reconnectClientTokenStream(C)),onExecutionState:C=>{(C||!g)&&Qo.setStoredResumableHandle?.(C?{executionId:C.executionId,after:C.lastEventId}:null),i?.(C)}}}let sA=()=>{let i=Hh();if(i&&Yo?.matches(i,Y(),o.persistState===!1)||!i&&!Yo)return;Yo?.destroy(),Yo=i?Wh(i):null;let c={...Qo};Yo?c.visitorStore=Yo:delete c.visitorStore,Qo=c,P.setHistoryInternals(Qo)},ps=null,iA=()=>{ps==null&&(ps=setInterval(()=>{let i=Pe.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(ps),ps=null;return}let c=Date.now();i.forEach(g=>{let f=Number(g.getAttribute("data-tool-elapsed"));f&&(g.textContent=Qc(c-f))})},100))},au=(i,c)=>{if(Object.is(i,c))return!0;if(i===null||c===null||typeof i!="object"||typeof c!="object")return!1;if(Array.isArray(i)||Array.isArray(c))return!Array.isArray(i)||!Array.isArray(c)||i.length!==c.length?!1:i.every((W,U)=>au(W,c[U]));let g=i,f=c,b=Object.keys(g),C=Object.keys(f);return b.length===C.length&&b.every(W=>Object.prototype.hasOwnProperty.call(f,W)&&au(g[W],f[W]))},Bh=i=>{let{content:c,rawContent:g,llmContent:f,...b}=i;return b},lu=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!np(i),aA=(i,c,g)=>{if(i.length!==c.length)return!1;let f=i[g.index],b=c[g.index];return!f||!b||f.id!==g.id||b.id!==g.id?!1:(!Object.is(f.content,b.content)||!Object.is(f.rawContent,b.rawContent)||!Object.is(f.llmContent,b.llmContent))&&lu(f)&&lu(b)&&au(Bh(f),Bh(b))},cu=null,ti=null,us=null,Xo=null,du=null,lA=i=>{if(!ie)return Ys(i);du=i,queueMicrotask(()=>{du===i&&(du=null,Ys(i))})},oc=i=>{cu=i;let c,g;ti=null;for(let b=i.length-1;b>=0;b-=1){let C=i[b];if(!c&&C.role==="user"&&(c=C),!g&&C.role==="assistant"&&(g=C),!ti&&lu(C)&&(ti={index:b,id:C.id}),c&&g&&ti)break}Yn(Pe,i,ut),lr()?.updateInlineArtifactBlocks(Pe,Gn.artifacts,{suppressTransition:_n}),iA(),ga(i),zs(i),xr(!_n),KS(i),i.length===0&&(lo(),oa=!0,Ul=!1,Gs=null,jl=!1),!$p||Ks?($p=!0,rs=c?.id??null,Up=g?.id??null):c&&c.id!==rs?(rs=c.id,US(c.id)):g&&g.id!==Up&&jS(),g&&(Up=g.id),VS(i);let f=ze.lastUserMessageId;c&&c.id!==f&&(ze.lastUserMessageId=c.id,A.emit("user:message",c)),ze.lastUserMessageWasVoice=!!c?.viaVoice,lA(i),Js()},pu=()=>{Xo!==null&&(cancelAnimationFrame(Xo),Xo=null);let i=us;us=null,i&&oc(i)},_h=()=>{Xo!==null&&cancelAnimationFrame(Xo),Xo=null,us=null},cA=i=>{let c=us??cu;if(_n&&c&&ti&&aA(c,i,ti)){us=i,Xo===null&&(Xo=requestAnimationFrame(()=>{Xo=null;let g=us;us=null,g&&oc(g)}));return}if(i.length===0){_h(),oc(i);return}pu(),oc(i)};P=new Qa(o,{onMessagesChanged(i){cA(i)},onStatusChanged(i){let c=o.statusIndicator??{};Sl(st,(f=>f==="idle"?c.idleText??qt.idle:f==="connecting"?c.connectingText??qt.connecting:f==="connected"?c.connectedText??qt.connected:f==="error"?c.errorText??qt.error:f==="paused"?c.pausedText??qt.paused:f==="resuming"?c.resumingText??qt.resuming:qt[f])(i),c,i),vp()},onStreamingChanged(i){i||(P?.getMessages().length===0?_h():pu()),_n=i,pa(i),vp(),P&&Yn(Pe,P.getMessages(),ut),i||(xr(!0),FS(),ch=!0,P&&dh(P.getMessages(),Br(o))),Vt(),El(i?"Responding\u2026":"Response complete."),Js()},onVoiceStatusChanged(i){if(A.emit("voice:status",{status:i,timestamp:Date.now()}),!(i!=="disconnected"&&!In(o.voiceRecognition?.provider)))switch(i){case"listening":nr(),ui();break;case"processing":nr(),pM();break;case"speaking":nr(),uM();break;default:i==="idle"&&P.isBargeInActive()?(nr(),ui(),ne?.setAttribute("aria-label","End voice session")):(ze.active=!1,nr(),Ko("system"),ao());break}},onArtifactsState(i){Gn=i,i.artifacts.length===0&&(Us=!1),lr()?.updateInlineArtifactBlocks(Pe,i.artifacts,{suppressTransition:_n}),io(),Ys()},onHistoryStateChanged(i){mf(i)},onHistoryNotice(i){ff(i)},onReconnect(i){let{executionId:c,lastEventId:g}=i.handle;i.phase==="paused"?A.emit("stream:paused",{executionId:c,after:g}):i.phase==="resuming"?A.emit("stream:resuming",{executionId:c,after:g,attempt:i.attempt??1}):A.emit("stream:resumed",{executionId:c,after:g})}},Qo),ct.current=P,me.push(()=>P.cancel()),me.push(()=>{P.destroy(),Yo?.destroy()});let uu=null;if(P.onReadAloudChange((i,c)=>{Ff=i,$f=c,Uf();let g=i??uu;i&&(uu=i);let f=g?P.getMessages().find(b=>b.id===g)??null:null;A.emit("message:read-aloud",{messageId:g,message:f,state:c,timestamp:Date.now()}),c==="idle"&&(uu=null)}),p=!0,$p=!0,o.voiceRecognition?.enabled===!0&&In(o.voiceRecognition.provider))try{P.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let dA=720,pA=250,Qe=Vm(o.features?.history?.copy),Fn=null,gu=!1,it=null,rc=null,sc="conversation",mu=null,pn=null,Eo=null,ic=P.getHistoryState(),fu=null,ma=0,hu=null,ac=null,lc=null,yu=`persona-history-${Math.random().toString(36).slice(2,8)}`,bu=()=>o.features?.history?.enabled===!0,To=()=>bu()&&!!Fn&&!gu,Dh=()=>{let i=P.getStatus();return _n||i==="paused"||i==="resuming"},vu=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",g=Fn?.capabilities.scopes;return!g||g.includes(c)?c:g[0]??c},ni=()=>rc?.scope??vu(),Nh=()=>P.getClientSession()?.targetId??null,Fh=i=>`${i.state}:${"reason"in i?i.reason:""}`,uA=i=>{let c=Fh(i);c!==fu&&(fu=c,A.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},cc=i=>{i&&($o.textContent="",$o.textContent=i)},$h=null,Uh=null,gA=()=>{if(!bu())return null;let i=cx();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:($h!==c&&($h=c,Uh=c()),Uh):P.isClientTokenMode()?dx({client:P.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:g=>P.bindActivatedSession(g),getClient:()=>P.getClient()}):null},jh=()=>{ac?.(),ac=null,lc?.(),lc=null,gu=!1,Fn=gA();let i={...Qo};Fn?i.historyProvider=Fn:delete i.historyProvider,Qo=i,P.setHistoryInternals(Qo),Fn&&(ac=Fn.subscribeAvailability?.(c=>{gu=!c,c||Tn({restoreFocus:!1}),Er()})??null,lc=Fn.subscribeIdentityStatus(c=>uA(c)),fu=Fh(Fn.getIdentityStatus()))},Cu=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!ce||St(o)))return"panel";let c=xo??de;return(c.getBoundingClientRect().width||c.clientWidth)>=dA?"rail":"panel"},Qn=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},dc="data-persona-history-suppressed",$n=null,Mr=null,gs=null,fa=null,wu=null,qh="",zh=()=>Ee===wu?qh:o.layout?.showHeader===!1?"none":"",mA=()=>_t==="panel"&&!!gs&&fa===gs.element&&o.layout?.showHeader!==!1&&zh()!=="none",fA=()=>{for(let i of Array.from(Ee.children))i!==$n&&i.setAttribute(dc,"")},hA=()=>{for(let i of Array.from(de.querySelectorAll(`[${dc}]`)))i.removeAttribute(dc)},yA=()=>{let i=gs;if(!i)return;if(Array.from(Ee.children).some(f=>f!==$n&&!f.hasAttribute(dc))){Mr&&Mr!==Ee&&(Mr.style.removeProperty("min-height"),Mr=null);let f=Ee.offsetHeight;f>0&&(Ee.style.minHeight=`${f}px`,Mr=Ee)}$n||($n=E("div","persona-history-header-host")),i.setHeaderPlacement("external");let g=i.getHeaderElement();g.parentNode!==$n&&$n.replaceChildren(g),$n.parentNode!==Ee&&Ee.appendChild($n),fA()},Vh=()=>{Mr&&(Mr.style.removeProperty("min-height"),Mr=null),$n&&(gs?.setHeaderPlacement("inline"),$n.remove(),$n=null,hA())},pc=null,xu=()=>{if(pc){if(te.style.display="none",Qn(te,!0),Le.hidden=!0,Qn(Le,!0),mA()){yA(),Ee.style.display=zh(),Qn(Ee,!1);return}Vh(),Ee.style.display="none",Qn(Ee,!0)}};bp=xu;let bA=i=>{let c=te.style.display,g=Le.hidden,f=Le,b=Ee,C=Ee.style.display;wu=b,qh=C,pc=()=>{pc=null,Vh(),wu=null,te.style.display=c,Qn(te,!1),f.hidden=g,Qn(f,!1),Le!==f&&(Le.hidden=!1,Qn(Le,!1)),b.style.display=C,Qn(b,!1),Ee!==b&&(Ee.style.display=o.layout?.showHeader===!1?"none":"",Qn(Ee,!1))},Le.parentNode?.insertBefore(i,Le),xu()},oi=null,ms=null,ha=null,ri=null,Kh=()=>[Ee,_e.closeButtonWrapper,_e.clearChatButtonWrapper,te,Le],vA=52,uc=()=>o.features?.history?.rail?.collapsible!==!1,si=()=>o.features?.history?.rail?.side==="right"?"right":"left",Su=200,Au=400,Mu=i=>Math.min(Au,Math.max(Su,Math.round(i))),CA=()=>o.features?.history?.rail?.resizable===!0,ya,wA=()=>{if(ya===void 0&&(ya=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Y()}rail-width`));i&&(ya=i)}catch{}return ya},ba=()=>Mu(wA()??o.features?.history?.rail?.width??260),xA=i=>{if(ya=i,o.persistState!==!1)try{window.localStorage.setItem(`${Y()}rail-width`,String(i))}catch{}},gc=()=>uc()&&o.features?.history?.rail?.collapsedBehavior==="overlay",Ft=!1,Gh=i=>{let c=E("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},SA=()=>{let i=o.features?.history?.rail?.brand;if(!i)return;let c=!1,g;return f=>{if(i.render)try{return i.render({collapsed:f})??null}catch(b){return c||(c=!0,console.warn("[persona] history rail brand threw",b)),null}return g===void 0&&(i.iconUrl?g=Gh(i.iconUrl):g=i.icon?le(i.icon,20):null),g?g.cloneNode(!0):null}},AA=()=>o.features?.history?.rail?.sections?.map(i=>{let c=!1,g=f=>{c||(c=!0,console.warn("[persona] history rail section threw",i.id,f))};return{id:i.id,title:i.title,placement:i.placement??"above-conversations",items:i.items.map(f=>{let b;return{id:f.id,label:f.label,badge:f.badge,iconNode:()=>{if(b!==void 0)return b;try{f.renderIcon?b=f.renderIcon()??null:f.iconUrl?b=Gh(f.iconUrl):b=f.icon?le(f.icon,20):null}catch(C){g(C),b=null}return b},onSelect:()=>{try{f.onSelect()}catch(C){g(C)}}}})}})??[],MA=i=>{let c=AA();for(let g of i)c.some(f=>f.id===g.id)?console.warn("[persona] duplicate history rail section id",g.id):c.push(g);return c.length?c:void 0},va=null,Yh=()=>`${Y()}rail-collapsed`,Eu=()=>{if(va===null&&(va=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(Yh());i&&(va=i==="1")}catch{}return va},Tu=i=>{if(va=i,o.persistState!==!1)try{window.localStorage.setItem(Yh(),i?"1":"0")}catch{}},Ca=()=>_t==="rail"&&uc()&&!gc()&&Eu(),Pu=()=>{},Qh=()=>{if(gc()){Pu();return}Tu(!Eu()),it?.view.setCollapsed(Ca()),Fo(),En()},ku=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!Ed(i)?null:{combo:i,hint:Td(i),aria:rl(i)}},Xh=()=>{d.forEach(c=>c()),d=[];let i=ku();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>At&&_t==="rail"&&uc()||ai(),run:()=>gc()?Pu():Qh()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&d.push(l.register({id:`header-action-${c.id}`,combo:c.shortcut,run:()=>{let g=e.querySelector(`[data-persona-header-action="${c.id}"]`);g?g.click():o.layout?.header?.onAction?.(c.id)}}));for(let c of a)for(let g of c.shortcuts??[])d.push(l.register({...g,id:`${c.id}:${g.id}`}))};Xh();let EA=300,mc="var(--persona-history-overlay-margin,8px)",Xn=null,Jo=null,fc=0,Zo=null,ii=null,fs=!1,Lu=0,Jh=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,ai=()=>To()&&gc()&&(_t??Cu())==="rail",TA=()=>At&&!Ft,wa=()=>{ii!==null&&clearTimeout(ii),ii=null},PA=()=>{jm().catch(()=>{})},Zh=()=>{wa(),Ft&&(ii=setTimeout(()=>{ii=null,!(fs||!Ft)&&(Zo?.contains(document.activeElement)||Tn({restoreFocus:!1}))},EA))},kA=(i,c)=>{let g=Zo?.getBoundingClientRect();if(!g)return!1;let f=Xn?.getBoundingClientRect(),b=f?Math.min(f.top,g.top):g.top;return i>=g.left&&i<=g.right&&c>=b&&c<=g.bottom||!!f&&i>=f.left&&i<=f.right&&c>=f.top&&c<=f.bottom},Iu=i=>{Ft&&(fs=kA(i.clientX,i.clientY),fs?wa():ii===null&&Zh())},ey=i=>{At||!ai()||(Ft=!0,Sa({invoker:Xn,keyboard:i?.keyboard===!0}).then(()=>{At?!fs&&document.activeElement!==Xn&&Tn():Ft=!1}))},ty=()=>{let i=fa?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",Ft?Qe.expandLabel:Qe.collapseLabel),i.setAttribute("aria-expanded",Ft?"false":"true"))},ny=()=>{Tu(!1);let i=it;if(!Ft||!i){Sa({invoker:Xn});return}let c=document.activeElement===Xn;Ft=!1,hc(),i.element.remove(),Hu(i.element),ty(),c&&bc(),En(),Er()},LA=()=>{Tu(!0),Tn()};Pu=()=>{!At||Ft?ny():LA()};let IA=()=>{let i=ku(),c=Ls({ariaLabel:Qe.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":yu,...i?{"aria-keyshortcuts":i.aria}:{}}}),g=c.button;g.addEventListener("mouseenter",()=>{fs=!0,wa(),!(Jh()||Date.now()<Lu)&&ey()}),g.addEventListener("mouseleave",()=>{fs=!1,Lu=0,Zh()}),g.addEventListener("focus",()=>{At||PA()}),g.addEventListener("click",f=>{To()&&(f.detail!==0&&Jh()&&!At?ey():ny())}),Xn=g,Jo=c.wrapper},xa=()=>{if(Jo&&!Jo.isConnected&&(Jo=null,Xn=null),!ai()){Jo?.remove(),Jo=null,Xn=null;return}Xn||IA();let i=Jo,c=Xn;if(!i||!c)return;let g=si()!=="right"?Ee.firstChild:null;(g??Ee.lastChild)!==i&&Ee.insertBefore(i,g),i.style.display=TA()||fc>0?"none":"",c.setAttribute("aria-label",Qe.expandLabel),c.setAttribute("aria-expanded",At?"true":"false"),Zo&&Fo()},oy=i=>{if(!Ft)return;let c=i.target;c instanceof Node&&(Zo?.contains(c)||Jo?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||Tn({restoreFocus:!1}))};document.addEventListener("pointerdown",oy,!0),me.push(()=>{document.removeEventListener("pointerdown",oy,!0),document.removeEventListener("pointermove",Iu),li?.(),wa()});let Ru=null,li=null,ry=16,sy=i=>{xA(Mu(i)),Fo(),En()},RA=()=>{let i=E("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(Su)),i.setAttribute("aria-valuemax",String(Au)),i.addEventListener("pointerdown",c=>{let g=ms;if(!g||c.button!==0)return;c.preventDefault(),li?.();let f=c.clientX,b=g.getBoundingClientRect().width||ba(),C=si()==="right"?-1:1,W=b,U=e.ownerDocument;g.style.transition="none";let $=Q=>{W=Mu(b+C*(Q.clientX-f)),g.style.flex=`0 0 ${W}px`,i.setAttribute("aria-valuenow",String(W))},j=()=>{li=null,U.removeEventListener("pointermove",$),U.removeEventListener("pointerup",j),U.removeEventListener("pointercancel",j),g.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}sy(W)};li=j,U.addEventListener("pointermove",$),U.addEventListener("pointerup",j),U.addEventListener("pointercancel",j);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let g=si()==="right"?-ry:ry,f=ba(),b=c.key==="ArrowRight"?f+g:c.key==="ArrowLeft"?f-g:c.key==="Home"?Su:c.key==="End"?Au:null;b!==null&&(c.preventDefault(),sy(b))}),i},HA=(i,c)=>{if(!CA()||Ca()){li?.(),Ru?.remove();return}let g=Ru??RA();Ru=g,g.setAttribute("aria-label",Qe.resizeLabel),g.setAttribute("aria-valuenow",String(ba())),g.nextElementSibling!==c&&i.insertBefore(g,c)};Fo=()=>{it?.view.setRailSide(si());let i=si()==="right",c=Zo;if(c){let U=Xn?Xn.getBoundingClientRect().bottom-de.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(U))}px + ${mc})`,c.style.width=`${ba()}px`,c.style.left=i?"":mc,c.style.right=i?mc:""}let g=ms,f=oi,b=ha;if(!g||!f||!b)return;g.style.flex=`0 0 ${Ca()?vA:ba()}px`;let C="1px solid var(--persona-divider,#e5e7eb)";g.style.borderRight=i?"":C,g.style.borderLeft=i?C:"";let W=i?b:g;f.firstElementChild!==W&&f.append(W,i?g:b),HA(f,i?g:b)};let iy=i=>{if(ri&&ms){ri.replaceWith(i),ri=null,Fo();return}let c=E("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let g=E("div","persona-history-rail-conversation");g.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let f=E("div","persona-history-rail-host");f.style.cssText="display:flex;min-height:0;overflow:hidden",de.insertBefore(c,Ee.parentNode===de?Ee:te);for(let b of Kh())b?.parentNode===de&&g.appendChild(b);c.append(f,g),f.appendChild(i),oi=c,ms=f,ha=g,Fo()},WA=()=>{if(oi)return;let i=E("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",ri=i,iy(i),En()},ay=()=>{ri&&(hc(),En())},OA=i=>{let c=E("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${mc};display:flex;overflow:hidden;z-index:${Ei-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,de.style.position="relative",de.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",Iu),Zo=c,Fo(),ty()},hc=()=>{pc?.(),Zo&&(fs&&(Lu=Date.now()+150),document.removeEventListener("pointermove",Iu),Zo.remove(),Zo=null);let i=oi;if(i){li?.();for(let c of Kh())c&&i.contains(c)&&de.insertBefore(c,i);i.remove(),oi=null,ms=null,ha=null,ri=null}},ly=i=>{fa=i,i.id=yu,i.style.flex="1 1 auto",i.style.minHeight="0"},Hu=i=>{ly(i),(_t!=="rail"||Ft)&&ay(),_t!=="rail"?bA(i):Ft?OA(i):iy(i)},yc=()=>{if(xa(),vy(),!At||!it)return;let i=Cu();if(i===_t)return;let c=document.activeElement,g=c instanceof HTMLElement&&(it.element.contains(c)||$n?.contains(c)===!0)?c:null;hc(),it.element.remove(),it.view.setHeaderPlacement("inline"),_t=i,it.view.setPresentation(i),it.view.setCollapsed(Ca()),it.requestRender(),it.element.isConnected||Hu(it.element),g?.isConnected?g.focus():bc(),Vt(),En(),Er()},cy=(i,c)=>$n?.querySelector(c)??i.querySelector(c),bc=()=>{let i=it?.element??fa;if(!i)return;let c=cy(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let g=cy(i,".persona-history-title")??i;g.tabIndex=-1,g.focus()},Sa=async i=>{if(!To()||At)return;let c=Fn;if(!c)return;if(!Ft&&ai()&&Eu()){xa();return}vc();let g=++ma;sc=i?.returnSurface??"conversation",mu=i?.invoker??pn;let f=ai()&&!Ft;f&&(fc+=1,xa(),WA());let b;try{b=await jm()}catch{cc(Qe.openHistoryLabel),f&&(fc-=1,g===ma&&(ay(),xa()));return}if(f&&(fc-=1),g!==ma||At)return;rc={scope:vu()},_t=Cu(),At=!0;let C=_t==="panel"&&o.layout?.showHeader!==!1&&Ee.style.display!=="none"?"external":"inline",W=o.features?.history?.rowAvatar,U=ku(),$=U?{hint:U.hint,aria:U.aria}:null,j={provider:c,context:rc,targetId:Nh(),presentation:_t,collapsible:uc(),collapsed:Ca(),railSide:si(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:SA(),onToggleCollapse:Qh,...$?{collapseShortcut:$}:{},headerPlacement:C,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:W===!1?!1:typeof W=="string"?W:o.launcher?.iconUrl,activeConversationId:P.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:Q=>Ou(Q,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Q=>hs(Q),attachTooltip:Zt,onStartNew:()=>Bu({focusComposer:!0}),onClose:()=>Tn(),onRequestDeleteConversation:Q=>by(Q),onRequestClearHistory:()=>$A(),...c.resetDevice?{onRequestResetIdentity:()=>UA()}:{}};it=lx({plugins:a,config:o,getPresentation:()=>_t??"panel",getReturnSurface:()=>sc,close:()=>Tn(),createView:({slots:Q,renderDom:oe,onModelChange:ue,railSections:Xe})=>(gs=b.createHistoryView({...j,railSections:MA(Xe),slots:Q,renderDom:oe,onModelChange:ue,onAnnounce:cc}),gs),onElementChanged:(Q,oe)=>{if(!oe?.isConnected)return Hu(Q);ly(Q),oe.replaceWith(Q),xu()}}),it.view.setNewConversationRequired(ic.recovery==="new_conversation_required"),i?.focus!==!1&&(_t!=="rail"||i?.keyboard===!0)&&bc(),Vt(),En(),Er(),A.emit("history:opened",{presentation:_t,returnSurface:sc,timestamp:Date.now()})},vc=()=>{},Tn=i=>{if(!At)return;ma+=1;let c=sc,g=mu,f=it,b=i?.restoreFocus!==!1;At=!1;let C=!1,W=null,U=()=>{if(!C){if(C=!0,vc=()=>{},W!==null&&clearTimeout(W),Ft=!1,wa(),hc(),f?.dispose(),f?.view.destroy(),f?.element.remove(),it===f&&(it=null,gs=null,fa=null,_t=null,rc=null,mu=null),Vt(),En(),Er(),b){let j=g??pn;j?.isConnected?j.focus():cs()}A.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},$=f&&f.element===f.view.element?f.view.playExit():null;if(!$){U();return}vc=U,W=setTimeout(U,pA),$.then(U)},dy=i=>{if(!(i.key!=="Escape"||!At||!it)){if(_t==="rail"){let c=i.target;if(!(c instanceof Node)||!(it.element.contains(c)||Ft&&Jo?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Tn()}};de.addEventListener("keydown",dy),me.push(()=>de.removeEventListener("keydown",dy));let Cc=null,py=!1,Aa=()=>{if(!gr)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&Cc?.trim()||null;gr.textContent=c??o.launcher?.title??"Chat Assistant";let g=gr.closest(".persona-combo-btn");if(!g)return;let f=!i||P.getActiveConversationId()!==null;g.setAttribute("data-persona-menu-locked",f?"false":"true"),g.setAttribute("aria-haspopup",f?"true":"false"),f||g.setAttribute("aria-expanded","false"),g.style.cursor=f?"pointer":"default";let b=g.querySelector("svg");b&&(b.style.display=f?"":"none")},BA=i=>{i!==Cc&&(Cc=i,Aa())},hs=i=>{py=i?.starred===!0,BA(i&&i.title.trim()||null),Aa()};Aa(),de.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,g=P.getActiveConversationId();g&&(c==="delete"?by(g):c==="star"&&P.canUpdateConversations()&&_u(g,{starred:!py}).catch(()=>{}))});let wc=0,_A=250,xc=null,Sc=()=>{xc&&clearTimeout(xc),xc=null};me.push(Sc);let uy=()=>{Sc();let i=ds;i&&(ua=!0,i.hidden=!1,Pe.style.display="none",ga())},Ac=()=>{wc+=1,Sc(),ds&&(ds.remove(),ds=null,ua=!1,Pe.style.removeProperty("display"),Qn(Le,!1),ga())},DA=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Pe.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Wu=(i,c)=>G("div",{className:gn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),gy=()=>G("div",{className:"persona-conversation-loading-body"},Wu("58%",!1),Wu("72%",!0),Wu("44%",!1)),my=i=>{ds?.remove(),ds=i,i.hidden=!ua,te.insertBefore(i,Pe),Sc(),ua||(xc=setTimeout(uy,_A)),Qn(Le,!0)},NA=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:gy},c=null,g=a.find(f=>f.renderLoadingIndicator);g?.renderLoadingIndicator&&(c=g.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),my(G("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Qe.openConversationLoadingLabel}},c??gy()))},FA=i=>{let c=()=>{Ou(i,{focusComposer:!0}).catch(()=>{})},g=To()?()=>{Ac(),Sa()}:void 0,f=(U,$)=>{let j=G("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:U});return j.addEventListener("click",$),j},b=()=>G("div",{className:"persona-conversation-loading-error-body"},G("p",{className:"persona-conversation-loading-error-title",text:Qe.openConversationErrorTitle}),G("div",{className:"persona-conversation-loading-error-actions"},f(Qe.openConversationRetryLabel,c),g?f(Qe.openConversationBackLabel,g):null)),C=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Qe.openConversationErrorTitle,retryLabel:Qe.openConversationRetryLabel,backLabel:Qe.openConversationBackLabel}),retry:c,...g?{back:g}:{},defaultRenderer:b}),W=null;for(let U of a)if(U.renderHistoryOpenError){try{W=U.renderHistoryOpenError(C)}catch($){console.warn("[persona] renderHistoryOpenError threw",$),W=null}if(W)break}my(G("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},W??b())),uy()};A.on("history:closed",()=>{ds&&Qn(Le,!0)});let Ou=async(i,{focusComposer:c=!1}={})=>{let g=ni(),f=!!it;it?.view.setActiveConversationId(i),Ac();let b=wc;NA(),At&&(_t==="panel"||Ft)&&Tn({restoreFocus:!1}),Ks=!0;try{await P.openConversation(i,{scope:g})}catch(C){throw b===wc&&FA(i),C}finally{Ks=!1}b===wc&&(Ac(),Nt.clear(),lo(),Mn(),Gp()||Gl(),DA(),er(),f||hs(null),A.emit("history:conversationOpened",{conversationId:i,title:Cc,scope:g,timestamp:Date.now()}),c&&cs())},Bu=async({focusComposer:i=!1}={})=>{Ac(),await P.startNewConversation({scope:ni()}),hs(null),Nt.clear(),lo(),Mn(),Gl(),er();let c=P.getActiveConversationId();it?.view.setActiveConversationId(c),A.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),At&&(_t==="panel"||Ft)&&Tn({restoreFocus:!1}),i&&cs()},_u=async(i,c)=>{let g=await P.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return it?.view.applyConversationSummary(g),!it&&i===P.getActiveConversationId()&&hs(g),g},fy=async i=>{let c=ni(),g=P.getActiveConversationId()===i;await P.deleteConversation(i,{scope:c}),it?.view.removeConversationSummary(i),g&&(hs(null),Nt.clear(),lo(),Mn(),er()),A.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:g,timestamp:Date.now()})},hy=async i=>{let c=i?.scope??ni(),g=i?.allTargets?null:i?.targetId??Nh(),f=await P.clearConversationHistory({...g?{targetId:g}:{},scope:c});return hs(null),Nt.clear(),lo(),Mn(),er(),A.emit("history:cleared",{deleted:f.deleted,scope:c,targetId:g,timestamp:Date.now()}),f},yy=async()=>{if(!Fn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await P.resetHistoryDevice()).remoteRevocationConfirmed}finally{hs(null),P.clearArtifacts(),Nt.clear(),cu=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),Z={},ye.syncFromMetadata(),K?.clear&&zl(()=>K.clear(),"[AgentWidget] Failed to clear storage adapter:"),lo(),Mn(),er(),Tn({restoreFocus:!1}),cs(),ve||Et?.launcher.element.focus()}return cc(i?Qe.identityResetNotice:Qe.identityResetUnconfirmedNotice),A.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},Du=()=>xo?Se:de,by=async i=>await tp({host:Du(),title:Qe.deleteConversationConfirmTitle,description:Qe.deleteConversationConfirm,confirmLabel:Qe.deleteConversationConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await fy(i),"deleted"):"cancelled",$A=async()=>{let i=ni()==="verified-user";return await tp({host:Du(),title:Qe.clearHistoryConfirmTitle,description:i?Qe.clearHistoryVerifiedConfirm:Qe.clearHistoryConfirm,confirmLabel:Qe.clearHistoryConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await hy(),"cleared"):"cancelled"},UA=async()=>{if(!await tp({host:Du(),title:Qe.resetIdentityConfirmTitle,description:Qe.resetIdentityConfirm,confirmLabel:Qe.resetIdentityConfirmLabel,cancelLabel:Qe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await yy();return{outcome:"reset",remoteRevocationConfirmed:c}},Jn=E("button","persona-history-earlier");Jn.type="button",Jn.textContent=Qe.showEarlierMessagesLabel,Jn.setAttribute("data-persona-history-earlier",""),Object.assign(Jn.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let er=()=>{if(!(To()&&!!ic.nextMessageCursor&&!!P.getActiveConversationId())){Jn.remove();return}Jn.textContent=Qe.showEarlierMessagesLabel,Jn.parentNode!==te&&te.insertBefore(Jn,te.firstChild)};Jn.addEventListener("click",()=>{let i=P.getActiveConversationId(),c=ic.nextMessageCursor;if(!i||!c||Jn.disabled)return;Jn.disabled=!0;let g=te.scrollHeight,f=te.scrollTop;P.loadOlderMessages(i,c,{scope:ni()}).then(()=>{te.scrollTop=f+(te.scrollHeight-g),En()}).catch(()=>{}).finally(()=>{Jn.disabled=!1,er()})});let jA=()=>{let i=Ls({ariaLabel:Qe.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return i.button.addEventListener("click",c=>{if(!(!To()||Dh())){if(At){Tn();return}Sa({invoker:i.button,keyboard:c.detail===0})}}),i},vy=()=>{if(!To()){Eo?.remove(),pn=null,Eo=null;return}if(Eo&&!Eo.isConnected&&(pn=null,Eo=null),!pn&&Ee){let f=jA();pn=f.button,Eo=f.wrapper;let b=_e.clearChatButtonWrapper||_e.closeButtonWrapper;b?.parentNode&&Ee.contains(b)?b.parentNode.insertBefore(Eo,b):Ee.appendChild(Eo)}if(!pn||!Eo)return;let i=ai()||At&&_t==="rail";if(Eo.style.display=i?"none":"",i){document.activeElement===pn&&bc();return}let c=Dh();pn.disabled=c,pn.setAttribute("aria-disabled",c?"true":"false");let g=c?Qe.openHistoryBusyLabel:Qe.openHistoryLabel;pn.setAttribute("aria-label",g),(o.features?.history?.presentation??"panel")==="panel"?(pn.removeAttribute("aria-expanded"),pn.removeAttribute("aria-controls")):(pn.setAttribute("aria-expanded",At?"true":"false"),pn.setAttribute("aria-controls",yu))},Mc=!1,qA=()=>{let i=_e.clearChatButton;if(i){if(To()){Mc||(hu=i.getAttribute("aria-label")??"",Mc=!0),i.setAttribute("aria-label",Qe.newConversationLabel),i.removeAttribute("title");return}Mc&&(Mc=!1,hu&&i.setAttribute("aria-label",hu))}},Er=()=>{Qe=Vm(o.features?.history?.copy),vy(),xa(),qA(),er()};vp=Er,mf=i=>{ic=i,it?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),pa(i.sendBlocked||_n),er()},ff=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(Nt.clear(),lo(),Mn()),cc(i.message),it?.view.refresh()},jh(),Er(),me.push(()=>{ac?.(),lc?.(),ma+=1,vc(),it?.dispose(),it?.view.destroy(),it=null}),o.clientToken&&P.initClientSession().then(()=>{if(To())return P.reconcileBootConversation({scope:vu()})}).then(()=>{er()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(S||o.onSSEEvent)&&P.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),yp(i,c)});let Cy=()=>{let i=o.resume??(ie?Qo.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&P.resumeFromHandle(i)};M?M.then(i=>{if(i){if(i.metadata&&(Z=Jm(i.metadata),ye.syncFromMetadata()),i.messages?.length){Ks=!0;try{P.hydrateMessages(i.messages)}finally{Ks=!1}Jl()}i.artifacts?.length&&P.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),hh(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{tu=!0,B(),Cy()}):(hh(R),Cy());let zA=()=>{!be()||ve||!(o.launcher?.composerBar?.expandOnSubmit??!0)||gt(!0,"auto")},VA=(i,c)=>i?c?{refs:[...i.refs,...c.refs],finalize:async()=>{let[g,f]=await Promise.allSettled([i.finalize(),c.finalize()]),b=[];return g.status==="fulfilled"?b.push(g.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",g.reason),f.status==="fulfilled"?b.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),$I(b)}}:i:c,Nu=()=>{let c=ae.getInlineMessageFields?.();return c&&c.contentSegments.some(f=>f.kind==="mention")?c.contentSegments:void 0},tr=!1,ys=null,Ec=()=>{ae.value="",ae.style.height="auto",vo(),Ea()},Fu="data-persona-composer-notice",ci=null;function KA(i){El(i),!(be()||!st)&&(st.hasAttribute(zi)||(st.setAttribute(Fu,""),st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.textContent=i,ci&&clearTimeout(ci),ci=setTimeout(()=>{if(ci=null,!!st?.hasAttribute(Fu)&&(st.removeAttribute(Fu),st.removeAttribute("role"),st.removeAttribute("aria-live"),p)){let c=P.getStatus();Sl(st,hf(c),o.statusIndicator??{},c)}},4e3)))}function GA(){let i=Ce.getState().pendingSubmission;i&&(Ns(void 0),ae&&(ae.value=i.text,ae.dispatchEvent(new Event("input",{bubbles:!0})),vo()),i.options.selectedModelId&&(Ce.setSelectedModelId(i.options.selectedModelId),fr?.repaint()),i.options.activeModeIds?.length&&Ll(i.options.activeModeIds),i.options.quote&&Co(i.options.quote),ae?.focus())}let YA=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},wy=(i={})=>{let c=(i.overrideText??ae?.value??"").trim();return i.resolveInlineCommand&&c?(Wt?.takeInlineCommand(c)??Promise.resolve(null)).then(g=>xy(i,c,g)):xy(i,c,null)},xy=(i,c,g)=>{if(g?.kind==="action"){Ec(),Wt?.clear(),Vr();return}let f=g?.kind==="server"?g.mentions:null,b=g?.kind==="prompt"?g.sendText:c,C=i.pending?.contentParts,W=(Ze?.hasAttachments()??!1)||(C?.length??0)>0;if(!vC({text:b,hasAttachments:W,attachmentsReady:Ze?.isReady()??!0,hasMentions:Wt?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:Mo(),sendDisabled:ls()}))return;let U=P.isStreaming()?Pp():"block";if(U==="defer-one"&&!i.pending){if(Ce.getState().pendingSubmission){KA("One message is already queued. Edit or remove it first.");return}QA({intent:i,sendText:b,serverMentions:f});return}let $={text:b,mentionRefs:[...Wt?.getMentionRefs()??[],...f?.refs??[]],contentSegments:g?.kind==="prompt"?void 0:Nu(),options:{...Ce.getState().selectedModelId&&{selectedModelId:Ce.getState().selectedModelId},...Ce.getState().activeModeIds.length>0&&{activeModeIds:[...Ce.getState().activeModeIds]},...Ce.getState().quote&&{quote:{...Ce.getState().quote}}},viaVoice:i.viaVoice};i.pending&&($.options={...i.pending.options},$.contentSegments=i.pending.contentSegments,$.mentionRefs=[...i.pending.mentionRefs],$.viaVoice=i.pending.viaVoice);let j=()=>{if(C?.length)return[...C];if(!Ze?.hasAttachments())return;let mt=[...Ze.getContentParts()];return $.text&&mt.push(mo($.text)),mt};$.contentParts=j();let Q=()=>{ts(),zA();let mt=Wt?.collectForSubmit()??null,Qt=VA(mt,f),$t=j();i.consumeDraft!==!1&&Ec();let Pt={selectedModelId:$.options.selectedModelId,activeModeIds:$.options.activeModeIds},an=U==="interrupt";an&&P.cancel(),P.sendMessage($.text,{contentParts:$t,mentions:Qt??void 0,contentSegments:$.contentSegments,viaVoice:$.viaVoice,composerOptions:Pt,...$.options.quote&&{quote:$.options.quote},...an&&{interrupt:!0}}),Ze?.hasAttachments()&&Ze.clearAttachments(),mt&&Wt?.clear(),Vr();let et=Ce.getState().activeModeIds,ln=sC(et,o.composer?.modes);ln.length!==et.length&&Ll(ln),Ce.getState().quote&&Co(void 0),Kl(),Hp.release(),ro()},oe=o.composer?.onBeforeSend;if(!oe){Q();return}let ue=new AbortController;ys=ue;let Xe=mt=>{if(ys=null,mt.status==="error"){YA(mt.error);return}mt.status==="proceed"&&Q()},dt=CC(oe,$,ue.signal);if(!(dt instanceof Promise)){Xe(dt);return}return Ce.setPreparing(!0),dt.then(Xe).finally(()=>Ce.setPreparing(!1))};function QA(i){let c=Ce.getState(),g=Ze?.hasAttachments()??!1,f=g?[...Ze.getContentParts()]:[];g&&i.sendText&&f.push(mo(i.sendText));let b=Qg({text:i.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Wt?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Nu(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});Ns(b),i.intent.consumeDraft!==!1&&Ec(),g&&Ze.clearAttachments(),Wt?.clear(),Vr(),c.quote&&Co(void 0),Kl(),Hp.release(),ro(),El("Message queued. It sends when the response finishes.")}function XA(){let i=Ce.getState().pendingSubmission;i&&(Ns(void 0),Pc(i.text,{consumeDraft:!1,pending:i}))}function JA(i){if(o.messageActions?.showEdit!==!0)return;let c=P.getMessages().find(g=>g.id===i);!c||!Mg(c)||es!==i&&(ts(),es=i,vr=dC({messageId:i,initialText:c.content,onSave:g=>ZA(i,g),onCancel:()=>ts()}),Nt.delete(i),Yn(Pe,P.getMessages(),ut),vr.focus())}function ZA(i,c){let g=vr;if(es=null,vr=null,g?.destroy(),Nt.delete(i),!P.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){Yn(Pe,P.getMessages(),ut);return}En()}function eM(i){if(P.isStreaming())return;let c=Ag(P.getMessages(),i);c&&(ts(),P.resubmitFrom(c,{reason:"retry"})&&En())}Il={regenerate:eM,edit:JA,quote:i=>{let g=P.getMessages().find(f=>f.id===i)?.content?.trim();g&&(Co({text:g,messageId:i}),ae?.focus())}};let Ma=async i=>{if(!tr){tr=!0;try{await wy({resolveInlineCommand:!0,...i})}finally{tr=!1}}};function Tc(i){ls()||(Ec(),Pc(i,{consumeDraft:!1}))}let Pc=(i,c)=>{if(tr)return;tr=!0;let g=()=>{tr=!1};try{let f=wy({...c,overrideText:i});f instanceof Promise?f.finally(g):g()}catch(f){throw g(),f}},tM=i=>{if(i.preventDefault(),P.isStreaming()){P.cancel(),rt?.reset(),ht?.update();return}tr||Ma()},nM=()=>o.features?.composerHistory!==!1,$u={...rm},Uu=!1,Ea=()=>{$u={...rm}},oM=()=>P.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),rM=i=>{if(!ae)return;Uu=!0,ae.value=i,ae.dispatchEvent(new Event("input",{bubbles:!0})),Uu=!1;let c=ae.value.length;ae.setSelectionRange(c,c)},sM=i=>{Uu||(i.isComposing||Wt?.handleInput(i.inputType??void 0),Ea())},iM=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:el(ae)}),aM=i=>{if(ae&&!Mo()&&!(!i.isComposing&&Wt?.handleKeydown(i))){if(nM()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let c=ae.selectionStart===0&&ae.selectionEnd===0,g=FC({direction:i.key==="ArrowUp"?"up":"down",history:oM(),currentValue:ae.value,atStart:c,state:$u});if($u=g.state,g.handled){i.preventDefault(),g.value!==void 0&&rM(g.value);return}}if(jv(i,iM())){if(P.isStreaming()){if(i.preventDefault(),Pp()==="block"||tr||ls())return;Ea(),Ma();return}if(tr){i.preventDefault();return}if(ls()){i.preventDefault();return}Ea(),i.preventDefault(),Me.click()}}},Sy=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(de)){if(ys){ys.abort(),ys=null,i.preventDefault(),i.stopImmediatePropagation();return}P.isStreaming()&&(P.cancel(),rt?.reset(),ht?.update(),Ea(),i.preventDefault(),i.stopImmediatePropagation())}},lM=async i=>{if(o.attachments?.enabled!==!0||!Ze||Mo())return;let c=_I(i.clipboardData);c.length!==0&&(i.preventDefault(),await Ze.handleFiles(c))},Zn=null,Po=!1,di=null,Ct=null,ju=()=>o.voiceRecognition?.completionBehavior==="review";function bs(i){ne?.setAttribute("data-state",i),i==="recording"?dM():Ku()}let Ay="--persona-voice-level",qu=.5,pi=null,zu=-1,kc=0,My=()=>{let i=[],c=On??ne?.parentElement??null;return c&&i.push(c),Le&&i.push(Le),i},Vu=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==zu){zu=c;for(let g of My())g.style.setProperty(Ay,String(c))}},cM=()=>{zu=-1,kc=0;for(let i of My())i.style.removeProperty(Ay)};function dM(){if(pi!==null)return;if(typeof requestAnimationFrame!="function"){Vu(p?P.getVoiceLevel()??qu:qu);return}let i=()=>{pi=requestAnimationFrame(i);let c=p?P.getVoiceLevel():null;if(c===null){Vu(qu);return}kc+=(c-kc)*.3,Vu(kc)};pi=requestAnimationFrame(i)}function Ku(){pi!==null&&(cancelAnimationFrame(pi),pi=null),cM()}let Ey=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Lc=(i="user")=>{if(Po||P.isStreaming())return;let c=Ey();if(!c)return;Zn=new c;let g=o.voiceRecognition??{},f=g.pauseDuration??2e3;Zn.continuous=g.provider?.browser?.continuous??!0,Zn.interimResults=!0,Zn.lang=g.provider?.browser?.language??"en-US";let b=ae.value;Zn.onresult=C=>{let W="",U="";for(let j=0;j<C.results.length;j++){let Q=C.results[j],oe=Q[0].transcript;Q.isFinal?W+=oe+" ":U=oe}let $=b+W+U;ae.value=$,vo(),di&&clearTimeout(di),(W||U)&&(di=window.setTimeout(()=>{if(ae.value.trim()&&Zn&&Po){if(Tr(),ju())return;Ma({viaVoice:!0})}},f))},Zn.onerror=C=>{C.error!=="no-speech"&&Tr()},Zn.onend=()=>{if(Po){let C=ae.value.trim();!ju()&&C&&C!==b.trim()&&Ma({viaVoice:!0}),Tr()}};try{if(Zn.start(),Po=!0,ze.active=!0,i!=="system"&&(ze.manuallyDeactivated=!1),Ko(i),ao(),ro(),ne){let C=o.voiceRecognition??{};Ct={backgroundColor:ne.style.backgroundColor,color:ne.style.color,borderColor:ne.style.borderColor,iconName:C.iconName??"mic",iconSize:parseFloat(C.iconSize??"")||mn};let W=C.recordingBackgroundColor,U=C.recordingIconColor,$=C.recordingBorderColor;if(ne.classList.add("persona-voice-recording"),bs("recording"),ne.style.backgroundColor=W??"var(--persona-voice-recording-bg, #ef4444)",ne.style.color=U??"var(--persona-voice-recording-indicator, #ffffff)",U){let j=ne.querySelector("svg");j&&j.setAttribute("stroke",U)}$&&(ne.style.borderColor=$),ne.setAttribute("aria-label","Stop voice recognition")}}catch{Tr("system")}},Tr=(i="user")=>{if(Po){if(Po=!1,di&&(clearTimeout(di),di=null),Zn){try{Zn.stop()}catch{}Zn=null}if(ze.active=!1,Ko(i),ao(),ro(),ne){if(ne.classList.remove("persona-voice-recording"),bs("idle"),Ct){ne.style.backgroundColor=Ct.backgroundColor,ne.style.color=Ct.color,ne.style.borderColor=Ct.borderColor;let c=ne.querySelector("svg");c&&c.setAttribute("stroke",Ct.color||"currentColor"),Ct=null}ne.setAttribute("aria-label","Start voice recognition")}}},Gu=()=>{if(!ne||Ct)return;let i=o.voiceRecognition??{};Ct={backgroundColor:ne.style.backgroundColor,color:ne.style.color,borderColor:ne.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||mn}},Yu=(i,c)=>{if(!ne)return;let g=ne.querySelector("svg");g&&g.remove();let f=Ct?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||mn),b=le(i,f,c,1.5);b&&ne.appendChild(b)},Ic=()=>{ne&&ne.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ui=()=>{if(!ne)return;Gu();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,g=i.recordingIconColor,f=i.recordingBorderColor;if(Ic(),ne.classList.add("persona-voice-recording"),bs("recording"),ne.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",ne.style.color=g??"var(--persona-voice-recording-indicator, #ffffff)",g){let b=ne.querySelector("svg");b&&b.setAttribute("stroke",g)}f&&(ne.style.borderColor=f),ne.setAttribute("aria-label","Stop voice recognition")},pM=()=>{if(!ne)return;Gu();let i=o.voiceRecognition??{},c=P.getVoiceInterruptionMode(),g=i.processingIconName??"loader",f=i.processingIconColor??Ct?.color??"",b=i.processingBackgroundColor??Ct?.backgroundColor??"",C=i.processingBorderColor??Ct?.borderColor??"";Ic(),ne.classList.add("persona-voice-processing"),bs("processing"),ne.style.backgroundColor=b,ne.style.borderColor=C;let W=f||"currentColor";ne.style.color=W,Yu(g,W),ne.setAttribute("aria-label","Processing voice input"),c==="none"&&(ne.style.cursor="default")},uM=()=>{if(!ne)return;Gu();let i=o.voiceRecognition??{},c=P.getVoiceInterruptionMode(),g=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",f=i.speakingIconName??g,b=i.speakingIconColor??(c==="barge-in"?i.recordingIconColor??Ct?.color??"":Ct?.color??""),C=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Ct?.backgroundColor??""),W=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":Ct?.borderColor??"");Ic(),ne.classList.add("persona-voice-speaking"),bs("speaking"),ne.style.backgroundColor=C,ne.style.borderColor=W;let U=b||"currentColor";ne.style.color=U,Yu(f,U);let $=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";ne.setAttribute("aria-label",$),c==="none"&&(ne.style.cursor="default"),c==="barge-in"&&ne.classList.add("persona-voice-recording")},nr=()=>{ne&&(Ic(),bs("idle"),Ct&&(ne.style.backgroundColor=Ct.backgroundColor??"",ne.style.color=Ct.color??"",ne.style.borderColor=Ct.borderColor??"",Yu(Ct.iconName,Ct.color||"currentColor"),Ct=null),ne.style.cursor="",ne.setAttribute("aria-label","Start voice recognition"))},Qu=()=>{if(!Mo()){if(In(o.voiceRecognition?.provider)){let i=P.getVoiceStatus(),c=P.getVoiceInterruptionMode();if(c==="none"&&(i==="processing"||i==="speaking"))return;if(c==="cancel"&&(i==="processing"||i==="speaking")){P.stopVoicePlayback();return}if(P.isBargeInActive()){P.stopVoicePlayback(),P.deactivateBargeIn().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,ao(),Ko("user"),nr()});return}P.toggleVoice().then(()=>{ze.active=P.isVoiceActive(),ze.manuallyDeactivated=!P.isVoiceActive(),ao(),Ko("user"),P.isVoiceActive()?ui():nr()});return}if(Po){let i=ae.value.trim();ze.manuallyDeactivated=!0,ao(),Tr("user"),i&&!ju()&&Ma()}else ze.manuallyDeactivated=!1,ao(),Lc("user")}};kp=Qu,ne&&me.push(()=>{In(o.voiceRecognition?.provider)?(P.isVoiceActive()&&P.toggleVoice(),nr()):Tr("system")});let gM=A.on("assistant:complete",()=>{Ce.getState().pendingSubmission&&setTimeout(()=>{P.isStreaming()||XA()},0)});me.push(gM);let mM=A.on("assistant:complete",()=>{gh&&(ze.active||ze.manuallyDeactivated||gh==="assistant"&&!ze.lastUserMessageWasVoice||setTimeout(()=>{!ze.active&&!ze.manuallyDeactivated&&(In(o.voiceRecognition?.provider)?P.toggleVoice().then(()=>{ze.active=P.isVoiceActive(),Ko("auto"),P.isVoiceActive()&&ui()}):Lc("auto"))},600))});me.push(mM);let fM=A.on("action:resubmit",()=>{setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)});me.push(fM);let Ty=()=>{gt(!ve,"user")},Et=null,un=null;if(ce&&!be()){let{instance:i,element:c}=Tm({config:o,plugins:a,onToggle:Ty});Et=i,i||(un=c)}Et?e.appendChild(Et.element):un&&e.appendChild(un),da(),zs(),tc(),iu(),pa(P.isStreaming()),Gp()||(Bn()==="follow"?xr(!0):Gl()),WS(),fe&&(!ce||be()?setTimeout(()=>cs(),0):ve&&setTimeout(()=>cs(),200));let vs=null,Py=()=>{vs&&(vs.disconnect(),vs.observe(Le),vs.observe(de))},Ta=()=>{if(be()){zr(),da();return}let i=St(o),c=o.launcher?.sidebarMode??!1,g=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640,C=g.innerWidth<=b,W=f&&C&&ce;try{if(W){Kr(),ea=Nl();return}let U=!1;Bt&&(Bt=!1,Kr(),U=!0);let $=Nl();if(!U&&$!==ea&&(Kr(),U=!0),ea=$,U&&Ol(),!ce&&!i){Se.style.height="",Se.style.width="";return}if(!c&&!i){let Q=o?.launcher?.width??o?.launcherWidth??no;Se.style.width=Q,Se.style.maxWidth=Q}Dl(),Xf()}finally{if(zr(),kl(),da(),ve&&ce){let $=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),j=o.launcher?.sidebarMode??!1,Q=o.launcher?.mobileFullscreen??!0,oe=St(o)&&Q&&$,ue=j||Q&&$&&ce||oe;if(ue&&!Ao){let Xe=e.getRootNode(),dt=Xe instanceof ShadowRoot?Xe.host:e.closest(".persona-host");dt&&!So&&(So=lm(dt,o.launcher?.zIndex??rn)),Ao=cm(e.ownerDocument)}else ue||(So?.(),So=null,Ao?.(),Ao=null)}}};Ta();let Rc=e.ownerDocument.defaultView??window;if(Rc.addEventListener("resize",Ta),me.push(()=>Rc.removeEventListener("resize",Ta)),typeof ResizeObserver<"u"){vs=new ResizeObserver(()=>{kl()}),Py(),me.push(()=>{vs?.disconnect(),vs=null});let i=new ResizeObserver(()=>{yc()});i.observe(de),me.push(()=>i.disconnect())}Rc.addEventListener("resize",yc),me.push(()=>Rc.removeEventListener("resize",yc)),Nn=te.scrollTop;let ky=Oo(te),Ly=()=>{let i=te.scrollTop,c=Oo(te),g=c<ky;if(ky=c,!mr()){Nn=i,Vt();return}let{action:f,nextLastScrollTop:b}=GC({following:Dn.isFollowing(),currentScrollTop:i,lastScrollTop:Nn,nearBottom:ks(te,zo),userScrollThreshold:LS,isAutoScrolling:An||$l||g,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Nn=b,f==="resume"){Yl()||Mn();return}f==="pause"&&sa()};if(te.addEventListener("scroll",Ly,{passive:!0}),me.push(()=>te.removeEventListener("scroll",Ly)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{$S(),sg(Pe)});i.observe(Pe),i.observe(te),me.push(()=>i.disconnect())}let Iy=()=>{mr()&&Dn.isFollowing()&&Yl()&&sa()},Ry=te.ownerDocument;Ry.addEventListener("selectionchange",Iy),me.push(()=>{Ry.removeEventListener("selectionchange",Iy)});let hM=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Hy=i=>{hM.has(i.key)&&(ss(),bf()&&mr()&&Dn.isFollowing()&&sa())},Wy=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(ss(),bf()&&mr()&&Dn.isFollowing()&&sa())};te.addEventListener("keydown",Hy),te.addEventListener("focusin",Wy),me.push(()=>{te.removeEventListener("keydown",Hy),te.removeEventListener("focusin",Wy)});let Oy=i=>{if(i.deltaY!==0&&ss(),!mr())return;let c=YC({following:Dn.isFollowing(),deltaY:i.deltaY,nearBottom:ks(te,zo),resumeWhenNearBottom:!0});c==="pause"?sa():c==="resume"&&!Yl()&&Mn()};te.addEventListener("wheel",Oy,{passive:!0}),te.addEventListener("touchmove",ss,{passive:!0}),te.addEventListener("pointerdown",ss,{passive:!0}),me.push(()=>{te.removeEventListener("touchmove",ss),te.removeEventListener("pointerdown",ss)}),me.push(()=>te.removeEventListener("wheel",Oy)),Dt.addEventListener("click",()=>{lo(),te.scrollTop=te.scrollHeight,Nn=te.scrollTop,Mn(),xr(!0),Vt()}),me.push(()=>Dt.remove()),me.push(()=>{bh(),lo()});let By=()=>{Fe&&(Xr&&(Fe.removeEventListener("click",Xr),Xr=null),Be()?(Fe.style.display="",Xr=()=>{gt(!1,"user")},Fe.addEventListener("click",Xr)):Fe.style.display="none")};By(),(()=>{let{clearChatButton:i}=_e;i&&i.addEventListener("click",()=>{if(To()){Bu({focusComposer:!0}).catch(g=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",g)});return}P.clearMessages(),Nt.clear(),Mn(),Es(_e.composerOverlay);try{localStorage.removeItem(qi),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qi}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==qi)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 c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),K?.clear&&zl(()=>K.clear(),"[AgentWidget] Failed to clear storage adapter:"),Z={},ye.syncFromMetadata(),Ze?.clearAttachments(),Kl(),Ns(void 0),Co(void 0),ts(),He?.clear(),rt?.reset(),ht?.update()})})();let _y=[["keydown",aM],["input",sM],["input",vo],["input",Vr],["keyup",Vr],["paste",lM],["focus",bS]],Dy=i=>{if(i)for(let[c,g]of _y)nt?.addListener(i,c,g)},yM=i=>{if(i)for(let[c,g]of _y)nt?.removeListener(i,c,g)},Ny=()=>{nt&&(nt.addListener(nt.form,"submit",tM),nt.addListener(nt.footer,"click",Vr),Dy(ae),ne&&nt.addListener(ne,"click",Qu))};Ny();let Fy=()=>{Wt?.onComposerSwap((i,c)=>{yM(c),ae=i,nt&&(nt.input=i),Dy(i),Ip(),Zp(),vo()})};Fy();let Xu=!1;function $y(){if(!Xu){Xu=!0;try{let i=ae?.value??"",c=Le.ownerDocument??document,g=ae?c.activeElement===ae:!1;Ku(),nt?.destroy(),nt=null,Wt?.destroy(),Wt=null;let f=null,b=()=>(f=be()?Od({config:o}):Wi({config:o}),f.footer),C=Pf(b)??b();Hn.replaceComposer(C),Le=Hn.composer.footer;let W=f!==null&&C===f.footer;$s=!W,yf=W?f.setSendButtonMode:()=>{},Tf(Le),Lf(Le),If(),Rf(),Hf(),Fy(),Wf(),Rp(),Of(),Ny();let U=Qr.indexOf(qo);qo.destroy(),qo=gl(ur),U>=0&&(Qr[U]=qo),ae&&(ae.value=i),vo(),Vr(),tc(),zs(),pa(P.isStreaming()),ze.active&&bs("recording"),Kr(),Py(),zr(),ro(),Zl(),g&&ae?.focus()}finally{Xu=!1}}}let Pa=e.ownerDocument??document;Pa.addEventListener("keydown",Sy,!0);let Uy=()=>{qp()},jy=()=>{Pa.visibilityState==="hidden"&&qp()};typeof window<"u"&&(window.addEventListener("pagehide",Uy),Pa.addEventListener("visibilitychange",jy),me.push(()=>{window.removeEventListener("pagehide",Uy),Pa.removeEventListener("visibilitychange",jy)}));let qy="persona-attachment-drop-active",ka=0,Ju=()=>{ka=0,de.classList.remove(qy)},gi=()=>o.attachments?.enabled===!0&&Ze!==null&&!Mo(),zy=i=>{!op(i.dataTransfer)||!gi()||(ka++,ka===1&&de.classList.add(qy))},Vy=i=>{!op(i.dataTransfer)||!gi()||(ka--,ka<=0&&Ju())},Ky=i=>{!op(i.dataTransfer)||!gi()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Gy=i=>{if(!op(i.dataTransfer)||!gi())return;i.preventDefault(),i.stopPropagation(),Ju();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&Ze.handleFiles(c)},Pr=!0;de.addEventListener("dragenter",zy,Pr),de.addEventListener("dragleave",Vy,Pr),e.addEventListener("dragover",Ky,Pr),e.addEventListener("drop",Gy,Pr);let Hc=e.ownerDocument,Yy=i=>{gi()&&i.preventDefault()},Qy=i=>{gi()&&i.preventDefault()};Hc.addEventListener("dragover",Yy),Hc.addEventListener("drop",Qy),me.push(()=>{nt?.destroy(),nt=null,Ku(),wo?.destroy(),wo=null,Uo?.destroy(),Uo=null,hr?.destroy(),hr=null,yr?.destroy(),yr=null,fr=null,Tp=null,qp(),ra.destroy(),ci&&clearTimeout(ci),ts(),ys?.abort(),ys=null,Ze?.destroy(),Ze=null,Ce.destroy(),Pa.removeEventListener("keydown",Sy,!0),Wt?.destroy()}),me.push(()=>{de.removeEventListener("dragenter",zy,Pr),de.removeEventListener("dragleave",Vy,Pr),e.removeEventListener("dragover",Ky,Pr),e.removeEventListener("drop",Gy,Pr),Hc.removeEventListener("dragover",Yy),Hc.removeEventListener("drop",Qy),Ju()}),me.push(()=>{P.cancel()}),Et?me.push(()=>{Et?.destroy()}):un&&me.push(()=>{un?.remove()});let Tt={update(i){let c=o.toolCall,g=o.messageActions,f=o.layout?.messages,b=o.colorScheme,C=o.loadingIndicator,W=o.iterationDisplay,U=o.features?.showReasoning,$=o.features?.showToolCalls,j=o.features?.toolCallDisplay,Q=o.features?.reasoningDisplay,oe=o.features?.streamAnimation?.type,ue=o.features?.history?.enabled===!0,Xe=o.features?.history?.provider,dt=o.getIdentityProof,mt=o.clientToken,Qt=o.contextMentions;o=Jd({...o,features:s},i),s=o.features,o=Qd(o),r(),Dp(),ki(e,o),yl(e,o),bl(e,o),Fo(),io(),o.colorScheme!==b&&Jf();let $t=Xd.getForInstance(o.plugins);a.length=0,a.push(...$t),Xh(),ce=o.launcher?.enabled??!0,Je=o.launcher?.autoExpand??!1,vn=o.features?.showReasoning??!0,q=o.features?.showToolCalls??!0,N=o.features?.scrollToBottom??{};let Pt=Bn();z=o.features?.scrollBehavior??{},Pt!==Bn()&&(lo(),Mn()),uh(),wf(),Vt();let an=S;if(S=o.features?.showEventStreamToggle??!1,S&&!an){if(He||(xl(),P.setSSEEventCallback((X,Ve)=>{o.onSSEEvent?.(X,Ve),yp(X,Ve)})),!tt&&Ee){let X=o.features?.eventStream?.classNames,Ve="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"+(X?.toggleButton?" "+X.toggleButton:"");tt=E("button",Ve),tt.style.width="28px",tt.style.height="28px",tt.style.color=hn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Ye=It(gx,"18px","currentColor",1.5);Ye&&tt.appendChild(Ye);let ot=_e.clearChatButtonWrapper,wt=_e.closeButtonWrapper,on=ot||wt;on&&on.parentNode===Ee?Ee.insertBefore(tt,on):Ee.appendChild(tt),tt.addEventListener("click",()=>{Gt?Fs():Lp()})}}else!S&&an&&(Fs(),tt&&(tt.remove(),tt=null),He?.clear(),Te?.destroy(),He=null,Te=null,rt?.reset(),rt=null,Ke=null);if(o.launcher?.enabled===!1&&Et&&(Et.destroy(),Et=null),o.launcher?.enabled===!1&&un&&(un.remove(),un=null),o.launcher?.enabled!==!1&&!Et&&!un){let{instance:X,element:Ve}=Tm({config:o,plugins:a,onToggle:Ty});Et=X,X||(un=Ve),e.appendChild(Ve)}Et&&Et.update(o),Aa(),jr&&o.launcher?.subtitle!==void 0&&(jr.textContent=o.launcher.subtitle);let et=o.layout?.header;if(et?.layout!==Ue&&Ee){let X=et?ml(o,et,{showClose:Be(),onClose:()=>gt(!1,"user")}):$r({config:o,showClose:Be(),onClose:()=>gt(!1,"user")});Hn.replaceHeader(X),Ee=Hn.header.element,Mt=Hn.header.iconHolder,gr=Hn.header.headerTitle,jr=Hn.header.headerSubtitle,Fe=Hn.header.closeButton,Ue=et?.layout,Aa()}else if(et){if(Mt&&(Mt.style.display=et.showIcon===!1?"none":""),gr&&(gr.style.display=et.showTitle===!1?"none":""),jr&&(jr.style.display=et.showSubtitle===!1?"none":""),Fe){let X=Be()&&et.showCloseButton!==!1;Fe.style.display=X?"":"none"}if(_e.clearChatButtonWrapper){let X=et.showClearChat;if(X!==void 0){_e.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:Ve}=_e;Ve&&!Ve.classList.contains("persona-absolute")&&(X?Ve.classList.remove("persona-ml-auto"):Ve.classList.add("persona-ml-auto"))}}}let ko=o.layout?.showHeader!==!1;Ee&&(Ee.style.display=ko?"":"none");let or=o.layout?.showFooter!==!1;Le&&(Le.style.display=or?"":"none"),zr(),Vt(),ce!==Oe?ce?gt(Je,"auto"):(ve=!0,da()):Je!==F&&gt(Je,"auto"),F=Je,Oe=ce,Ta(),By();let Cs=JSON.stringify(o.toolCall)!==JSON.stringify(c),po=JSON.stringify(o.messageActions)!==JSON.stringify(g),tn=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),uo=o.loadingIndicator?.render!==C?.render||o.loadingIndicator?.renderIdle!==C?.renderIdle||o.loadingIndicator?.showBubble!==C?.showBubble,mi=o.iterationDisplay!==W,L=(o.features?.showReasoning??!0)!==(U??!0)||(o.features?.showToolCalls??!0)!==($??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(j)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(Q);(Cs||po||tn||uo||mi||L)&&P&&(ns++,Yn(Pe,P.getMessages(),ut));let Ae=o.features?.streamAnimation?.type;if(Ae!==oe&&Ae&&Ae!=="none"){let X=Fp(Ae,o.features?.streamAnimation?.plugins);X&&dl(X,e)}let re=o.launcher??{},kt=re.headerIconHidden??!1,Ut=o.layout?.header?.showIcon,nn=kt||Ut===!1,jt=re.headerIconName,Kt=re.headerIconSize??"48px";if(Mt){let X=Ee,Ve=X?.querySelector(".persona-flex-col");if(nn)Mt.style.display="none",X&&Ve&&!X.contains(Ve)&&X.insertBefore(Ve,X.firstChild);else{if(Mt.style.display="",Mt.style.height=Kt,Mt.style.width=Kt,X&&Ve&&(X.contains(Mt)?Mt.nextSibling!==Ve&&(Mt.remove(),X.insertBefore(Mt,Ve)):X.insertBefore(Mt,Ve)),jt){let ot=parseFloat(Kt)||24,wt=le(jt,ot*.6,"currentColor",1);wt?Mt.replaceChildren(wt):Mt.textContent=re.agentIconText??"\u{1F4AC}"}else if(re.iconUrl){let ot=Mt.querySelector("img");if(ot)ot.src=re.iconUrl,ot.style.height=Kt,ot.style.width=Kt;else{let wt=document.createElement("img");wt.src=re.iconUrl,wt.alt="",wt.className="persona-rounded-xl persona-object-cover",wt.style.height=Kt,wt.style.width=Kt,Mt.replaceChildren(wt)}}else{let ot=Mt.querySelector("svg"),wt=Mt.querySelector("img");(ot||wt)&&Mt.replaceChildren(),Mt.textContent=re.agentIconText??"\u{1F4AC}"}let Ye=Mt.querySelector("img");Ye&&(Ye.style.height=Kt,Ye.style.width=Kt)}}let Lt=o.layout?.header?.showTitle,cn=o.layout?.header?.showSubtitle;if(gr&&(gr.style.display=Lt===!1?"none":""),jr&&(jr.style.display=cn===!1?"none":""),Fe){let X=Be()&&o.layout?.header?.showCloseButton!==!1;if(Fe.style.display=X?"":"none",!be()){let Xt=re.closeButtonSize??"";Fe.style.height=Xt,Fe.style.width=Xt,Fe.style.minWidth=Xt,Fe.style.minHeight=Xt}let Ve=re.closeButtonPlacement??"inline",{closeButtonWrapper:Ye}=_e,ot=Ve==="top-right",wt=Ye?.classList.contains("persona-absolute");if(Ye&&ot!==wt)if(Ye.remove(),ot){Ye.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Xt=ha??de;Xt.style.position="relative",Xt.appendChild(Ye)}else{let Xt=re.clearChat?.placement??"inline",Jt=re.clearChat?.enabled??!0;Ye.className=Jt&&Xt==="inline"?"":"persona-ml-auto",Ee&&Ee.appendChild(Ye)}if(Fe.style.color=re.closeButtonColor||hn.actionIconColor,re.closeButtonBackgroundColor?(Fe.style.backgroundColor=re.closeButtonBackgroundColor,Fe.classList.remove("hover:persona-bg-gray-100")):(Fe.style.backgroundColor="",Fe.classList.add("hover:persona-bg-gray-100")),re.closeButtonBorderWidth||re.closeButtonBorderColor){let Xt=re.closeButtonBorderWidth||"0px",Jt=re.closeButtonBorderColor||"transparent";Fe.style.border=`${Xt} solid ${Jt}`,Fe.classList.remove("persona-border-none")}else Fe.style.border="",Fe.classList.add("persona-border-none");re.closeButtonBorderRadius?(Fe.style.borderRadius=re.closeButtonBorderRadius,Fe.classList.remove("persona-rounded-full")):(Fe.style.borderRadius="",Fe.classList.add("persona-rounded-full")),re.closeButtonPaddingX?(Fe.style.paddingLeft=re.closeButtonPaddingX,Fe.style.paddingRight=re.closeButtonPaddingX):(Fe.style.paddingLeft="",Fe.style.paddingRight=""),re.closeButtonPaddingY?(Fe.style.paddingTop=re.closeButtonPaddingY,Fe.style.paddingBottom=re.closeButtonPaddingY):(Fe.style.paddingTop="",Fe.style.paddingBottom=""),Hd(Fe,re.closeButtonIconName??"x",{iconSize:be()?Sm:void 0,iconText:re.closeButtonIconText??"\xD7"});let on=re.closeButtonTooltipText??"Close chat",go=re.closeButtonShowTooltip??!0;Fe.setAttribute("aria-label",on),Ye&&Zt({anchor:Fe,trigger:Ye,text:()=>Fe?.getAttribute("aria-label")??on,enabled:go})}let{clearChatButton:Re,clearChatButtonWrapper:De}=_e;if(Re){let X=re.clearChat??{},Ve=X.enabled??!0,Ye=o.layout?.header?.showClearChat,ot=Ye!==void 0?Ye:Ve,wt=X.placement??"inline";if(De){De.style.display=ot?"":"none";let{closeButtonWrapper:on}=_e;!be()&&on&&!on.classList.contains("persona-absolute")&&(ot?on.classList.remove("persona-ml-auto"):on.classList.add("persona-ml-auto"));let go=wt==="top-right",Xt=De.classList.contains("persona-absolute");if(!be()&&go!==Xt&&ot){if(De.remove(),go){De.className="persona-absolute persona-top-4 persona-z-50",De.style.right="48px";let Lo=ha??de;Lo.style.position="relative",Lo.appendChild(De)}else{De.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",De.style.right="";let Lo=_e.closeButtonWrapper;Ee&&Lo&&Lo.parentElement===Ee?Ee.insertBefore(De,Lo):Ee&&Ee.appendChild(De)}let Jt=_e.closeButtonWrapper;Jt&&!Jt.classList.contains("persona-absolute")&&(go?Jt.classList.add("persona-ml-auto"):Jt.classList.remove("persona-ml-auto"))}}if(ot){if(!be()){let Jt=X.size??"";Re.style.height=Jt,Re.style.width=Jt,Re.style.minWidth=Jt,Re.style.minHeight=Jt}let on=X.iconColor??"";if(Re.style.color=on||hn.actionIconColor,Hd(Re,X.iconName??"refresh-cw",{iconSize:be()?Am:void 0}),X.backgroundColor?(Re.style.backgroundColor=X.backgroundColor,Re.classList.remove("hover:persona-bg-gray-100")):(Re.style.backgroundColor="",Re.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let Jt=X.borderWidth||"0px",Lo=X.borderColor||"transparent";Re.style.border=`${Jt} solid ${Lo}`,Re.classList.remove("persona-border-none")}else Re.style.border="",Re.classList.add("persona-border-none");X.borderRadius?(Re.style.borderRadius=X.borderRadius,Re.classList.remove("persona-rounded-full")):(Re.style.borderRadius="",Re.classList.add("persona-rounded-full")),X.paddingX?(Re.style.paddingLeft=X.paddingX,Re.style.paddingRight=X.paddingX):(Re.style.paddingLeft="",Re.style.paddingRight=""),X.paddingY?(Re.style.paddingTop=X.paddingY,Re.style.paddingBottom=X.paddingY):(Re.style.paddingTop="",Re.style.paddingBottom="");let go=X.tooltipText??"Clear chat",Xt=X.showTooltip??!0;Re.setAttribute("aria-label",go),De&&Zt({anchor:Re,trigger:De,text:()=>Re?.getAttribute("aria-label")??go,enabled:Xt})}}let we=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zd],dn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ji.message,ji.messageAndClick];ye=ep({parsers:we,handlers:dn,getSessionMetadata:pe,updateSessionMetadata:se,emit:A.emit,documentRef:typeof document<"u"?document:null}),ut=yx(o,ye,Rt),sA(),P.updateConfig(o),(o.features?.history?.enabled===!0!==ue||o.features?.history?.provider!==Xe||o.getIdentityProof!==dt||o.clientToken!==mt)&&(Tn({restoreFocus:!1}),jh()),Er(),yc(),Yn(Pe,P.getMessages(),ut),zs(),tc(),oA(),pa(P.isStreaming()),Qt!==o.contextMentions&&$y();let kr=o.voiceRecognition?.enabled===!0,Pn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),kn=In(o.voiceRecognition?.provider);if(kr&&(Pn||kn))if(!ne||!On){let X=Pi(o);if(X){ne=X.button,On=X.wrapper;let Ve=bo&&bo.parentElement===Al?bo:null;Al?Al.insertBefore(On,Ve):oo?.appendChild(On),nt&&(nt.micButton=ne),nt?.addListener(ne,"click",Qu),ne.disabled=Mo()||P.isStreaming()&&!Xp()}}else{let X=o.voiceRecognition??{},Ve=o.sendButton??{},Ye=X.iconName??"mic",ot=X.iconSize,wt=parseFloat(ot??"")||mn;ne.classList.add(jn),ne.classList.toggle(ho,!ot),ne.style.width=ot??"",ne.style.height=ot??"",ne.style.minWidth=ot??"",ne.style.minHeight=ot??"";let on=X.iconColor??Ve.textColor;ne.innerHTML="";let go=le(Ye,wt,on||"currentColor",1.5);go?ne.appendChild(go):ne.textContent="\u{1F3A4}";let Xt=X.backgroundColor??Ve.backgroundColor;Xt?ne.style.backgroundColor=Xt:ne.style.backgroundColor="",on?ne.style.color=on:ne.style.color="var(--persona-text, #111827)",X.borderWidth?(ne.style.borderWidth=X.borderWidth,ne.style.borderStyle="solid"):(ne.style.borderWidth="",ne.style.borderStyle=""),X.borderColor?ne.style.borderColor=X.borderColor:ne.style.borderColor="",X.paddingX?(ne.style.paddingLeft=X.paddingX,ne.style.paddingRight=X.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),X.paddingY?(ne.style.paddingTop=X.paddingY,ne.style.paddingBottom=X.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let Jt=X.tooltipText??"Start voice recognition",Lo=X.showTooltip??!1;ne.setAttribute("aria-label",Jt),On&&Zt({anchor:ne,trigger:On,text:()=>ne?.getAttribute("aria-label")??Jt,enabled:Lo}),On.style.display="",ne.disabled=Mo()||P.isStreaming()&&!Xp()}else ne&&On&&(On.style.display="none",In(o.voiceRecognition?.provider)?P.isVoiceActive()&&P.toggleVoice():Po&&Tr());if(o.attachments?.enabled===!0){if(!xn||!xt){let X=o.attachments??{};Sn||(Sn=E("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Sn.style.display="none",(ae.parentElement??oo).insertBefore(Sn,ae)),yt||(yt=document.createElement("input"),yt.type="file",yt.accept=(X.allowedTypes??ar).join(","),yt.multiple=(X.maxFiles??4)>1,yt.style.display="none",yt.setAttribute("aria-label","Attach files"),(ae.parentElement??oo).insertBefore(yt,ae)),xn=E("div","persona-send-button-wrapper"),xt=E("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${jn} ${ho}`),xt.type="button",xt.setAttribute("aria-label",X.buttonTooltipText??"Attach file");let Ve=X.buttonIconName??"paperclip";xt.style.fontSize="18px",xt.style.lineHeight="1";let Ye=le(Ve,mn,"currentColor",1.5);Ye?xt.appendChild(Ye):xt.textContent="\u{1F4CE}",xt.addEventListener("click",wt=>{wt.preventDefault(),yt?.click()}),xn.appendChild(xt);let ot=X.buttonTooltipText??"Attach file";Zt({anchor:xt,trigger:xn,text:()=>xt?.getAttribute("aria-label")??ot}),wp?wp.append(xn):oo.appendChild(xn),nt&&(nt.attachmentButton=xt,nt.attachmentInput=yt??void 0,nt.attachmentPreviews=Sn??void 0),!Ze&&yt&&Sn&&(Ze=Mi.fromConfig(X,xf),Ze.setPreviewsContainer(Sn),nt?.addListener(yt,"change",async()=>{Ze&&yt?.files&&(await Ze.handleFileSelect(yt.files),yt.value="")}))}else{xn.style.display="";let X=o.attachments??{};yt&&(yt.accept=(X.allowedTypes??ar).join(","),yt.multiple=(X.maxFiles??4)>1),Ze&&Ze.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles,adapter:X.adapter})}if(de.querySelector(".persona-attachment-drop-overlay")?.remove(),de.appendChild(bx(o.attachments?.dropOverlay)),xt){let X=o.attachments??{},Ve=X.buttonTooltipText??"Attach file";xt.setAttribute("aria-label",Ve),xt.textContent="";let Ye=le(X.buttonIconName??"paperclip",mn,"currentColor",1.5);Ye?xt.appendChild(Ye):xt.textContent="\u{1F4CE}",xn&&Zt({anchor:xt,trigger:xn,text:()=>xt?.getAttribute("aria-label")??Ve})}}else xn&&(xn.style.display="none"),Ze&&Ze.clearAttachments(),de.querySelector(".persona-attachment-drop-overlay")?.remove();let We=o.sendButton??{},rr=We.useIcon??!1,Ot=We.iconText??"\u2191",Ln=We.iconName,Ia=We.tooltipText??"Send message",CM=We.showTooltip??!1,Ra=We.size,wM=parseFloat(Ra??"")||$g,Wc=We.backgroundColor,Ha=We.textColor;if(rr){if(Me.style.width=Ra??"",Me.style.height=Ra??"",Me.style.minWidth=Ra??"",Me.style.minHeight=Ra??"",Me.style.fontSize="18px",Me.style.lineHeight="1",Ha?Me.style.color=Ha:Me.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!P.isStreaming())if(Me.innerHTML="",Ln){let X=parseFloat(We.iconSize??"")||Math.round(wM*.5),Ve=Ha?.trim()||"currentColor",Ye=We.iconStrokeWidth??2,ot=le(Ln,X,Ve,Ye),wt=le(We.stopIconName??"square",X,Ve,Ye);ot&&wt?Me.appendChild(Ug(ot,wt)):ot?Me.appendChild(ot):Me.textContent=Ot}else Me.textContent=Ot;Me.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${jn}`,Wc?(Me.style.backgroundColor=Wc,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",Wc?(Me.style.backgroundColor=Wc,Me.classList.remove("persona-bg-persona-accent")):Me.classList.add("persona-bg-persona-accent"),Ha?Me.style.color=Ha:Me.classList.add("persona-text-white");We.borderWidth?(Me.style.borderWidth=We.borderWidth,Me.style.borderStyle="solid"):(Me.style.borderWidth="",Me.style.borderStyle=""),We.borderColor?Me.style.borderColor=We.borderColor:Me.style.borderColor="",We.paddingX?(Me.style.paddingLeft=We.paddingX,Me.style.paddingRight=We.paddingX):(Me.style.paddingLeft="",Me.style.paddingRight=""),We.paddingY?(Me.style.paddingTop=We.paddingY,Me.style.paddingBottom=We.paddingY):(Me.style.paddingTop="",Me.style.paddingBottom=""),P.isStreaming()||Me.setAttribute("aria-label",Ia),Zl(),bo&&Zt({anchor:Me,trigger:bo,text:()=>Me.getAttribute("aria-label")??Ia,enabled:CM}),_f();let Xy=vd(Ce.getState().activeModeIds,o.composer?.modes);Ce.setActiveModeIds(Xy),_s().length>0!==!!Uo&&Rp(),Uo?.render(Xy,_s());for(let X of[...Ds.keys()])bd(X,o.composer?.modeGroups)||Ds.delete(X);Ds.forEach(X=>X.repaint()),fr?.repaint(),wo?.resolve();let Oc=Dr(o,be());if(Np(),Oc){Pe.style.maxWidth=Oc,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%",Wn.style.maxWidth=Oc,Wn.style.marginLeft="auto",Wn.style.marginRight="auto",Wn.style.width="100%";for(let X of[oo,ur,Sn,st])X&&(X.style.maxWidth=Oc,X.style.marginLeft="auto",X.style.marginRight="auto",X.style.width="100%")}else{Pe.style.maxWidth="",Pe.style.marginLeft="",Pe.style.marginRight="",Pe.style.width="",Wn.style.maxWidth="",Wn.style.marginLeft="",Wn.style.marginRight="",Wn.style.width="";for(let X of[oo,ur,Sn,st])X&&(X.style.maxWidth="",X.style.marginLeft="",X.style.marginRight="",X.style.width="")}let Lr=o.statusIndicator??{},xM=Lr.visible??!0;if(st.style.display=xM?"":"none",P){let X=P.getStatus();Sl(st,(Ye=>Ye==="idle"?Lr.idleText??qt.idle:Ye==="connecting"?Lr.connectingText??qt.connecting:Ye==="connected"?Lr.connectedText??qt.connected:Ye==="error"?Lr.errorText??qt.error:qt[Ye])(X),Lr,X)}st.classList.remove("persona-text-left","persona-text-center","persona-text-right");let SM=Lr.align==="left"?"persona-text-left":Lr.align==="center"?"persona-text-center":"persona-text-right";st.classList.add(SM),Ip(),Zp(),ro(),bp()},open(){Be()&&gt(!0,"api")},close(){Be()&&gt(!1,"api")},toggle(){Be()&&gt(!ve,"api")},reconnect(){P.reconnectNow()},clearChat(){jo=!1,P.clearMessages(),Nt.clear(),Mn();try{localStorage.removeItem(qi),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qi}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==qi)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),K?.clear&&zl(()=>K.clear(),"[AgentWidget] Failed to clear storage adapter:"),Z={},ye.syncFromMetadata(),Ze?.clearAttachments(),Kl(),Ns(void 0),Co(void 0),ts(),He?.clear(),rt?.reset(),ht?.update()},setMessage(i){return!ae||P.isStreaming()||Mo()?!1:(!ve&&Be()&&gt(!0,"system"),ae.value=i,ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(P.isStreaming()||ls())return!1;let c=i?.trim()||ae.value.trim();return c?(!ve&&Be()&&gt(!0,"system"),ae.value="",ae.style.height="auto",vo(),Pc(c,{consumeDraft:!1}),!0):!1},getComposerState(){return Ce.getState()},setQuote(i){let c=i?.text?.trim();c&&Co({...i,text:c})},clearQuote(){Co(void 0)},startVoiceRecognition(){return P.isStreaming()?!1:In(o.voiceRecognition?.provider)?(P.isVoiceActive()||P.isBargeInActive()||(!ve&&Be()&&gt(!0,"system"),ze.manuallyDeactivated=!1,ao(),P.toggleVoice().then(()=>{ze.active=P.isVoiceActive(),Ko("user"),P.isVoiceActive()&&ui()})),!0):Po?!0:Ey()?(!ve&&Be()&&gt(!0,"system"),ze.manuallyDeactivated=!1,ao(),Lc("user"),!0):!1},stopVoiceRecognition(){return In(o.voiceRecognition?.provider)?!P.isVoiceActive()&&!P.isBargeInActive()?!1:((P.isBargeInActive()?P.deactivateBargeIn():P.toggleVoice()).then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,ao(),Ko("user"),nr()}),!0):Po?(ze.manuallyDeactivated=!0,ao(),Tr("user"),!0):!1},injectMessage(i){return!ve&&Be()&&gt(!0,"system"),P.injectMessage(i)},injectAssistantMessage(i){!ve&&Be()&&gt(!0,"system");let c=P.injectAssistantMessage(i);return xe&&(xe=!1,bt&&(clearTimeout(bt),bt=null),setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)),c},injectUserMessage(i){return!ve&&Be()&&gt(!0,"system"),P.injectUserMessage(i)},injectSystemMessage(i){return!ve&&Be()&&gt(!0,"system"),P.injectSystemMessage(i)},injectMessageBatch(i){return!ve&&Be()&&gt(!0,"system"),P.injectMessageBatch(i)},injectComponentDirective(i){return!ve&&Be()&&gt(!0,"system"),P.injectComponentDirective(i)},injectTestMessage(i){!ve&&Be()&&gt(!0,"system"),P.injectTestEvent(i)},async connectStream(i,c){return P.connectStream(i,c)},__pushEventStreamEvent(i){S&&(xl(),yp(i.type,i.payload))},showEventStream(){S&&Lp()},hideEventStream(){Gt&&Fs()},isEventStreamVisible(){return Gt},listConversations(i){return P.listConversations(i)},getActiveConversationId(){return P.getActiveConversationId()},openConversation(i,c){return Ou(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return Bu({focusComposer:i?.focus===!0})},deleteConversation(i){return fy(i)},renameConversation(i,c){return _u(i,{title:c})},setConversationStarred(i,c){return _u(i,{starred:c})},clearConversationHistory(i){return hy(i)},resetHistoryIdentity(){return yy()},getHistoryIdentityStatus(){return Fn?Fn.getIdentityStatus():bu()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return Sa({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){Tn(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return At},showArtifacts(){bn(o)&&(jo=!1,Us=!0,io(),qe?.setMobileOpen(!0))},hideArtifacts(){bn(o)&&(jo=!0,io())},upsertArtifact(i){return bn(o)?(sr(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(jo=!1,Us=!0),P.upsertArtifact(i)):null},selectArtifact(i){bn(o)&&P.selectArtifact(i)},clearArtifacts(){bn(o)&&P.clearArtifacts()},getArtifacts(){return P?.getArtifacts()??[]},getSelectedArtifactId(){return P?.getSelectedArtifactId()??null},focusInput(){return ce&&!ve&&!be()||!ae?!1:(ae.focus(),!0)},async resolveApproval(i,c,g){let b=P.getMessages().find(C=>C.variant==="approval"&&C.approval?.id===i);if(!b?.approval)throw new Error(`Approval not found: ${i}`);if(b.approval.toolType==="webmcp"){P.resolveWebMcpApproval(b.id,c);return}return P.resolveApproval(b.approval,c,g)},setFollowUpSuggestions(i){PS(i)},clearFollowUpSuggestions(){ph()},getMessages(){return P.getMessages()},getStatus(){return P.getStatus()},getPersistentMetadata(){return{...Z}},updatePersistentMetadata(i){se(i)},on(i,c){return A.on(i,c)},off(i,c){A.off(i,c)},isOpen(){return Be()&&ve},isVoiceActive(){return ze.active},toggleReadAloud(i){P.toggleReadAloud(i)},stopReadAloud(){P.stopSpeaking()},getReadAloudState(i){return P.getReadAloudState(i)},onReadAloudChange(i){return P.onReadAloudChange(i)},getState(){return{open:Be()&&ve,launcherEnabled:ce,voiceActive:ze.active,streaming:P.isStreaming()}},showCSATFeedback(i){!ve&&Be()&&gt(!0,"system");let c=Pe.querySelector(".persona-feedback-container");c&&c.remove();let g=Qm({onSubmit:async(f,b)=>{P.isClientTokenMode()&&await P.submitCSATFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});Pe.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!ve&&Be()&&gt(!0,"system");let c=Pe.querySelector(".persona-feedback-container");c&&c.remove();let g=Xm({onSubmit:async(f,b)=>{P.isClientTokenMode()&&await P.submitNPSFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});Pe.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,c){return P.submitCSATFeedback(i,c)},async submitNPSFeedback(i,c){return P.submitNPSFeedback(i,c)},destroy(){pu(),ps!=null&&(clearInterval(ps),ps=null),me.forEach(i=>i()),Ge.remove(),Yt?.remove(),Et?.destroy(),un?.remove(),Xr&&Fe.removeEventListener("click",Xr)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:Tt,getMessages:Tt.getMessages,getStatus:Tt.getStatus,getMetadata:Tt.getPersistentMetadata,updateMetadata:Tt.updatePersistentMetadata,clearHistory:()=>Tt.clearChat(),setVoiceActive:g=>g?Tt.startVoiceRecognition():Tt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,me.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),c=j=>{let Q=j.detail;(!Q?.instanceId||Q.instanceId===i)&&Tt.focusInput()};if(window.addEventListener("persona:focusInput",c),me.push(()=>{window.removeEventListener("persona:focusInput",c)}),S){let j=oe=>{let ue=oe.detail;(!ue?.instanceId||ue.instanceId===i)&&Tt.showEventStream()},Q=oe=>{let ue=oe.detail;(!ue?.instanceId||ue.instanceId===i)&&Tt.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",Q),me.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",Q)})}let g=j=>{let Q=j.detail;(!Q?.instanceId||Q.instanceId===i)&&Tt.showHistory()},f=j=>{let Q=j.detail;(!Q?.instanceId||Q.instanceId===i)&&Tt.hideHistory()};window.addEventListener("persona:showHistory",g),window.addEventListener("persona:hideHistory",f),me.push(()=>{window.removeEventListener("persona:showHistory",g),window.removeEventListener("persona:hideHistory",f)});let b=j=>{let Q=j.detail;(!Q?.instanceId||Q.instanceId===i)&&Tt.showArtifacts()},C=j=>{let Q=j.detail;(!Q?.instanceId||Q.instanceId===i)&&Tt.hideArtifacts()},W=j=>{let Q=j.detail;Q?.instanceId&&Q.instanceId!==i||Q?.artifact&&Tt.upsertArtifact(Q.artifact)},U=j=>{let Q=j.detail;Q?.instanceId&&Q.instanceId!==i||typeof Q?.id=="string"&&Tt.selectArtifact(Q.id)},$=j=>{let Q=j.detail;(!Q?.instanceId||Q.instanceId===i)&&Tt.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",U),window.addEventListener("persona:clearArtifacts",$),me.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",U),window.removeEventListener("persona:clearArtifacts",$)})}let eo=DI(o.persistState);if(eo&&Be()){let i=NI(eo.storage),c=`${eo.keyPrefix}widget-open`,g=`${eo.keyPrefix}widget-voice`,f=`${eo.keyPrefix}widget-voice-mode`;if(i){let b=eo.persist?.openState&&i.getItem(c)==="true",C=eo.persist?.voiceState&&i.getItem(g)==="true",W=eo.persist?.voiceState&&i.getItem(f)==="true";if(b&&(Et?.setPanelOpen(!0,"auto"),setTimeout(()=>{Tt.open(),setTimeout(()=>{if(C||W)Tt.startVoiceRecognition();else if(eo.persist?.focusInput){let U=e.querySelector("textarea");U&&U.focus()}},100)},0)),eo.persist?.openState&&(A.on("widget:opened",()=>{i.setItem(c,"true")}),A.on("widget:closed",()=>{i.setItem(c,"false")})),eo.persist?.voiceState&&(A.on("voice:state",U=>{i.setItem(g,U.active?"true":"false")}),A.on("user:message",U=>{i.setItem(f,U.viaVoice?"true":"false")})),eo.clearOnChatClear){let U=()=>{i.removeItem(c),i.removeItem(g),i.removeItem(f)},$=()=>U();window.addEventListener("persona:clear-chat",$),me.push(()=>{window.removeEventListener("persona:clear-chat",$)})}}}if(J&&Be()&&(Et?.setPanelOpen(!0,"auto"),setTimeout(()=>{Tt.open()},0)),Js(),!kS){let i=Oa(()=>{P&&(ns++,Nt.clear(),Yn(Pe,P.getMessages(),ut))});me.push(i)}x=()=>{P&&(ns++,Nt.clear(),Yn(Pe,P.getMessages(),ut))},P.getMessages().length>0&&Jl(),T=()=>{P&&(ns++,Nt.clear(),Yn(Pe,P.getMessages(),ut))};let bM=rb(()=>{P&&(ns++,Nt.clear(),Yn(Pe,P.getMessages(),ut))});me.push(bM);let vM=Om(()=>{P&&(ns++,Nt.clear(),Yn(Pe,P.getMessages(),ut),lr()?.updateInlineArtifactBlocks(Pe,Gn.artifacts,{suppressTransition:!0}),io())});return me.push(vM),Tt};var vx=(e,t)=>{let n=e.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,t*parseFloat(r[1])/100):420},UI=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},jI=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},qI=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.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."+(t.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 ${t.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.")},Cx=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},of=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},wx=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",of(e)},ef=e=>{e.style.transition=""},tf=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},nf=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},rp=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},zI=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},VI=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},KI=e=>{let t=Ps(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:fn(t,r)??r;return{inset:o(n?.inset,Cd),canvasBackground:o(n?.canvasBackground,wd)}},xx=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},GI=(e,t,n,o,r,s,a,l)=>{let d=qn(s),p=d.reveal==="push",u=l!=null,m=l?.inset??"",y=l?.canvasBackground??"";zI(e,t,n,o,p),VI(e,t,n,o,d.side,p),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=d.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",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 h=e.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,x=s?.launcher?.mobileBreakpoint??640,w=h!=null?h.innerWidth<=x:!1;if(v&&w&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),tf(t),ef(o),wx(o),nf(n),rp(r,o),xx(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.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??rn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),wx(o),UI(o,d.maxHeight),xx(o,u&&a,m,y),d.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",tf(t),ef(o),nf(n),rp(r,o);let O=d.animate?"transform 180ms ease":"none",D=d.side==="right"?"translateX(100%)":"translateX(-100%)",T=a?"translateX(0)":D;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=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=O,o.style.transform=T,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ef(o),of(o),rp(r,o);let O=vx(d.width,e.clientWidth),D=Math.max(0,e.clientWidth),T=d.animate?"margin-left 180ms ease":"none",I=d.side==="right"?a?-O:0:a?0:-O;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${D+O}px`,t.style.transition=T,t.style.marginLeft=`${I}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${D}px`,n.style.maxWidth=`${D}px`,n.style.minWidth=`${D}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",tf(t),of(o),nf(n),rp(r,o);let O=d.reveal==="emerge";O?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let D=a?d.width:"0px",T=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",I=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${D}`,o.style.width=D,o.style.maxWidth=D,o.style.minWidth=D,o.style.minHeight="0",jI(o,d.maxHeight),o.style.overflow=O||I?"hidden":"visible",o.style.transition=T,O){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let A=u?`calc(${vx(d.width,e.clientWidth)}px - (2 * ${m}))`:d.width;r.style.width=A,r.style.minWidth=A,r.style.maxWidth=A,r.style.boxSizing="border-box"}}},YI=(e,t)=>{let n=e.ownerDocument.createElement("div");return Cx(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Cx(n,o)},destroy(){n.remove()}}},QI=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.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=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),p=n.createElement("aside"),u=n.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",p.appendChild(u),o.insertBefore(a,e),d.appendChild(e);let y=null,h=()=>{y?.disconnect(),y=null},v=null,x=()=>{v=t?.launcher?.detachedPanel===!0?KI(t):null};x();let w=()=>{GI(a,l,d,p,u,t,m,v)},k=null,O=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=nl(()=>{x(),w()}))},D=()=>{h(),qn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{w()}),y.observe(a)))},T=!1,I=()=>{w(),D(),m&&!T&&a.dataset.personaDockMobileFullscreen!=="true"&&(T=!0,qI(a,qn(t)))},A=a.ownerDocument.defaultView,_=()=>{I()};return A?.addEventListener("resize",_),qn(t).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),I(),O(),{mode:"docked",host:u,shell:a,syncWidgetState(K){let ie=K.launcherEnabled?K.open:!0;m!==ie&&(m=ie,I())},updateConfig(K){t=K,(t?.launcher?.enabled??!0)===!1&&(m=!0),x(),I(),O()},destroy(){A?.removeEventListener("resize",_),k?.(),k=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},sp=(e,t)=>St(t)?QI(e,t):YI(e,t);var XI=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Sx=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},ip=[],JI=()=>[...ip],Ax=e=>{let t=XI(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=sp(t,r),a,l=[],d=(w,k)=>{let D=!(k?.launcher?.enabled??!0)||St(k),T=o.createElement("div");if(T.setAttribute("data-persona-root","true"),D&&(T.style.height="100%",T.style.display="flex",T.style.flexDirection="column",T.style.flex="1",T.style.minHeight="0",T.style.minWidth="0"),n){let I=w.attachShadow({mode:"open"});I.appendChild(T),Sx(I,o)}else w.appendChild(T),Sx(w,o);return t.id&&T.setAttribute("data-persona-instance",t.id),T},p=()=>{s.syncWidgetState(a.getState())},u=()=>{l.forEach(w=>w()),l=[a.on("widget:opened",p),a.on("widget:closed",p)],p()},m=()=>{let w=d(s.host,r);a=Zm(w,r,{debugTools:e.debugTools}),u()},y=()=>{l.forEach(w=>w()),l=[],a.destroy()};m(),e.onChatReady?.();let h=w=>{y(),s.destroy(),s=sp(t,w),r=w,m()},v={update(w){let k=Jd(r??{},w),O=St(r),D=St(k),T=Fr(r),I=Fr(k);if(O!==D||T!==I){h(k);return}r=k,s.updateConfig(r),a.update(w),p()},destroy(){y(),s.destroy();let w=ip.indexOf(x);w!==-1&&ip.splice(w,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},x=new Proxy(v,{get(w,k,O){if(k==="host")return s.host;if(k in w)return Reflect.get(w,k,O);let D=a[k];return typeof D=="function"?D.bind(a):D}});return ip.push(x),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=x),x};var kx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),ZI=new Set(["button","a","input","select","textarea","details","summary"]),eR=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),rf=/\b(product|card|item|listing|result)\b/i,af=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,tR=3e3,nR=100;function Lx(e){let t=typeof e.className=="string"?e.className:"";if(rf.test(t)||e.id&&rf.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&rf.test(o.value))return!0}return!1}function Ix(e){return af.test((e.textContent??"").trim())}function Rx(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function oR(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Mx(e){let t=e.match(af);return t?t[0]:null}function Ex(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function rR(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var sR="commerce-card",iR="result-card";function Tx(e){return!Lx(e)||!Ix(e)||!Rx(e)&&!oR(e)?0:5200}function Px(e){return!Lx(e)||Ix(e)||!Rx(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Hx=[{id:sR,scoreElement(e){return Tx(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||af.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Tx(e)===0)return null;let{title:n,href:o}=Ex(e),r=Mx((e.textContent??"").trim())??Mx(t.text)??"",s=rR(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
138
+ `)}},{id:iR,scoreElement(e){return Px(e)},formatSummary(e,t){if(Px(e)===0)return null;let{title:n,href:o}=Ex(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
139
+ `)}}];function aR(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function lR(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,l=t.mode??"structured",d=t.maxCandidates??Math.max(500,n*10),p=e.rules??Hx;return l==="simple"&&e.rules&&e.rules.length>0?(aR(),p=[]):l==="simple"&&(p=[]),{mode:l,maxElements:n,maxCandidates:d,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:p}}function sf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var cR=["data-testid","data-product","data-action","data-id","data-name","data-type"];function dR(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||ZI.has(t)||n&&eR.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Wx(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function pR(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let l=e.getAttribute("name");l&&(t.name=l);let d=e.getAttribute("role");d&&(t.role=d);for(let p=0;p<e.attributes.length;p++){let u=e.attributes[p];u.name.startsWith("data-")&&(t[u.name]=u.value)}return t}function Ox(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${sf(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of cR){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${sf(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(a=>sf(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let l=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(l>=0){let d=`${r}:nth-of-type(${l+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function uR(e){return e==="static"?nR:tR}function Bx(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Ox(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:dR(e),attributes:pR(e)}}function gR(e,t,n,o){let r=uR(t.interactivity),s=null;for(let a of n){let l=a.scoreElement(e,t,o);l>0&&(r+=l,a.formatSummary&&!s&&(s=a))}return{score:r,formattingRule:s}}function mR(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function fR(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=a.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let p=l,u=p.tagName.toLowerCase();if(kx.has(u)){l=a.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){l=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Wx(p)){l=a.nextNode();continue}let m=Bx(p,e.maxTextLength),y=m.text.length>0,h=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(w=>w==="role");if(!y&&!h){l=a.nextNode();continue}if(o.has(m.selector)){l=a.nextNode();continue}o.add(m.selector);let{score:v,formattingRule:x}=gR(p,m,e.rules,n);r.push({el:p,domIndex:s,enriched:m,score:v,formattingRule:x}),s+=1}l=a.nextNode()}r.sort((p,u)=>{let m=p.enriched.interactivity==="static"?1:0,y=u.enriched.interactivity==="static"?1:0;return m!==y?m-y:u.score!==p.score?u.score-p.score:p.domIndex-u.domIndex});let d=[];for(let p of r){if(d.length>=e.maxElements)break;mR(d,p)||d.push(p)}return d.sort((p,u)=>{let m=p.enriched.interactivity==="static"?1:0,y=u.enriched.interactivity==="static"?1:0;return m!==y?m-y:m===1&&u.score!==p.score?u.score-p.score:p.domIndex-u.domIndex}),d.map(p=>{let u;if(p.formattingRule?.formatSummary){let y=p.formattingRule.formatSummary(p.el,p.enriched,n);y&&(u=y)}let m={...p.enriched};return u&&(m.formattedSummary=u),m})}function hR(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,p=d.tagName.toLowerCase();if(kx.has(p)){s=r.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Wx(d)){s=r.nextNode();continue}let u=Bx(d,e.maxTextLength),m=u.text.length>0,y=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(h=>h==="role");if(!m&&!y){s=r.nextNode();continue}o.has(u.selector)||(o.add(u.selector),n.push(u))}s=r.nextNode()}let a=[],l=[];for(let d of n)d.interactivity!=="static"?a.push(d):l.push(d);return[...a,...l].slice(0,e.maxElements)}function yR(e={}){let t=lR(e),n=t.root??document.body;return n?t.mode==="simple"?hR(t,n):fR(t,n):[]}var ap=100;function bR(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);s.length>0&&o.push(`Structured summaries:
140
140
  ${s.map(a=>`- ${a.split(`
141
141
  `).join(`
142
142
  `)}`).join(`
143
- `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(a=>`- ${a.selector}: "${a.text.substring(0,dp)}" (clickable)`);o.push(`Interactive elements:
143
+ `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(a=>`- ${a.selector}: "${a.text.substring(0,ap)}" (clickable)`);o.push(`Interactive elements:
144
144
  ${s.join(`
145
- `)}`)}if(r.navigable.length>0){let s=r.navigable.map(a=>`- ${a.selector}${a.attributes.href?`[href="${a.attributes.href}"]`:""}: "${a.text.substring(0,dp)}" (navigable)`);o.push(`Navigation links:
145
+ `)}`)}if(r.navigable.length>0){let s=r.navigable.map(a=>`- ${a.selector}${a.attributes.href?`[href="${a.attributes.href}"]`:""}: "${a.text.substring(0,ap)}" (navigable)`);o.push(`Navigation links:
146
146
  ${s.join(`
147
- `)}`)}if(r.input.length>0){let s=r.input.map(a=>`- ${a.selector}${a.attributes.type?`[type="${a.attributes.type}"]`:""}: "${a.text.substring(0,dp)}" (input)`);o.push(`Form inputs:
147
+ `)}`)}if(r.input.length>0){let s=r.input.map(a=>`- ${a.selector}${a.attributes.type?`[type="${a.attributes.type}"]`:""}: "${a.text.substring(0,ap)}" (input)`);o.push(`Form inputs:
148
148
  ${s.join(`
149
- `)}`)}if(r.static.length>0){let s=r.static.map(a=>`- ${a.selector}: "${a.text.substring(0,dp)}"`);o.push(`Content:
149
+ `)}`)}if(r.static.length>0){let s=r.static.map(a=>`- ${a.selector}: "${a.text.substring(0,ap)}"`);o.push(`Content:
150
150
  ${s.join(`
151
151
  `)}`)}return o.join(`
152
152
 
153
- `)}var fR={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Wx={components:{panel:{borderRadius:"0",shadow:"none"}}},Ox={id:"shop",label:"Shopping Assistant",config:{theme:fR,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:oo},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},Bx={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Wx}},_x={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Wx}},Dx={shop:Ox,minimal:Bx,fullscreen:_x};function hR(e){return Dx[e]}var yR=wx;function bR(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function vR(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function CR(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:Uo(e.colors.primary,.95),100:Uo(e.colors.primary,.9),200:Uo(e.colors.primary,.8),300:Uo(e.colors.primary,.7),400:Uo(e.colors.primary,.6),500:e.colors.primary,600:Uo(e.colors.primary,.8),700:Uo(e.colors.primary,.7),800:Uo(e.colors.primary,.6),900:Uo(e.colors.primary,.5),950:Uo(e.colors.primary,.45)}}),{...t,palette:n}}}}function wR(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function xR(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Uo(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(o+(255-o)*(1-t)),l=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}function SR(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}function lf(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,n=>`%${n.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fo}/dist`}function fr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function AR(e){if(e)return{getHeaders:fr(e.getHeaders),onFeedback:fr(e.onFeedback),onCopy:fr(e.onCopy),requestMiddleware:fr(e.requestMiddleware),actionHandlers:fr(e.actionHandlers),actionParsers:fr(e.actionParsers),postprocessMessage:fr(e.postprocessMessage),contextProviders:fr(e.contextProviders),streamParser:fr(e.streamParser)}}var Nx=`({ text, message }: any) => {
153
+ `)}var vR={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},_x={components:{panel:{borderRadius:"0",shadow:"none"}}},Dx={id:"shop",label:"Shopping Assistant",config:{theme:vR,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:no},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},Nx={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:_x}},Fx={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:_x}},$x={shop:Dx,minimal:Nx,fullscreen:Fx};function CR(e){return $x[e]}var wR=Ax;function xR(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function SR(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function AR(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:No(e.colors.primary,.95),100:No(e.colors.primary,.9),200:No(e.colors.primary,.8),300:No(e.colors.primary,.7),400:No(e.colors.primary,.6),500:e.colors.primary,600:No(e.colors.primary,.8),700:No(e.colors.primary,.7),800:No(e.colors.primary,.6),900:No(e.colors.primary,.5),950:No(e.colors.primary,.45)}}),{...t,palette:n}}}}function MR(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function ER(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function No(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(o+(255-o)*(1-t)),l=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}function TR(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}function lf(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,n=>`%${n.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Ro}/dist`}function pr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function PR(e){if(e)return{getHeaders:pr(e.getHeaders),onFeedback:pr(e.onFeedback),onCopy:pr(e.onCopy),requestMiddleware:pr(e.requestMiddleware),actionHandlers:pr(e.actionHandlers),actionParsers:pr(e.actionParsers),postprocessMessage:pr(e.postprocessMessage),contextProviders:pr(e.contextProviders),streamParser:pr(e.streamParser)}}var Ux=`({ text, message }: any) => {
154
154
  const jsonSource = (message as any).rawContent || text || message.content;
155
155
  if (!jsonSource || typeof jsonSource !== 'string') return null;
156
156
  let cleanJson = jsonSource
@@ -163,7 +163,7 @@ ${s.join(`
163
163
  if (parsed.action) return { type: parsed.action, payload: parsed };
164
164
  } catch (e) { return null; }
165
165
  return null;
166
- }`,Fx=`function(ctx) {
166
+ }`,jx=`function(ctx) {
167
167
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
168
168
  if (!jsonSource || typeof jsonSource !== 'string') return null;
169
169
  var cleanJson = jsonSource
@@ -176,7 +176,7 @@ ${s.join(`
176
176
  if (parsed.action) return { type: parsed.action, payload: parsed };
177
177
  } catch (e) { return null; }
178
178
  return null;
179
- }`,$x=`(action: any, context: any) => {
179
+ }`,qx=`(action: any, context: any) => {
180
180
  if (action.type !== 'nav_then_click') return;
181
181
  const payload = action.payload || action.raw || {};
182
182
  const url = payload?.page;
@@ -193,7 +193,7 @@ ${s.join(`
193
193
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
194
194
  window.location.href = targetUrl;
195
195
  return { handled: true, displayText: text };
196
- }`,Ux=`function(action, context) {
196
+ }`,zx=`function(action, context) {
197
197
  if (action.type !== 'nav_then_click') return;
198
198
  var payload = action.payload || action.raw || {};
199
199
  var url = payload.page;
@@ -210,27 +210,27 @@ ${s.join(`
210
210
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
211
211
  window.location.href = targetUrl;
212
212
  return { handled: true, displayText: text };
213
- }`,MR=`(parsed: any) => {
213
+ }`,kR=`(parsed: any) => {
214
214
  if (!parsed || typeof parsed !== 'object') return null;
215
215
  if (parsed.action === 'nav_then_click') return 'Navigating...';
216
216
  if (parsed.action === 'message') return parsed.text || '';
217
217
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
218
218
  return parsed.text || null;
219
- }`,ER=`function(parsed) {
219
+ }`,LR=`function(parsed) {
220
220
  if (!parsed || typeof parsed !== 'object') return null;
221
221
  if (parsed.action === 'nav_then_click') return 'Navigating...';
222
222
  if (parsed.action === 'message') return parsed.text || '';
223
223
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
224
224
  return parsed.text || null;
225
- }`;function TR(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function pp(e){return e.parserType??TR(e.streamParser)??"plain"}function up(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,r])=>{typeof r=="string"&&n.push(`${t} ${o}: "${r}",`)}),n.push(`${t}},`)),n}function gp(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([a,l])=>a!=="onFeedback"&&a!=="onCopy"&&l!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,l])=>{a==="onFeedback"||a==="onCopy"||(typeof l=="string"?o.push(`${t} ${a}: "${l}",`):typeof l=="boolean"&&o.push(`${t} ${a}: ${l},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function mp(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(o||r)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function fp(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
226
- `);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,a=r===n.length-1?",":"";return`${s}${o}${a}`})}function hp(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([l,d])=>{typeof d=="string"?n.push(`${t} ${l}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${l}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,p])=>{d!=="format"&&(typeof p=="string"?n.push(`${t} ${d}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${d}: ${p},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function cf(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function jx(e,t,n){Object.entries(t).forEach(([o,r])=>{if(!(r===void 0||typeof r=="function")){if(Array.isArray(r)){e.push(`${n}${o}: ${JSON.stringify(r)},`);return}if(r&&typeof r=="object"){e.push(`${n}${o}: {`),jx(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Kr(e,t,n,o){n&&(e.push(`${o}${t}: {`),jx(e,n,`${o} `),e.push(`${o}},`))}function xl(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function kR(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:AR(n.hooks)}:void 0;return t==="esm"?PR(o,r):t==="script-installer"?RR(o,r):t==="script-advanced"?WR(o,r):t==="react-component"?LR(o,r):t==="react-advanced"?IR(o,r):HR(o,r)}function PR(e,t){let n=t?.hooks,o=pp(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${xl(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Kr(s,"theme",e.theme," "),e.launcher&&Kr(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,l])=>{s.push(` ${a}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,l])=>{typeof l=="string"?s.push(` ${a}: "${l}",`):typeof l=="boolean"&&s.push(` ${a}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,l])=>{typeof l=="string"?s.push(` ${a}: "${l}",`):typeof l=="boolean"?s.push(` ${a}: ${l},`):typeof l=="number"&&s.push(` ${a}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,l])=>{typeof l=="string"?s.push(` ${a}: "${l}",`):typeof l=="boolean"&&s.push(` ${a}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,l])=>{s.push(` ${a}: ${l},`)}),s.push(" },")),s.push(...fp(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...up(e," ")),s.push(...gp(e," ",n)),s.push(...mp(e," ")),s.push(...hp(e," ")),s.push(...cf(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
227
- `)}function LR(e,t){let n=t?.hooks,o=pp(e),r=o!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${xl(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Kr(s,"theme",e.theme," "),e.launcher&&Kr(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,l])=>{s.push(` ${a}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,l])=>{typeof l=="string"?s.push(` ${a}: "${l}",`):typeof l=="boolean"&&s.push(` ${a}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,l])=>{typeof l=="string"?s.push(` ${a}: "${l}",`):typeof l=="boolean"?s.push(` ${a}: ${l},`):typeof l=="number"&&s.push(` ${a}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,l])=>{typeof l=="string"?s.push(` ${a}: "${l}",`):typeof l=="boolean"&&s.push(` ${a}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,l])=>{s.push(` ${a}: ${l},`)}),s.push(" },")),s.push(...fp(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...up(e," ")),s.push(...gp(e," ",n)),s.push(...mp(e," ")),s.push(...hp(e," ")),s.push(...cf(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
228
- `)}function IR(e,t){let n=t?.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${xl(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Kr(o,"theme",e.theme," "),e.launcher&&Kr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),o.push(...fp(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...up(e," ")),o.push(...gp(e," ",n)),o.push(...mp(e," ")),o.push(...hp(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${MR}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${Nx}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${Nx}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${$x}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${$x}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
229
- `)}function qx(e){let t=pp(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestions&&(o.suggestions=e.suggestions),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&(r[s]=a)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,a])=>{s!=="onFeedback"&&s!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(r[s]=a)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([a,l])=>{a!=="render"&&(typeof l=="string"||typeof l=="boolean")&&(s[a]=l)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([a,l])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof l=="object"&&l!==null)s.avatar=l;else if(a==="timestamp"&&typeof l=="object"&&l!==null){let d={};Object.entries(l).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(d[p]=u)}),Object.keys(d).length>0&&(s.timestamp=d)}else(typeof l=="string"||typeof l=="boolean")&&(s[a]=l)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function RR(e,t){let n=qx(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="${lf(t)}/install.global.js" data-config='${s}'></script>`}function HR(e,t){let n=t?.hooks,o=pp(e),r=o!=="plain",s=lf(t),a=["<!-- Load CSS -->",`<link rel="stylesheet" href="${s}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${s}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${xl(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),r&&a.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Kr(a,"theme",e.theme," "),e.launcher&&Kr(a,"launcher",e.launcher," "),e.copy&&(a.push(" copy: {"),Object.entries(e.copy).forEach(([l,d])=>{a.push(` ${l}: "${d}",`)}),a.push(" },")),e.sendButton&&(a.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([l,d])=>{typeof d=="string"?a.push(` ${l}: "${d}",`):typeof d=="boolean"&&a.push(` ${l}: ${d},`)}),a.push(" },")),e.voiceRecognition&&(a.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([l,d])=>{typeof d=="string"?a.push(` ${l}: "${d}",`):typeof d=="boolean"?a.push(` ${l}: ${d},`):typeof d=="number"&&a.push(` ${l}: ${d},`)}),a.push(" },")),e.statusIndicator&&(a.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([l,d])=>{typeof d=="string"?a.push(` ${l}: "${d}",`):typeof d=="boolean"&&a.push(` ${l}: ${d},`)}),a.push(" },")),e.features&&(a.push(" features: {"),Object.entries(e.features).forEach(([l,d])=>{a.push(` ${l}: ${d},`)}),a.push(" },")),a.push(...fp(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(" suggestionChips: ["),e.suggestionChips.forEach(l=>{a.push(` "${l}",`)}),a.push(" ],")),e.suggestionChipsConfig&&(a.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(" },")),a.push(...up(e," ")),a.push(...gp(e," ",n)),a.push(...mp(e," ")),a.push(...hp(e," ")),a.push(...cf(n," ")),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),a.push(" }"),a.push(" });"),a.push("</script>"),a.join(`
230
- `)}function WR(e,t){let n=t?.hooks,o=qx(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
225
+ }`;function IR(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function lp(e){return e.parserType??IR(e.streamParser)??"plain"}function cp(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,r])=>{typeof r=="string"&&n.push(`${t} ${o}: "${r}",`)}),n.push(`${t}},`)),n}function dp(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([a,l])=>a!=="onFeedback"&&a!=="onCopy"&&l!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,l])=>{a==="onFeedback"||a==="onCopy"||(typeof l=="string"?o.push(`${t} ${a}: "${l}",`):typeof l=="boolean"&&o.push(`${t} ${a}: ${l},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function pp(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(o||r)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function up(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
226
+ `);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,a=r===n.length-1?",":"";return`${s}${o}${a}`})}function gp(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([l,d])=>{typeof d=="string"?n.push(`${t} ${l}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${l}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,p])=>{d!=="format"&&(typeof p=="string"?n.push(`${t} ${d}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${d}: ${p},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function cf(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function Vx(e,t,n){Object.entries(t).forEach(([o,r])=>{if(!(r===void 0||typeof r=="function")){if(Array.isArray(r)){e.push(`${n}${o}: ${JSON.stringify(r)},`);return}if(r&&typeof r=="object"){e.push(`${n}${o}: {`),Vx(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Ur(e,t,n,o){n&&(e.push(`${o}${t}: {`),Vx(e,n,`${o} `),e.push(`${o}},`))}function vl(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function RR(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:PR(n.hooks)}:void 0;return t==="esm"?HR(o,r):t==="script-installer"?BR(o,r):t==="script-advanced"?DR(o,r):t==="react-component"?WR(o,r):t==="react-advanced"?OR(o,r):_R(o,r)}function HR(e,t){let n=t?.hooks,o=lp(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${vl(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ur(s,"theme",e.theme," "),e.launcher&&Ur(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,l])=>{s.push(` ${a}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,l])=>{typeof l=="string"?s.push(` ${a}: "${l}",`):typeof l=="boolean"&&s.push(` ${a}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,l])=>{typeof l=="string"?s.push(` ${a}: "${l}",`):typeof l=="boolean"?s.push(` ${a}: ${l},`):typeof l=="number"&&s.push(` ${a}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,l])=>{typeof l=="string"?s.push(` ${a}: "${l}",`):typeof l=="boolean"&&s.push(` ${a}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,l])=>{s.push(` ${a}: ${l},`)}),s.push(" },")),s.push(...up(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...cp(e," ")),s.push(...dp(e," ",n)),s.push(...pp(e," ")),s.push(...gp(e," ")),s.push(...cf(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
227
+ `)}function WR(e,t){let n=t?.hooks,o=lp(e),r=o!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${vl(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ur(s,"theme",e.theme," "),e.launcher&&Ur(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,l])=>{s.push(` ${a}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,l])=>{typeof l=="string"?s.push(` ${a}: "${l}",`):typeof l=="boolean"&&s.push(` ${a}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,l])=>{typeof l=="string"?s.push(` ${a}: "${l}",`):typeof l=="boolean"?s.push(` ${a}: ${l},`):typeof l=="number"&&s.push(` ${a}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,l])=>{typeof l=="string"?s.push(` ${a}: "${l}",`):typeof l=="boolean"&&s.push(` ${a}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,l])=>{s.push(` ${a}: ${l},`)}),s.push(" },")),s.push(...up(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...cp(e," ")),s.push(...dp(e," ",n)),s.push(...pp(e," ")),s.push(...gp(e," ")),s.push(...cf(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
228
+ `)}function OR(e,t){let n=t?.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${vl(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ur(o,"theme",e.theme," "),e.launcher&&Ur(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),o.push(...up(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...cp(e," ")),o.push(...dp(e," ",n)),o.push(...pp(e," ")),o.push(...gp(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${kR}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${Ux}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${Ux}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${qx}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${qx}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
229
+ `)}function Kx(e){let t=lp(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestions&&(o.suggestions=e.suggestions),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&(r[s]=a)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,a])=>{s!=="onFeedback"&&s!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(r[s]=a)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([a,l])=>{a!=="render"&&(typeof l=="string"||typeof l=="boolean")&&(s[a]=l)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([a,l])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof l=="object"&&l!==null)s.avatar=l;else if(a==="timestamp"&&typeof l=="object"&&l!==null){let d={};Object.entries(l).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(d[p]=u)}),Object.keys(d).length>0&&(s.timestamp=d)}else(typeof l=="string"||typeof l=="boolean")&&(s[a]=l)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function BR(e,t){let n=Kx(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="${lf(t)}/install.global.js" data-config='${s}'></script>`}function _R(e,t){let n=t?.hooks,o=lp(e),r=o!=="plain",s=lf(t),a=["<!-- Load CSS -->",`<link rel="stylesheet" href="${s}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${s}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${vl(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),r&&a.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ur(a,"theme",e.theme," "),e.launcher&&Ur(a,"launcher",e.launcher," "),e.copy&&(a.push(" copy: {"),Object.entries(e.copy).forEach(([l,d])=>{a.push(` ${l}: "${d}",`)}),a.push(" },")),e.sendButton&&(a.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([l,d])=>{typeof d=="string"?a.push(` ${l}: "${d}",`):typeof d=="boolean"&&a.push(` ${l}: ${d},`)}),a.push(" },")),e.voiceRecognition&&(a.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([l,d])=>{typeof d=="string"?a.push(` ${l}: "${d}",`):typeof d=="boolean"?a.push(` ${l}: ${d},`):typeof d=="number"&&a.push(` ${l}: ${d},`)}),a.push(" },")),e.statusIndicator&&(a.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([l,d])=>{typeof d=="string"?a.push(` ${l}: "${d}",`):typeof d=="boolean"&&a.push(` ${l}: ${d},`)}),a.push(" },")),e.features&&(a.push(" features: {"),Object.entries(e.features).forEach(([l,d])=>{a.push(` ${l}: ${d},`)}),a.push(" },")),a.push(...up(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(" suggestionChips: ["),e.suggestionChips.forEach(l=>{a.push(` "${l}",`)}),a.push(" ],")),e.suggestionChipsConfig&&(a.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(" },")),a.push(...cp(e," ")),a.push(...dp(e," ",n)),a.push(...pp(e," ")),a.push(...gp(e," ")),a.push(...cf(n," ")),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),a.push(" }"),a.push(" });"),a.push("</script>"),a.join(`
230
+ `)}function DR(e,t){let n=t?.hooks,o=Kx(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
231
231
  `).map((a,l)=>l===0?a:" "+a).join(`
232
- `)};`,""," // Constants",` var CDN_BASE = '${lf(t)}';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n?.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n?.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${ER});`),s.push(" };")),s.push(""),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Fx}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Fx}`),s.push(" ];")),s.push(""),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Ux}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Ux}`),s.push(" ];")),s.push(""),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n?.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n?.onFeedback||n?.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${xl(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
233
- `)}import{ChevronDown as OR}from"lucide";var zx={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Vx=.1,Kx=.15,Gx=1.5,df=24,Yx=40,BR=`
232
+ `)};`,""," // Constants",` var CDN_BASE = '${lf(t)}';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n?.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n?.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${LR});`),s.push(" };")),s.push(""),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${jx}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${jx}`),s.push(" ];")),s.push(""),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${zx}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${zx}`),s.push(" ];")),s.push(""),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n?.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n?.onFeedback||n?.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${vl(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
233
+ `)}import{ChevronDown as NR}from"lucide";var Gx={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Yx=.1,Qx=.15,Xx=1.5,df=24,Jx=40,FR=`
234
234
  /* \u2500\u2500 Root \u2500\u2500 */
235
235
  .persona-dc-root {
236
236
  display: flex;
@@ -471,10 +471,10 @@ ${s.join(`
471
471
  min-height: 300px;
472
472
  }
473
473
  }
474
- `;function _R(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=BR,document.head.appendChild(e)}function DR(e,t){let n=e.clientWidth-df*2-Yx,o=e.clientHeight-df*2-Yx;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function NR(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function FR(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:l=!0,showColorSchemeToggle:d=!0,onChange:p}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");_R();let u=Math.max(0,Math.min(o,n.length-1)),m=r,y=s,h=null,C=1,S=!1,x=M("div","persona-dc-root"),P=M("div","persona-dc-toolbar"),O=M("div","persona-dc-toolbar-lead"),$=M("div","persona-dc-toolbar-trail"),T=qn({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Fe(-1)}),R=M("div");R.style.position="relative";let A=M("button","persona-dc-title-btn");A.type="button",A.setAttribute("aria-expanded","false"),A.setAttribute("aria-haspopup","listbox");let N=M("span","persona-dc-title-text"),G=M("span","persona-dc-title-chevron"),ae=Wt(OR,12,"currentColor",2);ae&&G.appendChild(ae),A.append(N,G);let Y=M("div","persona-dc-dropdown");Y.setAttribute("role","listbox"),Y.style.display="none";let E=!1;function B(){Y.innerHTML="";for(let Pe=0;Pe<n.length;Pe++){let At=n[Pe],Yt=M("button","persona-dc-dropdown-item");Yt.type="button",Yt.setAttribute("role","option"),Yt.setAttribute("aria-current",Pe===u?"true":"false");let ft=M("span");if(ft.textContent=At.title,Yt.appendChild(ft),At.description){let pn=M("span","persona-dc-dropdown-desc");pn.textContent=At.description,Yt.appendChild(pn)}Yt.addEventListener("click",()=>{L(),mt(Pe)}),Y.appendChild(Yt)}}function H(){E=!E,Y.style.display=E?"":"none",A.setAttribute("aria-expanded",E?"true":"false"),E&&B()}function L(){E&&(E=!1,Y.style.display="none",A.setAttribute("aria-expanded","false"))}A.addEventListener("click",Pe=>{Pe.stopPropagation(),H()});let ee=()=>L();document.addEventListener("click",ee),R.append(A,Y);let K=qn({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Fe(1)}),ue=M("span","persona-dc-counter");O.append(T,R,K,ue);let le=null;l&&(le=_d({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:Pe=>{m=Pe,Ge.dataset.device=m,h=null,Ce()}}),$.appendChild(le.element));let me=null;if(a){let Pe=M("div","persona-dc-zoom-controls"),At=qn({icon:"minus",label:"Zoom out",size:14,onClick:()=>{h=Math.max(Kx,(h??C)-Vx),Ce()}});me=M("span","persona-dc-zoom-level"),me.title="Reset to 100%",me.style.cursor="pointer",me.addEventListener("click",()=>{h=1,Ce()});let Yt=qn({icon:"plus",label:"Zoom in",size:14,onClick:()=>{h=Math.min(Gx,(h??C)+Vx),Ce()}}),ft=qn({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{h=null,Ce()}});Pe.append(At,me,Yt,ft),$.appendChild(Pe)}if(d){let Pe=M("div","persona-dc-separator");$.appendChild(Pe);let At=_d({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:Yt=>{y=Yt,Ge.dataset.colorScheme=y,j()}});$.appendChild(At.element)}let Re=M("div","persona-dc-separator");$.appendChild(Re);let He=qn({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[u].url,"_blank")}});$.appendChild(He),P.append(O,$);let ve=M("div","persona-dc-stage"),Ge=M("div","persona-dc-iframe-wrapper");Ge.dataset.device=m,Ge.dataset.colorScheme=y;let be=M("iframe","persona-dc-iframe");be.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),be.setAttribute("loading","lazy"),be.title=n[u].title,Ge.appendChild(be),ve.appendChild(Ge),x.append(P,ve),e.appendChild(x);function j(){try{let Pe=be.contentDocument?.body;if(!Pe)return;y==="dark"?Pe.classList.add("theme-dark"):Pe.classList.remove("theme-dark")}catch{}}be.addEventListener("load",()=>j());function _e(){let Pe=n[u];N.textContent=Pe.title,ue.textContent=`${u+1} / ${n.length}`,be.title=Pe.title}function Fe(Pe){let At=((u+Pe)%n.length+n.length)%n.length;mt(At)}function mt(Pe){Pe<0||Pe>=n.length||(u=Pe,be.src=n[u].url,_e(),p?.(u,n[u]))}function Ce(){if(S)return;let Pe=zx[m]??zx.desktop;C=DR(ve,Pe);let At=Math.max(Kx,Math.min(Gx,h??C));NR(Ge,be,Pe,At,m),me&&(me.textContent=`${Math.round(At*100)}%`)}let Ee=new ResizeObserver(()=>Ce());Ee.observe(ve),_e(),be.src=n[u].url,requestAnimationFrame(()=>Ce());function he(){S||(S=!0,Ee.disconnect(),document.removeEventListener("click",ee),x.remove())}return{element:x,goTo:mt,next:()=>Fe(1),prev:()=>Fe(-1),getIndex:()=>u,setDevice(Pe){m=Pe,Ge.dataset.device=Pe,le?.setSelected(Pe),h=null,Ce()},setColorScheme(Pe){y=Pe,Ge.dataset.colorScheme=Pe},setZoom(Pe){h=Pe,Ce()},destroy:he}}kg();var Qx=16e3,$R=24e3,UR=4096,jR=4,qR=1380533830;function zR(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===qR?new Uint8Array(e,44):new Uint8Array(e)}function VR(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Sl=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.levelCallbacks=[];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 t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)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:Qx,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(m=>m.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:Qx});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Li($R);if(r!==this.callGeneration){d.destroy(),s.getTracks().forEach(m=>m.stop()),l.close().catch(()=>{});return}this.playback=d,d.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let p=`${VR(o)}/ws/agents/${encodeURIComponent(t)}/voice`,u=new WebSocket(p,["runtype.bearer",n]);u.binaryType="arraybuffer",this.ws=u,u.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,u,r))},u.onmessage=m=>this.handleMessage(m,r),u.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},u.onclose=m=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(m.code!==1e3){let y=m.code?` (code ${m.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),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}onLevel(t){this.levelCallbacks.push(t)}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(UR,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),p=new Int16Array(d.length),u=0;for(let m=0;m<d.length;m++){let y=Math.max(-1,Math.min(1,d[m]));u+=y*y,p[m]=y<0?y*32768:y*32767}if(o.send(p.buffer),this.levelCallbacks.length>0){let m=Math.sqrt(u/d.length),y=Math.max(0,Math.min(1,m*jR));for(let h of this.levelCallbacks)h(y)}},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.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(t,n){if(n!==this.callGeneration||!this.playback)return;let o=zR(t);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(t=>t.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(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var $s=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,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(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Al(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Sl(e.runtype);case"browser":if(!$s.isSupported())throw new Error("Browser speech recognition not supported");return new $s(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;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: ${e.type}`)}}function pf(e){if(e?.type==="custom"&&e.custom)return Al({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Al({type:"runtype",runtype:e.runtype});if($s.isSupported())return Al({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Xx(e){try{return pf(e),!0}catch{return!1}}var Jx="webmcp:",KR=e=>e.startsWith(Jx)?e.slice(Jx.length):e,yp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},vp=class{constructor(t,n){this.config=t;this.deps=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return yp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.deps.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s=YR(r.annotations);return{name:r.name,description:r.description,parametersSchema:QR(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return vo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let C=typeof document<"u"&&!!document.modelContext;return vo(C?"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=KR(t),a;try{a=await r.getTools()}catch(C){let S=C instanceof Error?C.message:String(C);return vo(`Failed to read WebMCP registry: ${S}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(C=>C.name===s);if(!l)return vo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return vo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return vo("Aborted by cancel()");let d=this.deps.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(p))return vo("User declined the tool call.");if(o?.aborted)return vo("Aborted by cancel()");let u=new AbortController,m=!1,y=setTimeout(()=>{m=!0,u.abort()},this.timeoutMs),h=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",h,{once:!0}));try{let C=await r.executeTool(l,eH(n),{signal:u.signal});return XR(C)}catch(C){if(m)return vo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return vo("Aborted by cancel()");let S=C instanceof Error?C.message:String(C);return vo(S)}finally{clearTimeout(y),o&&o.removeEventListener("abort",h)}}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}(await this.deps.loadPolyfill()).initializeWebMCPPolyfill(),this.installed=!0}catch(t){yp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,yp.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):t}async requestConfirm(t){let n=this.confirmHandler??JR;try{return await n(t)}catch(o){return yp.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>GR(t,o))}},GR=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},bp={type:"object",properties:{}},YR=e=>{if(!e||typeof e!="object")return;let t={...typeof e.readOnlyHint=="boolean"?{readOnlyHint:e.readOnlyHint}:{},...typeof e.untrustedContentHint=="boolean"?{untrustedContentHint:e.untrustedContentHint}:{}};return Object.keys(t).length>0?t:void 0},QR=e=>{if(e===void 0||e==="")return{...bp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...bp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...bp}}catch{return{...bp}}},XR=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:tH(t)}]}},vo=e=>({isError:!0,content:[{type:"text",text:e}]}),JR=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=ZR(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
474
+ `;function $R(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=FR,document.head.appendChild(e)}function UR(e,t){let n=e.clientWidth-df*2-Jx,o=e.clientHeight-df*2-Jx;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function jR(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function qR(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:l=!0,showColorSchemeToggle:d=!0,onChange:p}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");$R();let u=Math.max(0,Math.min(o,n.length-1)),m=r,y=s,h=null,v=1,x=!1,w=E("div","persona-dc-root"),k=E("div","persona-dc-toolbar"),O=E("div","persona-dc-toolbar-lead"),D=E("div","persona-dc-toolbar-trail"),T=Vn({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ue(-1)}),I=E("div");I.style.position="relative";let A=E("button","persona-dc-title-btn");A.type="button",A.setAttribute("aria-expanded","false"),A.setAttribute("aria-haspopup","listbox");let _=E("span","persona-dc-title-text"),K=E("span","persona-dc-title-chevron"),ie=It(NR,12,"currentColor",2);ie&&K.appendChild(ie),A.append(_,K);let Z=E("div","persona-dc-dropdown");Z.setAttribute("role","listbox"),Z.style.display="none";let M=!1;function B(){Z.innerHTML="";for(let xe=0;xe<n.length;xe++){let bt=n[xe],Rt=E("button","persona-dc-dropdown-item");Rt.type="button",Rt.setAttribute("role","option"),Rt.setAttribute("aria-current",xe===u?"true":"false");let ut=E("span");if(ut.textContent=bt.title,Rt.appendChild(ut),bt.description){let vn=E("span","persona-dc-dropdown-desc");vn.textContent=bt.description,Rt.appendChild(vn)}Rt.addEventListener("click",()=>{R(),Bt(xe)}),Z.appendChild(Rt)}}function H(){M=!M,Z.style.display=M?"":"none",A.setAttribute("aria-expanded",M?"true":"false"),M&&B()}function R(){M&&(M=!1,Z.style.display="none",A.setAttribute("aria-expanded","false"))}A.addEventListener("click",xe=>{xe.stopPropagation(),H()});let J=()=>R();document.addEventListener("click",J),I.append(A,Z);let V=Vn({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ue(1)}),pe=E("span","persona-dc-counter");O.append(T,I,V,pe);let se=null;l&&(se=Wd({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:xe=>{m=xe,Je.dataset.device=m,h=null,be()}}),D.appendChild(se.element));let ge=null;if(a){let xe=E("div","persona-dc-zoom-controls"),bt=Vn({icon:"minus",label:"Zoom out",size:14,onClick:()=>{h=Math.max(Qx,(h??v)-Yx),be()}});ge=E("span","persona-dc-zoom-level"),ge.title="Reset to 100%",ge.style.cursor="pointer",ge.addEventListener("click",()=>{h=1,be()});let Rt=Vn({icon:"plus",label:"Zoom in",size:14,onClick:()=>{h=Math.min(Xx,(h??v)+Yx),be()}}),ut=Vn({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{h=null,be()}});xe.append(bt,ge,Rt,ut),D.appendChild(xe)}if(d){let xe=E("div","persona-dc-separator");D.appendChild(xe);let bt=Wd({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:Rt=>{y=Rt,Je.dataset.colorScheme=y,F()}});D.appendChild(bt.element)}let Ie=E("div","persona-dc-separator");D.appendChild(Ie);let ye=Vn({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[u].url,"_blank")}});D.appendChild(ye),k.append(O,D);let ce=E("div","persona-dc-stage"),Je=E("div","persona-dc-iframe-wrapper");Je.dataset.device=m,Je.dataset.colorScheme=y;let fe=E("iframe","persona-dc-iframe");fe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),fe.setAttribute("loading","lazy"),fe.title=n[u].title,Je.appendChild(fe),ce.appendChild(Je),w.append(k,ce),e.appendChild(w);function F(){try{let xe=fe.contentDocument?.body;if(!xe)return;y==="dark"?xe.classList.add("theme-dark"):xe.classList.remove("theme-dark")}catch{}}fe.addEventListener("load",()=>F());function Oe(){let xe=n[u];_.textContent=xe.title,pe.textContent=`${u+1} / ${n.length}`,fe.title=xe.title}function Ue(xe){let bt=((u+xe)%n.length+n.length)%n.length;Bt(bt)}function Bt(xe){xe<0||xe>=n.length||(u=xe,fe.src=n[u].url,Oe(),p?.(u,n[u]))}function be(){if(x)return;let xe=Gx[m]??Gx.desktop;v=UR(ce,xe);let bt=Math.max(Qx,Math.min(Xx,h??v));jR(Je,fe,xe,bt,m),ge&&(ge.textContent=`${Math.round(bt*100)}%`)}let Be=new ResizeObserver(()=>be());Be.observe(ce),Oe(),fe.src=n[u].url,requestAnimationFrame(()=>be());function ve(){x||(x=!0,Be.disconnect(),document.removeEventListener("click",J),w.remove())}return{element:w,goTo:Bt,next:()=>Ue(1),prev:()=>Ue(-1),getIndex:()=>u,setDevice(xe){m=xe,Je.dataset.device=xe,se?.setSelected(xe),h=null,be()},setColorScheme(xe){y=xe,Je.dataset.colorScheme=xe},setZoom(xe){h=xe,be()},destroy:ve}}Pg();var Zx=16e3,zR=24e3,VR=4096,KR=4,GR=1380533830;function YR(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===GR?new Uint8Array(e,44):new Uint8Array(e)}function QR(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Cl=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.levelCallbacks=[];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 t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)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:Zx,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(m=>m.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:Zx});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ai(zR);if(r!==this.callGeneration){d.destroy(),s.getTracks().forEach(m=>m.stop()),l.close().catch(()=>{});return}this.playback=d,d.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let p=`${QR(o)}/ws/agents/${encodeURIComponent(t)}/voice`,u=new WebSocket(p,["runtype.bearer",n]);u.binaryType="arraybuffer",this.ws=u,u.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,u,r))},u.onmessage=m=>this.handleMessage(m,r),u.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},u.onclose=m=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(m.code!==1e3){let y=m.code?` (code ${m.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),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}onLevel(t){this.levelCallbacks.push(t)}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(VR,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),p=new Int16Array(d.length),u=0;for(let m=0;m<d.length;m++){let y=Math.max(-1,Math.min(1,d[m]));u+=y*y,p[m]=y<0?y*32768:y*32767}if(o.send(p.buffer),this.levelCallbacks.length>0){let m=Math.sqrt(u/d.length),y=Math.max(0,Math.min(1,m*KR));for(let h of this.levelCallbacks)h(y)}},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.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(t,n){if(n!==this.callGeneration||!this.playback)return;let o=YR(t);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(t=>t.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(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Ws=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,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(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function wl(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Cl(e.runtype);case"browser":if(!Ws.isSupported())throw new Error("Browser speech recognition not supported");return new Ws(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;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: ${e.type}`)}}function pf(e){if(e?.type==="custom"&&e.custom)return wl({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return wl({type:"runtype",runtype:e.runtype});if(Ws.isSupported())return wl({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function eS(e){try{return pf(e),!0}catch{return!1}}var tS="webmcp:",XR=e=>e.startsWith(tS)?e.slice(tS.length):e,mp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},hp=class{constructor(t,n){this.config=t;this.deps=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return mp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.deps.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s=ZR(r.annotations);return{name:r.name,description:r.description,parametersSchema:eH(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return yo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let v=typeof document<"u"&&!!document.modelContext;return yo(v?"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=XR(t),a;try{a=await r.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return yo(`Failed to read WebMCP registry: ${x}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(v=>v.name===s);if(!l)return yo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return yo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return yo("Aborted by cancel()");let d=this.deps.getToolDisplayTitle(s),p={toolName:s,args:n,description:l.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(p))return yo("User declined the tool call.");if(o?.aborted)return yo("Aborted by cancel()");let u=new AbortController,m=!1,y=setTimeout(()=>{m=!0,u.abort()},this.timeoutMs),h=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",h,{once:!0}));try{let v=await r.executeTool(l,rH(n),{signal:u.signal});return tH(v)}catch(v){if(m)return yo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return yo("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return yo(x)}finally{clearTimeout(y),o&&o.removeEventListener("abort",h)}}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}(await this.deps.loadPolyfill()).initializeWebMCPPolyfill(),this.installed=!0}catch(t){mp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,mp.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):t}async requestConfirm(t){let n=this.confirmHandler??nH;try{return await n(t)}catch(o){return mp.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>JR(t,o))}},JR=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},fp={type:"object",properties:{}},ZR=e=>{if(!e||typeof e!="object")return;let t={...typeof e.readOnlyHint=="boolean"?{readOnlyHint:e.readOnlyHint}:{},...typeof e.untrustedContentHint=="boolean"?{untrustedContentHint:e.untrustedContentHint}:{}};return Object.keys(t).length>0?t:void 0},eH=e=>{if(e===void 0||e==="")return{...fp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...fp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...fp}}catch{return{...fp}}},tH=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:sH(t)}]}},yo=e=>({isError:!0,content:[{type:"text",text:e}]}),nH=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=oH(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
475
475
 
476
476
  Arguments:
477
477
  ${t}`:"")+(e.description?`
478
478
 
479
- ${e.description}`:"");return window.confirm(n)},ZR=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},eH=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},tH=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var uf=class extends vp{constructor(t){super(t,{recordToolDisplayTitles:zc,getToolDisplayTitle:Si,loadPolyfill:Vc})}};function nH(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function oH(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:nH(o,n)?2:3}function Zx(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function gf(e,t){let n=t.trim();if(!n)return[...e].sort(Zx);let o=[];for(let r of e){let s=oH(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:Zx(r.item,s.item)),o.map(r=>r.item)}function rH(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function sH(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>gf(e.items,t),resolve:e.resolve}}function iH(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>gf(t,rH(r).name),resolve:(r,s)=>{let a=n.get(r.id);return a?a.kind==="server"?{context:(typeof a.data=="function"?a.data(s.args):a.data)??{}}:{insertText:typeof a.prompt=="function"?a.prompt(s.args):a.prompt??""}:{}}}}function aH(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,l=m=>{typeof m.scrollIntoView=="function"&&m.scrollIntoView({block:"nearest",inline:"nearest"})},d=m=>{let y=m;return s.findIndex(h=>h===y||h.contains(y))},p=m=>{let y=d(m.target);if(y<0)return;let h=y;if(m.key===r)h=Math.min(y+1,s.length-1);else if(m.key===o)h=Math.max(y-1,0);else if(m.key==="Home")h=0;else if(m.key==="End")h=s.length-1;else return;m.preventDefault(),h!==y&&t.onSelect(h)},u=m=>{let y=d(m.target);y>=0&&l(s[y])};return e.addEventListener("keydown",p),e.addEventListener("focusin",u),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(m,y){if(s=m,m.forEach((h,C)=>{h.setAttribute("role","tab");let S=C===y;h.setAttribute("aria-selected",S?"true":"false"),h.tabIndex=S||y<0&&C===0?0:-1}),a){let h=(y>=0?m[y]:void 0)??m[0];h&&typeof h.focus=="function"&&(l(h),h.focus())}},destroy(){e.removeEventListener("keydown",p),e.removeEventListener("focusin",u)}}}export{jb as ASK_USER_QUESTION_CLIENT_TOOL,Ub as ASK_USER_QUESTION_PARAMETERS_SCHEMA,Kc as ASK_USER_QUESTION_TOOL_NAME,ki as AgentWidgetClient,Za as AgentWidgetSession,Ii as AttachmentManager,Ws as BrowserSpeechEngine,kC as DEFAULT_COMPONENTS,Bg as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,oo as DEFAULT_FLOATING_LAUNCHER_WIDTH,EC as DEFAULT_PALETTE,TC as DEFAULT_SEMANTIC,at as DEFAULT_WIDGET_CONFIG,yo as HistoryProviderError,Dx as PRESETS,_x as PRESET_FULLSCREEN,Bx as PRESET_MINIMAL,Ox as PRESET_SHOP,Pi as ReadAloudController,ug as SUGGEST_REPLIES_CLIENT_TOOL,Nb as SUGGEST_REPLIES_PARAMETERS_SCHEMA,dr as SUGGEST_REPLIES_TOOL_NAME,p0 as THEME_ZONES,fo as VERSION,qc as WEBMCP_TOOL_PREFIX,uf as WebMcpBridge,bR as accessibilityPlugin,vR as animationsPlugin,Kw as applyFeaturePreferences,Oi as applyThemeVariables,Di as attachHeaderToContainer,CR as brandPlugin,Fi as buildComposer,ow as buildDefaultHeader,Vr as buildHeader,yl as buildHeaderWithLayout,rw as buildMinimalHeader,za as builtInClientToolsForDispatch,Fn as canonicalArtifactDisplayMode,gR as collectEnrichedPageContext,Fo as componentRegistry,op as createActionManager,Zm as createAgentExperience,Lk as createAskUserQuestionBubble,pf as createBestAvailableVoiceProvider,gL as createBubbleWithLayout,Qm as createCSATFeedback,mm as createComboButton,EI as createComponentMiddleware,Km as createComponentStreamParser,lb as createDefaultSanitizer,FR as createDemoCarousel,VT as createDirectivePostprocessor,Ni as createDropdownMenu,_k as createFlexibleJsonStreamParser,qn as createIconButton,Cg as createImagePart,yg as createJsonStreamParser,nw as createLabelButton,Um as createLocalStorageAdapter,Uc as createMarkdownProcessor,jc as createMarkdownProcessorFromConfig,mw as createMessageActions,Xm as createNPSFeedback,fg as createPlainTextParser,SR as createPlugin,hg as createRegexJsonParser,aH as createRovingTablist,iH as createSlashCommandsSource,z0 as createSplitButton,vl as createStandardBubble,sH as createStaticMentionSource,ho as createTextPart,Md as createTheme,sl as createThemeObserver,_d as createToggleGroup,$i as createTypingIndicator,Al as createVoiceProvider,lp as createWidgetHostLayout,bg as createXmlParser,yR as default,Yi as defaultActionHandlers,np as defaultJsonActionParser,gf as defaultMentionFilter,Lx as defaultParseRules,Ed as detectColorScheme,KT as directivePostprocessor,qa as ensureAskUserQuestionSheet,Br as escapeHtml,Ym as extractComponentDirectiveFromMessage,$k as fileToImagePart,mR as formatEnrichedContext,Is as generateAssistantMessageId,kR as generateCodeSnippet,rk as generateMessageId,Rx as generateStableSelector,$a as generateUserMessageId,Os as getActiveTheme,GI as getAgentWidgetHandles,tm as getColorScheme,vg as getDisplayText,sw as getHeaderLayout,Fk as getImageParts,hR as getPreset,sp as hasComponentDirective,Ya as hasImages,fm as headerLayouts,xR as highContrastPlugin,wx as initAgentWidget,_r as isAskUserQuestionMessage,MI as isComponentDirectiveType,Tt as isDockedMountMode,oP as isHistoryProviderError,Ei as isSuggestRepliesMessage,Xx as isVoiceSupported,Ps as isWebMcpToolName,Ds as isWelcomeVisible,gg as latestAgentSuggestions,M0 as listRegisteredStreamAnimations,eg as loadMarkdownParsers,sb as markdownPostprocessor,nl as mergeWithDefaults,Nk as normalizeContent,Ls as normalizeMediaType,Na as onMarkdownParsersReady,Dr as parseAskUserQuestionPayload,$b as parseSuggestRepliesPayload,qw as parseWidgetPreferenceSlice,Ja as pickBestVoice,ep as pluginRegistry,wR as reducedMotionPlugin,$T as registerIcons,Hd as registerStreamAnimationPlugin,Hs as removeAskUserQuestionSheet,Gm as renderComponentDirective,uw as renderLoadingIndicatorWithFallback,pe as renderLucideIcon,xb as resolveArtifactDisplay,cr as resolveArtifactDisplayMode,Zd as resolveConfigPreferences,Un as resolveDockConfig,rg as resolveSanitizer,Zg as resolveTokens,No as resolveWelcomeConfig,Cb as stripWebMcpPrefix,em as themeToCssVariables,A0 as unregisterStreamAnimationPlugin,Uk as validateImageFile,PC as validateTheme};
479
+ ${e.description}`:"");return window.confirm(n)},oH=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},rH=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},sH=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var uf=class extends hp{constructor(t){super(t,{recordToolDisplayTitles:Uc,getToolDisplayTitle:yi,loadPolyfill:jc})}};function iH(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function aH(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:iH(o,n)?2:3}function nS(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function gf(e,t){let n=t.trim();if(!n)return[...e].sort(nS);let o=[];for(let r of e){let s=aH(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:nS(r.item,s.item)),o.map(r=>r.item)}function lH(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function cH(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>gf(e.items,t),resolve:e.resolve}}function dH(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>gf(t,lH(r).name),resolve:(r,s)=>{let a=n.get(r.id);return a?a.kind==="server"?{context:(typeof a.data=="function"?a.data(s.args):a.data)??{}}:{insertText:typeof a.prompt=="function"?a.prompt(s.args):a.prompt??""}:{}}}}function pH(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,l=m=>{typeof m.scrollIntoView=="function"&&m.scrollIntoView({block:"nearest",inline:"nearest"})},d=m=>{let y=m;return s.findIndex(h=>h===y||h.contains(y))},p=m=>{let y=d(m.target);if(y<0)return;let h=y;if(m.key===r)h=Math.min(y+1,s.length-1);else if(m.key===o)h=Math.max(y-1,0);else if(m.key==="Home")h=0;else if(m.key==="End")h=s.length-1;else return;m.preventDefault(),h!==y&&t.onSelect(h)},u=m=>{let y=d(m.target);y>=0&&l(s[y])};return e.addEventListener("keydown",p),e.addEventListener("focusin",u),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(m,y){if(s=m,m.forEach((h,v)=>{h.setAttribute("role","tab");let x=v===y;h.setAttribute("aria-selected",x?"true":"false"),h.tabIndex=x||y<0&&v===0?0:-1}),a){let h=(y>=0?m[y]:void 0)??m[0];h&&typeof h.focus=="function"&&(l(h),h.focus())}},destroy(){e.removeEventListener("keydown",p),e.removeEventListener("focusin",u)}}}export{Kb as ASK_USER_QUESTION_CLIENT_TOOL,Vb as ASK_USER_QUESTION_PARAMETERS_SCHEMA,qc as ASK_USER_QUESTION_TOOL_NAME,xi as AgentWidgetClient,Qa as AgentWidgetSession,Mi as AttachmentManager,Ts as BrowserSpeechEngine,IC as DEFAULT_COMPONENTS,Bg as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,no as DEFAULT_FLOATING_LAUNCHER_WIDTH,kC as DEFAULT_PALETTE,LC as DEFAULT_SEMANTIC,lt as DEFAULT_WIDGET_CONFIG,fo as HistoryProviderError,$x as PRESETS,Fx as PRESET_FULLSCREEN,Nx as PRESET_MINIMAL,Dx as PRESET_SHOP,Si as ReadAloudController,ug as SUGGEST_REPLIES_CLIENT_TOOL,jb as SUGGEST_REPLIES_PARAMETERS_SCHEMA,ir as SUGGEST_REPLIES_TOOL_NAME,f0 as THEME_ZONES,Ro as VERSION,$c as WEBMCP_TOOL_PREFIX,uf as WebMcpBridge,xR as accessibilityPlugin,SR as animationsPlugin,Qw as applyFeaturePreferences,ki as applyThemeVariables,Ri as attachHeaderToContainer,AR as brandPlugin,Wi as buildComposer,iw as buildDefaultHeader,$r as buildHeader,ml as buildHeaderWithLayout,aw as buildMinimalHeader,$a as builtInClientToolsForDispatch,Un as canonicalArtifactDisplayMode,yR as collectEnrichedPageContext,_o as componentRegistry,ep as createActionManager,Zm as createAgentExperience,OP as createAskUserQuestionBubble,pf as createBestAvailableVoiceProvider,yL as createBubbleWithLayout,Qm as createCSATFeedback,mm as createComboButton,LI as createComponentMiddleware,Km as createComponentStreamParser,ub as createDefaultSanitizer,qR as createDemoCarousel,XT as createDirectivePostprocessor,Hi as createDropdownMenu,UP as createFlexibleJsonStreamParser,Vn as createIconButton,Cg as createImagePart,yg as createJsonStreamParser,sw as createLabelButton,Um as createLocalStorageAdapter,Nc as createMarkdownProcessor,Fc as createMarkdownProcessorFromConfig,yw as createMessageActions,Xm as createNPSFeedback,fg as createPlainTextParser,TR as createPlugin,hg as createRegexJsonParser,pH as createRovingTablist,dH as createSlashCommandsSource,Y0 as createSplitButton,hl as createStandardBubble,cH as createStaticMentionSource,mo as createTextPart,xd as createTheme,nl as createThemeObserver,Wd as createToggleGroup,Oi as createTypingIndicator,wl as createVoiceProvider,sp as createWidgetHostLayout,bg as createXmlParser,wR as default,ji as defaultActionHandlers,Zd as defaultJsonActionParser,gf as defaultMentionFilter,Hx as defaultParseRules,Sd as detectColorScheme,JT as directivePostprocessor,Fa as ensureAskUserQuestionSheet,Ir as escapeHtml,Ym as extractComponentDirectiveFromMessage,VP as fileToImagePart,bR as formatEnrichedContext,As as generateAssistantMessageId,RR as generateCodeSnippet,cP as generateMessageId,Ox as generateStableSelector,_a as generateUserMessageId,Ps as getActiveTheme,JI as getAgentWidgetHandles,tm as getColorScheme,vg as getDisplayText,lw as getHeaderLayout,zP as getImageParts,CR as getPreset,np as hasComponentDirective,za as hasImages,fm as headerLayouts,ER as highContrastPlugin,Ax as initAgentWidget,Rr as isAskUserQuestionMessage,kI as isComponentDirectiveType,St as isDockedMountMode,lk as isHistoryProviderError,Ci as isSuggestRepliesMessage,eS as isVoiceSupported,xs as isWebMcpToolName,Is as isWelcomeVisible,gg as latestAgentSuggestions,k0 as listRegisteredStreamAnimations,eg as loadMarkdownParsers,cb as markdownPostprocessor,Za as mergeWithDefaults,qP as normalizeContent,Ss as normalizeMediaType,Oa as onMarkdownParsersReady,Hr as parseAskUserQuestionPayload,zb as parseSuggestRepliesPayload,Kw as parseWidgetPreferenceSlice,Ga as pickBestVoice,Xd as pluginRegistry,MR as reducedMotionPlugin,zT as registerIcons,Ld as registerStreamAnimationPlugin,Es as removeAskUserQuestionSheet,Gm as renderComponentDirective,fw as renderLoadingIndicatorWithFallback,le as renderLucideIcon,Eb as resolveArtifactDisplay,sr as resolveArtifactDisplayMode,Qd as resolveConfigPreferences,qn as resolveDockConfig,rg as resolveSanitizer,Zg as resolveTokens,Bo as resolveWelcomeConfig,Ab as stripWebMcpPrefix,em as themeToCssVariables,P0 as unregisterStreamAnimationPlugin,KP as validateImageFile,RC as validateTheme};
480
480
  //# sourceMappingURL=index.js.map