@runtypelabs/persona 4.19.0 → 4.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) 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-CG-bLFmk.d.cts → types-B_JdVK9o.d.cts} +2 -0
  4. package/dist/animations/{types-CG-bLFmk.d.ts → types-B_JdVK9o.d.ts} +2 -0
  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 +2 -0
  8. package/dist/animations-extra.d.ts +2 -0
  9. package/dist/approval-ui.d.cts +99 -5
  10. package/dist/approval-ui.d.ts +99 -5
  11. package/dist/artifacts-ui.d.cts +99 -5
  12. package/dist/artifacts-ui.d.ts +99 -5
  13. package/dist/codegen.cjs +1 -1
  14. package/dist/codegen.js +1 -1
  15. package/dist/context-mentions.d.cts +99 -5
  16. package/dist/context-mentions.d.ts +99 -5
  17. package/dist/event-stream-view.d.cts +99 -5
  18. package/dist/event-stream-view.d.ts +99 -5
  19. package/dist/forms-ui.d.cts +123 -9
  20. package/dist/forms-ui.d.ts +123 -9
  21. package/dist/history-view.d.cts +2 -0
  22. package/dist/history-view.d.ts +2 -0
  23. package/dist/index.cjs +51 -51
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +128 -10
  26. package/dist/index.d.ts +128 -10
  27. package/dist/index.global.js +34 -34
  28. package/dist/index.global.js.map +1 -1
  29. package/dist/index.js +51 -51
  30. package/dist/index.js.map +1 -1
  31. package/dist/launcher.global.js.map +1 -1
  32. package/dist/session-reconnect.d.cts +99 -5
  33. package/dist/session-reconnect.d.ts +99 -5
  34. package/dist/smart-dom-reader.d.cts +99 -5
  35. package/dist/smart-dom-reader.d.ts +99 -5
  36. package/dist/theme-editor-preview.cjs +53 -53
  37. package/dist/theme-editor-preview.d.cts +99 -5
  38. package/dist/theme-editor-preview.d.ts +99 -5
  39. package/dist/theme-editor-preview.js +31 -31
  40. package/dist/theme-editor.d.cts +99 -5
  41. package/dist/theme-editor.d.ts +99 -5
  42. package/dist/theme-reference.cjs +1 -1
  43. package/dist/theme-reference.d.cts +46 -5
  44. package/dist/theme-reference.d.ts +46 -5
  45. package/dist/theme-reference.js +1 -1
  46. package/dist/webmcp-runtime.d.cts +16 -0
  47. package/dist/webmcp-runtime.d.ts +16 -0
  48. package/dist/widget.css +1 -1
  49. package/package.json +1 -1
  50. package/src/client-visitor-history.test.ts +342 -3
  51. package/src/client.test.ts +141 -3
  52. package/src/client.ts +157 -39
  53. package/src/components/composer-actions.ts +27 -1
  54. package/src/components/composer-model-picker.ts +4 -14
  55. package/src/components/composer-overflow-menu.ts +14 -0
  56. package/src/components/composer-parts.ts +20 -0
  57. package/src/generated/runtype-openapi-contract.ts +2 -0
  58. package/src/index-core.ts +2 -0
  59. package/src/session.ts +139 -103
  60. package/src/session.webmcp.test.ts +48 -1
  61. package/src/styles/widget-styles.test.ts +83 -1
  62. package/src/styles/widget.css +50 -14
  63. package/src/theme-reference.ts +1 -1
  64. package/src/types/theme.ts +47 -5
  65. package/src/types.ts +63 -0
  66. package/src/ui.composer-action-visibility.test.ts +202 -0
  67. package/src/ui.composer-models.test.ts +37 -0
  68. package/src/ui.composer-modes.test.ts +82 -0
  69. package/src/ui.composer-overflow.test.ts +78 -0
  70. package/src/ui.history-lifecycle.test.ts +2 -2
  71. package/src/ui.ts +77 -6
  72. package/src/utils/__snapshots__/tokens-parity.test.ts.snap +1633 -686
  73. package/src/utils/composer-modes.test.ts +33 -0
  74. package/src/utils/composer-modes.ts +19 -2
  75. package/src/utils/tokens-parity.test.ts +20 -0
  76. package/src/utils/tokens.test.ts +76 -0
  77. package/src/utils/tokens.ts +4 -4
package/dist/index.js CHANGED
@@ -1,31 +1,31 @@
1
- var uM=Object.defineProperty;var Ba=(e,t)=>()=>(e&&(t=e(e=0)),t);var jy=(e,t)=>{for(var n in t)uM(e,n,{get:t[n],enumerable:!0})};var qy={};jy(qy,{DOMPurify:()=>mM,Marked:()=>gM});import{Marked as gM}from"marked";import mM from"dompurify";var zy=Ba(()=>{"use strict"});var Ai,wg=Ba(()=>{"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 XP(e){return e.replace(/\/+$/,"")}async function JP(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 od,uv=Ba(()=>{"use strict";wg();od=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=`${XP(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 JP(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 rd,gv=Ba(()=>{"use strict";rd=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 mv={};jy(mv,{FallbackSpeechEngine:()=>rd,RuntypeSpeechEngine:()=>od});var fv=Ba(()=>{"use strict";uv();gv()});import{Marked as yM}from"marked";import bM from"dompurify";var ht=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:oH,load:fM,provide:hM,getSync:Ku}=ht({fallbackImport:()=>Promise.resolve().then(()=>(zy(),qy))}),_c=new Set,Vy=()=>{let e=[..._c];_c.clear();for(let t of e)try{t()}catch{}};var Gu=()=>{let e=Ku();return e?Promise.resolve(e):fM().then(t=>(Vy(),t))},_a=e=>Ku()?()=>{}:(_c.add(e),()=>{_c.delete(e)}),Ky=e=>{hM(e),Vy()},Ho=Ku;Ky({Marked:yM,DOMPurify:bM});import{Ban as vM,Bell as CM,Bookmark as wM,Building as xM,Calendar as SM,CalendarDays as AM,Camera as MM,ChartColumn as EM,CircleCheck as TM,CircleX as PM,Clock as kM,CreditCard as LM,DollarSign as IM,EyeOff as RM,Files as HM,Film as WM,Flag as OM,Folder as BM,FolderOpen as _M,Funnel as DM,Gift as NM,Globe as FM,Hash as $M,Headphones as UM,Heart as jM,House as qM,Image as zM,Info as VM,Key as KM,Lightbulb as GM,Link as QM,Lock as YM,Mail as XM,MapPin as JM,MessageCircle as ZM,Monitor as eE,Moon as tE,Package as nE,Pause as oE,PenLine as rE,Percent as sE,Phone as iE,Play as aE,Receipt as lE,RotateCw as cE,Save as dE,Settings as pE,Share as uE,Shield as gE,ShoppingBag as mE,ShoppingCart as fE,Smartphone as hE,Sparkles as yE,Store as bE,Sun as vE,Tag as CE,Timer as wE,TriangleAlert as xE,Truck as SE,User as AE,VolumeX as ME,Wallet as EE,Zap as TE}from"lucide";var Gy={user:AE,mail:XM,phone:iE,calendar:SM,clock:kM,building:xM,"map-pin":JM,lock:YM,key:KM,"credit-card":LM,hash:$M,globe:FM,link:QM,"circle-check":TM,"circle-x":PM,"triangle-alert":xE,info:VM,ban:vM,shield:gE,house:qM,"pen-line":rE,save:dE,share:uE,funnel:DM,settings:pE,"rotate-cw":cE,"shopping-cart":fE,"shopping-bag":mE,package:nE,truck:SE,tag:CE,gift:NM,receipt:lE,wallet:EE,store:bE,"dollar-sign":IM,percent:sE,play:aE,pause:oE,"volume-x":ME,camera:MM,image:zM,film:WM,headphones:UM,"message-circle":ZM,bell:CM,heart:jM,"eye-off":RM,bookmark:wM,"calendar-days":AM,timer:wE,folder:BM,"folder-open":_M,files:HM,"chart-column":EM,sparkles:yE,zap:TE,sun:vE,moon:tE,flag:OM,lightbulb:GM,monitor:eE,smartphone:hE};var Ht=(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:uH,load:PE}=ht({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")});var Dc=PE;import{Activity as kE,ArrowDown as LE,ArrowLeft as IE,ArrowRight as RE,ArrowUp as HE,ArrowUpRight as WE,AtSign as OE,Bot as BE,Check as _E,ChevronDown as DE,ChevronLeft as NE,ChevronRight as FE,ChevronUp as $E,Clipboard as UE,ClipboardCopy as jE,CodeXml as qE,Copy as zE,Download as VE,Ellipsis as KE,EllipsisVertical as GE,ExternalLink as QE,Eye as YE,File as XE,FileCode as JE,FileSpreadsheet as ZE,FileText as eT,History as tT,ImagePlus as nT,Loader as oT,LoaderCircle as rT,Maximize as sT,Menu as iT,MessageSquare as aT,Mic as lT,Minimize as cT,Minus as dT,PanelLeft as pT,Paperclip as uT,Pencil as gT,Plus as mT,Quote as fT,RefreshCw as hT,Search as yT,Send as bT,ShieldAlert as vT,ShieldCheck as CT,ShieldX as wT,Square as xT,Star as ST,ThumbsDown as AT,ThumbsUp as MT,Trash as ET,Trash2 as TT,Upload as PT,Volume2 as kT,X as LT}from"lucide";var IT={activity:kE,"arrow-down":LE,"arrow-up":HE,"arrow-up-right":WE,bot:BE,"chevron-down":DE,"chevron-up":$E,"chevron-right":FE,"chevron-left":NE,check:_E,clipboard:UE,"clipboard-copy":jE,"code-xml":qE,copy:zE,file:XE,"file-code":JE,"file-spreadsheet":ZE,"file-text":eT,"image-plus":nT,loader:oT,"loader-circle":rT,mic:lT,paperclip:uT,quote:fT,"refresh-cw":hT,search:yT,send:bT,"shield-alert":vT,"shield-check":CT,"shield-x":wT,square:xT,"thumbs-down":AT,"thumbs-up":MT,upload:PT,"volume-2":kT,x:LT,"at-sign":OE,"arrow-left":IE,"arrow-right":RE,"external-link":QE,ellipsis:KE,"ellipsis-vertical":GE,menu:iT,"panel-left":pT,plus:mT,minus:dT,pencil:gT,trash:ET,"trash-2":TT,download:VE,maximize:sT,minimize:cT,"message-square":aT,star:ST,eye:YE,history:tT},RT=["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"],Es=new Map(Object.entries(IT)),fi=new Set,hi=!1,Nc=new Set,Yu=e=>{let t=[...Nc];e&&Nc.clear();for(let n of t)try{n()}catch{}},Qy=e=>hi?()=>{}:(Nc.add(e),()=>{Nc.delete(e)}),Xu=()=>{let e=0;for(let t of[...fi]){let n=Es.get(t.name);if(!n)continue;fi.delete(t),e++;let o=Ht(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},HT=e=>{for(let[t,n]of Object.entries(e))Es.set(t,n);Xu()>0&&!hi&&Yu(!1)},Yy=e=>{if(!hi){for(let[t,n]of Object.entries(e))Es.has(t)||Es.set(t,n);hi=!0,Xu(),Yu(!0)}},Qu=!1,WT=()=>{Dc().then(e=>{if(!hi){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))Es.has(t)||Es.set(t,n);hi=!0,Xu(),Yu(!0)}}).catch(e=>{Qu=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},OT=(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=Es.get(e);if(r)return Ht(r,t,n,o);if(RT.includes(e)){Qu&&(Qu=!1);let s=OT(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}),WT(),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};Yy(Gy);var BT=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},Fc=e=>{let t=null;return n=>{let o=Ho();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=BT(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},$c=e=>e?Fc({markedOptions:e.options,renderer:e.renderer}):Fc(),_T=Fc(),Jy=e=>_T(e),Ir=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Zy=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Xy=e=>`%%FORM_PLACEHOLDER_${e}%%`,eb=(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=Xy(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=Xy(t.length);return t.push({token:s,type:r}),s}),n},DT=e=>{let t=$c(e);return n=>{let o=[],r=eb(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="${Zy(l)}"></div>`;s=s.replace(d,u)}),s}},NT=e=>{let t=[],n=eb(e,t),o=Jy(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="${Zy(s)}"></div>`;o=o.replace(a,d)}),o};var FT={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"]},$T=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,tb=()=>{let e=null;return t=>{let n=Ho();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:")&&!$T.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,FT)}},Ju=e=>e===!1?null:typeof e=="function"?e:tb();var nb=/^\s*\|?[\s:|-]*-[\s:|-]*$/,ob=e=>e.includes("|"),rb=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())},UT=e=>`| ${e.join(" | ")} |`,jT=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,qT=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),sb=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(!ob(r)||nb.test(r)||!nb.test(s))continue;let a=rb(r).length;if(a<1)continue;let l=jT(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()===""||!ob(p))break;let u=UT(qT(rb(p),a));t[d]!==u&&(t[d]=u,n=!0)}o=d-1}return n?t.join(`
3
- `):e};var ib="var(--persona-md-table-scroll-fade, 24px)",ab=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 lb(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":ib),e.style.setProperty("--persona-fade-r",r<=1?"0px":ib)}function Zu(e){ab.has(e)||(ab.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&lb(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(lb)}var Uc="webmcp:",eg=new Map,jc=e=>{eg.clear();for(let t of e){let n=t.title?.trim();n&&eg.set(t.name,n)}},yi=e=>eg.get(gb(e)),db=null;function ub(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 pb(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=pb(e,0).toString(36),n=pb(e,2654435761).toString(36);return`${t}.${n}`}var gb=e=>e.startsWith(Uc)?e.slice(Uc.length):e,Ts=e=>e.startsWith(Uc),qc=()=>db?db():import("@mcp-b/webmcp-polyfill");var{setLoader:kH,load:VT}=ht({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var mb=VT;function Un(e){return e==="card"?"collapsed":e}function Ps(e){return e.split(";",1)[0].trim().toLowerCase()}function KT(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Ps(r)===t)return{mode:Un(s),selector:Ps(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ps(r)===o)return{mode:Un(s),selector:o}}function fb(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?Ps(t.file.mimeType):void 0,d=l?KT(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 or(e,t){return fb(e,t).mode}function Da(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 GT="agent_",QT="flow_";function hb(e){return e.startsWith(GT)?{kind:"agentId",agentId:e}:e.startsWith(QT)?{kind:"flowId",flowId:e}:null}function yb(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=hb(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=hb(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 YT(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Na(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ks(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function bb(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}import{parse as XT,ARR as JT,OBJ as ZT,STR as eP}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},fn=(...e)=>e.filter(Boolean).join(" ");var zc="ask_user_question",Fa=8,bi="data-persona-ask-sheet-for",tP="Other",nP="Other\u2026",Cb="Type your own answer here",wb="Send",oP="Next",rP="Back",sP="Submit all",iP="Skip",aP=3,tg="data-ask-current-index",ng="data-ask-question-count",xb="data-ask-answers",og="data-ask-grouped",Sb="data-ask-layout",lP=e=>e.layout==="pills"?"pills":"rows",cP=e=>e.getAttribute(Sb)==="pills"?"pills":"rows",vb=!1,Ab=e=>e.replace(/["\\]/g,"\\$&"),Rr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===zc,Vc=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=XT(r,eP|ZT|JT);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},$a=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Fa&&!vb&&(vb=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Fa}.`)),t.slice(0,Fa)},dP=e=>$a(e)[0]??null,pP=(e,t)=>$a(e)[t]??null,Mb=(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))},Eb=(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},uP=(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=Eb(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},gP=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},mP=(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<aP;u++)s.appendChild(gP(o));return s}if(d.forEach((u,m)=>{s.appendChild(uP(u,m,o,a))}),e?.allowFreeText!==!1){let u=o==="rows"?tP:nP;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??Cb,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??u),y.appendChild(h),m.appendChild(y);let C=Eb(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},Tb=(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??Cb,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??wb,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},fP=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??wb,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},hP=(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??rP,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??iP,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??sP:n.nextLabel??oP,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ls=e=>{let t=e.getAttribute(xb);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Pb=(e,t)=>{e.setAttribute(xb,JSON.stringify(t))},no=e=>{let t=Number(e.getAttribute(tg)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},yP=(e,t)=>{e.setAttribute(tg,String(Math.max(0,Math.floor(t))))},vi=e=>{let t=Number(e.getAttribute(ng)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Wr=e=>e.getAttribute(og)==="true",bP=(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},vP=(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)))},Kc=(e,t)=>{let{payload:n}=Hr(t),o=$a(n),r=Ls(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},kb=e=>{let t=Ls(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="")},Lb=e=>{if(!Wr(e))return;let t=Ls(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}},rg=(e,t,n)=>{let o=Vc(n),r=cP(e),{payload:s,complete:a}=Hr(t),l=Wr(e),d=no(e),p=vi(e),u=l?pP(s,d):dP(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 B=typeof u?.question=="string"?u.question:"";C.textContent=B,C.classList.toggle("persona-ask-question-skeleton",!B&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let B=mP(u,o,a,r);x.replaceWith(B)}if(r!=="rows"){let B=e.querySelector('[data-ask-free-text-row="true"]');B&&B.replaceWith(Tb(o,r))}let S=e.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!S?e.appendChild(fP(o)):(!m||l)&&S&&S.remove(),e.setAttribute("data-multi-select",m?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(l){let B=hP(d,p,o);k?k.replaceWith(B):e.appendChild(B)}else k&&k.remove();kb(e),Lb(e)},CP=(e,t,n)=>{let o=Vc(t),r=lP(o),s=e.toolCall.id,a=$a(n),l=Math.max(1,a.length),d=l>1,p=bP(e,a),u=d?vP(e,l):0,m=M("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(ng,String(l)),m.setAttribute(tg,String(u)),m.setAttribute(og,d?"true":"false"),m.setAttribute(Sb,r),Pb(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`),Mb(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 S=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 S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),m.appendChild(S),r!=="rows"&&m.appendChild(Tb(o,r)),rg(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,$a(o).length);r>vi(e)&&(e.setAttribute(ng,String(r)),r>1&&!Wr(e)&&e.setAttribute(og,"true")),rg(e,t,n)},xP=(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=Vc(t);Mb(n,o);let r=M("span","persona-ask-stub-label"),{complete:s}=Hr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Ua=(e,t,n)=>{if(!n||!Rr(e)||Vc(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}="${Ab(r)}"]`);if(a){wP(a,e,t);return}let{payload:l}=Hr(e),d=CP(e,t,l);n.appendChild(d)},Is=(e,t)=>{if(!e)return;let n=t?`[${bi}="${Ab(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)})},sg=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=Ls(e),o=no(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Pb(e,n),kb(e),Lb(e)},Gc=(e,t,n,o)=>{let r=vi(e),s=Math.max(0,Math.min(r-1,o));yP(e,s),rg(e,t,n)};var rr="suggest_replies";var Rb={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},ig={name:rr,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:Rb,origin:"sdk",annotations:{readOnlyHint:!0}},Hb=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ci=e=>e.variant==="tool"&&e.toolCall?.name===rr,Wb=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},ag=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=Wb(n.toolCall?.args);return o.length>0?o:null}return null},Ib=new Set,SP=(e,t,n)=>{let o=`${e}:${t}:${n}`;Ib.has(o)||(Ib.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&&SP(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 Ob={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Fa,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},Bb={name:zc,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:Ob,origin:"sdk",annotations:{readOnlyHint:!0}},ja=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Bb),Br(e).expose&&t.push(ig),t};import{parse as _b,STR as Db,OBJ as Nb}from"partial-json";var Qc=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)}},AP=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`},Fb=e=>e.status==="complete"?AP(e):e.status==="pending"?"Waiting":"",MP=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 $b=e=>e.status==="complete"?MP(e):"Using tool...",Xc=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},za=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 Xc(t)},Jc=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Xc(t)},lg=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=za(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Zc=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&qa(o,n.slice(s,a.index),[]),a[1]!==void 0?qa(o,a[1],["bold"]):a[2]!==void 0?qa(o,a[2],["italic"]):a[3]!==void 0&&qa(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&qa(o,n.slice(s),[]),o},qa=(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})},EP=()=>{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 fM=Object.defineProperty;var Ba=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ky=(e,t)=>{for(var n in t)fM(e,n,{get:t[n],enumerable:!0})};var Gy={};Ky(Gy,{DOMPurify:()=>yM,Marked:()=>hM});import{Marked as hM}from"marked";import yM from"dompurify";var Qy=Ba(()=>{"use strict"});var Mi,Ag=Ba(()=>{"use strict";Mi=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 ek(e){return e.replace(/\/+$/,"")}async function tk(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 od,fv=Ba(()=>{"use strict";Ag();od=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 Mi(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=`${ek(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 tk(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 rd,hv=Ba(()=>{"use strict";rd=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 yv={};Ky(yv,{FallbackSpeechEngine:()=>rd,RuntypeSpeechEngine:()=>od});var bv=Ba(()=>{"use strict";fv();hv()});import{Marked as CM}from"marked";import wM from"dompurify";var ht=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:cH,load:bM,provide:vM,getSync:Qu}=ht({fallbackImport:()=>Promise.resolve().then(()=>(Qy(),Gy))}),_c=new Set,Yy=()=>{let e=[..._c];_c.clear();for(let t of e)try{t()}catch{}};var Yu=()=>{let e=Qu();return e?Promise.resolve(e):bM().then(t=>(Yy(),t))},_a=e=>Qu()?()=>{}:(_c.add(e),()=>{_c.delete(e)}),Xy=e=>{vM(e),Yy()},Wo=Qu;Xy({Marked:CM,DOMPurify:wM});import{Ban as xM,Bell as SM,Bookmark as AM,Building as MM,Calendar as EM,CalendarDays as TM,Camera as PM,ChartColumn as kM,CircleCheck as LM,CircleX as IM,Clock as RM,CreditCard as HM,DollarSign as WM,EyeOff as OM,Files as BM,Film as _M,Flag as DM,Folder as NM,FolderOpen as FM,Funnel as $M,Gift as UM,Globe as jM,Hash as qM,Headphones as zM,Heart as VM,House as KM,Image as GM,Info as QM,Key as YM,Lightbulb as XM,Link as JM,Lock as ZM,Mail as eE,MapPin as tE,MessageCircle as nE,Monitor as oE,Moon as rE,Package as sE,Pause as iE,PenLine as aE,Percent as lE,Phone as cE,Play as dE,Receipt as pE,RotateCw as uE,Save as gE,Settings as mE,Share as fE,Shield as hE,ShoppingBag as yE,ShoppingCart as bE,Smartphone as vE,Sparkles as CE,Store as wE,Sun as xE,Tag as SE,Timer as AE,TriangleAlert as ME,Truck as EE,User as TE,VolumeX as PE,Wallet as kE,Zap as LE}from"lucide";var Jy={user:TE,mail:eE,phone:cE,calendar:EM,clock:RM,building:MM,"map-pin":tE,lock:ZM,key:YM,"credit-card":HM,hash:qM,globe:jM,link:JM,"circle-check":LM,"circle-x":IM,"triangle-alert":ME,info:QM,ban:xM,shield:hE,house:KM,"pen-line":aE,save:gE,share:fE,funnel:$M,settings:mE,"rotate-cw":uE,"shopping-cart":bE,"shopping-bag":yE,package:sE,truck:EE,tag:SE,gift:UM,receipt:pE,wallet:kE,store:wE,"dollar-sign":WM,percent:lE,play:dE,pause:iE,"volume-x":PE,camera:PM,image:GM,film:_M,headphones:zM,"message-circle":nE,bell:SM,heart:VM,"eye-off":OM,bookmark:AM,"calendar-days":TM,timer:AE,folder:NM,"folder-open":FM,files:BM,"chart-column":kM,sparkles:CE,zap:LE,sun:xE,moon:rE,flag:DM,lightbulb:XM,monitor:oE,smartphone:vE};var Ht=(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:bH,load:IE}=ht({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")});var Dc=IE;import{Activity as RE,ArrowDown as HE,ArrowLeft as WE,ArrowRight as OE,ArrowUp as BE,ArrowUpRight as _E,AtSign as DE,Bot as NE,Check as FE,ChevronDown as $E,ChevronLeft as UE,ChevronRight as jE,ChevronUp as qE,Clipboard as zE,ClipboardCopy as VE,CodeXml as KE,Copy as GE,Download as QE,Ellipsis as YE,EllipsisVertical as XE,ExternalLink as JE,Eye as ZE,File as eT,FileCode as tT,FileSpreadsheet as nT,FileText as oT,History as rT,ImagePlus as sT,Loader as iT,LoaderCircle as aT,Maximize as lT,Menu as cT,MessageSquare as dT,Mic as pT,Minimize as uT,Minus as gT,PanelLeft as mT,Paperclip as fT,Pencil as hT,Plus as yT,Quote as bT,RefreshCw as vT,Search as CT,Send as wT,ShieldAlert as xT,ShieldCheck as ST,ShieldX as AT,Square as MT,Star as ET,ThumbsDown as TT,ThumbsUp as PT,Trash as kT,Trash2 as LT,Upload as IT,Volume2 as RT,X as HT}from"lucide";var WT={activity:RE,"arrow-down":HE,"arrow-up":BE,"arrow-up-right":_E,bot:NE,"chevron-down":$E,"chevron-up":qE,"chevron-right":jE,"chevron-left":UE,check:FE,clipboard:zE,"clipboard-copy":VE,"code-xml":KE,copy:GE,file:eT,"file-code":tT,"file-spreadsheet":nT,"file-text":oT,"image-plus":sT,loader:iT,"loader-circle":aT,mic:pT,paperclip:fT,quote:bT,"refresh-cw":vT,search:CT,send:wT,"shield-alert":xT,"shield-check":ST,"shield-x":AT,square:MT,"thumbs-down":TT,"thumbs-up":PT,upload:IT,"volume-2":RT,x:HT,"at-sign":DE,"arrow-left":WE,"arrow-right":OE,"external-link":JE,ellipsis:YE,"ellipsis-vertical":XE,menu:cT,"panel-left":mT,plus:yT,minus:gT,pencil:hT,trash:kT,"trash-2":LT,download:QE,maximize:lT,minimize:uT,"message-square":dT,star:ET,eye:ZE,history:rT},OT=["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"],Es=new Map(Object.entries(WT)),hi=new Set,yi=!1,Nc=new Set,Ju=e=>{let t=[...Nc];e&&Nc.clear();for(let n of t)try{n()}catch{}},Zy=e=>yi?()=>{}:(Nc.add(e),()=>{Nc.delete(e)}),Zu=()=>{let e=0;for(let t of[...hi]){let n=Es.get(t.name);if(!n)continue;hi.delete(t),e++;let o=Ht(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},BT=e=>{for(let[t,n]of Object.entries(e))Es.set(t,n);Zu()>0&&!yi&&Ju(!1)},eb=e=>{if(!yi){for(let[t,n]of Object.entries(e))Es.has(t)||Es.set(t,n);yi=!0,Zu(),Ju(!0)}},Xu=!1,_T=()=>{Dc().then(e=>{if(!yi){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))Es.has(t)||Es.set(t,n);yi=!0,Zu(),Ju(!0)}}).catch(e=>{Xu=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},DT=(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=Es.get(e);if(r)return Ht(r,t,n,o);if(OT.includes(e)){Xu&&(Xu=!1);let s=DT(t,n,o);if(hi.size>=500){let a=hi.values().next().value;a&&hi.delete(a)}return hi.add({el:s,name:e,size:t,color:n,strokeWidth:o}),_T(),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};eb(Jy);var NT=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},Fc=e=>{let t=null;return n=>{let o=Wo();if(!o)return Rr(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=NT(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},$c=e=>e?Fc({markedOptions:e.options,renderer:e.renderer}):Fc(),FT=Fc(),nb=e=>FT(e),Rr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),ob=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),tb=e=>`%%FORM_PLACEHOLDER_${e}%%`,rb=(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=tb(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=tb(t.length);return t.push({token:s,type:r}),s}),n},$T=e=>{let t=$c(e);return n=>{let o=[],r=rb(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="${ob(l)}"></div>`;s=s.replace(d,u)}),s}},UT=e=>{let t=[],n=rb(e,t),o=nb(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="${ob(s)}"></div>`;o=o.replace(a,d)}),o};var jT={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"]},qT=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,sb=()=>{let e=null;return t=>{let n=Wo();if(!n)return Rr(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:")&&!qT.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,jT)}},eg=e=>e===!1?null:typeof e=="function"?e:sb();var ib=/^\s*\|?[\s:|-]*-[\s:|-]*$/,ab=e=>e.includes("|"),lb=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())},zT=e=>`| ${e.join(" | ")} |`,VT=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,KT=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),cb=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(!ab(r)||ib.test(r)||!ib.test(s))continue;let a=lb(r).length;if(a<1)continue;let l=VT(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()===""||!ab(p))break;let u=zT(KT(lb(p),a));t[d]!==u&&(t[d]=u,n=!0)}o=d-1}return n?t.join(`
3
+ `):e};var db="var(--persona-md-table-scroll-fade, 24px)",pb=new WeakSet;function gb(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 ub(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":db),e.style.setProperty("--persona-fade-r",r<=1?"0px":db)}function tg(e){pb.has(e)||(pb.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&ub(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(ub)}var Uc="webmcp:",ng=new Map,jc=e=>{ng.clear();for(let t of e){let n=t.title?.trim();n&&ng.set(t.name,n)}},bi=e=>ng.get(yb(e)),mb=null;function hb(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}:${GT(t.join(""))}`}function fb(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 GT(e){let t=fb(e,0).toString(36),n=fb(e,2654435761).toString(36);return`${t}.${n}`}var yb=e=>e.startsWith(Uc)?e.slice(Uc.length):e,Ts=e=>e.startsWith(Uc),qc=()=>mb?mb():import("@mcp-b/webmcp-polyfill");var{setLoader:OH,load:QT}=ht({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var bb=QT;function Un(e){return e==="card"?"collapsed":e}function Ps(e){return e.split(";",1)[0].trim().toLowerCase()}function YT(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Ps(r)===t)return{mode:Un(s),selector:Ps(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ps(r)===o)return{mode:Un(s),selector:o}}function vb(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?Ps(t.file.mimeType):void 0,d=l?YT(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 vb(e,t).mode}function Da(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 XT="agent_",JT="flow_";function Cb(e){return e.startsWith(XT)?{kind:"agentId",agentId:e}:e.startsWith(JT)?{kind:"flowId",flowId:e}:null}function wb(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=Cb(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=Cb(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 ZT(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Na(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ks(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function xb(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}import{parse as eP,ARR as tP,OBJ as nP,STR as oP}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},hn=(...e)=>e.filter(Boolean).join(" ");var zc="ask_user_question",Fa=8,vi="data-persona-ask-sheet-for",rP="Other",sP="Other\u2026",Ab="Type your own answer here",Mb="Send",iP="Next",aP="Back",lP="Submit all",cP="Skip",dP=3,og="data-ask-current-index",rg="data-ask-question-count",Eb="data-ask-answers",sg="data-ask-grouped",Tb="data-ask-layout",pP=e=>e.layout==="pills"?"pills":"rows",uP=e=>e.getAttribute(Tb)==="pills"?"pills":"rows",Sb=!1,Pb=e=>e.replace(/["\\]/g,"\\$&"),Hr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===zc,Vc=e=>e?.features?.askUserQuestion??{},Wr=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=eP(r,oP|nP|tP);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},$a=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Fa&&!Sb&&(Sb=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Fa}.`)),t.slice(0,Fa)},gP=e=>$a(e)[0]??null,mP=(e,t)=>$a(e)[t]??null,kb=(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))},Lb=(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},fP=(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=Lb(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},hP=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},yP=(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<dP;u++)s.appendChild(hP(o));return s}if(d.forEach((u,m)=>{s.appendChild(fP(u,m,o,a))}),e?.allowFreeText!==!1){let u=o==="rows"?rP:sP;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??Ab,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??u),y.appendChild(h),m.appendChild(y);let C=Lb(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},Ib=(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??Ab,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??Mb,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},bP=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??Mb,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},vP=(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??aP,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??cP,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??lP:n.nextLabel??iP,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ls=e=>{let t=e.getAttribute(Eb);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Rb=(e,t)=>{e.setAttribute(Eb,JSON.stringify(t))},no=e=>{let t=Number(e.getAttribute(og)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},CP=(e,t)=>{e.setAttribute(og,String(Math.max(0,Math.floor(t))))},Ci=e=>{let t=Number(e.getAttribute(rg)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Or=e=>e.getAttribute(sg)==="true",wP=(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},xP=(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)))},Kc=(e,t)=>{let{payload:n}=Wr(t),o=$a(n),r=Ls(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},Hb=e=>{let t=Ls(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="")},Wb=e=>{if(!Or(e))return;let t=Ls(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}},ig=(e,t,n)=>{let o=Vc(n),r=uP(e),{payload:s,complete:a}=Wr(t),l=Or(e),d=no(e),p=Ci(e),u=l?mP(s,d):gP(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 B=typeof u?.question=="string"?u.question:"";C.textContent=B,C.classList.toggle("persona-ask-question-skeleton",!B&&!a)}let S=e.querySelector('[data-ask-pill-list="true"]');if(S){let B=yP(u,o,a,r);S.replaceWith(B)}if(r!=="rows"){let B=e.querySelector('[data-ask-free-text-row="true"]');B&&B.replaceWith(Ib(o,r))}let x=e.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!x?e.appendChild(bP(o)):(!m||l)&&x&&x.remove(),e.setAttribute("data-multi-select",m?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(l){let B=vP(d,p,o);k?k.replaceWith(B):e.appendChild(B)}else k&&k.remove();Hb(e),Wb(e)},SP=(e,t,n)=>{let o=Vc(t),r=pP(o),s=e.toolCall.id,a=$a(n),l=Math.max(1,a.length),d=l>1,p=wP(e,a),u=d?xP(e,l):0,m=M("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(vi,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",e.id),m.setAttribute(rg,String(l)),m.setAttribute(og,String(u)),m.setAttribute(sg,d?"true":"false"),m.setAttribute(Tb,r),Rb(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`),kb(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(Ib(o,r)),ig(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},AP=(e,t,n)=>{let{payload:o}=Wr(t),r=Math.max(1,$a(o).length);r>Ci(e)&&(e.setAttribute(rg,String(r)),r>1&&!Or(e)&&e.setAttribute(sg,"true")),ig(e,t,n)},MP=(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=Vc(t);kb(n,o);let r=M("span","persona-ask-stub-label"),{complete:s}=Wr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Ua=(e,t,n)=>{if(!n||!Hr(e)||Vc(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${vi}]`).forEach(p=>{p.getAttribute(vi)!==r&&p.remove()});let a=n.querySelector(`[${vi}="${Pb(r)}"]`);if(a){AP(a,e,t);return}let{payload:l}=Wr(e),d=SP(e,t,l);n.appendChild(d)},Is=(e,t)=>{if(!e)return;let n=t?`[${vi}="${Pb(t)}"]`:`[${vi}]`;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)})},ag=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),Br=(e,t)=>{let n=Ls(e),o=no(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Rb(e,n),Hb(e),Wb(e)},Gc=(e,t,n,o)=>{let r=Ci(e),s=Math.max(0,Math.min(r-1,o));CP(e,s),ig(e,t,n)};var ir="suggest_replies";var Bb={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},lg={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:Bb,origin:"sdk",annotations:{readOnlyHint:!0}},_b=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),wi=e=>e.variant==="tool"&&e.toolCall?.name===ir,Db=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},cg=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!wi(n))continue;let o=Db(n.toolCall?.args);return o.length>0?o:null}return null},Ob=new Set,EP=(e,t,n)=>{let o=`${e}:${t}:${n}`;Ob.has(o)||(Ob.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&&EP(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 Nb={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Fa,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},Fb={name:zc,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:Nb,origin:"sdk",annotations:{readOnlyHint:!0}},ja=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Fb),_r(e).expose&&t.push(lg),t};import{parse as $b,STR as Ub,OBJ as jb}from"partial-json";var Qc=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)}},TP=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`},qb=e=>e.status==="complete"?TP(e):e.status==="pending"?"Waiting":"",PP=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"?PP(e):"Using tool...",Xc=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},za=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 Xc(t)},Jc=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Xc(t)},dg=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=za(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Zc=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&qa(o,n.slice(s,a.index),[]),a[1]!==void 0?qa(o,a[1],["bold"]):a[2]!==void 0?qa(o,a[2],["italic"]):a[3]!==void 0&&qa(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&qa(o,n.slice(s),[]),o},qa=(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})},kP=()=>{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()=>{}}},Va=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},cg=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},dg=()=>{let e=EP();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)}},pg=()=>{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=_b(n,Db|Nb);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Qc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Qc(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},TP=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=l=>typeof l=="string"?Qc(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Qc(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=_b(s,Db|Nb),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ug=()=>{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 Ub="4.19.0";var sr=Ub;var wi="[Image]";function kP(e){return typeof e=="string"?[{type:"text",text:e}]:e}function gg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ka(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function LP(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function mo(e){return{type:"text",text:e}}function mg(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function IP(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 RP(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 jb=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],HP=["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"],ir=[...jb,...HP];function WP(e){return jb.includes(e)||e.startsWith("image/")}function ed(e){return WP(e.type)}function qb(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;ed(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 Vb(e,t=ir,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 OP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Kb(e,t){let n=OP(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 BP=["user","assistant","system"],_P=0;function Gb(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function td(e){return typeof e=="string"?e:void 0}function DP(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"?mg(t.image,{mimeType:td(t.mimeType),alt:td(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?qb(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...td(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...td(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function NP(e,t){let n=Gb(t),o=e.map(a=>Gb(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:_P+y;s=l+1}return r.map(a=>new Date(a).toISOString())}function Qb(e,t){let n=NP(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!BP.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(DP).filter(u=>u!==null),p=gg(d);o.push({id:r.id,role:a,content:p||(Ka(d)?wi:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Ga(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 Qa(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 FP="https://api.runtype.com/v1/dispatch",Yb="https://api.runtype.com",je=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Xb=32768,fg=49152,Jb=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:""}},Zb=e=>"reason"in e?e.reason:void 0,ev="The identity proof was not admitted; account history is unavailable",tv="The identity proof was rejected",nv="The request carried no visitor credential",ov="The stored visitor belongs to a different signed-in user",rv=(e,t)=>e instanceof je&&e.code===t;function $P(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 hg=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 UP(e){switch(e){case"json":return pg;case"regex-json":return dg;case"xml":return ug;default:return cg}}var sv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function jP(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=sv(n);if(!sv(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Va(e);return Va(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??FP,this.headers={"Content-Type":"application/json","X-Persona-Version":sr,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??UP(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:jc,getToolDisplayTitle:yi,loadPolyfill:qc});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=yb(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$/,"")||Yb}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let 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&&Zb(n)===Zb(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=null;n&&(await this.historyInternals.historyBootstrapReady,o=await this.readVisitorToken());let r=this.routing(),s=r.agentId??r.flowId,a=n?t.conversationId:void 0,l={token:this.config.clientToken,...s&&{flowId:s},...n&&{visitorHistory:!0},...n&&o?{visitorToken:o}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...a?{conversationId:a}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},d=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":sr},body:JSON.stringify(l)});if(!d.ok){let u=await d.json().catch(()=>({error:"Session initialization failed"}));if(n&&d.status===403&&u.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),a)throw new je("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw n&&d.status===401&&u.error==="visitor_required"?new je("visitor_required","Visitor credential no longer resolves"):a&&d.status===404?new je("not_found","Conversation not found"):d.status===401?new Error(`Invalid client token: ${u.hint||u.error}`):d.status===403?new Error(`Origin not allowed: ${u.hint||u.error}`):new Error(u.error||"Failed to initialize session")}let p=await d.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId??p.flow?.id?{targetId:p.targetId??p.flow?.id}:{},...p.conversationRevision?{conversationRevision:p.conversationRevision}:{},...p.visitor?{visitor:p.visitor}:{},config:{welcomeMessage:p.config.welcomeMessage,placeholder:p.config.placeholder,theme:p.config.theme}}}async _doInitSession(){if(!this.isHistoryCapable()){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o});return this.config.setStoredSessionId?.(r.sessionId),r}await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=await this.readVisitorToken();if(t&&n)try{let o=await this.createClientSession({conversationId:t});return this.finishInit(o,t,!1)}catch(o){if(!rv(o,"not_found")&&!rv(o,"visitor_required"))throw o;return this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,n){let o=this.historyInternals.visitorStore;return o&&this.isHistoryCapable()&&!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())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 je("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 je("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":sr},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 je("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 je("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 je("proof_not_admitted",ev);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 je("invalid_identity_proof",tv);if(r.includes("visitor token required"))throw new je("visitor_token_missing",nv);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new je("visitor_identity_mismatch",ov);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new je("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,n){let o=await this.readErrorCode(t);if(t.status===404)return new je("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new je("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 je("proof_not_admitted",ev);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 je("invalid_identity_proof",tv)):r.includes("visitor token required")?new je("visitor_token_missing",nv):r.includes("visitor_identity_mismatch")?new je("visitor_identity_mismatch",ov):new je("unauthorized",o||"History request was not authorized")}return new je("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 je("identity_contract_violation","Server reported an ignored identity proof on a success response"):new je("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new je("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 je("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":sr,...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 je("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 je("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(Jb),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:Jb(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>Xb)throw new je("payload_too_large",`displayContent exceeds the ${Xb} character limit`);o+=p}if(o>fg)throw new je("payload_too_large",`Display projection batch exceeds the ${fg} 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<=fg,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=bb();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 h=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:h}),h}let l=await this.buildPayload(t.messages),d=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([h])=>h!=="sessionId"&&h!=="session_id")):void 0,p=this.isHistoryCapable(),u={sessionId:a.sessionId,messages:t.messages.filter(hg).map(h=>{let C=p?Ga(h):void 0;return{id:h.id,role:h.role,content:h.contentParts??h.llmContent??h.rawContent??h.content,...C!==void 0&&{displayContent:C}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...d&&Object.keys(d).length>0&&{metadata:d},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},{response:m,commit:y}=await this.sendWithClientToolsDiff(a.sessionId,l.clientTools,h=>{let C={...u,...h};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":sr},body:JSON.stringify(C),signal:t.signal})});if(!m.ok){let h=await m.json().catch(()=>({error:"Chat request failed"}));if(m.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(m.status===429){let x=new Error(h.hint||"Message limit reached for this session.");throw s({type:"error",error:x}),x}if(m.status===410&&h.error==="conversation_deleted"){let x=new je("conversation_deleted","This conversation was deleted");throw s({type:"error",error:x}),x}let C=new Error(h.error||"Failed to send message");throw s({type:"error",error:C}),C}if(!m.body){let h=new Error("No response body received");throw s({type:"error",error:h}),h}y(),s({type:"status",status:"connected"});try{await this.streamResponse(m.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 je)&&!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?ub(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(/\/+$/,"")||Yb}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(d.sessionId=a),r&&a){let p=[...ja(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:u,commit:m}=await this.sendWithClientToolsDiff(a,p,y=>{let h={...d,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",h),fetch(s,{method:"POST",headers:l,body:JSON.stringify(h),signal:o?.signal})},{emptyMeansReplace:!0});return u.ok&&m(),u}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(d),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(hg).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=[...ja(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(hg).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=[...ja(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=R=>{let ee=R.reasoning?{...R.reasoning,chunks:[...R.reasoning.chunks]}:void 0,v=R.toolCall?{...R.toolCall,chunks:R.toolCall.chunks?[...R.toolCall.chunks]:void 0}:void 0,N=R.tools?R.tools.map(F=>({...F,chunks:F.chunks?[...F.chunks]:void 0})):void 0;return{...R,reasoning:ee,toolCall:v,tools:N}},y=R=>{if(R.role!=="assistant"||R.variant)return!0;let ee=Array.isArray(R.contentParts)&&R.contentParts.length>0,v=typeof R.rawContent=="string"&&R.rawContent.trim()!=="";return typeof R.content=="string"&&R.content.trim()!==""||ee||v||!!R.stopReason},h=R=>{y(R)&&n({type:"message",message:m(R)})},C=null,x=null,S={current:null},k={current:null},B=null,$="",T=new Map,I=new Map,A=new Map,_=new Map,G=new Map,ie={lastId:null,byStep:new Map},ne={lastId:null,byCall:new Map},E=R=>{if(R==null)return null;try{return String(R)}catch{return null}},D=R=>E(R.stepId??R.step_id??R.step??R.parentId??R.flowStepId??R.flow_step_id),W=R=>E(R.callId??R.call_id??R.requestId??R.request_id??R.toolCallId??R.tool_call_id??R.stepId??R.step_id),L=o,Y=!1,K=()=>{if(C)return C;let R,ee="",v=B;return!Y&&L?(R=L,Y=!0,ee=r??""):L&&v?R=`${L}_${v}`:R=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,C={id:R,role:"assistant",content:ee,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},h(C),C},le=(R,ee)=>{ie.lastId=ee,R&&ie.byStep.set(R,ee)},de=(R,ee)=>{let v=R.reasoningId??R.id,N=D(R);if(v){let U=String(v);return le(N,U),U}if(N){let U=ie.byStep.get(N);if(U)return ie.lastId=U,U}if(ie.lastId&&!ee)return ie.lastId;if(!ee)return null;let F=`reason-${u()}`;return le(N,F),F},ge=R=>{let ee=_.get(R);if(ee)return ee;let v={id:`reason-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:R,status:"streaming",chunks:[]}};return _.set(R,v),h(v),v},Me=(R,ee)=>{ne.lastId=ee,R&&ne.byCall.set(R,ee)},fe=new Set,_e=new Map,it=new Set,be=new Map,j=R=>{if(!R)return!1;let ee=R.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},De=(R,ee)=>{let v=R.toolId??R.id,N=W(R);if(v){let U=String(v);return Me(N,U),U}if(N){let U=ne.byCall.get(N);if(U)return ne.lastId=U,U}if(ne.lastId&&!ee)return ne.lastId;if(!ee)return null;let F=`tool-${u()}`;return Me(N,F),F},Ne=R=>{let ee=G.get(R);if(ee)return ee;let v={id:`tool-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:R,status:"pending"}};return G.set(R,v),h(v),v},we=R=>{if(typeof R=="number"&&Number.isFinite(R))return R;if(typeof R=="string"){let ee=Number(R);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let v=Date.parse(R);if(!Number.isNaN(v))return v}return Date.now()},ke=R=>{if(typeof R=="string")return R;if(R==null)return"";try{return JSON.stringify(R)}catch{return String(R)}},he=new Map,dt=new Map,Ie=new Map,Ut=(R,ee,v)=>{let N=Ie.get(R);N||(N=[],Ie.set(R,N));let F=0,U=N.length;for(;F<U;){let te=F+U>>>1;N[te].seq<ee?F=te+1:U=te}N[F]?.seq===ee?N[F]={seq:ee,text:v}:N.splice(F,0,{seq:ee,text:v});let Z="";for(let te=0;te<N.length;te++)Z+=N[te].text;return Z},at=(R,ee)=>{let v=ke(ee),N=dt.get(R.id),F=jP(N,v);R.rawContent=F;let U=he.get(R.id),Z=qe=>{let Ot=R.content??"";qe.trim()!==""&&(Ot.trim().length===0||qe.startsWith(Ot)||qe.trimStart().startsWith(Ot.trim()))&&(R.content=qe)},te=()=>{if(U){let qe=U.close?.();qe instanceof Promise&&qe.catch(()=>{})}he.delete(R.id),dt.delete(R.id),R.streaming=!1,h(R)};if(!U){Z(v),te();return}let ae=Va(F);if(ae!==null&&ae.trim()!==""){Z(ae),te();return}let Se=qe=>{let Ot=typeof qe=="string"?qe:qe?.text??null;if(Ot!==null&&Ot.trim()!=="")return Ot;let St=U.getExtractedText();return St!==null&&St.trim()!==""?St:v},yt;try{yt=U.processChunk(F)}catch{Z(v),te();return}if(yt instanceof Promise){yt.then(qe=>{Z(Se(qe)),te()}).catch(()=>{Z(v),te()});return}Z(Se(yt)),te()},nn=null,wn=(R,ee,v,N)=>{R.rawContent=ee,he.has(R.id)||he.set(R.id,this.createStreamParser());let F=he.get(R.id),U=ee.trim().startsWith("{")||ee.trim().startsWith("[");if(U&&dt.set(R.id,ee),F.__isPlainTextParser===!0){R.content=N!==void 0?ee:R.content+v,dt.delete(R.id),he.delete(R.id),R.rawContent=void 0,h(R);return}let te=F.processChunk(ee);if(te instanceof Promise)te.then(ae=>{let Se=typeof ae=="string"?ae:ae?.text??null;Se!==null&&Se.trim()!==""?(R.content=Se,h(R)):!U&&!ee.trim().startsWith("<")&&(R.content=N!==void 0?ee:R.content+v,dt.delete(R.id),he.delete(R.id),R.rawContent=void 0,h(R))}).catch(()=>{R.content=N!==void 0?ee:R.content+v,dt.delete(R.id),he.delete(R.id),R.rawContent=void 0,h(R)});else{let ae=typeof te=="string"?te:te?.text??null;ae!==null&&ae.trim()!==""?(R.content=ae,h(R)):!U&&!ee.trim().startsWith("<")&&(R.content=N!==void 0?ee:R.content+v,dt.delete(R.id),he.delete(R.id),R.rawContent=void 0,h(R))}},Wt=(R,ee)=>{let v=ee??R.content;if(v==null||v===""){R.streaming=!1,h(R);return}let F=dt.get(R.id)??ke(v);R.rawContent=F;let U=he.get(R.id),Z=null,te=!1;if(U&&(Z=U.getExtractedText(),Z===null&&(Z=Va(F)),Z===null)){let ae=U.processChunk(F);ae instanceof Promise?(te=!0,ae.then(Se=>{let yt=typeof Se=="string"?Se:Se?.text??null;yt!==null&&(R.content=yt,R.streaming=!1,he.delete(R.id),dt.delete(R.id),h(R))}).catch(()=>{})):Z=typeof ae=="string"?ae:ae?.text??null}if(!te){Z!==null&&Z.trim()!==""?R.content=Z:dt.has(R.id)||(R.content=ke(v));let ae=he.get(R.id);if(ae){let Se=ae.close?.();Se instanceof Promise&&Se.catch(()=>{}),he.delete(R.id)}dt.delete(R.id),R.streaming=!1,h(R)}},jr=(R,ee,v)=>{let N=I.get(R);if(N)return N;let F={id:`nested-${ee}-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:R,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return I.set(R,F),h(F),F},xn=[],bo,Vi=new Map,qr=0,pn="agent",Ki=!1,Tt=null,gt=null,ro=new Map,Sl=this.config.iterationDisplay??"separate";for(bo=()=>{for(let R=0;R<xn.length;R++){let ee=xn[R].payloadType,v=xn[R].payload;if(!Ki&&pn!=="flow"&&typeof v.stepType=="string"&&(pn="flow"),ee==="reasoning_start"){let N=typeof v.id=="string"?v.id:null,F=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(N&&F){T.set(N,F),jr(N,F,"reasoning");continue}let U=de(v,!0)??`reason-${u()}`,Z=ge(U);Z.reasoning=Z.reasoning??{id:U,status:"streaming",chunks:[]},Z.reasoning.startedAt=Z.reasoning.startedAt??we(v.startedAt??v.timestamp),Z.reasoning.completedAt=void 0,Z.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(Z.reasoning.scope=v.scope),Z.streaming=!0,Z.reasoning.status="streaming",h(Z)}else if(ee==="reasoning_delta"){let N=typeof v.id=="string"?v.id:null;if(N&&T.has(N)&&I.has(N)){let te=I.get(N),ae=v.reasoningText??v.text??v.delta??"";ae&&v.hidden!==!0&&te.reasoning&&(te.reasoning.chunks.push(String(ae)),h(te));continue}let F=de(v,!1)??de(v,!0)??`reason-${u()}`,U=ge(F);U.reasoning=U.reasoning??{id:F,status:"streaming",chunks:[]},U.reasoning.startedAt=U.reasoning.startedAt??we(v.startedAt??v.timestamp);let Z=v.reasoningText??v.text??v.delta??"";if(Z&&v.hidden!==!0){let te=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(te!==void 0){let ae=Ut(F,te,String(Z));U.reasoning.chunks=[ae]}else U.reasoning.chunks.push(String(Z))}if(U.reasoning.status=v.done?"complete":"streaming",v.done){U.reasoning.completedAt=we(v.completedAt??v.timestamp);let te=U.reasoning.startedAt??Date.now();U.reasoning.durationMs=Math.max(0,(U.reasoning.completedAt??Date.now())-te)}U.streaming=U.reasoning.status!=="complete",h(U)}else if(ee==="reasoning_complete"){let N=typeof v.id=="string"?v.id:null;if(N&&T.has(N)&&I.has(N)){let ae=I.get(N);if(ae.reasoning){let Se=typeof v.text=="string"?v.text:"";Se&&ae.reasoning.chunks.length===0&&ae.reasoning.chunks.push(Se),ae.reasoning.status="complete",ae.streaming=!1,h(ae)}T.delete(N),I.delete(N);continue}let F=de(v,!1)??de(v,!0)??`reason-${u()}`,U=typeof v.text=="string"?v.text:"";!_.get(F)&&(U||v.scope==="loop")&&ge(F);let Z=_.get(F);if(Z?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(Z.reasoning.scope=v.scope),U&&Z.reasoning.chunks.length===0&&Z.reasoning.chunks.push(U),Z.reasoning.status="complete",Z.reasoning.completedAt=we(v.completedAt??v.timestamp);let ae=Z.reasoning.startedAt??Date.now();Z.reasoning.durationMs=Math.max(0,(Z.reasoning.completedAt??Date.now())-ae),Z.streaming=!1,h(Z)}let te=D(v);te&&ie.byStep.delete(te)}else if(ee==="tool_start"){C&&(C.streaming=!1,h(C),C=null),typeof v.iteration=="number"&&(qr=v.iteration);let N=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??De(v,!0)??`tool-${u()}`,F=v.toolName??v.name;if(j(F)){fe.add(N);continue}Me(W(v),N);let U=Ne(N),Z=U.toolCall??{id:N,status:"pending"};Z.name=F??Z.name,Z.status="running",v.parameters!==void 0?Z.args=v.parameters:v.args!==void 0&&(Z.args=v.args),Z.startedAt=Z.startedAt??we(v.startedAt??v.timestamp),Z.completedAt=void 0,Z.durationMs=void 0,U.toolCall=Z,U.streaming=!0,v.executionId&&(U.agentMetadata={executionId:v.executionId,iteration:v.iteration}),h(U)}else if(ee==="tool_output_delta"){let N=De(v,!1)??De(v,!0)??`tool-${u()}`;if(fe.has(N))continue;let F=Ne(N),U=F.toolCall??{id:N,status:"running"};U.startedAt=U.startedAt??we(v.startedAt??v.timestamp);let Z=v.text??v.delta??v.message??"";Z&&(U.chunks=U.chunks??[],U.chunks.push(String(Z))),U.status="running",F.toolCall=U,F.streaming=!0;let te=v.agentContext;(te||v.executionId)&&(F.agentMetadata=F.agentMetadata??{executionId:te?.executionId??v.executionId,iteration:te?.iteration??v.iteration}),h(F)}else if(ee==="tool_complete"){let N=De(v,!1)??De(v,!0)??`tool-${u()}`;if(fe.has(N)){fe.delete(N);continue}let F=Ne(N),U=F.toolCall??{id:N,status:"running"};U.status="complete",v.result!==void 0&&(U.result=v.result),typeof v.duration=="number"&&(U.duration=v.duration),U.completedAt=we(v.completedAt??v.timestamp);let Z=v.duration??v.executionTime;if(typeof Z=="number")U.durationMs=Z;else{let Se=U.startedAt??Date.now();U.durationMs=Math.max(0,(U.completedAt??Date.now())-Se)}F.toolCall=U,F.streaming=!1;let te=v.agentContext;(te||v.executionId)&&(F.agentMetadata=F.agentMetadata??{executionId:te?.executionId??v.executionId,iteration:te?.iteration??v.iteration}),h(F);let ae=W(v);ae&&ne.byCall.delete(ae)}else if(ee==="await"&&v.toolName){let N=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,F=N??v.toolId??`local-${u()}`,U=Ne(F),Z=v.toolName,te=v.origin==="webmcp"&&!Ts(Z)?`webmcp:${Z}`:Z,ae=Ts(te),Se=U.toolCall??{id:F,status:"pending"};Se.name=te,Se.args=v.parameters,Se.status=ae?"running":"complete",Se.chunks=Se.chunks??[],Se.startedAt=Se.startedAt??we(v.startedAt??v.timestamp??v.awaitedAt),ae?(Se.completedAt=void 0,Se.duration=void 0,Se.durationMs=void 0):Se.completedAt=Se.completedAt??Se.startedAt,U.toolCall=Se,U.streaming=!1,U.agentMetadata={...U.agentMetadata,executionId:v.executionId??U.agentMetadata?.executionId,awaitingLocalTool:!0,...N?{webMcpToolCallId:N}:{}},h(U)}else if(ee==="text_start"){let N=typeof v.id=="string"?v.id:null,F=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(N&&F){T.set(N,F);continue}let U=C;U&&(pn==="flow"?(Wt(U),nn=U):(U.streaming=!1,h(U)),C=null),B=typeof v.id=="string"?v.id:B,$=""}else if(ee==="text_delta"){let N=typeof v.id=="string"?v.id:null,F=N?T.get(N):void 0;if(N&&F){let Z=typeof v.delta=="string"?v.delta:"",te=(A.get(N)??"")+Z;if(A.set(N,te),te.trim()==="")continue;let ae=jr(N,F);ae.agentMetadata={...ae.agentMetadata,executionId:v.executionId,parentToolId:F},wn(ae,te,Z,void 0);continue}if(B=typeof v.id=="string"?v.id:B,pn==="flow"){let Z=typeof v.delta=="string"?v.delta:"";if($+=Z,$.trim()==="")continue;let te=K();te.agentMetadata={executionId:v.executionId,iteration:v.iteration},wn(te,$,Z,void 0),x=te;continue}let U=K();U.content+=v.delta??"",U.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:Tt??void 0,agentName:gt?.agentName},x=U,h(U)}else if(ee==="text_complete"){let N=typeof v.id=="string"?v.id:null;if(N&&T.has(N)){let U=I.get(N);U&&Wt(U),T.delete(N),A.delete(N),I.delete(N);continue}let F=C;F&&(pn==="flow"?(Wt(F),nn=F):((F.content??"")===""&&typeof v.text=="string"&&(F.content=v.text),F.streaming=!1,h(F)),C=null),B=null,$=""}else if(ee==="step_complete"){let N=v.stepType,F=v.executionType;if(N==="tool"||F==="context")continue;if(v.success===!1){let U=v.error,Z=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(Z)});let te=C;te&&te.streaming&&(te.streaming=!1,h(te)),n({type:"status",status:"idle"});continue}{let U=nn;nn=null;let Z=v.stopReason,te=v.result?.response;if(U)Z&&(U.stopReason=Z),te!=null?at(U,te):U.streaming!==!1&&(he.delete(U.id),dt.delete(U.id),U.streaming=!1,h(U));else{let ae=te!=null&&te!=="";if(ae||Z){let Se=K();Z&&(Se.stopReason=Z),ae?Wt(Se,te):(Se.streaming=!1,h(Se))}}continue}}else if(ee==="execution_start")pn=v.kind==="flow"?"flow":"agent",Ki=!0,pn==="agent"&&(gt={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:we(v.startedAt)});else if(ee==="turn_start"){let N=typeof v.iteration=="number"?v.iteration:qr;if(N!==qr){if(gt&&(gt.currentIteration=N),Sl==="separate"&&N>1){let F=C;F&&(F.streaming=!1,h(F),ro.set(N-1,F),C=null)}qr=N}Tt=typeof v.id=="string"?v.id:null,x=null}else if(ee==="tool_input_delta"){let N=v.toolCallId??ne.lastId;if(N){let F=G.get(N);F?.toolCall&&(F.toolCall.chunks=F.toolCall.chunks??[],F.toolCall.chunks.push(v.delta??""),h(F))}}else{if(ee==="tool_input_complete")continue;if(ee==="turn_complete"){let N=v.stopReason,F=C??x;if(N&&F!==null){let U=v.id;(!U||F.agentMetadata?.turnId===U)&&(F.stopReason=N,h(F))}Tt===v.id&&(Tt=null)}else if(ee==="media_start"){let N=String(v.id);Vi.set(N,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(ee==="media_delta"){let N=Vi.get(String(v.id));N&&typeof v.delta=="string"&&N.parts.push(v.delta)}else if(ee==="media_complete"){let N=String(v.id),F=Vi.get(N);Vi.delete(N);let U=(typeof v.mediaType=="string"?v.mediaType:void 0)??F?.mediaType??"application/octet-stream",Z=typeof v.data=="string"?v.data:void 0,te=typeof v.url=="string"?v.url:F&&F.parts.length>0?F.parts.join(""):void 0,ae=null;if(Z)ae={type:"media",data:Z,mediaType:U};else if(te){let Ot=U.toLowerCase();ae={type:Ot==="image"||Ot.startsWith("image/")?"image-url":"file-url",url:te,mediaType:U}}let Se=v.toolCallId??F?.toolCallId,yt=ae?[ae]:[],qe=[];for(let Ot of yt){if(!Ot||typeof Ot!="object")continue;let St=Ot,zr=typeof St.type=="string"?St.type:void 0,In=typeof St.mediaType=="string"?St.mediaType.toLowerCase():"",jt=null,un="";if(zr==="media"){let sn=typeof St.data=="string"?St.data:void 0;if(!sn)continue;un=In.length>0?In:"application/octet-stream",jt=`data:${un};base64,${sn}`}else if(zr==="image-url"){let sn=typeof St.url=="string"?St.url:void 0;if(!sn)continue;un=In,jt=sn}else if(zr==="file-url"){let sn=typeof St.url=="string"?St.url:void 0;if(!sn)continue;un=In,jt=sn}else continue;if(jt)if(zr==="image-url"||un.startsWith("image/"))qe.push({type:"image",image:jt,...un.includes("/")?{mimeType:un}:{}});else if(un.startsWith("audio/"))qe.push({type:"audio",audio:jt,mimeType:un});else if(un.startsWith("video/"))qe.push({type:"video",video:jt,mimeType:un});else{let sn=un||"application/octet-stream";qe.push({type:"file",data:jt,mimeType:sn,filename:$P(sn)})}}if(qe.length>0){let Ot=u(),St=Se,In={id:`agent-media-${typeof St=="string"&&St.length>0?`${St}-${Ot}`:String(Ot)}`,role:"assistant",content:"",contentParts:qe,createdAt:new Date().toISOString(),streaming:!1,sequence:Ot,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:qr}};h(In);let jt=C;jt&&(jt.streaming=!1,h(jt)),C=null,S.current=null}}else if(ee==="execution_complete"){let N=v.kind??pn;N==="agent"&&gt&&(gt.status=v.success?"complete":"error",gt.completedAt=we(v.completedAt),gt.stopReason=v.stopReason);let F=C;F&&(N==="flow"&&F.streaming!==!1?Wt(F):(F.streaming=!1,h(F)),C=null),B=null,$="",nn=null,n({type:"status",status:"idle",terminal:!0})}else if(ee==="execution_error"){let N=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(N)})}else if(ee!=="ping"){if(ee==="approval_start"){let N=v.approvalId??`approval-${u()}`,F={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:"pending",agentId:gt?.agentId??"virtual",executionId:v.executionId??gt?.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(ee==="step_await"&&v.awaitReason==="approval_required"){let N=v.approvalId??`approval-${u()}`,F={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:"pending",agentId:gt?.agentId??"virtual",executionId:v.executionId??gt?.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(ee==="approval_complete"){let N=v.approvalId;if(N){let U={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:v.decision??"approved",agentId:gt?.agentId??"virtual",executionId:v.executionId??gt?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};h(U)}}else if(ee==="artifact_start"||ee==="artifact_delta"||ee==="artifact_update"||ee==="artifact_complete"){if(ee==="artifact_start"){let N=v.artifactType,F=String(v.id),U=typeof v.title=="string"?v.title:void 0,Z=v.file,te;Z&&typeof Z=="object"&&!Array.isArray(Z)&&typeof Z.path=="string"&&typeof Z.mimeType=="string"&&(te={path:Z.path,mimeType:Z.mimeType,...typeof Z.language=="string"?{language:Z.language}:{}}),n({type:"artifact_start",id:F,artifactType:N,title:U,component:typeof v.component=="string"?v.component:void 0,...te?{file:te}:{}});let ae=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(be.set(F,{markdown:"",title:U,file:te,...ae?{props:ae}:{}}),!it.has(F)){it.add(F);let Se=or(this.config.features?.artifacts,{artifactType:N,...te?{file:te}:{}}),yt=typeof v.component=="string"?v.component:void 0,qe={id:`artifact-ref-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:Da(Se,{artifactId:F,title:U,artifactType:N,status:"streaming",...te?{file:te}:{},...yt?{component:yt}:{}})};_e.set(F,qe),h(qe)}}else if(ee==="artifact_delta"){let N=String(v.id),F=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:N,artDelta:F});let U=be.get(N);U&&(U.markdown+=F)}else if(ee==="artifact_update"){let N=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:N,component:typeof v.component=="string"?v.component:void 0});let F=be.get(String(v.id));F&&(F.props={...F.props??{},...N})}else if(ee==="artifact_complete"){let N=String(v.id);n({type:"artifact_complete",id:N});let F=_e.get(N);if(F){F.streaming=!1;try{let U=JSON.parse(F.rawContent??"{}");if(U.props){U.props.status="complete";let Z=be.get(N);Z?.markdown&&(U.props.markdown=Z.markdown),Z?.file&&(U.props.file=Z.file),U.component==="PersonaArtifactInline"&&Z?.props&&Object.keys(Z.props).length>0&&(U.props.componentProps=Z.props)}F.rawContent=JSON.stringify(U)}catch{}be.delete(N),h(F),_e.delete(N)}}}else if(ee==="transcript_insert"){let N=v.message;if(!N||typeof N!="object")continue;let F=String(N.id??`msg-${u()}`),U=N.role,te={id:F,role:U==="user"?"user":U==="system"?"system":"assistant",content:typeof N.content=="string"?N.content:"",rawContent:typeof N.rawContent=="string"?N.rawContent:void 0,createdAt:typeof N.createdAt=="string"?N.createdAt:new Date().toISOString(),streaming:N.streaming===!0,...typeof N.variant=="string"?{variant:N.variant}:{},sequence:u()};if(h(te),te.rawContent)try{let Se=JSON.parse(te.rawContent)?.props?.artifactId;typeof Se=="string"&&it.add(Se)}catch{}C=null,S.current=null,he.delete(F),dt.delete(F)}else if(ee==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let N=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(N)});let F=C;F&&F.streaming&&(F.streaming=!1,h(F)),n({type:"status",status:"idle"})}}else if(ee==="step_error"||ee==="dispatch_error"||ee==="flow_error"){let N=null;if(v.error instanceof Error)N=v.error;else if(ee==="dispatch_error"){let F=v.message??v.error;F!=null&&F!==""&&(N=new Error(String(F)))}else{let F=v.error;typeof F=="string"&&F!==""?N=new Error(F):F!=null&&typeof F=="object"&&Reflect.has(F,"message")&&(N=new Error(String(F.message??F)))}if(N){n({type:"error",error:N});let F=C;F&&F.streaming&&(F.streaming=!1,h(F)),n({type:"status",status:"idle"})}}}}}xn.length=0};;){let{done:R,value:ee}=await s.read();if(R)break;l+=a.decode(ee,{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()=>{}}},Va=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},pg=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ug=()=>{let e=kP();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)}},gg=()=>{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=$b(n,Ub|jb);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Qc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Qc(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},LP=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=l=>typeof l=="string"?Qc(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Qc(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=$b(s,Ub|jb),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},mg=()=>{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 Vb="4.21.0";var mo=Vb;var xi="[Image]";function RP(e){return typeof e=="string"?[{type:"text",text:e}]:e}function fg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ka(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function HP(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function fo(e){return{type:"text",text:e}}function hg(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function WP(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 OP(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 Kb=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],BP=["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=[...Kb,...BP];function _P(e){return Kb.includes(e)||e.startsWith("image/")}function ed(e){return _P(e.type)}function Gb(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function Qb(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ed(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 Yb(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 DP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Xb(e,t){let n=DP(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 NP=["user","assistant","system"],FP=0;function Jb(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function td(e){return typeof e=="string"?e:void 0}function $P(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?fo(t.text):null;case"image":return typeof t.image=="string"?hg(t.image,{mimeType:td(t.mimeType),alt:td(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?Gb(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...td(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...td(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function UP(e,t){let n=Jb(t),o=e.map(a=>Jb(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:FP+y;s=l+1}return r.map(a=>new Date(a).toISOString())}function Zb(e,t){let n=UP(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!NP.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($P).filter(u=>u!==null),p=fg(d);o.push({id:r.id,role:a,content:p||(Ka(d)?xi:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Ga(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 Qa(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 jP="https://api.runtype.com/v1/dispatch",ev="https://api.runtype.com",Ue=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},tv=32768,yg=49152,nv=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:""}},ov=e=>"reason"in e?e.reason:void 0,rv="The identity proof was not admitted; account history is unavailable",sv="The identity proof was rejected",iv="The request carried no visitor credential",av="The stored visitor belongs to a different signed-in user",bg=(e,t)=>e instanceof Ue&&e.code===t;function qP(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 vg=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 zP(e){switch(e){case"json":return gg;case"regex-json":return ug;case"xml":return mg;default:return pg}}var lv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function VP(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=lv(n);if(!lv(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Va(e);return Va(t)!==null&&a===null?t:e}var Si=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??jP,this.headers={"Content-Type":"application/json","X-Persona-Version":mo,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??zP(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 bb().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:jc,getToolDisplayTitle:bi,loadPolyfill:qc});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=wb(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$/,"")||ev}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 Ue("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":mo,"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&&ov(n)===ov(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":mo},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":mo},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 Ue("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 Ue("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&m.error==="visitor_required"?new Ue("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new Ue("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(!bg(r,"not_found")&&!bg(r,"visitor_required")&&!bg(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 Ue("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 Ue("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":mo},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 Ue("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 Ue("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 Ue("proof_not_admitted",rv);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 Ue("invalid_identity_proof",sv);if(r.includes("visitor token required"))throw new Ue("visitor_token_missing",iv);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Ue("visitor_identity_mismatch",av);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new Ue("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,n){let o=await this.readErrorCode(t);if(t.status===404)return new Ue("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new Ue("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 Ue("proof_not_admitted",rv);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 Ue("invalid_identity_proof",sv)):r.includes("visitor token required")?new Ue("visitor_token_missing",iv):r.includes("visitor_identity_mismatch")?new Ue("visitor_identity_mismatch",av):new Ue("unauthorized",o||"History request was not authorized")}return new Ue("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 Ue("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Ue("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new Ue("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 Ue("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":mo,...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 Ue("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 Ue("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(nv),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:nv(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>tv)throw new Ue("payload_too_large",`displayContent exceeds the ${tv} character limit`);o+=p}if(o>yg)throw new Ue("payload_too_large",`Display projection batch exceeds the ${yg} 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<=yg,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=xb();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(vg).map(C=>{let S=u?Ga(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":mo,...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 Ue("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 Ue)&&!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?hb(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(/\/+$/,"")||ev}/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=[...ja(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(vg).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=[...ja(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(vg).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=[...ja(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=R=>{let Z=R.reasoning?{...R.reasoning,chunks:[...R.reasoning.chunks]}:void 0,v=R.toolCall?{...R.toolCall,chunks:R.toolCall.chunks?[...R.toolCall.chunks]:void 0}:void 0,N=R.tools?R.tools.map(F=>({...F,chunks:F.chunks?[...F.chunks]:void 0})):void 0;return{...R,reasoning:Z,toolCall:v,tools:N}},y=R=>{if(R.role!=="assistant"||R.variant)return!0;let Z=Array.isArray(R.contentParts)&&R.contentParts.length>0,v=typeof R.rawContent=="string"&&R.rawContent.trim()!=="";return typeof R.content=="string"&&R.content.trim()!==""||Z||v||!!R.stopReason},h=R=>{y(R)&&n({type:"message",message:m(R)})},C=null,S=null,x={current:null},k={current:null},B=null,$="",T=new Map,I=new Map,A=new Map,D=new Map,G=new Map,se={lastId:null,byStep:new Map},ne={lastId:null,byCall:new Map},E=R=>{if(R==null)return null;try{return String(R)}catch{return null}},_=R=>E(R.stepId??R.step_id??R.step??R.parentId??R.flowStepId??R.flow_step_id),W=R=>E(R.callId??R.call_id??R.requestId??R.request_id??R.toolCallId??R.tool_call_id??R.stepId??R.step_id),L=o,Y=!1,K=()=>{if(C)return C;let R,Z="",v=B;return!Y&&L?(R=L,Y=!0,Z=r??""):L&&v?R=`${L}_${v}`:R=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,C={id:R,role:"assistant",content:Z,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},h(C),C},le=(R,Z)=>{se.lastId=Z,R&&se.byStep.set(R,Z)},de=(R,Z)=>{let v=R.reasoningId??R.id,N=_(R);if(v){let U=String(v);return le(N,U),U}if(N){let U=se.byStep.get(N);if(U)return se.lastId=U,U}if(se.lastId&&!Z)return se.lastId;if(!Z)return null;let F=`reason-${u()}`;return le(N,F),F},ge=R=>{let Z=D.get(R);if(Z)return Z;let v={id:`reason-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:R,status:"streaming",chunks:[]}};return D.set(R,v),h(v),v},Ae=(R,Z)=>{ne.lastId=Z,R&&ne.byCall.set(R,Z)},fe=new Set,_e=new Map,it=new Set,be=new Map,j=R=>{if(!R)return!1;let Z=R.replace(/_+/g,"_").replace(/^_|_$/g,"");return Z==="emit_artifact_markdown"||Z==="emit_artifact_component"},De=(R,Z)=>{let v=R.toolId??R.id,N=W(R);if(v){let U=String(v);return Ae(N,U),U}if(N){let U=ne.byCall.get(N);if(U)return ne.lastId=U,U}if(ne.lastId&&!Z)return ne.lastId;if(!Z)return null;let F=`tool-${u()}`;return Ae(N,F),F},Ne=R=>{let Z=G.get(R);if(Z)return Z;let v={id:`tool-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:R,status:"pending"}};return G.set(R,v),h(v),v},xe=R=>{if(typeof R=="number"&&Number.isFinite(R))return R;if(typeof R=="string"){let Z=Number(R);if(!Number.isNaN(Z)&&Number.isFinite(Z))return Z;let v=Date.parse(R);if(!Number.isNaN(v))return v}return Date.now()},ke=R=>{if(typeof R=="string")return R;if(R==null)return"";try{return JSON.stringify(R)}catch{return String(R)}},he=new Map,dt=new Map,Ie=new Map,Ut=(R,Z,v)=>{let N=Ie.get(R);N||(N=[],Ie.set(R,N));let F=0,U=N.length;for(;F<U;){let te=F+U>>>1;N[te].seq<Z?F=te+1:U=te}N[F]?.seq===Z?N[F]={seq:Z,text:v}:N.splice(F,0,{seq:Z,text:v});let ee="";for(let te=0;te<N.length;te++)ee+=N[te].text;return ee},at=(R,Z)=>{let v=ke(Z),N=dt.get(R.id),F=VP(N,v);R.rawContent=F;let U=he.get(R.id),ee=qe=>{let Ot=R.content??"";qe.trim()!==""&&(Ot.trim().length===0||qe.startsWith(Ot)||qe.trimStart().startsWith(Ot.trim()))&&(R.content=qe)},te=()=>{if(U){let qe=U.close?.();qe instanceof Promise&&qe.catch(()=>{})}he.delete(R.id),dt.delete(R.id),R.streaming=!1,h(R)};if(!U){ee(v),te();return}let ae=Va(F);if(ae!==null&&ae.trim()!==""){ee(ae),te();return}let we=qe=>{let Ot=typeof qe=="string"?qe:qe?.text??null;if(Ot!==null&&Ot.trim()!=="")return Ot;let St=U.getExtractedText();return St!==null&&St.trim()!==""?St:v},yt;try{yt=U.processChunk(F)}catch{ee(v),te();return}if(yt instanceof Promise){yt.then(qe=>{ee(we(qe)),te()}).catch(()=>{ee(v),te()});return}ee(we(yt)),te()},nn=null,pn=(R,Z,v,N)=>{R.rawContent=Z,he.has(R.id)||he.set(R.id,this.createStreamParser());let F=he.get(R.id),U=Z.trim().startsWith("{")||Z.trim().startsWith("[");if(U&&dt.set(R.id,Z),F.__isPlainTextParser===!0){R.content=N!==void 0?Z:R.content+v,dt.delete(R.id),he.delete(R.id),R.rawContent=void 0,h(R);return}let te=F.processChunk(Z);if(te instanceof Promise)te.then(ae=>{let we=typeof ae=="string"?ae:ae?.text??null;we!==null&&we.trim()!==""?(R.content=we,h(R)):!U&&!Z.trim().startsWith("<")&&(R.content=N!==void 0?Z:R.content+v,dt.delete(R.id),he.delete(R.id),R.rawContent=void 0,h(R))}).catch(()=>{R.content=N!==void 0?Z:R.content+v,dt.delete(R.id),he.delete(R.id),R.rawContent=void 0,h(R)});else{let ae=typeof te=="string"?te:te?.text??null;ae!==null&&ae.trim()!==""?(R.content=ae,h(R)):!U&&!Z.trim().startsWith("<")&&(R.content=N!==void 0?Z:R.content+v,dt.delete(R.id),he.delete(R.id),R.rawContent=void 0,h(R))}},Wt=(R,Z)=>{let v=Z??R.content;if(v==null||v===""){R.streaming=!1,h(R);return}let F=dt.get(R.id)??ke(v);R.rawContent=F;let U=he.get(R.id),ee=null,te=!1;if(U&&(ee=U.getExtractedText(),ee===null&&(ee=Va(F)),ee===null)){let ae=U.processChunk(F);ae instanceof Promise?(te=!0,ae.then(we=>{let yt=typeof we=="string"?we:we?.text??null;yt!==null&&(R.content=yt,R.streaming=!1,he.delete(R.id),dt.delete(R.id),h(R))}).catch(()=>{})):ee=typeof ae=="string"?ae:ae?.text??null}if(!te){ee!==null&&ee.trim()!==""?R.content=ee:dt.has(R.id)||(R.content=ke(v));let ae=he.get(R.id);if(ae){let we=ae.close?.();we instanceof Promise&&we.catch(()=>{}),he.delete(R.id)}dt.delete(R.id),R.streaming=!1,h(R)}},qr=(R,Z,v)=>{let N=I.get(R);if(N)return N;let F={id:`nested-${Z}-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:R,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:Z}};return I.set(R,F),h(F),F},xn=[],vo,Ki=new Map,zr=0,un="agent",Gi=!1,Tt=null,gt=null,ro=new Map,Sl=this.config.iterationDisplay??"separate";for(vo=()=>{for(let R=0;R<xn.length;R++){let Z=xn[R].payloadType,v=xn[R].payload;if(!Gi&&un!=="flow"&&typeof v.stepType=="string"&&(un="flow"),Z==="reasoning_start"){let N=typeof v.id=="string"?v.id:null,F=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(N&&F){T.set(N,F),qr(N,F,"reasoning");continue}let U=de(v,!0)??`reason-${u()}`,ee=ge(U);ee.reasoning=ee.reasoning??{id:U,status:"streaming",chunks:[]},ee.reasoning.startedAt=ee.reasoning.startedAt??xe(v.startedAt??v.timestamp),ee.reasoning.completedAt=void 0,ee.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(ee.reasoning.scope=v.scope),ee.streaming=!0,ee.reasoning.status="streaming",h(ee)}else if(Z==="reasoning_delta"){let N=typeof v.id=="string"?v.id:null;if(N&&T.has(N)&&I.has(N)){let te=I.get(N),ae=v.reasoningText??v.text??v.delta??"";ae&&v.hidden!==!0&&te.reasoning&&(te.reasoning.chunks.push(String(ae)),h(te));continue}let F=de(v,!1)??de(v,!0)??`reason-${u()}`,U=ge(F);U.reasoning=U.reasoning??{id:F,status:"streaming",chunks:[]},U.reasoning.startedAt=U.reasoning.startedAt??xe(v.startedAt??v.timestamp);let ee=v.reasoningText??v.text??v.delta??"";if(ee&&v.hidden!==!0){let te=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(te!==void 0){let ae=Ut(F,te,String(ee));U.reasoning.chunks=[ae]}else U.reasoning.chunks.push(String(ee))}if(U.reasoning.status=v.done?"complete":"streaming",v.done){U.reasoning.completedAt=xe(v.completedAt??v.timestamp);let te=U.reasoning.startedAt??Date.now();U.reasoning.durationMs=Math.max(0,(U.reasoning.completedAt??Date.now())-te)}U.streaming=U.reasoning.status!=="complete",h(U)}else if(Z==="reasoning_complete"){let N=typeof v.id=="string"?v.id:null;if(N&&T.has(N)&&I.has(N)){let ae=I.get(N);if(ae.reasoning){let we=typeof v.text=="string"?v.text:"";we&&ae.reasoning.chunks.length===0&&ae.reasoning.chunks.push(we),ae.reasoning.status="complete",ae.streaming=!1,h(ae)}T.delete(N),I.delete(N);continue}let F=de(v,!1)??de(v,!0)??`reason-${u()}`,U=typeof v.text=="string"?v.text:"";!D.get(F)&&(U||v.scope==="loop")&&ge(F);let ee=D.get(F);if(ee?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(ee.reasoning.scope=v.scope),U&&ee.reasoning.chunks.length===0&&ee.reasoning.chunks.push(U),ee.reasoning.status="complete",ee.reasoning.completedAt=xe(v.completedAt??v.timestamp);let ae=ee.reasoning.startedAt??Date.now();ee.reasoning.durationMs=Math.max(0,(ee.reasoning.completedAt??Date.now())-ae),ee.streaming=!1,h(ee)}let te=_(v);te&&se.byStep.delete(te)}else if(Z==="tool_start"){C&&(C.streaming=!1,h(C),C=null),typeof v.iteration=="number"&&(zr=v.iteration);let N=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??De(v,!0)??`tool-${u()}`,F=v.toolName??v.name;if(j(F)){fe.add(N);continue}Ae(W(v),N);let U=Ne(N),ee=U.toolCall??{id:N,status:"pending"};ee.name=F??ee.name,ee.status="running",v.parameters!==void 0?ee.args=v.parameters:v.args!==void 0&&(ee.args=v.args),ee.startedAt=ee.startedAt??xe(v.startedAt??v.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,U.toolCall=ee,U.streaming=!0,v.executionId&&(U.agentMetadata={executionId:v.executionId,iteration:v.iteration}),h(U)}else if(Z==="tool_output_delta"){let N=De(v,!1)??De(v,!0)??`tool-${u()}`;if(fe.has(N))continue;let F=Ne(N),U=F.toolCall??{id:N,status:"running"};U.startedAt=U.startedAt??xe(v.startedAt??v.timestamp);let ee=v.text??v.delta??v.message??"";ee&&(U.chunks=U.chunks??[],U.chunks.push(String(ee))),U.status="running",F.toolCall=U,F.streaming=!0;let te=v.agentContext;(te||v.executionId)&&(F.agentMetadata=F.agentMetadata??{executionId:te?.executionId??v.executionId,iteration:te?.iteration??v.iteration}),h(F)}else if(Z==="tool_complete"){let N=De(v,!1)??De(v,!0)??`tool-${u()}`;if(fe.has(N)){fe.delete(N);continue}let F=Ne(N),U=F.toolCall??{id:N,status:"running"};U.status="complete",v.result!==void 0&&(U.result=v.result),typeof v.duration=="number"&&(U.duration=v.duration),U.completedAt=xe(v.completedAt??v.timestamp);let ee=v.duration??v.executionTime;if(typeof ee=="number")U.durationMs=ee;else{let we=U.startedAt??Date.now();U.durationMs=Math.max(0,(U.completedAt??Date.now())-we)}F.toolCall=U,F.streaming=!1;let te=v.agentContext;(te||v.executionId)&&(F.agentMetadata=F.agentMetadata??{executionId:te?.executionId??v.executionId,iteration:te?.iteration??v.iteration}),h(F);let ae=W(v);ae&&ne.byCall.delete(ae)}else if(Z==="await"&&v.toolName){let N=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,F=N??v.toolId??`local-${u()}`,U=Ne(F),ee=v.toolName,te=v.origin==="webmcp"&&!Ts(ee)?`webmcp:${ee}`:ee,ae=Ts(te),we=U.toolCall??{id:F,status:"pending"};we.name=te,we.args=v.parameters,we.status=ae?"running":"complete",we.chunks=we.chunks??[],we.startedAt=we.startedAt??xe(v.startedAt??v.timestamp??v.awaitedAt),ae?(we.completedAt=void 0,we.duration=void 0,we.durationMs=void 0):we.completedAt=we.completedAt??we.startedAt,U.toolCall=we,U.streaming=!1,U.agentMetadata={...U.agentMetadata,executionId:v.executionId??U.agentMetadata?.executionId,awaitingLocalTool:!0,...N?{webMcpToolCallId:N}:{}},h(U)}else if(Z==="text_start"){let N=typeof v.id=="string"?v.id:null,F=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(N&&F){T.set(N,F);continue}let U=C;U&&(un==="flow"?(Wt(U),nn=U):(U.streaming=!1,h(U)),C=null),B=typeof v.id=="string"?v.id:B,$=""}else if(Z==="text_delta"){let N=typeof v.id=="string"?v.id:null,F=N?T.get(N):void 0;if(N&&F){let te=typeof v.delta=="string"?v.delta:"",ae=(A.get(N)??"")+te;if(A.set(N,ae),ae.trim()==="")continue;let we=qr(N,F);we.agentMetadata={...we.agentMetadata,executionId:v.executionId,parentToolId:F},pn(we,ae,te,void 0);continue}if(B=typeof v.id=="string"?v.id:B,un==="flow"){let te=typeof v.delta=="string"?v.delta:"";if($+=te,$.trim()==="")continue;let ae=K();ae.agentMetadata={executionId:v.executionId,iteration:v.iteration},pn(ae,$,te,void 0),S=ae;continue}let U=typeof v.delta=="string"?v.delta:"";$+=U;let ee=K();ee.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:Tt??void 0,agentName:gt?.agentName},pn(ee,$,U,void 0),S=ee}else if(Z==="text_complete"){let N=typeof v.id=="string"?v.id:null;if(N&&T.has(N)){let U=I.get(N);U&&Wt(U),T.delete(N),A.delete(N),I.delete(N);continue}let F=C;F&&(un==="flow"?(Wt(F),nn=F):((F.content??"")===""&&typeof v.text=="string"&&(F.content=v.text),F.streaming=!1,h(F)),C=null),B=null,$=""}else if(Z==="step_complete"){let N=v.stepType,F=v.executionType;if(N==="tool"||F==="context")continue;if(v.success===!1){let U=v.error,ee=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(ee)});let te=C;te&&te.streaming&&(te.streaming=!1,h(te)),n({type:"status",status:"idle"});continue}{let U=nn;nn=null;let ee=v.stopReason,te=v.result?.response;if(U)ee&&(U.stopReason=ee),te!=null?at(U,te):U.streaming!==!1&&(he.delete(U.id),dt.delete(U.id),U.streaming=!1,h(U));else{let ae=te!=null&&te!=="";if(ae||ee){let we=K();ee&&(we.stopReason=ee),ae?Wt(we,te):(we.streaming=!1,h(we))}}continue}}else if(Z==="execution_start")un=v.kind==="flow"?"flow":"agent",Gi=!0,un==="agent"&&(gt={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:xe(v.startedAt)});else if(Z==="turn_start"){let N=typeof v.iteration=="number"?v.iteration:zr;if(N!==zr){if(gt&&(gt.currentIteration=N),Sl==="separate"&&N>1){let F=C;F&&(F.streaming=!1,h(F),ro.set(N-1,F),C=null)}zr=N}Tt=typeof v.id=="string"?v.id:null,S=null}else if(Z==="tool_input_delta"){let N=v.toolCallId??ne.lastId;if(N){let F=G.get(N);F?.toolCall&&(F.toolCall.chunks=F.toolCall.chunks??[],F.toolCall.chunks.push(v.delta??""),h(F))}}else{if(Z==="tool_input_complete")continue;if(Z==="turn_complete"){let N=v.stopReason,F=C??S;if(N&&F!==null){let U=v.id;(!U||F.agentMetadata?.turnId===U)&&(F.stopReason=N,h(F))}Tt===v.id&&(Tt=null)}else if(Z==="media_start"){let N=String(v.id);Ki.set(N,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(Z==="media_delta"){let N=Ki.get(String(v.id));N&&typeof v.delta=="string"&&N.parts.push(v.delta)}else if(Z==="media_complete"){let N=String(v.id),F=Ki.get(N);Ki.delete(N);let U=(typeof v.mediaType=="string"?v.mediaType:void 0)??F?.mediaType??"application/octet-stream",ee=typeof v.data=="string"?v.data:void 0,te=typeof v.url=="string"?v.url:F&&F.parts.length>0?F.parts.join(""):void 0,ae=null;if(ee)ae={type:"media",data:ee,mediaType:U};else if(te){let Ot=U.toLowerCase();ae={type:Ot==="image"||Ot.startsWith("image/")?"image-url":"file-url",url:te,mediaType:U}}let we=v.toolCallId??F?.toolCallId,yt=ae?[ae]:[],qe=[];for(let Ot of yt){if(!Ot||typeof Ot!="object")continue;let St=Ot,Vr=typeof St.type=="string"?St.type:void 0,In=typeof St.mediaType=="string"?St.mediaType.toLowerCase():"",jt=null,gn="";if(Vr==="media"){let sn=typeof St.data=="string"?St.data:void 0;if(!sn)continue;gn=In.length>0?In:"application/octet-stream",jt=`data:${gn};base64,${sn}`}else if(Vr==="image-url"){let sn=typeof St.url=="string"?St.url:void 0;if(!sn)continue;gn=In,jt=sn}else if(Vr==="file-url"){let sn=typeof St.url=="string"?St.url:void 0;if(!sn)continue;gn=In,jt=sn}else continue;if(jt)if(Vr==="image-url"||gn.startsWith("image/"))qe.push({type:"image",image:jt,...gn.includes("/")?{mimeType:gn}:{}});else if(gn.startsWith("audio/"))qe.push({type:"audio",audio:jt,mimeType:gn});else if(gn.startsWith("video/"))qe.push({type:"video",video:jt,mimeType:gn});else{let sn=gn||"application/octet-stream";qe.push({type:"file",data:jt,mimeType:sn,filename:qP(sn)})}}if(qe.length>0){let Ot=u(),St=we,In={id:`agent-media-${typeof St=="string"&&St.length>0?`${St}-${Ot}`:String(Ot)}`,role:"assistant",content:"",contentParts:qe,createdAt:new Date().toISOString(),streaming:!1,sequence:Ot,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:zr}};h(In);let jt=C;jt&&(jt.streaming=!1,h(jt)),C=null,x.current=null}}else if(Z==="execution_complete"){let N=v.kind??un;N==="agent"&&gt&&(gt.status=v.success?"complete":"error",gt.completedAt=xe(v.completedAt),gt.stopReason=v.stopReason);let F=C;F&&(N==="flow"&&F.streaming!==!1?Wt(F):(F.streaming=!1,h(F)),C=null),B=null,$="",nn=null,n({type:"status",status:"idle",terminal:!0})}else if(Z==="execution_error"){let N=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(N)})}else if(Z!=="ping"){if(Z==="approval_start"){let N=v.approvalId??`approval-${u()}`,F={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:"pending",agentId:gt?.agentId??"virtual",executionId:v.executionId??gt?.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(Z==="step_await"&&v.awaitReason==="approval_required"){let N=v.approvalId??`approval-${u()}`,F={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:"pending",agentId:gt?.agentId??"virtual",executionId:v.executionId??gt?.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(Z==="approval_complete"){let N=v.approvalId;if(N){let U={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:v.decision??"approved",agentId:gt?.agentId??"virtual",executionId:v.executionId??gt?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};h(U)}}else if(Z==="artifact_start"||Z==="artifact_delta"||Z==="artifact_update"||Z==="artifact_complete"){if(Z==="artifact_start"){let N=v.artifactType,F=String(v.id),U=typeof v.title=="string"?v.title:void 0,ee=v.file,te;ee&&typeof ee=="object"&&!Array.isArray(ee)&&typeof ee.path=="string"&&typeof ee.mimeType=="string"&&(te={path:ee.path,mimeType:ee.mimeType,...typeof ee.language=="string"?{language:ee.language}:{}}),n({type:"artifact_start",id:F,artifactType:N,title:U,component:typeof v.component=="string"?v.component:void 0,...te?{file:te}:{}});let ae=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(be.set(F,{markdown:"",title:U,file:te,...ae?{props:ae}:{}}),!it.has(F)){it.add(F);let we=sr(this.config.features?.artifacts,{artifactType:N,...te?{file:te}:{}}),yt=typeof v.component=="string"?v.component:void 0,qe={id:`artifact-ref-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:Da(we,{artifactId:F,title:U,artifactType:N,status:"streaming",...te?{file:te}:{},...yt?{component:yt}:{}})};_e.set(F,qe),h(qe)}}else if(Z==="artifact_delta"){let N=String(v.id),F=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:N,artDelta:F});let U=be.get(N);U&&(U.markdown+=F)}else if(Z==="artifact_update"){let N=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:N,component:typeof v.component=="string"?v.component:void 0});let F=be.get(String(v.id));F&&(F.props={...F.props??{},...N})}else if(Z==="artifact_complete"){let N=String(v.id);n({type:"artifact_complete",id:N});let F=_e.get(N);if(F){F.streaming=!1;try{let U=JSON.parse(F.rawContent??"{}");if(U.props){U.props.status="complete";let ee=be.get(N);ee?.markdown&&(U.props.markdown=ee.markdown),ee?.file&&(U.props.file=ee.file),U.component==="PersonaArtifactInline"&&ee?.props&&Object.keys(ee.props).length>0&&(U.props.componentProps=ee.props)}F.rawContent=JSON.stringify(U)}catch{}be.delete(N),h(F),_e.delete(N)}}}else if(Z==="transcript_insert"){let N=v.message;if(!N||typeof N!="object")continue;let F=String(N.id??`msg-${u()}`),U=N.role,te={id:F,role:U==="user"?"user":U==="system"?"system":"assistant",content:typeof N.content=="string"?N.content:"",rawContent:typeof N.rawContent=="string"?N.rawContent:void 0,createdAt:typeof N.createdAt=="string"?N.createdAt:new Date().toISOString(),streaming:N.streaming===!0,...typeof N.variant=="string"?{variant:N.variant}:{},sequence:u()};if(h(te),te.rawContent)try{let we=JSON.parse(te.rawContent)?.props?.artifactId;typeof we=="string"&&it.add(we)}catch{}C=null,x.current=null,he.delete(F),dt.delete(F)}else if(Z==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let N=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(N)});let F=C;F&&F.streaming&&(F.streaming=!1,h(F)),n({type:"status",status:"idle"})}}else if(Z==="step_error"||Z==="dispatch_error"||Z==="flow_error"){let N=null;if(v.error instanceof Error)N=v.error;else if(Z==="dispatch_error"){let F=v.message??v.error;F!=null&&F!==""&&(N=new Error(String(F)))}else{let F=v.error;typeof F=="string"&&F!==""?N=new Error(F):F!=null&&typeof F=="object"&&Reflect.has(F,"message")&&(N=new Error(String(F.message??F)))}if(N){n({type:"error",error:N});let F=C;F&&F.streaming&&(F.streaming=!1,h(F)),n({type:"status",status:"idle"})}}}}}xn.length=0};;){let{done:R,value:Z}=await s.read();if(R)break;l+=a.decode(Z,{stream:!0});let v=l.split(`
7
7
 
8
8
  `);l=v.pop()??"";for(let N of v){let F=N.split(`
9
- `),U="message",Z="",te=null;for(let qe of F)qe.startsWith("event:")?U=qe.replace("event:","").trim():qe.startsWith("data:")?Z+=qe.replace("data:","").trim():qe.startsWith("id:")&&(te=qe.slice(3).trim());let ae=()=>{te!==null&&te!==""&&n({type:"cursor",id:te})};if(!Z){ae();continue}let Se;try{Se=JSON.parse(Z)}catch(qe){n({type:"error",error:qe instanceof Error?qe:new Error("Failed to parse chat stream payload")});continue}let yt=U!=="message"?U:Se.type??"message";if(this.onSSEEvent?.(yt,Se),this.parseSSEEvent){S.current=C;let qe=await this.handleCustomSSEEvent(Se,n,S,h,u,k);if(S.current&&S.current!==C&&(C=S.current),qe){ae();continue}}xn.push({payloadType:yt,payload:Se}),bo(),ae()}}bo()}};function qP(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 iv(e,t){let n="`".repeat(Math.max(3,qP(t)+1));return`${n}${e}
9
+ `),U="message",ee="",te=null;for(let qe of F)qe.startsWith("event:")?U=qe.replace("event:","").trim():qe.startsWith("data:")?ee+=qe.replace("data:","").trim():qe.startsWith("id:")&&(te=qe.slice(3).trim());let ae=()=>{te!==null&&te!==""&&n({type:"cursor",id:te})};if(!ee){ae();continue}let we;try{we=JSON.parse(ee)}catch(qe){n({type:"error",error:qe instanceof Error?qe:new Error("Failed to parse chat stream payload")});continue}let yt=U!=="message"?U:we.type??"message";if(this.onSSEEvent?.(yt,we),this.parseSSEEvent){x.current=C;let qe=await this.handleCustomSSEEvent(we,n,x,h,u,k);if(x.current&&x.current!==C&&(C=x.current),qe){ae();continue}}xn.push({payloadType:yt,payload:we}),vo(),ae()}}vo()}};function KP(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 cv(e,t){let n="`".repeat(Math.max(3,KP(t)+1));return`${n}${e}
11
11
  ${t}
12
- ${n}`}var zP=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function VP(e){let t=e?.text?.trim()??"";return t?iv(zP(e),t):""}function av(e){let t=VP(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[mo(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
12
+ ${n}`}var GP=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function QP(e){let t=e?.text?.trim()??"";return t?cv(GP(e),t):""}function dv(e){let t=QP(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[fo(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
13
13
 
14
- `)}:{}}function nd(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function lv(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 yg(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 yg(e,n.id)?n.id:null}return null}function bg(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 KP(e){return e instanceof fo}function Ya(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 Rs=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):Ya(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 GP=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function dv(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:GP()}catch{return!1}}var{setLoader:hW,load:QP}=ht({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var vg=QP;function Cg(e){if(!e)return"";let t=YP(e);return pv(t!==null?t:e)}function YP(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 pv(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 nd(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function pv(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 Cg(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 uv(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 Cg(e,n.id)?n.id:null}return null}function wg(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 ho=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function YP(e){return e instanceof ho}function Ya(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 Rs=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):Ya(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 Ai=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 XP=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function gv(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:XP()}catch{return!1}}var{setLoader:xW,load:JP}=ht({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var xg=JP;function Sg(e){if(!e)return"";let t=ZP(e);return mv(t!==null?t:e)}function ZP(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 mv(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 hv=null;var xg=()=>hv?hv():Promise.resolve().then(()=>(fv(),mv));var{setLoader:TW,load:ZP}=ht({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var yv=ZP;var ek=["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 tk(e,t){return ek.some(n=>e[n]!==t[n])}var Wo=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function Sg(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 vv=null;var Mg=()=>vv?vv():Promise.resolve().then(()=>(bv(),yv));var{setLoader:HW,load:nk}=ht({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var Cv=nk;var ok=["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 rk(e,t){return ok.some(n=>e[n]!==t[n])}var Oo=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function Eg(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 Ag=e=>({isError:!0,content:[{type:"text",text:e}]}),nk=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,bv=e=>Ts(e)||e===rr,Xa=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 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&&(Ts(n.name)||n.name===rr&&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.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&&vg().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||xg().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 dv(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=Rs.isSupported()?new Rs({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 xg().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=vg().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 Wo("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 Wo("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 Wo("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new Wo("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=Qa(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 Wo("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 Wo("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 Wo("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 Wo("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.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=Qa(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=Ga(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=Ga(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 je&&(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 je?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 je&&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(!tk(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 xi(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"?Na():n==="assistant"?ks():`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"?Na():r==="assistant"?ks():`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(`
18
+ _Details: ${n.message}_`:o}var Tg=e=>({isError:!0,content:[{type:"text",text:e}]}),sk=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,wv=e=>Ts(e)||e===ir,Xa=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 Ai(()=>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&&(Ts(n.name)||n.name===ir&&_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 Si(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&&xg().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||Mg().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 gv(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=Rs.isSupported()?new Rs({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 Mg().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=xg().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 Oo("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 ho("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 Oo("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 Oo("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new Oo("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=Qa(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 Oo("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 Oo("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 Oo("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 Oo("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=Qa(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=Ga(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=Ga(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 Ue&&(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 Ue?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 Ue&&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(!rk(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 Si(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"?Na():n==="assistant"?ks():`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"?Na():r==="assistant"?ks():`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(`
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(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=Na(),a=ks();this.activeAssistantMessageId=null;let l=n?.contentParts&&Ka(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=av({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=Sg(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=lv(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=ks();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=Sg(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],x=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:x||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n});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!==rr?!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=await Promise.all(n.map(async l=>{let d=l.toolCall?.name,p=l.toolCall?.id;if(!d||!p)return null;let u=`${t}:${p}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(l))return null;this.webMcpInflightKeys.add(u),o.push(u);let m=this.markWebMcpToolRunning(l),y=l.agentMetadata?.webMcpToolCallId??d;if(d===rr)return{dedupeKey:u,resumeKey:y,output:Hb(),toolMessage:l,startedAt:m,completedAt:Date.now()};let h=this.client.executeWebMcpToolCall(d,l.toolCall?.args,r.signal),C;if(!h)C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{C=await h}catch(x){let S=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));return S||this.callbacks.onError?.(x instanceof Error?x:new Error(String(x))),this.markWebMcpToolComplete(l,Ag(S?"Aborted by cancel()":nk(x)),m),this.webMcpInflightKeys.delete(u),null}return r.signal.aborted?(this.markWebMcpToolComplete(l,Ag("Aborted by cancel()"),m),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:y,output:C,toolMessage:l,startedAt:m,completedAt:Date.now()}})),a=[];try{if(a=s.filter(p=>p!==null),a.length===0)return;let l={};for(let p of a)l[p.resumeKey]=p.output;let d=await this.client.resumeFlow(t,l,{signal:r.signal});if(!d.ok){let p=await d.json().catch(()=>null);throw new Error(p?.error??`Resume failed: ${d.status}`)}for(let p of a)this.webMcpResolvedKeys.add(p.dedupeKey),this.markWebMcpToolComplete(p.toolMessage,p.output,p.startedAt,p.completedAt,p.toolMessage.toolCall?.name===rr?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(l){if(!(l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"))))this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)));else for(let p of a)this.markWebMcpToolComplete(p.toolMessage,Ag("Aborted by cancel()"),p.startedAt)}finally{for(let l of o)this.webMcpInflightKeys.delete(l);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});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=or(this.config.features?.artifacts,t),r=Da(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=or(this.config.features?.artifacts,n),s=Da(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=yv().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=>Sg(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=ks(),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=Cg(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ya(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Cg(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&&bv(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&&bv(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 ok,FileCode as rk,FileSpreadsheet as sk,FileText as Mg,X as ik}from"lucide";var ak={add:e=>zb(e)},lk=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,sd={allowedTypes:ir,maxFileSize:10*1024*1024,maxFiles:4};function ck(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function dk(e){return e==="application/pdf"?Mg:e.startsWith("text/")?Mg:e.includes("word")?Mg:e.includes("excel")||e.includes("spreadsheet")?sk:e==="application/json"?rk:ok}var Mi=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??sd.allowedTypes,maxFileSize:t.maxFileSize??sd.maxFileSize,maxFiles:t.maxFiles??sd.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:ak}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:sd.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=Vb(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:ck(),file:o,previewUrl:ed(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=lk(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=ed(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=dk(t.file.type),y=Ht(m,20,"var(--persona-muted, #6b7280)",1.5);y&&u.appendChild(y);let h=M("span");h.textContent=Kb(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=Ht(ik,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 vv=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),pk=(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 Cv(){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=>{pk(e.attachments,u)||(e.attachments=[...u],p())},setMentionRefs:u=>{vv(e.mentionRefs,u)||(e.mentionRefs=[...u],p())},setSelectedModelId:u=>{e.selectedModelId!==u&&(e.selectedModelId=u,p())},setActiveModeIds:u=>{vv(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 Ln=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},wv=(e,t)=>{let n=M("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function xv(e,t={}){let n=Ln(e,"[data-persona-composer-form]"),o=Ln(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:Ln(e,"[data-persona-composer-header]"),body:Ln(e,"[data-persona-composer-body]"),actionsStart:Ln(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Ln(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Ln(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Ln(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Ln(e,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=wv("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=(S,k,B,$,T)=>{if(k)return k;s.add(S);let I=wv(B,$);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=[],C=(S,k)=>S.target===k.target&&S.type===k.type&&S.handler===k.handler,x=Ln(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:Ln(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Ln(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Ln(e,"[data-persona-composer-submit]")??void 0,micButton:Ln(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(S,k,B,$)=>{S.addEventListener(k,B,$),h.push({target:S,type:k,handler:B,options:$})},removeListener:(S,k,B,$)=>{S.removeEventListener(k,B,$),h=h.filter(T=>!C(T,{target:S,type:k,handler:B}))},destroy:()=>{for(let S of h)S.target.removeEventListener(S.type,S.handler,S.options);h=[]}}}var $t={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},rn=1e5,Ei=rn+1;var uk=8,gk=8,Eg=10,Sv=200,Av=300,Mv=0,ad=e=>Math.max(0,e);function Ev(e){e.delayMs!==void 0&&(Sv=ad(e.delayMs)),e.skipDelayMs!==void 0&&(Av=ad(e.skipDelayMs))}var mk=()=>Date.now()<Mv,fk=e=>{Mv=e>0?Date.now()+e:0},id=new WeakMap,Pg="data-persona-tooltip-suppressed",hk=e=>typeof e.closest=="function"&&e.closest(`[${Pg}]`)!==null;function Tv(e){id.get(e)?.hide()}var Pv=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,yk=e=>{let t=e.getRootNode?.();return Pv(t)?t:e.ownerDocument.body},Tg=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),bk=[...["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 en(e){id.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:a=uk,viewportPadding:l=gk}=e,d=()=>t.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,y=null,h=null,C,x=!1,S=!1,k=!1,B=()=>(typeof o=="function"?o():o).trim(),$=()=>(typeof r=="function"?r():r??"").trim(),T=()=>ad(e.delayMs??Sv),I=()=>ad(e.skipDelayMs??Av),A=()=>{C!==void 0&&(p().clearTimeout(C),C=void 0)},_=()=>{A();let ge=u!==null;h?.(),h=null,u?.remove(),u=null,m=null,y=null,ge&&fk(I())},G=()=>{if(!u)return;let ge=d(),Me=p(),fe=t.getBoundingClientRect(),_e=u.getBoundingClientRect(),it=ge.documentElement.clientWidth||Me.innerWidth,be=ge.documentElement.clientHeight||Me.innerHeight,j=it-l-_e.width,De=fe.left+fe.width/2-_e.width/2,Ne=Tg(De,l,j),we=fe.top-l,ke=be-l-fe.bottom,he=_e.height+a,dt=we>=he||we>=ke?"top":"bottom",Ie=dt==="top"?fe.top-a-_e.height:fe.bottom+a,Ut=be-l-_e.height,at=Tg(Ie,l,Ut),nn=fe.left+fe.width/2,wn=Math.max(Eg,_e.width-Eg),Wt=Tg(nn-Ne,Eg,wn);u.dataset.placement=dt,u.style.left=`${Ne}px`,u.style.top=`${at}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${Wt}px`)},ie=()=>{if(k||!s||u||!t.isConnected||hk(t))return;let ge=B(),Me=yk(t);if(!ge||!Me)return;let fe=d(),_e=p();u=fe.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Ei);let it=_e.getComputedStyle?.(t);if(it){for(let he of bk){let dt=it.getPropertyValue(he).trim();dt&&u.style.setProperty(he,dt)}it.fontFamily&&(u.style.fontFamily=it.fontFamily)}m=fe.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ge,u.appendChild(m);let be=$();be&&(y=fe.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=be,u.appendChild(y));let j=fe.createElement("span");j.className="persona-control-tooltip__arrow",u.appendChild(j),Me.appendChild(u),G(),u.dataset.state="open";let De=()=>{if(!t.isConnected){_();return}m&&(m.textContent=B()),y&&(y.textContent=$()),G()};_e.addEventListener("scroll",De,!0),_e.addEventListener("resize",De);let Ne=t.getRootNode(),we=Pv(Ne)?Ne:fe.documentElement,ke=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||_()});ke?.observe(we,{childList:!0,subtree:!0}),h=()=>{_e.removeEventListener("scroll",De,!0),_e.removeEventListener("resize",De),ke?.disconnect()}},ne=ge=>{if(!(k||u)){if(A(),ge||T()<=0||mk()){ie();return}C=p().setTimeout(()=>{C=void 0,ie()},T())}},E=()=>{x||S?ne(S):_()},D=()=>{let ge=p();(!ge.matchMedia||!ge.matchMedia("(hover: none)").matches)&&(x=!0,E())},W=()=>{x=!1,E()},L=()=>{try{S=t.matches(":focus-visible")}catch{S=!0}E()},Y=()=>{S=!1,E()},K=()=>{x=!1,S=!1,_()},le=ge=>{ge.key==="Escape"&&K()};n.addEventListener("mouseenter",D),n.addEventListener("mouseleave",W),t.addEventListener("focus",L),t.addEventListener("blur",Y),t.addEventListener("keydown",le),t.addEventListener("click",K);let de={get isOpen(){return u!==null},show:ie,hide:_,reposition:G,destroy:()=>{k||(k=!0,_(),n.removeEventListener("mouseenter",D),n.removeEventListener("mouseleave",W),t.removeEventListener("focus",L),t.removeEventListener("blur",Y),t.removeEventListener("keydown",le),t.removeEventListener("click",K),id.delete(t))}};return id.set(t,de),de}var kv=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];kv(s)&&kv(r)?n[o]=Ti(s,r):n[o]=r}return n}var oo="min(440px, calc(100vw - 24px))",kg="440px",Lg="How can I help...",vk={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)"},st={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:vk,copy:{inputPlaceholder:Lg,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 Lv(e,t){if(!(!e&&!t))return e?t?Ti(e,t):e:t}function el(e){return e?{...st,...e,theme:Lv(st.theme,e.theme),darkTheme:Lv(st.darkTheme,e.darkTheme),launcher:{...st.launcher,...e.launcher,dock:{...st.launcher?.dock,...e.launcher?.dock},clearChat:{...st.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...st.tooltip,...e.tooltip},copy:{...st.copy,...e.copy},sendButton:{...st.sendButton,...e.sendButton},statusIndicator:{...st.statusIndicator,...e.statusIndicator},voiceRecognition:{...st.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=st.features?.artifacts,n=e.features?.artifacts,o=st.features?.scrollToBottom,r=e.features?.scrollToBottom,s=st.features?.scrollBehavior,a=e.features?.scrollBehavior,l=st.features?.streamAnimation,d=e.features?.streamAnimation,p=st.features?.askUserQuestion,u=e.features?.askUserQuestion,m=st.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},x=s===void 0&&a===void 0?void 0:{...s,...a},S=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}},B=m===void 0&&y===void 0?void 0:{...m,...y,copy:{...m?.copy,...y?.copy}};return{...st.features,...e.features,...C!==void 0?{scrollToBottom:C}:{},...x!==void 0?{scrollBehavior:x}:{},...h!==void 0?{artifacts:h}:{},...S!==void 0?{streamAnimation:S}:{},...k!==void 0?{askUserQuestion:k}:{},...B!==void 0?{history:B}:{}}})(),suggestionChips:e.suggestionChips??st.suggestionChips,suggestionChipsConfig:{...st.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...st.layout,...e.layout,header:{...st.layout?.header,...e.layout?.header},messages:{...st.layout?.messages,...e.layout?.messages,avatar:{...st.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...st.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...st.layout?.slots,...e.layout?.slots}},markdown:{...st.markdown,...e.markdown,options:{...st.markdown?.options,...e.markdown?.options}},messageActions:{...st.messageActions,...e.messageActions}}:st}function Ig(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 ld(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function Iv(e,t){e.style.maxHeight=`${t*Ig(e)}px`,e.style.overflowY="auto"}function tl(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 Rv(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Hv(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||!Rv(t)}function Ck(e){return(e.submitKey??"enter")!=="enter"||Rv(e)?"enter":"send"}function cd(e,t){e.setAttribute("enterkeyhint",Ck(t))}function dd(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 Rg(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",Wg=40,hn=24,pd=(e,t)=>{let n=M("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Lg,n.dir="auto",cd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:tl(n)}),dd(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=ld(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*Ig(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}},xk="[data-persona-glyph-stack]",Og=(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},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??"")||Wg,h=t.backgroundColor,C=t.textColor,x=M("div","persona-send-button-wrapper"),S=Q("button",{className:fn("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&&!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}}),k=null,B=null,$=null;if(n){let A=parseFloat(t.iconSize??"")||Math.round(y*.5),_=t.iconStrokeWidth??2,G=C?.trim()||"currentColor";r&&(k=pe(r,A,G,_)),B=pe(s,A,G,_),k&&B?($=Og(k,B),S.appendChild($)):k?S.appendChild(k):(S.textContent=o,B=null)}else S.textContent=d;S.setAttribute("aria-label",a),x.appendChild(S),en({anchor:S,trigger:x,text:()=>S.getAttribute("aria-label")??"",enabled:u});let T="send";return{button:S,wrapper:x,setMode:A=>{if(A===T)return;T=A;let _=A==="stop"?l:a;S.setAttribute("aria-label",_),S.setAttribute("data-persona-send-mode",A),n?(S.querySelector(xk)??$)?.setAttribute("data-mode",A):S.textContent=A==="stop"?p:d},glyphStack:$}},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??"")||hn,u=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,y=M("div","persona-send-button-wrapper"),h=Q("button",{className:fn("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=pe(l,p,m||"currentColor",1.5);x?h.appendChild(x):h.textContent="\u{1F3A4}",y.appendChild(h);let S=t.tooltipText??"Start voice recognition",k=t.showTooltip??!1;return en({anchor:h,trigger:y,text:()=>h.getAttribute("aria-label")??S,enabled:k}),{button:h,wrapper:y}},gd=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??ir).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 ${jn} ${ho}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=pe(r,hn,"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 en({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=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},fd=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function Sk(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??Sk(t),y=!1,h=null,C=()=>{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 B=n.getBoundingClientRect(),$=l?.()??null,T=$!=null?k.top+$:k.top,I=o==="top-start"||o==="top-end"?T-r-B.height:k.bottom+r,_=o==="bottom-end"||o==="top-end"?k.right-B.width:k.left,G=a?.()??null;if(G!=null){let ie=Math.max(k.left,k.right-B.width);_=Math.min(Math.max(k.left+G,k.left),ie)}n.style.top=`${I}px`,n.style.left=`${_}px`},x=()=>{y&&(y=!1,h&&(h(),h=null),n.remove())},S=()=>{if(y)return;y=!0,d!=null&&(n.style.zIndex=String(d)),m.appendChild(n),C();let k=(t.ownerDocument??document).defaultView??window,B=t.ownerDocument??document,$=()=>{if(!t.isConnected){x(),u?.("anchor-removed");return}C()},T=A=>{let _=typeof A.composedPath=="function"?A.composedPath():[];_.includes(n)||_.includes(t)||(x(),u?.("outside"))},I=k.setTimeout(()=>{B.addEventListener("pointerdown",T,!0)},0);k.addEventListener("scroll",$,!0),k.addEventListener("resize",$),h=()=>{k.clearTimeout(I),B.removeEventListener("pointerdown",T,!0),k.removeEventListener("scroll",$,!0),k.removeEventListener("resize",$)},p?.()};return{get isOpen(){return y},open:S,close:x,toggle:()=>y?x():S(),reposition:C,destroy:x}}var Ak='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',Bg="data-persona-menu-focus",Mk=new Set(["ArrowDown","ArrowUp","Home","End"]);function Wv(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(Ak)??e}var Ek=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function Ov(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 ${jn} ${ho}`,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 Y=pe("plus",hn,"currentColor",1.5);Y?r.appendChild(Y):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 Y=s.getRootNode().activeElement;return Y instanceof HTMLElement?Y:null},y=()=>{let L=m();for(let Y of d){let K=!!L&&Wv(Y)===L;Y.toggleAttribute(Bg,K&&u)}},h=()=>d.filter(L=>L.isConnected||s.contains(L)).map(Wv).filter(L=>!Ek(L)),C=(L,Y)=>{L.forEach((K,le)=>{K.setAttribute("tabindex",le===Y?"0":"-1")})},x=L=>{let Y=h();if(Y.length===0)return;let K=(L%Y.length+Y.length)%Y.length;p=K,C(Y,K),Y[K].focus(),y()},S=()=>o.ownerDocument??document,k=null,B=null,$=null,T=()=>{k&&(S().removeEventListener("focusin",k,!0),k=null)},I=()=>{B&&(s.removeEventListener("focusin",B),B=null),$&&(s.removeEventListener("pointerdown",$,!0),$=null)},A=null,_=()=>(A||(A=hd({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),T()}})),A),G=()=>A?.isOpen===!0,ie=(L=!1)=>{if(G()){A?.close(),r.setAttribute("aria-expanded","false"),T(),I(),p=-1,u=!1;for(let Y of d)Y.removeAttribute(Bg);L&&r.focus()}},ne=(L=0,Y=!1)=>{if(n||G())return;u=Y,_().open(),r.setAttribute("aria-expanded","true");let K=h();C(K,-1),x(L<0?K.length-1:L),k=le=>{let de=typeof le.composedPath=="function"?le.composedPath():[];de.includes(s)||de.includes(o)||ie()},S().addEventListener("focusin",k,!0),B=()=>y(),s.addEventListener("focusin",B),$=()=>{u=!1},s.addEventListener("pointerdown",$,!0)},E=L=>{L.preventDefault(),L.stopPropagation(),G()?ie(!0):ne(0)},D=L=>{if(L.key==="ArrowDown"||L.key==="Enter"||L.key===" "){L.preventDefault(),u=!0,G()?x(0):ne(0,!0);return}L.key==="ArrowUp"&&(L.preventDefault(),u=!0,G()?x(-1):ne(-1,!0))},W=L=>{switch(Mk.has(L.key)&&(u=!0),L.key){case"ArrowDown":L.preventDefault(),x(p+1);return;case"ArrowUp":L.preventDefault(),x(p-1);return;case"Home":L.preventDefault(),x(0);return;case"End":L.preventDefault(),x(h().length-1);return;case"Escape":L.preventDefault(),L.stopPropagation(),ie(!0);return;case"Tab":ie(!0);return;default:}};return r.addEventListener("click",E),r.addEventListener("keydown",D),s.addEventListener("keydown",W),{trigger:o,triggerButton:r,panel:s,setItems:L=>{for(let K of d)L.includes(K)||K.removeAttribute(Bg);if(d=[...L],!G())return;let Y=h();C(Y,Math.min(p,Y.length-1)),y()},isOpen:G,open:()=>ne(0),close:ie,setLabel:L=>{L!==t&&(t=L,l())},applyButtonSize:a,destroy:()=>{n=!0,T(),I(),r.removeEventListener("click",E),r.removeEventListener("keydown",D),s.removeEventListener("keydown",W),A?.destroy(),A=null,o.remove(),s.remove(),d=[]}}}var Oo={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Bv="data-persona-composer-action",_g="data-persona-composer-disable-when-streaming",Tk="core:overflow",Pk=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function kk(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 Dg(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 _v=(e,t)=>{!e||typeof console>"u"||console.warn(t)},Lk=(e,t)=>t.includes(":")?t:`${e}:${t}`;function Ik(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){_v(t,`[Persona] composer action "${l.id}" is already contributed by ${Dv(d)}; the ${Dv(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?Lk(p,l.id):l.id,m=l.order??Oo.custom;l.placement==="end"&&m>=Oo.send&&(_v(t,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${Oo.send-1}.`),m=Oo.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 Dv=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",Nv=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,_r=e=>e.kind==="custom",Ng=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,Rk=e=>{let t=Ng(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},Hk='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Wk(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(Hk)||o.childNodes.forEach(n)};return n(e),t.trim()}var Ok=e=>Wk(e).length===0;function Fv(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(E,D)=>{let W=E.button;if(!W)return;W.setAttribute("role","menuitem"),W.setAttribute("tabindex","-1"),W.className="persona-composer-overflow-menu__item";for(let K of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])W.style[K]="";W.style.lineHeight="1",D.tooltipText?W.setAttribute("title",D.tooltipText):W.removeAttribute("title"),W.replaceChildren();let L=M("span","persona-composer-overflow-menu__icon");if(D.iconName){let K=pe(D.iconName,16,"currentColor",1.5);K&&L.appendChild(K)}let Y=M("span","persona-composer-overflow-menu__label");Y.textContent=D.shortLabel??D.label,W.append(L,Y)},a=(E,D)=>{let W=E.button;if(!W)return;if(W.setAttribute("aria-label",D.label),D.pressed===void 0?W.removeAttribute("aria-pressed"):W.setAttribute("aria-pressed",D.pressed?"true":"false"),W.toggleAttribute(_g,D.disableWhenStreaming===!0),E.mode==="menu"){E.tooltip?.destroy(),E.tooltip=void 0,s(E,D);return}W.removeAttribute("role"),W.removeAttribute("tabindex"),W.removeAttribute("title");let L=r(),Y=!!D.shortLabel;if(W.className=fn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",jn,ho,Y&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),W.style.width=L&&!Y?L:"",W.style.height=L??"",W.style.minWidth=L&&!Y?L:"",W.style.minHeight=L??"",W.style.fontSize=Y?"":"18px",W.style.lineHeight="1",W.style.color=D.iconColor??"",W.style.backgroundColor=D.backgroundColor??"",W.replaceChildren(),D.iconName){let K=pe(D.iconName,hn,"currentColor",1.5);K&&W.appendChild(K)}if(Y){let K=M("span","persona-composer-action-button__label");K.textContent=D.shortLabel,W.appendChild(K)}else W.firstChild||(W.textContent=D.label);E.tooltip?.destroy(),E.tooltip=en({anchor:W,trigger:E.element,text:()=>D.tooltipText??D.label,enabled:!!D.tooltipText})},l=(E,D)=>{let W=E.action,L=Q("button",{attrs:{type:"button"}}),Y=L;if(D==="bar"){let de=M("div","persona-send-button-wrapper");de.appendChild(L),Y=de}Y.setAttribute(Bv,E.id);let K={resolved:E,element:Y,button:L,owned:!0,managed:!0,busy:!1,visible:!0,mode:D},le=de=>{if(de.preventDefault(),de.stopPropagation(),K.busy||L.disabled)return;let ge=K.resolved.action;K.mode==="menu"&&h?.close(!0);let Me;try{Me=ge.onSelect(e.actionContext,de)}catch(fe){e.reportError(fe,{actionId:K.resolved.id});return}!Me||typeof Me.then!="function"||(K.busy=!0,L.setAttribute("aria-busy","true"),Me.catch(fe=>{e.reportError(fe,{actionId:K.resolved.id})}).finally(()=>{K.busy=!1,L.removeAttribute("aria-busy")}))};return L.addEventListener("click",le),K.detach=()=>L.removeEventListener("click",le),a(K,W),K},d=E=>{let D=E.action,W;try{W=D.render({...e.actionContext,id:E.id,action:D})}catch(L){return e.reportError(L,{actionId:E.id}),null}return W?.element?(W.element.setAttribute(Bv,E.id),W.element.toggleAttribute(_g,D.disableWhenStreaming===!0),{resolved:E,element:W.element,owned:!0,managed:!0,destroy:W.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(E,D)=>{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 W=E.action;return W?_r(W)?d(E):l(E,D):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(D){e.reportError(D,{actionId:E.resolved.id})}E.element.remove()}},m=(E,D)=>{for(let W=0;W<D.length;W++){let L=D[W];if(!L.managed)continue;let Y=null;for(let K=W+1;K<D.length;K++){let le=D[K];if(!le.managed&&le.element.parentElement===E){Y=le.element;break}}Y?(L.element.parentElement!==E||L.element.nextSibling!==Y)&&E.insertBefore(L.element,Y):E.lastChild!==L.element&&E.appendChild(L.element)}},y=(E,D)=>{if(E.button){E.button.disabled=D;return}if(!E.owned)return;let W=E.element;W.toggleAttribute("data-disabled",D),W.setAttribute("aria-disabled",D?"true":"false");let L=W instanceof HTMLButtonElement||W instanceof HTMLSelectElement||W instanceof HTMLInputElement||W instanceof HTMLTextAreaElement?W:W.querySelector("button, select, input, textarea");L&&(L.disabled=D)},h=null,C=null,x=null,S=0,k=()=>{let E=e.getOverflow?.();return E?.enabled===!0?E:void 0},B=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=Ov({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),$=E=>{C!==E&&(x?.disconnect(),C=E,S=Dg(E),!(typeof ResizeObserver>"u")&&(x=new ResizeObserver(D=>{let L=D[D.length-1]?.contentRect?.width??Dg(E);L!==S&&(S=L,ie())}),x.observe(E)))},T=(E,D)=>{let W=kk(E.collapseAutoActionsBelow,D);if(W===null)return!1;let L=S||Dg(D);return L>0&&L<W},I=(E,D,W)=>{if(!D)return"bar";if(E.resolved.builtIn){let Y=Pk(E.resolved.id);return Y&&D.includeBuiltIns?.includes(Y)?"menu":"bar"}let L=E.resolved.presentation;return L==="overflow"||L==="auto"&&W?"menu":"bar"},A=E=>{let D=E.menuSlot;if(!D)return;if(!Ok(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let W=Rk(E.element);if(!W){E.menuLabel?.remove(),E.menuLabel=void 0;return}E.menuLabel||(E.menuLabel=M("span","persona-composer-overflow-menu__label")),E.menuLabel.textContent!==W&&(E.menuLabel.textContent=W),E.menuLabel.parentElement!==D&&D.appendChild(E.menuLabel)},_=(E,D)=>{if(E.mode===D)return E;let W=E.resolved.action;if(W&&!_r(W)){u(E),t.delete(E.resolved.id);let L=l(E.resolved,D);return t.set(E.resolved.id,L),L}if(D==="menu"){let L=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Pg]:""}});L.appendChild(E.element),Tv(Ng(E.element)),E.menuSlot=L;let Y=K=>{let le=Ng(E.element);if(le.disabled)return;let de=K.target===le||le.contains(K.target);h?.close(!0),de||le.click()};L.addEventListener("click",Y,!0),E.detachMenuSlot=()=>L.removeEventListener("click",Y,!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=D,E},G=(E,D)=>{let W=D.map(L=>L.menuSlot??L.element);for(W.forEach((L,Y)=>{let K=E.children[Y];K!==L&&(K?E.insertBefore(L,K):E.appendChild(L))});E.children.length>W.length;)E.lastElementChild?.remove()},ie=()=>{if(o)return;let E=e.getBindings();if(!E)return;let D=e.getState(),W=D.phase==="streaming",L=k();L&&$(E.footer);let Y=L?T(L,E.footer):!1,K={start:[],end:[]},le=[];for(let de of n){let ge=t.get(de.id);if(!ge)continue;let Me=de.action,fe=Me?Nv(Me.visible,D,!0):!0;if(ge.visible!==fe&&(ge.visible=fe,!fe&&ge.managed&&(ge.menuSlot??ge.element).remove()),!!fe){if(ge=_(ge,I(ge,L,Y)),Me){let _e=Nv(Me.disabled,D,!1)||Me.disableWhenStreaming===!0&&W;y(ge,_e),!_r(Me)&&Me.pressed!==void 0&&ge.button?.setAttribute("aria-pressed",Me.pressed?"true":"false")}ge.mode==="menu"?(A(ge),le.push(ge)):K[de.placement].push(ge)}}if(le.length>0){let de=B();G(de.panel,le),de.setItems(le.map(_e=>_e.menuSlot??_e.element)),de.applyButtonSize();let ge=Number.isFinite(L?.order)?L?.order:Oo.overflow,Me=K.start.findIndex(_e=>_e.resolved.order>ge),fe={resolved:{id:Tk,placement:"start",presentation:"bar",order:ge,sequence:-1,source:"core"},element:de.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};K.start.splice(Me<0?K.start.length:Me,0,fe)}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=Ik(e.collect()),D=new Set(E.map(W=>W.id));for(let[W,L]of t)D.has(W)||(u(L),t.delete(W));for(let W of E){let L=t.get(W.id);if(!L){let de=p(W,"bar");de&&t.set(W.id,de);continue}let Y=L.resolved.action,K=W.action;if(!!Y!=!!K||Y&&K&&_r(Y)!==_r(K)||Y&&K&&_r(Y)&&_r(K)&&Y.render!==K.render){u(L),t.delete(W.id);let de=p(W,L.mode);de&&t.set(W.id,de);continue}L.resolved=W,W.builtIn?(L.managed=W.builtIn.managed===!0||L.mode==="menu",W.builtIn.element&&L.mode==="bar"&&(L.element=W.builtIn.element)):K&&!_r(K)?a(L,K):K&&L.element.toggleAttribute(_g,K.disableWhenStreaming===!0)}n=E,ie()},sync:ie,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,x?.disconnect(),x=null,C=null;for(let E of t.values())u(E);t.clear(),h?.destroy(),h=null,n=[]}}}}var Bk="core:model",_k=700,$v=16,Dk=["--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"],Nk=(e,t)=>{let n=e.ownerDocument?.defaultView;if(!n)return;let o=n.getComputedStyle(e);for(let r of Dk){let s=o.getPropertyValue(r).trim();s&&t.style.setProperty(r,s)}},Uv=()=>{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 jv(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 x=e.getModels(),S=x.map(k=>`${k.id}:${k.label}`).join("|");S!==p&&(p=S,d.replaceChildren(...x.map(k=>{let B=Q("option",{attrs:{value:k.id}});return B.textContent=k.label,B}))),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:C}=Uv();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,x=()=>C?.isOpen===!0,S=(D=!1)=>{x()&&(C?.close(),d.setAttribute("aria-expanded","false"),D&&d.focus())},k=D=>{let W=[...y.values()];if(W.length===0)return;let L=(D%W.length+W.length)%W.length;W[L].focus()},B=D=>{if(x())return;C||(C=hd({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),Nk(d,m),C.open(),d.setAttribute("aria-expanded","true");let L=[...y.keys()].indexOf(r(e.getModels())?.id??"");k(D??(L>=0?L:0))},$=D=>{S(!0),e.onSelect(D)},T=D=>{D.preventDefault(),D.stopPropagation();let W=D.currentTarget.getAttribute("data-persona-model-option");W&&$(W)},I=D=>{let W=Q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":D.id}});if(D.icon){let de=pe(D.icon,$v,"currentColor",1.5);if(de){let ge=M("span","persona-composer-model-option-icon");ge.appendChild(de),W.appendChild(ge)}}let L=M("span","persona-composer-model-option-body"),Y=M("span","persona-composer-model-option-label");if(Y.textContent=D.label,L.appendChild(Y),D.description){let de=M("span","persona-composer-model-option-description");de.textContent=D.description,L.appendChild(de)}W.appendChild(L);let K=M("span","persona-composer-model-option-check");K.setAttribute("aria-hidden","true");let le=pe("check",$v,"currentColor",2);return le&&K.appendChild(le),W.appendChild(K),W.addEventListener("click",T),W},A=()=>{let D=e.getModels(),W=D.map(K=>`${K.id}:${K.label}:${K.icon??""}:${K.description??""}`).join("|");if(W!==h){h=W;for(let K of y.values())K.removeEventListener("click",T);y.clear(),m.replaceChildren(...D.map(K=>{let le=I(K);return y.set(K.id,le),le}))}let L=r(D);for(let[K,le]of y)le.setAttribute("aria-selected",String(K===L?.id));p.textContent=L?.label??"";let Y=e.getSuffix?.()??"";u.textContent=Y,d.setAttribute("aria-label",[t,[L?.label,Y].filter(Boolean).join(" ")].filter(Boolean).join(": "))};A(),o=A;let _=D=>{D.preventDefault(),D.stopPropagation(),x()?S(!0):B()},G=D=>{if(D.key==="ArrowDown"){D.preventDefault(),x()?k(0):B(0);return}D.key==="ArrowUp"&&(D.preventDefault(),x()?k(-1):B(-1))},ie=D=>{let W=[...y.values()],L=W.indexOf(D.target?.closest?.(".persona-composer-model-option"));switch(D.key){case"ArrowDown":D.preventDefault(),k(L+1);return;case"ArrowUp":D.preventDefault(),k(L-1);return;case"Home":D.preventDefault(),k(0);return;case"End":D.preventDefault(),k(W.length-1);return;case"Escape":D.preventDefault(),D.stopPropagation(),S(!0);return;case"Tab":S(!0);return;default:}};d.addEventListener("click",_),d.addEventListener("keydown",G),m.addEventListener("keydown",ie);let{wrapper:ne,chevron:E}=Uv();return ne.append(d,E),{element:ne,destroy:()=>{o===A&&(o=null),d.removeEventListener("click",_),d.removeEventListener("keydown",G),m.removeEventListener("keydown",ie);for(let D of y.values())D.removeEventListener("click",T);y.clear(),C?.destroy(),C=null,m.remove()}}};return{action:{id:Bk,kind:"custom",placement:"end",order:_k,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}var Fg="[data-persona-composer-chip-row]";function yd(e){e.style.display=e.childElementCount>0?"flex":"none"}function $g(e){let t=e.querySelector(Fg);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 Fk=":scope > [data-persona-composer-mode]";function qv(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"),x=pe(p.iconName,12,"currentColor",1.5);x&&C.appendChild(x),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(Fk)),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 S=x.getAttribute("data-persona-composer-mode");S&&m.some(B=>B.id===S)&&!x.hasAttribute("data-persona-chip-exit")?h.set(S,x):x.hasAttribute("data-persona-chip-exit")||l(x)}let C=t.firstChild;for(let x of m){let S=h.get(x.id);S||(S=s(x),r.has(x.id)||(S.setAttribute("data-persona-chip-enter",""),S.addEventListener("animationend",()=>S?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(x.id),S!==C&&t.insertBefore(S,C),C=S.nextSibling}yd(t)},destroy:()=>{o=!0,d(),yd(t)}}}var zv=e=>`core:mode:${e}`;var Ug=e=>Math.min(300+e,499),Vv=e=>`core:mode-group:${e}`;function bd(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function Kv(e,t){return e?.length?e.filter(n=>!bd(n.groupId,t)):[]}var $k=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function Gv(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($k(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 Qv(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Yv(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var Uk=16;function Xv(e){let t=null;return{action:{id:Vv(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,Uk,"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 x=l(C);return r.set(C.id,x),x});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 Jv(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=nd(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 Zv(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=nd(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 eC(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 tC(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 nC(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 oC(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 rC(e){return e.wrapped||e.text.includes(`
23
- `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function sC(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function iC(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 aC(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function jg(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 cC(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var jk=e=>typeof e?.then=="function";function lC(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 dC(e,t,n){let o;try{o=e(jg(t),{signal:n})}catch(r){return{status:"error",error:r}}return jk(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:lC(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):lC(t,o)}var pC=/\s/;function qk(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===""||pC.test(o)}function zk(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 qk(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
25
- `||a==="\uFFFC"||!r&&pC.test(a))return null;s--}return null}function uC(e,t,n){for(let o of n){let r=zk(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function gC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function mC(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 fC(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 ${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=pe(o,hn,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),s.appendChild(a),en({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}var{setLoader:mB,load:Vk}=ht({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var qg=Vk;var{setLoader:yB,load:Kk}=ht({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var hC=Kk;function nl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Q("span",{className:fn("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 yC(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=mC(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??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,x=()=>{if(d)return Promise.resolve(d);if(p)return p;let T=qg().then(I=>(I.setMentionIconRenderer(pe),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:$,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},S=()=>{hC().then(T=>{let I=T.mountInlineComposer({textarea:e.textarea,renderToken:_=>nl(_,{render:t.renderMentionToken}),onMentionRemoved:_=>d?.untrackMention(_)});m=I.input,y=I.destroy;let A=u;A.replaceWith(I.element),u=I.element,C={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"&&S();let k=[],B=new Map;for(let T of n){if(!T.showButton)continue;let I=fC({config:{...t,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},onOpen:()=>{x().then(A=>A?.openMenu(T.trigger))}});k.push(I),B.set(T.trigger,I.button)}let $=(T,I,A)=>{let _=B.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(!gC(T))return;let I=u,A=I.selectionStart??0;uC(I.value,A,n)&&x().then(_=>_?.handleInput())},handleKeydown:T=>{if(d?.isMenuOpen())return d.handleKeydown(T);if(T.key==="Backspace"&&d?.hasMentions()&&!C){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:()=>{qg().catch(()=>{})},onComposerSwap:T=>{h=T,C&&T(C.next,C.prev)},destroy:()=>{d?.destroy(),y?.();for(let T of k)T.wrapper.remove();a&&l.remove()}}}var Cd="16px",wd="transparent",Gk=(()=>{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})(),vC={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:Gk,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"}},CC={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"}},wC={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:kg,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"}},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 yn(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."))?yn(e,o):o}function Vg(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=yn(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 xC(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 SC(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]=SC(s,r):n[o]=r}return n}function Qk(e,t){return t?SC(e,t):e}function xd(e,t={}){let n={palette:vC,semantic:CC,components:wC},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:Qk(n.components,e?.components)};if(t.validate!==!1){let r=xC(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 zg=e=>e.trim()==="0"?"0px":e,bC="--persona-",Yk=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},Xk=.179,tn=(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[bC+s],r!==void 0)break;r!==void 0&&(e[bC+n]=r)}};function Kg(e){let t=Vg(e),n={};for(let[j,De]of Object.entries(t)){let Ne=j.replace(/\./g,"-");n[`--persona-${Ne}`]=De.value}tn(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"],tn(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"]]),tn(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"]}`,tn(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,tn(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"]]),tn(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"],tn(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"],tn(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,De]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ne=n[`--persona-components-history-overlay-${j}`];Ne&&(n[`--persona-history-overlay-${De}`]=Ne)}for(let[j,De]of[["background","bg"],["borderRadius","radius"]]){let Ne=n[`--persona-components-history-menu-${j}`];Ne&&(n[`--persona-history-menu-${De}`]=Ne)}let m=e.components?.history?.motion;if(m){let j=we=>{if(we===void 0)return;let ke=String(we).trim();return/^\d+(\.\d+)?$/.test(ke)?`${ke}ms`:ke},De=j(m.enterDurationMs);De!==void 0&&(n["--persona-history-enter-ms"]=De);let Ne=j(m.exitDurationMs);Ne!==void 0&&(n["--persona-history-exit-ms"]=Ne),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 De=n[`--persona-components-history-confirm-${j}`];De&&(n[`--persona-history-confirm-${j}`]=De)}for(let[j,De]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ne=n[`--persona-components-tooltip-${j}`];Ne&&(n[`--persona-tooltip-${De}`]=Ne)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[j,De]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ne=n[`--persona-components-messageActions-${j}`];Ne&&(n[`--persona-message-action-${De}`]=Ne)}tn(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"],x=(!h||h==="transparent"||h==="none")&&(!C||C==="none"),S=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=x&&S==="1.5rem"?"1.5rem 0":S,tn(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"],["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"]]),tn(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 B=n["--persona-components-markdown-heading-h1-fontWeight"];B&&(n["--persona-md-h1-weight"]=B);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 I=n["--persona-components-markdown-prose-fontFamily"];I&&I!=="inherit"&&(n["--persona-md-prose-font-family"]=I),tn(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"]]),tn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),tn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),tn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),tn(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"],tn(n,[["message-border","components-message-border","border"]]),tn(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 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 ie=A?.toggleGroup;ie&&(ie.gap&&(n["--persona-toggle-group-gap"]=ie.gap),ie.borderRadius&&(n["--persona-toggle-group-radius"]=ie.borderRadius));let ne=A?.artifact;if(ne?.toolbar){let j=ne.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"]=zg(j.toggleGroupGap)),j.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=j.toggleBorderRadius),j.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=zg(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"]=yn(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"]=zg(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(ne?.tab){let j=ne.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(ne?.pane){let j=ne.pane;if(j.toolbarBackground){let De=yn(e,j.toolbarBackground)??j.toolbarBackground;n["--persona-artifact-toolbar-bg"]=De}}if(ne?.card){let j=ne.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(ne?.inline){let j=ne.inline;j.background&&(n["--persona-artifact-inline-bg"]=yn(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"]=yn(e,j.chromeBackground)??j.chromeBackground),j.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=yn(e,j.chromeBorder)??j.chromeBorder),j.titleColor&&(n["--persona-artifact-inline-title-color"]=yn(e,j.titleColor)??j.titleColor),j.mutedColor&&(n["--persona-artifact-inline-muted-color"]=yn(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"]=yn(e,E.background)??E.background));let D=n["--persona-surface"],W=n["--persona-container"],L=n["--persona-palette-colors-gray-100"]??"#f3f4f6",Y=n["--persona-palette-colors-gray-200"]??"#e5e7eb",K=n["--persona-palette-colors-gray-300"]??"#d1d5db",le=!W||W===D,de=Yk(D??n["--persona-background"]),ge=le&&de!==void 0&&de<Xk,Me=ge?"rgba(255, 255, 255, 0.08)":L,fe=ge?"rgba(255, 255, 255, 0.12)":Y,_e=ge?"rgba(255, 255, 255, 0.16)":K,it=le?Me:W,be=le?fe:W;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??it,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??be,le&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??_e),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??it,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??it,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??it,n}var Jk={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 Zk={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"}}},eL={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},AC=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",tL=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Sd()},Gg=e=>tL(e),nL=e=>xd(e),oL=e=>{let t=Ti(eL,e??{})??{};return xd({...t,palette:{...t.palette,colors:{...Zk.colors,...t.palette?.colors}}},{validate:!1})},Hs=e=>{let t=Gg(e),n=AC(e?.theme),o=AC(e?.darkTheme);return t==="dark"?oL(Ti(n??{},o??{})):nL(n)},rL=e=>Kg(e),ki=(e,t)=>{let n=Hs(t),o=rL(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Gg(t))},ol=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 ox,Check as rx,Copy as sx}from"lucide";var Dr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Ad="24px",Qg=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",rl=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},MC=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var EC=null;var Yg=()=>{if(EC!==null)return EC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},sL="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)},iL=e=>sL.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),TC=(e,t)=>{let n=Ed(e);if(!n)return"";let o=Yg(),r=iL(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=>TC(e,!1),sl=e=>TC(e,!0),aL=(e,t)=>t.key?.toLowerCase()===e.key&&(Yg()?t.metaKey:t.ctrlKey)===e.mod&&!(Yg()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,lL=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},PC=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(aL(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&lL(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",sl(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 cL}from"idiomorph";var Pd=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;cL.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 kC=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Xg={index:-1,draft:""};function LC(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 IC(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 RC(){return new Map}function HC(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function WC(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function OC(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function BC(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 _C(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Bo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ws(e,t){return Bo(e)-e.scrollTop<=t}function DC(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 NC(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 FC(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Jg(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 $C(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var il={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},dL=["pre","code","a","script","style"],kd=e=>({type:e?.type??il.type,placeholder:e?.placeholder??il.placeholder,speed:e?.speed??il.speed,duration:e?.duration??il.duration,buffer:e?.buffer??il.buffer}),jC=[{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"}],al=new Map;for(let e of jC)al.set(e.name,e);var qC=["wipe","glyph-cycle"],Ld=e=>{al.set(e.name,e)},pL=e=>{jC.some(t=>t.name===e)||al.delete(e)},uL=()=>Array.from(al.keys()),ll=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:al.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},gL=(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},mL=(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},Zg=/\s/,fL=(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},hL=(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(Zg.test(s[l])){let d=l;for(;d<s.length&&Zg.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&&!Zg.test(s[p]);)d.appendChild(gL(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,e)},yL=(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(mL(o,d,t,n.value)),n.value+=1));r.replaceChild(a,e)},cl=(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??dL).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)fL(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=t==="char"?hL:yL;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},dl=(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},UC=new WeakMap,bL=(e,t)=>{if(!e.styles)return;let n=UC.get(t);if(n||(n=new Set,UC.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)},em=new WeakMap,vL=(e,t)=>{if(!e.onAttach)return;let n=em.get(t);if(n||(n=new Map,em.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},zC=e=>{let t=em.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},pl=(e,t)=>{bL(e,t),vL(e,t)};var{setLoader:KB,load:CL}=ht({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var VC=CL;function tm(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 ul=0,Nr=null;function nm(e=document){if(ul++,ul===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,ul=Math.max(0,ul-1),ul===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 gl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Et=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??gl.side,width:t?.width??gl.width,animate:t?.animate??gl.animate,reveal:t?.reveal??gl.reveal,maxHeight:t?.maxHeight??gl.maxHeight}};import{ArrowRight as wL}from"lucide";var om=e=>e==="followUp"?"follow-up":e,rm=(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"}},xL=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'}},KC=new WeakSet,SL=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,AL=e=>{SL()||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"})})},sm=e=>{var $,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,C=o==="followUp",x=t.behavior,S=()=>{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(C&&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 G=m();if(x==="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)},k=()=>{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=x,s==="chip"&&(p?.fontFamily&&(A.style.fontFamily=xL(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 _=M("span","persona-suggestion__copy");if(_.appendChild(Q("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&_.appendChild(Q("span",{className:"persona-suggestion__description",text:t.description})),A.appendChild(_),s!=="chip"){let G=Ht(wL,16,"currentColor",1.8);G&&(G.classList.add("persona-suggestion__arrow"),A.appendChild(G))}return A.addEventListener("click",S),A},B=null;for(let A of d)if(A.renderSuggestion&&(B=A.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:k,select:S}),B))break;return B??(B=k()),($=B.dataset).suggestionId||($.suggestionId=t.id),(T=B.dataset).behavior||(T.behavior=x),(I=B.dataset).emphasis||(I.emphasis=t.emphasis),B instanceof HTMLButtonElement||B.setAttribute("aria-disabled",a?"true":"false"),B},ml=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,x=y>=u-h,S=m?!x:!C,k=m?!C:!x;e.toggleAttribute("data-scroll-left",S),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,C,x)=>{e.replaceChildren(),t.length=0,n.length=0;let S=x?.source??"config",k=x?.surface??(S==="config"?"starter":"followUp"),B=k==="followUp",$=x?.variant??"chip",T=x?.behavior??"send",I=x?.overflow??"wrap",A=x?.config??{},_=x?.plugins??[],G=typeof x?.maxItems=="number"?Math.max(0,Math.floor(x.maxItems)):void 0,ie=B?"followUps":"starters";!KC.has(A)&&A.debug===!0&&$!=="chip"&&A.suggestions?.[ie]?.overflow!==void 0&&(KC.add(A),console.info(`[persona] suggestions.${ie}.overflow applies to the "chip" variant only; the "${$}" variant manages its own stacking.`));let ne=K=>K.map(rm).filter(le=>le!==null).map(le=>({...le,behavior:le.behavior??T})),E=ne(u??[]);_.forEach(K=>{K.transformSuggestions&&(E=ne(K.transformSuggestions({suggestions:E.map(le=>({...le})),surface:k,source:S,config:A})))});let D=G===void 0?E:E.slice(0,G);if(!D.length){e.hidden=!0,o=null,s();return}if(!B&&(h??m.getMessages()).some(le=>le.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=om(k),e.dataset.variant=$,e.dataset.overflow=I;let W=document.createDocumentFragment(),L=m.isStreaming();D.forEach((K,le)=>{let de=sm({item:K,index:le,surface:k,source:S,variant:$,streaming:L,config:A,plugins:_,chipsConfig:C,session:m,getTextarea:()=>y,eventTarget:e,submitPrompt:x?.submitPrompt});W.appendChild(de),n.push(de),[...de instanceof HTMLButtonElement?[de]:[],...Array.from(de.querySelectorAll("button"))].forEach(Me=>{t.includes(Me)||(Me.disabled=L,t.push(Me))})}),e.appendChild(W),a(),l();let Y=JSON.stringify({normalized:D,surface:k,variant:$,source:S});Y!==o&&(o=Y,AL(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:D.map(K=>({...K})),surface:k,source:S,variant:$},bubbles:!0,composed:!0})),B&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:D.map(K=>K.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 ML="persona-header-control",EL="persona-header-control--glyph",TL="persona-header-control--sparse",PL=20,kL={x:[1.4,1.05]},GC="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",LL="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Hd=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=kL[t]??[1,1.5],l=!o;e.classList.toggle(EL,l),e.classList.toggle(TL,l&&s!==1);let d=parseFloat(o??"")||PL,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)},Os=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=GC,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:y,borderRadius:h,paddingX:C,paddingY:x,hidden:S,extraClassName:k,attrs:B}=e,$=M("div",a),T=!!(m||y),I=Q("button",{className:fn(ML,"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,...B},style:{width:l,height:l,minWidth:l,minHeight:l,display:S?"none":void 0,color:p||bn.actionIconColor,backgroundColor:u,border:T?`${m||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:h,paddingLeft:C,paddingRight:C,paddingTop:x,paddingBottom:x}});return r?Hd(I,r,{iconSize:d,iconText:s}):s&&(I.textContent=s),$.appendChild(I),en({anchor:I,trigger:$,text:()=>I.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:I,wrapper:$}},Li=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=GC,buttonSize:r,iconSize:s}=t,a=e?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=Os({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=LL,buttonSize:o,iconSize:r}=t,a=(e?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=Os({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 bn={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)"},im={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)"},IL={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=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:bn.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 I=parseFloat(s)||24,A=pe(d,I*.6,"currentColor",1);A?p.replaceChildren(A):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let I=M("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=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:bn.titleColor,...im}}),y=Q("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:bn.subtitleColor,...IL}});u.append(m,y),l?o.append(u):o.append(p,u);let h=r.clearChat??{},C=h.enabled??!0,x=h.placement??"inline",S=null,k=null;if(C){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"});S=A.button,k=A.wrapper,x==="top-right"&&(k.style.right="48px"),x==="inline"&&o.appendChild(k)}let B=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:$,wrapper:T}=Li(t,{showClose:n,wrapperClassName:B});return a!=="top-right"&&o.appendChild(T),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:y,closeButton:$,closeButtonWrapper:T,clearChatButton:S,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=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(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 C of t){if(C.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",C.id),C.destructive&&x.setAttribute("data-destructive",""),C.icon){let k=pe(C.icon,16,"currentColor",1.5);k&&x.appendChild(k)}let S=document.createElement("span");S.textContent=C.label,x.appendChild(S),x.addEventListener("click",k=>{k.stopPropagation(),m(),n(C.id)}),l.appendChild(x)}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 x=S=>{!l.contains(S.target)&&!o.contains(S.target)&&m()};document.addEventListener("click",x,!0),d=()=>document.removeEventListener("click",x,!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 Vn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=e,p=M("button",fn(!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 QC(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 Wd(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=Vn({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 RL(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,x=M("div","persona-split-btn"+(y?" "+y:"")),S={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},k=r&&n?Vn({...S,icon:n,size:o??14}):QC({...S,icon:n,iconSize:o??14}),B=Vn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(C?" "+C:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});x.append(k,B);let $=null,T=()=>{if($)return $;let I=(typeof p=="function"?p():p)??void 0;return $=Hi({items:s,onSelect:a,anchor:x,position:d,portal:I,onOpenChange:A=>{B.setAttribute("aria-expanded",A?"true":"false")}}),I||x.appendChild($.element),$};return x.isConnected?T():requestAnimationFrame(()=>{$||T()}),B.addEventListener("click",I=>{I.stopPropagation(),T().toggle()}),{element:x,primaryButton:k,chevronButton:B,openMenu:()=>T().show(),closeMenu:()=>$?.hide(),toggleMenu:()=>T().toggle(),destroy:()=>{$?.destroy(),x.remove()}}}function am(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=Hi({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 x=!y.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",x?"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 YC=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 HL(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=Os({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=sl(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 XC=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=bn.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=am({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:I=>{let A=G=>{G===!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=bn.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=bn.titleColor,Object.assign(u.style,im),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 C=M("div","persona-flex persona-items-center persona-gap-1");d||HL(C,r?.trailingActions,r?.onAction??s);let x=a.clearChat??{},S=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});S=I.button,k=I.wrapper,T==="top-right"?k.style.right="48px":C.appendChild(k)}C.appendChild(h),l.appendChild(C);let B=M("div");B.style.display="none";let $=M("span");return $.style.display="none",{header:l,iconHolder:B,headerTitle:u,headerSubtitle:$,closeButton:y,closeButtonWrapper:h,clearChatButton:S,clearChatButtonWrapper:k}},lm={default:YC,minimal:XC},JC=e=>lm[e]??lm.default,fl=(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=JC(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=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=fd(),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}=pd(t);a();let l=ud(t),d=Pi(t),p=gd(t),u=md(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",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:C,setSendButtonMode:l.setMode}};import{ChevronUp as WL,MessageSquare as OL}from"lucide";var ZC=()=>{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=Ht(OL,16,"currentColor",1.5);n&&t.appendChild(n);let o=M("span","persona-pill-peek__text"),r=M("span","persona-pill-peek__caret"),s=Ht(WL,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=Q("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=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",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=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 BL=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}},_L=(e,t)=>{if(!e)return null;let n=BL(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},DL=(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},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(":"))},dm=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(":"))},pm=320,rw=320,FL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),$L=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),UL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),jL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),qL=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},zL=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(nl(o.ref,{readonly:!0,render:t}))}return n},ew="\uE000",tw="\uE001",VL=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${ew}${r}:${y}${tw}`,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(zL(t,o));return}e.innerHTML=l;let p=new RegExp(`${ew}${r}:(\\d+)${tw}`),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 x=t[Number(C[1])],S=h.splitText(C.index);S.data=S.data.slice(C[0].length),x?.kind==="mention"&&S.parentNode?.insertBefore(nl(x.ref,{readonly:!0,render:o}),S),h=S}}},KL=(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=`${pm}px`,p.style.maxHeight=`${rw}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}},GL=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(!dm(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=`${pm}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},QL=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(!dm(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=`${pm}px`,r.style.maxHeight=`${rw}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}},YL=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(!dm(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}},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},sw=(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()},XL=(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},nw=(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},hl=(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},ow={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"}},JL=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=ow[n??"bubble"]??ow.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:",ZL=e=>`${Bd}${e}`,iw=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),aw=(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=iw(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",x={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],S={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[C],k=M("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${x} ${S} ${y==="hover"?"persona-message-actions-hover":""}`);k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id);let B=($,T,I)=>{let A=Vn({icon:$,label:T,size:14,className:"persona-message-action-btn",chromeless:!0});return A.setAttribute("data-action",I),A};r&&k.appendChild(B("copy","Copy message","copy")),l&&k.appendChild(B("volume-2","Read aloud","read-aloud")),s&&k.appendChild(B("thumbs-up","Upvote","upvote")),a&&k.appendChild(B("thumbs-down","Downvote","downvote")),d&&k.appendChild(B("refresh-cw","Regenerate response","regenerate")),p&&k.appendChild(B("pencil","Edit message","edit")),u&&k.appendChild(B("quote","Quote message","quote"));for(let $ of m)k.appendChild(B($.iconName??"ellipsis",$.label,ZL($.id)));return k},yl=(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=hl(e.role,l),x=M("div",C.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let S=s?.widgetConfig?.theme?.components?.message;JL(x,e.role,l,e.role==="user"?S?.user:S?.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=FL(e),B=e.content?.trim()??"",T=k.length>0&&B===wi,I=kd(s?.widgetConfig?.features?.streamAnimation),A=s?.widgetConfig?.features?.streamAnimation?.plugins,_=e.role==="assistant"&&I.type!=="none"?ll(I.type,A):null,G=e.role==="assistant"&&_?.isAnimating?.(e)===!0,ie=e.role==="assistant"&&_!==null&&(!!e.streaming||G);ie&&_?.bubbleClass&&x.classList.add(_.bubbleClass);let ne=document.createElement("div");ne.classList.add("persona-message-content"),e.streaming&&ne.classList.add("persona-content-streaming"),ie&&_&&(_.containerClass&&ne.classList.add(_.containerClass),ne.style.setProperty("--persona-stream-step",`${I.speed}ms`),ne.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let E=ie?Id(e.content??"",I.buffer,_,e,!!e.streaming):e.content??"",D=()=>{let be=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent});return ie&&_?.wrap==="char"?cl(be,"char",e.id,{skipTags:_.skipTags}):ie&&_?.wrap==="word"?cl(be,"word",e.id,{skipTags:_.skipTags}):be},W=null;if(T?(W=document.createElement("div"),W.innerHTML=D(),W.style.display="none",ne.appendChild(W)):e.contentSegments?.length?VL(ne,e.contentSegments,be=>t({text:be,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):ne.innerHTML=D(),ie&&_?.useCaret&&!T&&B){let be=Rd(),j=ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),De=j[j.length-1];if(De?.parentNode)De.parentNode.insertBefore(be,De.nextSibling);else{let Ne=ne.lastElementChild;Ne?Ne.appendChild(be):ne.appendChild(be)}}if(m&&h==="inline"&&e.createdAt){let be=nw(e,p,"span");be.classList.add("persona-timestamp-inline");let j=ne.lastElementChild;j?j.appendChild(be):ne.appendChild(be)}if(k.length>0){let be=KL(k,!T&&!!B,()=>{T&&W&&(W.style.display="")});be?x.appendChild(be):T&&W&&(W.style.display="")}let L=$L(e);if(L.length>0){let be=GL(L);be&&x.appendChild(be)}let Y=UL(e);if(Y.length>0){let be=QL(Y);be&&x.appendChild(be)}let K=jL(e);if(K.length>0){let be=YL(K);be&&x.appendChild(be)}let le=e.contentSegments?.length?null:qL(e.contextMentions);if(le&&x.appendChild(le),x.appendChild(ne),m&&h==="below"&&e.createdAt){let be=nw(e,p);be.classList.add("persona-mt-1"),x.appendChild(be)}let de=e.role==="assistant"?_L(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let be=!!(E&&E.trim()),j=I.placeholder==="skeleton",De=j&&I.buffer==="line"&&be;if(be)De&&x.appendChild(dl());else if(j)x.appendChild(dl());else{let Ne=sw("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);Ne&&x.appendChild(Ne)}}de&&e.stopReason&&!e.streaming&&(B||(ne.style.display="none"),x.appendChild(DL(e.stopReason,de)));let ge=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1,Me=s?.actionEligibility,fe=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Me?.canEdit===!0||o?.showQuote===!0&&Me?.canQuote===!0||iw(o,"user").length>0);if((ge||fe)&&o){let be=aw(e,fe?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Me);x.appendChild(be)}if(!u||e.role==="system")return x;let _e=M("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),it=XL(d,e.role);return y==="right"||y==="left"&&e.role==="user"?_e.append(x,it):_e.append(it,x),_e},e0=(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}):yl(e,t,n,o,r,s)};var t0=40,n0=(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,t0);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},lw=(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}},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==="",n0(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")},o0="data-persona-welcome-plugin",cw="data-persona-welcome-overlay",_d="persona-welcome-overlay-active",um=new WeakMap,gm=(e,t,n)=>{n.setAttribute(o0,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(cw,""),e.classList.contains(_d)||(um.set(e,e.scrollTop),e.classList.add(_d),e.scrollTop=0)},mm=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(cw),e.classList.contains(_d)&&(e.classList.remove(_d),e.scrollTop=um.get(e)??e.scrollTop,um.delete(e))},dw=()=>{let e=Q("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=Q("div",{className:hl("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},pw=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,uw=(e,t)=>{if(pw()||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 x=e.previousElementSibling,S=e.nextElementSibling,B=o.getBoundingClientRect().top+(parseFloat(C.borderTopWidth)||0)+(parseFloat(C.paddingTop)||0)-o.scrollTop;s=Math.max(0,x?n.top-x.getBoundingClientRect().bottom-r:n.top-B),a=Math.max(0,S?S.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},gw=(e,t,n)=>{if(t<=1||pw()||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 r0="Hello \u{1F44B}",s0="I can answer questions and help you get things done here.",mw=new WeakSet,vn=(e,t)=>!!e&&e[t]!==void 0,i0=(e,t)=>{!e||e.debug!==!0||!t.length||mw.has(e)||(mw.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},_o=e=>{let t=e?.welcome,n=e?.copy,o=vn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":vn(t,"dismiss")?t.dismiss:"never",s=[];vn(t,"title")&&vn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),vn(t,"subtitle")&&vn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),vn(t,"variant")&&vn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&vn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&vn(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=rl(t?.anchorComposerTop)!==null;return vn(t,"anchorComposerTop")&&!l&&s.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),a!=="center"&&(vn(t,"anchorComposerTop")||vn(t,"composerGap"))&&s.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),i0(e,s),{title:vn(t,"title")?t.title:n?.welcomeTitle??r0,kicker:t?.kicker??"",subtitle:vn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??s0,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}},fw=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Bs=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var hw="16px",hm="10px",ym="14px",yw=e=>{let t=e?.launcher?.enabled??!0,n=Et(e);if(Fr(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??rn);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??rn),{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&&zn[r.position]?zn[r.position]:zn["bottom-right"],a=M("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??rn);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}},bm=e=>{let t=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":om(e)}});return t.hidden=!0,t},bw=(e,t)=>{let n=bm("starter"),o=lw(e,n,{flatShadow:Et(e)}),r=_o(e);Dd(o,r),Bi(t,o.host,Bs(r,e?.initialMessages));let s=dw();return Nd(s,r.message,e),{welcome:o,greetingHost:s}},a0=(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}=Li(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:hw,iconSize:hm});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:hw,iconSize:ym});a=_.button,l=_.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}=bw(e,p),{host:y,title:h,subtitle:C}=u,x=u.starterSuggestions,S=M("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),k=bm("followUp"),B=Dr(e,!0);B&&(S.style.maxWidth=B,S.style.marginLeft="auto",S.style.marginRight="auto",S.style.width="100%"),p.append(y,m,S,k);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=Od({config:e}),{root:I,textNode:A}=ZC();return n.append(d,r,p,$),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:S,starterSuggestions:x,transcriptSuggestions:k,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:I,peekTextNode:A}},vw=(e,t=!0)=>{if(Fr(e))return a0(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?fl(e,o,{showClose:t}):$r({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}=bw(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=bm("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,C);let S=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 B=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 k||(S.footer.style.display="none"),n.append(S.footer),n.append(B),{container:n,body:a,messagesWrapper:h,starterSuggestions:y,transcriptSuggestions:C,composerOverlay:B,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.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:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode}};var vm=(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(fo(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(d){let p=[];a&&p.push(fo(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=Na(),a=ks();this.activeAssistantMessageId=null;let l=n?.contentParts&&Ka(n.contentParts)?xi:"",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=dv({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=Eg(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=pv(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=ks();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=Eg(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!==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:_b(),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 k=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));return k||this.callbacks.onError?.(x instanceof Error?x:new Error(String(x))),this.markWebMcpToolComplete(d,Tg(k?"Aborted by cancel()":sk(x)),y),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,Tg("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===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,Tg("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=sr(this.config.features?.artifacts,t),r=Da(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=Da(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=Cv().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=>Eg(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=ks(),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=Sg(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ya(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Sg(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&&wv(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&&wv(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 ik,FileCode as ak,FileSpreadsheet as lk,FileText as Pg,X as ck}from"lucide";var dk={add:e=>Qb(e)},pk=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,sd={allowedTypes:ar,maxFileSize:10*1024*1024,maxFiles:4};function uk(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function gk(e){return e==="application/pdf"?Pg:e.startsWith("text/")?Pg:e.includes("word")?Pg:e.includes("excel")||e.includes("spreadsheet")?lk:e==="application/json"?ak:ik}var Ei=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??sd.allowedTypes,maxFileSize:t.maxFileSize??sd.maxFileSize,maxFiles:t.maxFiles??sd.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:dk}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:sd.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=Yb(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:uk(),file:o,previewUrl:ed(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=pk(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=ed(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=gk(t.file.type),y=Ht(m,20,"var(--persona-muted, #6b7280)",1.5);y&&u.appendChild(y);let h=M("span");h.textContent=Xb(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=Ht(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 xv=(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 Sv(){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=>{xv(e.mentionRefs,u)||(e.mentionRefs=[...u],p())},setSelectedModelId:u=>{e.selectedModelId!==u&&(e.selectedModelId=u,p())},setActiveModeIds:u=>{xv(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 Ln=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},Av=(e,t)=>{let n=M("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function Mv(e,t={}){let n=Ln(e,"[data-persona-composer-form]"),o=Ln(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:Ln(e,"[data-persona-composer-header]"),body:Ln(e,"[data-persona-composer-body]"),actionsStart:Ln(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Ln(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Ln(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Ln(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Ln(e,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=Av("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,k,B,$,T)=>{if(k)return k;s.add(x);let I=Av(B,$);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=[],C=(x,k)=>x.target===k.target&&x.type===k.type&&x.handler===k.handler,S=Ln(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:Ln(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Ln(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Ln(e,"[data-persona-composer-submit]")??void 0,micButton:Ln(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(x,k,B,$)=>{x.addEventListener(k,B,$),h.push({target:x,type:k,handler:B,options:$})},removeListener:(x,k,B,$)=>{x.removeEventListener(k,B,$),h=h.filter(T=>!C(T,{target:x,type:k,handler:B}))},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"},rn=1e5,Ti=rn+1;var fk=8,hk=8,kg=10,Ev=200,Tv=300,Pv=0,ad=e=>Math.max(0,e);function kv(e){e.delayMs!==void 0&&(Ev=ad(e.delayMs)),e.skipDelayMs!==void 0&&(Tv=ad(e.skipDelayMs))}var yk=()=>Date.now()<Pv,bk=e=>{Pv=e>0?Date.now()+e:0},id=new WeakMap,Ig="data-persona-tooltip-suppressed",vk=e=>typeof e.closest=="function"&&e.closest(`[${Ig}]`)!==null;function Lv(e){id.get(e)?.hide()}var Iv=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Ck=e=>{let t=e.getRootNode?.();return Iv(t)?t:e.ownerDocument.body},Lg=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),wk=[...["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 en(e){id.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:a=fk,viewportPadding:l=hk}=e,d=()=>t.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,y=null,h=null,C,S=!1,x=!1,k=!1,B=()=>(typeof o=="function"?o():o).trim(),$=()=>(typeof r=="function"?r():r??"").trim(),T=()=>ad(e.delayMs??Ev),I=()=>ad(e.skipDelayMs??Tv),A=()=>{C!==void 0&&(p().clearTimeout(C),C=void 0)},D=()=>{A();let ge=u!==null;h?.(),h=null,u?.remove(),u=null,m=null,y=null,ge&&bk(I())},G=()=>{if(!u)return;let ge=d(),Ae=p(),fe=t.getBoundingClientRect(),_e=u.getBoundingClientRect(),it=ge.documentElement.clientWidth||Ae.innerWidth,be=ge.documentElement.clientHeight||Ae.innerHeight,j=it-l-_e.width,De=fe.left+fe.width/2-_e.width/2,Ne=Lg(De,l,j),xe=fe.top-l,ke=be-l-fe.bottom,he=_e.height+a,dt=xe>=he||xe>=ke?"top":"bottom",Ie=dt==="top"?fe.top-a-_e.height:fe.bottom+a,Ut=be-l-_e.height,at=Lg(Ie,l,Ut),nn=fe.left+fe.width/2,pn=Math.max(kg,_e.width-kg),Wt=Lg(nn-Ne,kg,pn);u.dataset.placement=dt,u.style.left=`${Ne}px`,u.style.top=`${at}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${Wt}px`)},se=()=>{if(k||!s||u||!t.isConnected||vk(t))return;let ge=B(),Ae=Ck(t);if(!ge||!Ae)return;let fe=d(),_e=p();u=fe.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Ti);let it=_e.getComputedStyle?.(t);if(it){for(let he of wk){let dt=it.getPropertyValue(he).trim();dt&&u.style.setProperty(he,dt)}it.fontFamily&&(u.style.fontFamily=it.fontFamily)}m=fe.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ge,u.appendChild(m);let be=$();be&&(y=fe.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=be,u.appendChild(y));let j=fe.createElement("span");j.className="persona-control-tooltip__arrow",u.appendChild(j),Ae.appendChild(u),G(),u.dataset.state="open";let De=()=>{if(!t.isConnected){D();return}m&&(m.textContent=B()),y&&(y.textContent=$()),G()};_e.addEventListener("scroll",De,!0),_e.addEventListener("resize",De);let Ne=t.getRootNode(),xe=Iv(Ne)?Ne:fe.documentElement,ke=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||D()});ke?.observe(xe,{childList:!0,subtree:!0}),h=()=>{_e.removeEventListener("scroll",De,!0),_e.removeEventListener("resize",De),ke?.disconnect()}},ne=ge=>{if(!(k||u)){if(A(),ge||T()<=0||yk()){se();return}C=p().setTimeout(()=>{C=void 0,se()},T())}},E=()=>{S||x?ne(x):D()},_=()=>{let ge=p();(!ge.matchMedia||!ge.matchMedia("(hover: none)").matches)&&(S=!0,E())},W=()=>{S=!1,E()},L=()=>{try{x=t.matches(":focus-visible")}catch{x=!0}E()},Y=()=>{x=!1,E()},K=()=>{S=!1,x=!1,D()},le=ge=>{ge.key==="Escape"&&K()};n.addEventListener("mouseenter",_),n.addEventListener("mouseleave",W),t.addEventListener("focus",L),t.addEventListener("blur",Y),t.addEventListener("keydown",le),t.addEventListener("click",K);let de={get isOpen(){return u!==null},show:se,hide:D,reposition:G,destroy:()=>{k||(k=!0,D(),n.removeEventListener("mouseenter",_),n.removeEventListener("mouseleave",W),t.removeEventListener("focus",L),t.removeEventListener("blur",Y),t.removeEventListener("keydown",le),t.removeEventListener("click",K),id.delete(t))}};return id.set(t,de),de}var Rv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Pi(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];Rv(s)&&Rv(r)?n[o]=Pi(s,r):n[o]=r}return n}var oo="min(440px, calc(100vw - 24px))",Rg="440px",Hg="How can I help...",xk={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)"},st={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:xk,copy:{inputPlaceholder:Hg,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 Hv(e,t){if(!(!e&&!t))return e?t?Pi(e,t):e:t}function el(e){return e?{...st,...e,theme:Hv(st.theme,e.theme),darkTheme:Hv(st.darkTheme,e.darkTheme),launcher:{...st.launcher,...e.launcher,dock:{...st.launcher?.dock,...e.launcher?.dock},clearChat:{...st.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...st.tooltip,...e.tooltip},copy:{...st.copy,...e.copy},sendButton:{...st.sendButton,...e.sendButton},statusIndicator:{...st.statusIndicator,...e.statusIndicator},voiceRecognition:{...st.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=st.features?.artifacts,n=e.features?.artifacts,o=st.features?.scrollToBottom,r=e.features?.scrollToBottom,s=st.features?.scrollBehavior,a=e.features?.scrollBehavior,l=st.features?.streamAnimation,d=e.features?.streamAnimation,p=st.features?.askUserQuestion,u=e.features?.askUserQuestion,m=st.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},k=p===void 0&&u===void 0?void 0:{...p,...u,styles:{...p?.styles,...u?.styles}},B=m===void 0&&y===void 0?void 0:{...m,...y,copy:{...m?.copy,...y?.copy}};return{...st.features,...e.features,...C!==void 0?{scrollToBottom:C}:{},...S!==void 0?{scrollBehavior:S}:{},...h!==void 0?{artifacts:h}:{},...x!==void 0?{streamAnimation:x}:{},...k!==void 0?{askUserQuestion:k}:{},...B!==void 0?{history:B}:{}}})(),suggestionChips:e.suggestionChips??st.suggestionChips,suggestionChipsConfig:{...st.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...st.layout,...e.layout,header:{...st.layout?.header,...e.layout?.header},messages:{...st.layout?.messages,...e.layout?.messages,avatar:{...st.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...st.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...st.layout?.slots,...e.layout?.slots}},markdown:{...st.markdown,...e.markdown,options:{...st.markdown?.options,...e.markdown?.options}},messageActions:{...st.messageActions,...e.messageActions}}:st}function Wg(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 ld(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function Wv(e,t){e.style.maxHeight=`${t*Wg(e)}px`,e.style.overflowY="auto"}function tl(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 Ov(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Bv(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||!Ov(t)}function Sk(e){return(e.submitKey??"enter")!=="enter"||Ov(e)?"enter":"send"}function cd(e,t){e.setAttribute("enterkeyhint",Sk(t))}function dd(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 Og(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",yo="persona-composer-control--glyph",_g=40,yn=24,pd=(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)}},ud=(e,t)=>{let n=M("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Hg,n.dir="auto",cd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:tl(n)}),dd(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=ld(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*Wg(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}},Mk="[data-persona-glyph-stack]",Dg=(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},gd=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:hn("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&&!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}}),k=null,B=null,$=null;if(n){let A=parseFloat(t.iconSize??"")||Math.round(y*.5),D=t.iconStrokeWidth??2,G=C?.trim()||"currentColor";r&&(k=pe(r,A,G,D)),B=pe(s,A,G,D),k&&B?($=Dg(k,B),x.appendChild($)):k?x.appendChild(k):(x.textContent=o,B=null)}else x.textContent=d;x.setAttribute("aria-label",a),S.appendChild(x),en({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 D=A==="stop"?l:a;x.setAttribute("aria-label",D),x.setAttribute("data-persona-send-mode",A),n?(x.querySelector(Mk)??$)?.setAttribute("data-mode",A):x.textContent=A==="stop"?p:d},glyphStack:$}},ki=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??"")||yn,u=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,y=M("div","persona-send-button-wrapper"),h=Q("button",{className:hn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",jn,!d&&yo),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",k=t.showTooltip??!1;return en({anchor:h,trigger:y,text:()=>h.getAttribute("aria-label")??x,enabled:k}),{button:h,wrapper:y}},md=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??ar).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 ${jn} ${yo}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=pe(r,yn,"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 en({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},fd=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},hd=()=>Q("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function Ek(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function yd(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??Ek(t),y=!1,h=null,C=()=>{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 B=n.getBoundingClientRect(),$=l?.()??null,T=$!=null?k.top+$:k.top,I=o==="top-start"||o==="top-end"?T-r-B.height:k.bottom+r,D=o==="bottom-end"||o==="top-end"?k.right-B.width:k.left,G=a?.()??null;if(G!=null){let se=Math.max(k.left,k.right-B.width);D=Math.min(Math.max(k.left+G,k.left),se)}n.style.top=`${I}px`,n.style.left=`${D}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 k=(t.ownerDocument??document).defaultView??window,B=t.ownerDocument??document,$=()=>{if(!t.isConnected){S(),u?.("anchor-removed");return}C()},T=A=>{let D=typeof A.composedPath=="function"?A.composedPath():[];D.includes(n)||D.includes(t)||(S(),u?.("outside"))},I=k.setTimeout(()=>{B.addEventListener("pointerdown",T,!0)},0);k.addEventListener("scroll",$,!0),k.addEventListener("resize",$),h=()=>{k.clearTimeout(I),B.removeEventListener("pointerdown",T,!0),k.removeEventListener("scroll",$,!0),k.removeEventListener("resize",$)},p?.()};return{get isOpen(){return y},open:x,close:S,toggle:()=>y?S():x(),reposition:C,destroy:S}}var Tk='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',Pk=["--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"],Ng="data-persona-menu-focus",kk=new Set(["ArrowDown","ArrowUp","Home","End"]);function _v(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(Tk)??e}var Lk=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function Dv(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 ${jn} ${yo}`,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 Y=pe("plus",yn,"currentColor",1.5);Y?r.appendChild(Y):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 Y=s.getRootNode().activeElement;return Y instanceof HTMLElement?Y:null},y=()=>{let L=m();for(let Y of d){let K=!!L&&_v(Y)===L;Y.toggleAttribute(Ng,K&&u)}},h=()=>d.filter(L=>L.isConnected||s.contains(L)).map(_v).filter(L=>!Lk(L)),C=(L,Y)=>{L.forEach((K,le)=>{K.setAttribute("tabindex",le===Y?"0":"-1")})},S=L=>{let Y=h();if(Y.length===0)return;let K=(L%Y.length+Y.length)%Y.length;p=K,C(Y,K),Y[K].focus(),y()},x=()=>o.ownerDocument??document,k=null,B=null,$=null,T=()=>{k&&(x().removeEventListener("focusin",k,!0),k=null)},I=()=>{B&&(s.removeEventListener("focusin",B),B=null),$&&(s.removeEventListener("pointerdown",$,!0),$=null)},A=null,D=()=>(A||(A=yd({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),T()}})),A),G=()=>A?.isOpen===!0,se=(L=!1)=>{if(G()){A?.close(),r.setAttribute("aria-expanded","false"),T(),I(),p=-1,u=!1;for(let Y of d)Y.removeAttribute(Ng);L&&r.focus()}},ne=(L=0,Y=!1)=>{if(n||G())return;u=Y,pd(r,s,Pk),D().open(),r.setAttribute("aria-expanded","true");let K=h();C(K,-1),S(L<0?K.length-1:L),k=le=>{let de=typeof le.composedPath=="function"?le.composedPath():[];de.includes(s)||de.includes(o)||se()},x().addEventListener("focusin",k,!0),B=()=>y(),s.addEventListener("focusin",B),$=()=>{u=!1},s.addEventListener("pointerdown",$,!0)},E=L=>{L.preventDefault(),L.stopPropagation(),G()?se(!0):ne(0)},_=L=>{if(L.key==="ArrowDown"||L.key==="Enter"||L.key===" "){L.preventDefault(),u=!0,G()?S(0):ne(0,!0);return}L.key==="ArrowUp"&&(L.preventDefault(),u=!0,G()?S(-1):ne(-1,!0))},W=L=>{switch(kk.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(),se(!0);return;case"Tab":se(!0);return;default:}};return r.addEventListener("click",E),r.addEventListener("keydown",_),s.addEventListener("keydown",W),{trigger:o,triggerButton:r,panel:s,setItems:L=>{for(let K of d)L.includes(K)||K.removeAttribute(Ng);if(d=[...L],!G())return;let Y=h();C(Y,Math.min(p,Y.length-1)),y()},isOpen:G,open:()=>ne(0),close:se,setLabel:L=>{L!==t&&(t=L,l())},applyButtonSize:a,destroy:()=>{n=!0,T(),I(),r.removeEventListener("click",E),r.removeEventListener("keydown",_),s.removeEventListener("keydown",W),A?.destroy(),A=null,o.remove(),s.remove(),d=[]}}}var Bo={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Nv="data-persona-composer-action",Fg="data-persona-composer-disable-when-streaming",Ik="core:overflow",Rk=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function Hk(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 $g(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 Fv=(e,t)=>{!e||typeof console>"u"||console.warn(t)},Wk=(e,t)=>t.includes(":")?t:`${e}:${t}`;function Ok(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){Fv(t,`[Persona] composer action "${l.id}" is already contributed by ${$v(d)}; the ${$v(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?Wk(p,l.id):l.id,m=l.order??Bo.custom;l.placement==="end"&&m>=Bo.send&&(Fv(t,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${Bo.send-1}.`),m=Bo.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 $v=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",Uv=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,Bk=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function _k(e,t){if(!e||e==="always")return!0;let n=Bk(t);return e==="when-text"?n:!n}var Dr=e=>e.kind==="custom",Ug=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,Dk=e=>{let t=Ug(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},Nk='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Fk(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(Nk)||o.childNodes.forEach(n)};return n(e),t.trim()}var $k=e=>Fk(e).length===0;function jv(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(E,_)=>{let W=E.button;if(!W)return;W.setAttribute("role","menuitem"),W.setAttribute("tabindex","-1"),W.className="persona-composer-overflow-menu__item";for(let K of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])W.style[K]="";W.style.lineHeight="1",_.tooltipText?W.setAttribute("title",_.tooltipText):W.removeAttribute("title"),W.replaceChildren();let L=M("span","persona-composer-overflow-menu__icon");if(_.iconName){let K=pe(_.iconName,16,"currentColor",1.5);K&&L.appendChild(K)}let Y=M("span","persona-composer-overflow-menu__label");Y.textContent=_.shortLabel??_.label,W.append(L,Y)},a=(E,_)=>{let W=E.button;if(!W)return;if(W.setAttribute("aria-label",_.label),_.pressed===void 0?W.removeAttribute("aria-pressed"):W.setAttribute("aria-pressed",_.pressed?"true":"false"),W.toggleAttribute(Fg,_.disableWhenStreaming===!0),E.mode==="menu"){E.tooltip?.destroy(),E.tooltip=void 0,s(E,_);return}W.removeAttribute("role"),W.removeAttribute("tabindex"),W.removeAttribute("title");let L=r(),Y=!!_.shortLabel;if(W.className=hn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",jn,yo,Y&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),W.style.width=L&&!Y?L:"",W.style.height=L??"",W.style.minWidth=L&&!Y?L:"",W.style.minHeight=L??"",W.style.fontSize=Y?"":"18px",W.style.lineHeight="1",W.style.color=_.iconColor??"",W.style.backgroundColor=_.backgroundColor??"",W.replaceChildren(),_.iconName){let K=pe(_.iconName,yn,"currentColor",1.5);K&&W.appendChild(K)}if(Y){let K=M("span","persona-composer-action-button__label");K.textContent=_.shortLabel,W.appendChild(K)}else W.firstChild||(W.textContent=_.label);E.tooltip?.destroy(),E.tooltip=en({anchor:W,trigger:E.element,text:()=>_.tooltipText??_.label,enabled:!!_.tooltipText})},l=(E,_)=>{let W=E.action,L=Q("button",{attrs:{type:"button"}}),Y=L;if(_==="bar"){let de=M("div","persona-send-button-wrapper");de.appendChild(L),Y=de}Y.setAttribute(Nv,E.id);let K={resolved:E,element:Y,button:L,owned:!0,managed:!0,busy:!1,visible:!0,mode:_},le=de=>{if(de.preventDefault(),de.stopPropagation(),K.busy||L.disabled)return;let ge=K.resolved.action;K.mode==="menu"&&h?.close(!0);let Ae;try{Ae=ge.onSelect(e.actionContext,de)}catch(fe){e.reportError(fe,{actionId:K.resolved.id});return}!Ae||typeof Ae.then!="function"||(K.busy=!0,L.setAttribute("aria-busy","true"),Ae.catch(fe=>{e.reportError(fe,{actionId:K.resolved.id})}).finally(()=>{K.busy=!1,L.removeAttribute("aria-busy")}))};return L.addEventListener("click",le),K.detach=()=>L.removeEventListener("click",le),a(K,W),K},d=E=>{let _=E.action,W;try{W=_.render({...e.actionContext,id:E.id,action:_})}catch(L){return e.reportError(L,{actionId:E.id}),null}return W?.element?(W.element.setAttribute(Nv,E.id),W.element.toggleAttribute(Fg,_.disableWhenStreaming===!0),{resolved:E,element:W.element,owned:!0,managed:!0,destroy:W.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(E,_)=>{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 W=E.action;return W?Dr(W)?d(E):l(E,_):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(_){e.reportError(_,{actionId:E.resolved.id})}E.element.remove()}},m=(E,_)=>{for(let W=0;W<_.length;W++){let L=_[W];if(!L.managed)continue;let Y=null;for(let K=W+1;K<_.length;K++){let le=_[K];if(!le.managed&&le.element.parentElement===E){Y=le.element;break}}Y?(L.element.parentElement!==E||L.element.nextSibling!==Y)&&E.insertBefore(L.element,Y):E.lastChild!==L.element&&E.appendChild(L.element)}},y=(E,_)=>{if(E.button){E.button.disabled=_;return}if(!E.owned)return;let W=E.element;W.toggleAttribute("data-disabled",_),W.setAttribute("aria-disabled",_?"true":"false");let L=W instanceof HTMLButtonElement||W instanceof HTMLSelectElement||W instanceof HTMLInputElement||W instanceof HTMLTextAreaElement?W:W.querySelector("button, select, input, textarea");L&&(L.disabled=_)},h=null,C=null,S=null,x=0,k=()=>{let E=e.getOverflow?.();return E?.enabled===!0?E:void 0},B=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=Dv({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),$=E=>{C!==E&&(S?.disconnect(),C=E,x=$g(E),!(typeof ResizeObserver>"u")&&(S=new ResizeObserver(_=>{let L=_[_.length-1]?.contentRect?.width??$g(E);L!==x&&(x=L,se())}),S.observe(E)))},T=(E,_)=>{let W=Hk(E.collapseAutoActionsBelow,_);if(W===null)return!1;let L=x||$g(_);return L>0&&L<W},I=(E,_,W)=>{if(!_)return"bar";if(E.resolved.builtIn){let Y=Rk(E.resolved.id);return Y&&_.includeBuiltIns?.includes(Y)?"menu":"bar"}let L=E.resolved.presentation;return L==="overflow"||L==="auto"&&W?"menu":"bar"},A=E=>{let _=E.menuSlot;if(!_)return;if(!$k(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let W=Dk(E.element);if(!W){E.menuLabel?.remove(),E.menuLabel=void 0;return}E.menuLabel||(E.menuLabel=M("span","persona-composer-overflow-menu__label")),E.menuLabel.textContent!==W&&(E.menuLabel.textContent=W),E.menuLabel.parentElement!==_&&_.appendChild(E.menuLabel)},D=(E,_)=>{if(E.mode===_)return E;let W=E.resolved.action;if(W&&!Dr(W)){u(E),t.delete(E.resolved.id);let L=l(E.resolved,_);return t.set(E.resolved.id,L),L}if(_==="menu"){let L=Q("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Ig]:""}});L.appendChild(E.element),Lv(Ug(E.element)),E.menuSlot=L;let Y=K=>{let le=Ug(E.element);if(le.disabled)return;let de=K.target===le||le.contains(K.target);h?.close(!0),de||le.click()};L.addEventListener("click",Y,!0),E.detachMenuSlot=()=>L.removeEventListener("click",Y,!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=_,E},G=(E,_)=>{let W=_.map(L=>L.menuSlot??L.element);for(W.forEach((L,Y)=>{let K=E.children[Y];K!==L&&(K?E.insertBefore(L,K):E.appendChild(L))});E.children.length>W.length;)E.lastElementChild?.remove()},se=()=>{if(o)return;let E=e.getBindings();if(!E)return;let _=e.getState(),W=_.phase==="streaming",L=k();L&&$(E.footer);let Y=L?T(L,E.footer):!1,K={start:[],end:[]},le=[];for(let de of n){let ge=t.get(de.id);if(!ge)continue;let Ae=de.action,fe=Ae?Uv(Ae.visible,_,!0)&&_k(Ae.visibility,_):!0;if(ge.visible!==fe&&(ge.visible=fe,!fe&&ge.managed&&(ge.menuSlot??ge.element).remove()),!!fe){if(ge=D(ge,I(ge,L,Y)),Ae){let _e=Uv(Ae.disabled,_,!1)||Ae.disableWhenStreaming===!0&&W;y(ge,_e),!Dr(Ae)&&Ae.pressed!==void 0&&ge.button?.setAttribute("aria-pressed",Ae.pressed?"true":"false")}ge.mode==="menu"?(A(ge),le.push(ge)):K[de.placement].push(ge)}}if(le.length>0){let de=B();G(de.panel,le),de.setItems(le.map(_e=>_e.menuSlot??_e.element)),de.applyButtonSize();let ge=Number.isFinite(L?.order)?L?.order:Bo.overflow,Ae=K.start.findIndex(_e=>_e.resolved.order>ge),fe={resolved:{id:Ik,placement:"start",presentation:"bar",order:ge,sequence:-1,source:"core"},element:de.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};K.start.splice(Ae<0?K.start.length:Ae,0,fe)}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=Ok(e.collect()),_=new Set(E.map(W=>W.id));for(let[W,L]of t)_.has(W)||(u(L),t.delete(W));for(let W of E){let L=t.get(W.id);if(!L){let de=p(W,"bar");de&&t.set(W.id,de);continue}let Y=L.resolved.action,K=W.action;if(!!Y!=!!K||Y&&K&&Dr(Y)!==Dr(K)||Y&&K&&Dr(Y)&&Dr(K)&&Y.render!==K.render){u(L),t.delete(W.id);let de=p(W,L.mode);de&&t.set(W.id,de);continue}L.resolved=W,W.builtIn?(L.managed=W.builtIn.managed===!0||L.mode==="menu",W.builtIn.element&&L.mode==="bar"&&(L.element=W.builtIn.element)):K&&!Dr(K)?a(L,K):K&&L.element.toggleAttribute(Fg,K.disableWhenStreaming===!0)}n=E,se()},sync:se,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 Uk="core:model",jk=700,qv=16,qk=["--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"],zv=()=>{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 Vv(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(k=>`${k.id}:${k.label}`).join("|");x!==p&&(p=x,d.replaceChildren(...S.map(k=>{let B=Q("option",{attrs:{value:k.id}});return B.textContent=k.label,B}))),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}=zv();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=(_=!1)=>{S()&&(C?.close(),d.setAttribute("aria-expanded","false"),_&&d.focus())},k=_=>{let W=[...y.values()];if(W.length===0)return;let L=(_%W.length+W.length)%W.length;W[L].focus()},B=_=>{if(S())return;C||(C=yd({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),pd(d,m,qk),C.open(),d.setAttribute("aria-expanded","true");let L=[...y.keys()].indexOf(r(e.getModels())?.id??"");k(_??(L>=0?L:0))},$=_=>{x(!0),e.onSelect(_)},T=_=>{_.preventDefault(),_.stopPropagation();let W=_.currentTarget.getAttribute("data-persona-model-option");W&&$(W)},I=_=>{let W=Q("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":_.id}});if(_.icon){let de=pe(_.icon,qv,"currentColor",1.5);if(de){let ge=M("span","persona-composer-model-option-icon");ge.appendChild(de),W.appendChild(ge)}}let L=M("span","persona-composer-model-option-body"),Y=M("span","persona-composer-model-option-label");if(Y.textContent=_.label,L.appendChild(Y),_.description){let de=M("span","persona-composer-model-option-description");de.textContent=_.description,L.appendChild(de)}W.appendChild(L);let K=M("span","persona-composer-model-option-check");K.setAttribute("aria-hidden","true");let le=pe("check",qv,"currentColor",2);return le&&K.appendChild(le),W.appendChild(K),W.addEventListener("click",T),W},A=()=>{let _=e.getModels(),W=_.map(K=>`${K.id}:${K.label}:${K.icon??""}:${K.description??""}`).join("|");if(W!==h){h=W;for(let K of y.values())K.removeEventListener("click",T);y.clear(),m.replaceChildren(..._.map(K=>{let le=I(K);return y.set(K.id,le),le}))}let L=r(_);for(let[K,le]of y)le.setAttribute("aria-selected",String(K===L?.id));p.textContent=L?.label??"";let Y=e.getSuffix?.()??"";u.textContent=Y,d.setAttribute("aria-label",[t,[L?.label,Y].filter(Boolean).join(" ")].filter(Boolean).join(": "))};A(),o=A;let D=_=>{_.preventDefault(),_.stopPropagation(),S()?x(!0):B()},G=_=>{if(_.key==="ArrowDown"){_.preventDefault(),S()?k(0):B(0);return}_.key==="ArrowUp"&&(_.preventDefault(),S()?k(-1):B(-1))},se=_=>{let W=[...y.values()],L=W.indexOf(_.target?.closest?.(".persona-composer-model-option"));switch(_.key){case"ArrowDown":_.preventDefault(),k(L+1);return;case"ArrowUp":_.preventDefault(),k(L-1);return;case"Home":_.preventDefault(),k(0);return;case"End":_.preventDefault(),k(W.length-1);return;case"Escape":_.preventDefault(),_.stopPropagation(),x(!0);return;case"Tab":x(!0);return;default:}};d.addEventListener("click",D),d.addEventListener("keydown",G),m.addEventListener("keydown",se);let{wrapper:ne,chevron:E}=zv();return ne.append(d,E),{element:ne,destroy:()=>{o===A&&(o=null),d.removeEventListener("click",D),d.removeEventListener("keydown",G),m.removeEventListener("keydown",se);for(let _ of y.values())_.removeEventListener("click",T);y.clear(),C?.destroy(),C=null,m.remove()}}};return{action:{id:Uk,kind:"custom",placement:"end",order:jk,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}var jg="[data-persona-composer-chip-row]";function bd(e){e.style.display=e.childElementCount>0?"flex":"none"}function qg(e){let t=e.querySelector(jg);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 zk=":scope > [data-persona-composer-mode]";function Kv(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(zk)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),bd(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(B=>B.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}bd(t)},destroy:()=>{o=!0,d(),bd(t)}}}var Gv=e=>`core:mode:${e}`;var zg=e=>Math.min(300+e,499),Qv=e=>`core:mode-group:${e}`;function vd(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function Vk(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function Yv(e,t){return e?.length?e.filter(n=>!vd(n.groupId,t)&&!Vk(n.groupId,t)):[]}var Kk=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function Xv(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(Kk(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 Cd(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function Jv(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function Zv(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var Gk=16;function eC(e){let t=null;return{action:{id:Qv(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,Gk,"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 tC(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=nd(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 nC(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=nd(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 oC(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 rC(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 sC(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 iC(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 aC(e){return e.wrapped||e.text.includes(`
23
+ `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function lC(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function cC(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 dC(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Vg(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 uC(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var Qk=e=>typeof e?.then=="function";function pC(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 gC(e,t,n){let o;try{o=e(Vg(t),{signal:n})}catch(r){return{status:"error",error:r}}return Qk(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:pC(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):pC(t,o)}var mC=/\s/;function Yk(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===""||mC.test(o)}function Xk(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 Yk(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
25
+ `||a==="\uFFFC"||!r&&mC.test(a))return null;s--}return null}function fC(e,t,n){for(let o of n){let r=Xk(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function hC(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function yC(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 bC(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 ${jn} ${yo}`,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,yn,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),s.appendChild(a),en({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}var{setLoader:wB,load:Jk}=ht({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var Kg=Jk;var{setLoader:AB,load:Zk}=ht({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var vC=Zk;function nl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Q("span",{className:hn("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 CC(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=yC(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(D=>D.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??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=Kg().then(I=>(I.setMentionIconRenderer(pe),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:$,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},x=()=>{vC().then(T=>{let I=T.mountInlineComposer({textarea:e.textarea,renderToken:D=>nl(D,{render:t.renderMentionToken}),onMentionRemoved:D=>d?.untrackMention(D)});m=I.input,y=I.destroy;let A=u;A.replaceWith(I.element),u=I.element,C={next:I.element,prev:A},h?.(I.element,A),d?d.rebindComposer(I.input):p&&p.then(D=>D?.rebindComposer(I.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};t.display==="inline"&&x();let k=[],B=new Map;for(let T of n){if(!T.showButton)continue;let I=bC({config:{...t,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},onOpen:()=>{S().then(A=>A?.openMenu(T.trigger))}});k.push(I),B.set(T.trigger,I.button)}let $=(T,I,A)=>{let D=B.get(I);D&&(D.setAttribute("aria-expanded",T?"true":"false"),T?D.setAttribute("aria-controls",A):D.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(T=>T.wrapper),contextRow:l,handleInput:T=>{if(d){d.handleInput();return}if(!hC(T))return;let I=u,A=I.selectionStart??0;fC(I.value,A,n)&&S().then(D=>D?.handleInput())},handleKeydown:T=>{if(d?.isMenuOpen())return d.handleKeydown(T);if(T.key==="Backspace"&&d?.hasMentions()&&!C){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 S())?.dispatchInlineCommand(T)??null:null,clear:()=>d?.clear(),prefetch:()=>{Kg().catch(()=>{})},onComposerSwap:T=>{h=T,C&&T(C.next,C.prev)},destroy:()=>{d?.destroy(),y?.();for(let T of k)T.wrapper.remove();a&&l.remove()}}}var wd="16px",xd="transparent",eL=(()=>{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})(),xC={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:eL,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"}},SC={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"}},AC={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:Rg,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:wd,canvasBackground:xd},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"}},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 bn(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."))?bn(e,o):o}function Qg(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=bn(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 MC(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 EC(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]=EC(s,r):n[o]=r}return n}function tL(e,t){return t?EC(e,t):e}function Sd(e,t={}){let n={palette:xC,semantic:SC,components:AC},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:tL(n.components,e?.components)};if(t.validate!==!1){let r=MC(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 Gg=e=>e.trim()==="0"?"0px":e,wC="--persona-",nL=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},oL=.179,tn=(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[wC+s],r!==void 0)break;r!==void 0&&(e[wC+n]=r)}};function Yg(e){let t=Qg(e),n={};for(let[j,De]of Object.entries(t)){let Ne=j.replace(/\./g,"-");n[`--persona-${Ne}`]=De.value}tn(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"],tn(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"]]),tn(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"]}`,tn(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"]??wd,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??xd,tn(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"]]),tn(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"],tn(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"],tn(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,De]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ne=n[`--persona-components-history-overlay-${j}`];Ne&&(n[`--persona-history-overlay-${De}`]=Ne)}for(let[j,De]of[["background","bg"],["borderRadius","radius"]]){let Ne=n[`--persona-components-history-menu-${j}`];Ne&&(n[`--persona-history-menu-${De}`]=Ne)}let m=e.components?.history?.motion;if(m){let j=xe=>{if(xe===void 0)return;let ke=String(xe).trim();return/^\d+(\.\d+)?$/.test(ke)?`${ke}ms`:ke},De=j(m.enterDurationMs);De!==void 0&&(n["--persona-history-enter-ms"]=De);let Ne=j(m.exitDurationMs);Ne!==void 0&&(n["--persona-history-exit-ms"]=Ne),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 De=n[`--persona-components-history-confirm-${j}`];De&&(n[`--persona-history-confirm-${j}`]=De)}for(let[j,De]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ne=n[`--persona-components-tooltip-${j}`];Ne&&(n[`--persona-tooltip-${De}`]=Ne)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[j,De]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ne=n[`--persona-components-messageActions-${j}`];Ne&&(n[`--persona-message-action-${De}`]=Ne)}tn(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,tn(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"],["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"]]),tn(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 B=n["--persona-components-markdown-heading-h1-fontWeight"];B&&(n["--persona-md-h1-weight"]=B);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 I=n["--persona-components-markdown-prose-fontFamily"];I&&I!=="inherit"&&(n["--persona-md-prose-font-family"]=I),tn(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"]]),tn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),tn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),tn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),tn(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"],tn(n,[["message-border","components-message-border","border"]]),tn(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,D=A?.iconButton;D&&(D.background&&(n["--persona-icon-btn-bg"]=D.background),D.border&&(n["--persona-icon-btn-border"]=D.border),D.color&&(n["--persona-icon-btn-color"]=D.color),D.padding&&(n["--persona-icon-btn-padding"]=D.padding),D.borderRadius&&(n["--persona-icon-btn-radius"]=D.borderRadius),D.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=D.hoverBackground),D.hoverColor&&(n["--persona-icon-btn-hover-color"]=D.hoverColor),D.activeBackground&&(n["--persona-icon-btn-active-bg"]=D.activeBackground),D.activeBorder&&(n["--persona-icon-btn-active-border"]=D.activeBorder));let 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 se=A?.toggleGroup;se&&(se.gap&&(n["--persona-toggle-group-gap"]=se.gap),se.borderRadius&&(n["--persona-toggle-group-radius"]=se.borderRadius));let ne=A?.artifact;if(ne?.toolbar){let j=ne.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"]=Gg(j.toggleGroupGap)),j.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=j.toggleBorderRadius),j.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Gg(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"]=bn(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"]=Gg(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(ne?.tab){let j=ne.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(ne?.pane){let j=ne.pane;if(j.toolbarBackground){let De=bn(e,j.toolbarBackground)??j.toolbarBackground;n["--persona-artifact-toolbar-bg"]=De}}if(ne?.card){let j=ne.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(ne?.inline){let j=ne.inline;j.background&&(n["--persona-artifact-inline-bg"]=bn(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"]=bn(e,j.chromeBackground)??j.chromeBackground),j.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=bn(e,j.chromeBorder)??j.chromeBorder),j.titleColor&&(n["--persona-artifact-inline-title-color"]=bn(e,j.titleColor)??j.titleColor),j.mutedColor&&(n["--persona-artifact-inline-muted-color"]=bn(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"]=bn(e,E.background)??E.background));let _=n["--persona-surface"],W=n["--persona-container"],L=n["--persona-palette-colors-gray-100"]??"#f3f4f6",Y=n["--persona-palette-colors-gray-200"]??"#e5e7eb",K=n["--persona-palette-colors-gray-300"]??"#d1d5db",le=!W||W===_,de=nL(_??n["--persona-background"]),ge=le&&de!==void 0&&de<oL,Ae=ge?"rgba(255, 255, 255, 0.08)":L,fe=ge?"rgba(255, 255, 255, 0.12)":Y,_e=ge?"rgba(255, 255, 255, 0.16)":K,it=le?Ae:W,be=le?fe:W;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??it,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??be,le&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??_e),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??it,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??it,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??it,n}var rL={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 sL={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"}}},iL={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},TC=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ad=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",aL=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ad()},Xg=e=>aL(e),lL=e=>Sd(e),cL=e=>{let t=Pi(iL,e??{})??{};return Sd({...t,palette:{...t.palette,colors:{...sL.colors,...t.palette?.colors}}},{validate:!1})},Hs=e=>{let t=Xg(e),n=TC(e?.theme),o=TC(e?.darkTheme);return t==="dark"?cL(Pi(n??{},o??{})):lL(n)},dL=e=>Yg(e),Li=(e,t)=>{let n=Hs(t),o=dL(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Xg(t))},ol=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ad())});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(Ad());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 ix,Check as ax,Copy as lx}from"lucide";var Nr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Md="24px",Jg=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",rl=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},PC=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var kC=null;var Zg=()=>{if(kC!==null)return kC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},pL="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Ed=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Td=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 Ed("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Ed("unsupported",e),null):(n==="space"&&(o.key=" "),o)},uL=e=>pL.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),LC=(e,t)=>{let n=Td(e);if(!n)return"";let o=Zg(),r=uL(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("+")},Pd=e=>LC(e,!1),sl=e=>LC(e,!0),gL=(e,t)=>t.key?.toLowerCase()===e.key&&(Zg()?t.metaKey:t.ctrlKey)===e.mod&&!(Zg()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,mL=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},IC=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(gL(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&mL(a))){s.preventDefault();try{l.run(s)}catch(d){Ed(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=Td(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=t.get(l);return d?(Ed(`${d.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",sl(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 fL}from"idiomorph";var kd=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;fL.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 RC=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var em={index:-1,draft:""};function HC(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 WC(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 OC(){return new Map}function BC(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 DC(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function NC(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 FC(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function _o(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ws(e,t){return _o(e)-e.scrollTop<=t}function $C(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 UC(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 jC(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function tm(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 qC(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var il={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},hL=["pre","code","a","script","style"],Ld=e=>({type:e?.type??il.type,placeholder:e?.placeholder??il.placeholder,speed:e?.speed??il.speed,duration:e?.duration??il.duration,buffer:e?.buffer??il.buffer}),VC=[{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"}],al=new Map;for(let e of VC)al.set(e.name,e);var KC=["wipe","glyph-cycle"],Id=e=>{al.set(e.name,e)},yL=e=>{VC.some(t=>t.name===e)||al.delete(e)},bL=()=>Array.from(al.keys()),ll=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:al.get(e)??null,Rd=(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},vL=(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},CL=(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},nm=/\s/,wL=(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},xL=(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(nm.test(s[l])){let d=l;for(;d<s.length&&nm.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&&!nm.test(s[p]);)d.appendChild(vL(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,e)},SL=(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(CL(o,d,t,n.value)),n.value+=1));r.replaceChild(a,e)},cl=(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??hL).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)wL(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=t==="char"?xL:SL;for(let m of l)u(m,n,p);return r.innerHTML},Hd=(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},dl=(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},zC=new WeakMap,AL=(e,t)=>{if(!e.styles)return;let n=zC.get(t);if(n||(n=new Set,zC.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)},om=new WeakMap,ML=(e,t)=>{if(!e.onAttach)return;let n=om.get(t);if(n||(n=new Map,om.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},GC=e=>{let t=om.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},pl=(e,t)=>{AL(e,t),ML(e,t)};var{setLoader:e_,load:EL}=ht({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var QC=EL;function rm(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 ul=0,Fr=null;function sm(e=document){if(ul++,ul===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Fr={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,ul=Math.max(0,ul-1),ul===0&&Fr)){let n=e.body,o=e.defaultView??window;n.style.overflow=Fr.originalOverflow,n.style.position=Fr.originalPosition,n.style.top=Fr.originalTop,n.style.width=Fr.originalWidth,o.scrollTo(0,Fr.scrollY),Fr=null}}}var gl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Et=e=>(e?.launcher?.mountMode??"floating")==="docked",$r=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",qn=e=>{let t=e?.launcher?.dock;return{side:t?.side??gl.side,width:t?.width??gl.width,animate:t?.animate??gl.animate,reveal:t?.reveal??gl.reveal,maxHeight:t?.maxHeight??gl.maxHeight}};import{ArrowRight as TL}from"lucide";var im=e=>e==="followUp"?"follow-up":e,am=(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"}},PL=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'}},YC=new WeakSet,kL=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,LL=e=>{kL()||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"})})},lm=e=>{var $,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,C=o==="followUp",S=t.behavior,x=()=>{if(u.isStreaming())return;let A={suggestion:{...t},surface:o,source:r,behavior:S},D=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})),!D)return;for(let se of d)if(se.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)},k=()=>{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=PL(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 D=M("span","persona-suggestion__copy");if(D.appendChild(Q("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&D.appendChild(Q("span",{className:"persona-suggestion__description",text:t.description})),A.appendChild(D),s!=="chip"){let G=Ht(TL,16,"currentColor",1.8);G&&(G.classList.add("persona-suggestion__arrow"),A.appendChild(G))}return A.addEventListener("click",x),A},B=null;for(let A of d)if(A.renderSuggestion&&(B=A.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:k,select:x}),B))break;return B??(B=k()),($=B.dataset).suggestionId||($.suggestionId=t.id),(T=B.dataset).behavior||(T.behavior=S),(I=B.dataset).emphasis||(I.emphasis=t.emphasis),B instanceof HTMLButtonElement||B.setAttribute("aria-disabled",a?"true":"false"),B},ml=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,k=m?!C:!S;e.toggleAttribute("data-scroll-left",x),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,C,S)=>{e.replaceChildren(),t.length=0,n.length=0;let x=S?.source??"config",k=S?.surface??(x==="config"?"starter":"followUp"),B=k==="followUp",$=S?.variant??"chip",T=S?.behavior??"send",I=S?.overflow??"wrap",A=S?.config??{},D=S?.plugins??[],G=typeof S?.maxItems=="number"?Math.max(0,Math.floor(S.maxItems)):void 0,se=B?"followUps":"starters";!YC.has(A)&&A.debug===!0&&$!=="chip"&&A.suggestions?.[se]?.overflow!==void 0&&(YC.add(A),console.info(`[persona] suggestions.${se}.overflow applies to the "chip" variant only; the "${$}" variant manages its own stacking.`));let ne=K=>K.map(am).filter(le=>le!==null).map(le=>({...le,behavior:le.behavior??T})),E=ne(u??[]);D.forEach(K=>{K.transformSuggestions&&(E=ne(K.transformSuggestions({suggestions:E.map(le=>({...le})),surface:k,source:x,config:A})))});let _=G===void 0?E:E.slice(0,G);if(!_.length){e.hidden=!0,o=null,s();return}if(!B&&(h??m.getMessages()).some(le=>le.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=im(k),e.dataset.variant=$,e.dataset.overflow=I;let W=document.createDocumentFragment(),L=m.isStreaming();_.forEach((K,le)=>{let de=lm({item:K,index:le,surface:k,source:x,variant:$,streaming:L,config:A,plugins:D,chipsConfig:C,session:m,getTextarea:()=>y,eventTarget:e,submitPrompt:S?.submitPrompt});W.appendChild(de),n.push(de),[...de instanceof HTMLButtonElement?[de]:[],...Array.from(de.querySelectorAll("button"))].forEach(Ae=>{t.includes(Ae)||(Ae.disabled=L,t.push(Ae))})}),e.appendChild(W),a(),l();let Y=JSON.stringify({normalized:_,surface:k,variant:$,source:x});Y!==o&&(o=Y,LL(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:_.map(K=>({...K})),surface:k,source:x,variant:$},bubbles:!0,composed:!0})),B&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:_.map(K=>K.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 IL="persona-header-control",RL="persona-header-control--glyph",HL="persona-header-control--sparse",WL=20,OL={x:[1.4,1.05]},XC="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",BL="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wd=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=OL[t]??[1,1.5],l=!o;e.classList.toggle(RL,l),e.classList.toggle(HL,l&&s!==1);let d=parseFloat(o??"")||WL,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)},Os=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=XC,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:y,borderRadius:h,paddingX:C,paddingY:S,hidden:x,extraClassName:k,attrs:B}=e,$=M("div",a),T=!!(m||y),I=Q("button",{className:hn(IL,"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,...B},style:{width:l,height:l,minWidth:l,minHeight:l,display:x?"none":void 0,color:p||vn.actionIconColor,backgroundColor:u,border:T?`${m||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:h,paddingLeft:C,paddingRight:C,paddingTop:S,paddingBottom:S}});return r?Wd(I,r,{iconSize:d,iconText:s}):s&&(I.textContent=s),$.appendChild(I),en({anchor:I,trigger:$,text:()=>I.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:I,wrapper:$}},Ii=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=XC,buttonSize:r,iconSize:s}=t,a=e?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=Os({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}},Ri=(e,t={})=>{let{wrapperClassName:n=BL,buttonSize:o,iconSize:r}=t,a=(e?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=Os({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 vn={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)"},cm={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)"},_L={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)"},Ur=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:vn.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 I=parseFloat(s)||24,A=pe(d,I*.6,"currentColor",1);A?p.replaceChildren(A):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let I=M("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=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:vn.titleColor,...cm}}),y=Q("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:vn.subtitleColor,..._L}});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,k=null;if(C){let A=Ri(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,k=A.wrapper,S==="top-right"&&(k.style.right="48px"),S==="inline"&&o.appendChild(k)}let B=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}=Ii(t,{showClose:n,wrapperClassName:B});return a!=="top-right"&&o.appendChild(T),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:y,closeButton:$,closeButtonWrapper:T,clearChatButton:x,clearChatButtonWrapper:k}},Hi=(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 Wi(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(Ti)):(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 k=document.createElement("hr");l.appendChild(k)}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 k=pe(C.icon,16,"currentColor",1.5);k&&S.appendChild(k)}let x=document.createElement("span");x.textContent=C.label,S.appendChild(x),S.addEventListener("click",k=>{k.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 Vn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=e,p=M("button",hn(!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 JC(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 Od(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=Vn({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 DL(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},k=r&&n?Vn({...x,icon:n,size:o??14}):JC({...x,icon:n,iconSize:o??14}),B=Vn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(C?" "+C:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});S.append(k,B);let $=null,T=()=>{if($)return $;let I=(typeof p=="function"?p():p)??void 0;return $=Wi({items:s,onSelect:a,anchor:S,position:d,portal:I,onOpenChange:A=>{B.setAttribute("aria-expanded",A?"true":"false")}}),I||S.appendChild($.element),$};return S.isConnected?T():requestAnimationFrame(()=>{$||T()}),B.addEventListener("click",I=>{I.stopPropagation(),T().toggle()}),{element:S,primaryButton:k,chevronButton:B,openMenu:()=>T().show(),closeMenu:()=>$?.hide(),toggleMenu:()=>T().toggle(),destroy:()=>{$?.destroy(),S.remove()}}}function dm(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=Wi({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 ZC=e=>{let t=Ur({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 NL(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=Os({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Pd(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=sl(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=Wi({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 ew=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=vn.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=dm({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:I=>{let A=G=>{G===!1&&T.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:I}}))},D=d.onSelect(I);D instanceof Promise?D.then(A,()=>{}):A(D)},hover:d.hover,className:""});p=T.element,p.style.color=vn.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=vn.titleColor,Object.assign(u.style,cm),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}=Ii(t,{showClose:n,wrapperClassName:m});o&&y.addEventListener("click",o);let C=M("div","persona-flex persona-items-center persona-gap-1");d||NL(C,r?.trailingActions,r?.onAction??s);let S=a.clearChat??{},x=null,k=null;if(S.enabled??!0){let T=S.placement??"inline",I=Ri(t,{wrapperClassName:T==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});x=I.button,k=I.wrapper,T==="top-right"?k.style.right="48px":C.appendChild(k)}C.appendChild(h),l.appendChild(C);let B=M("div");B.style.display="none";let $=M("span");return $.style.display="none",{header:l,iconHolder:B,headerTitle:u,headerSubtitle:$,closeButton:y,closeButtonWrapper:h,clearChatButton:x,clearChatButtonWrapper:k}},pm={default:ZC,minimal:ew},tw=e=>pm[e]??pm.default,fl=(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=tw(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 Oi=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=hd(),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}=ud(t);a();let l=gd(t),d=ki(t),p=md(t),u=fd(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 FL,MessageSquare as $L}from"lucide";var nw=()=>{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=Ht($L,16,"currentColor",1.5);n&&t.appendChild(n);let o=M("span","persona-pill-peek__text"),r=M("span","persona-pill-peek__caret"),s=Ht(FL,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Bd=e=>{let{config:t}=e,n=Q("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=hd(),r=fd(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=ud(t,{defaultMaxLines:5});a();let l=gd(t),d=ki(t),p=md(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 UL=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}},jL=(e,t)=>{if(!e)return null;let n=UL(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},qL=(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},zL=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},gm=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(":"))},mm=320,aw=320,VL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),KL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),GL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),QL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),YL=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},XL=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(nl(o.ref,{readonly:!0,render:t}))}return n},ow="\uE000",rw="\uE001",JL=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${ow}${r}:${y}${rw}`,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(XL(t,o));return}e.innerHTML=l;let p=new RegExp(`${ow}${r}:(\\d+)${rw}`),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(nl(S.ref,{readonly:!0,render:o}),x),h=x}}},ZL=(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=`${mm}px`,p.style.maxHeight=`${aw}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}),zL(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}},e0=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(!gm(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=`${mm}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},t0=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(!gm(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=`${mm}px`,r.style.maxHeight=`${aw}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}},n0=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(!gm(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}},Bi=()=>{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},lw=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Bi};if(t){let r=t(o);if(r!==null)return r}return Bi()},o0=(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},sw=(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},hl=(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},iw={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"}},r0=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=iw[n??"bubble"]??iw.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)`)},_d="custom:",s0=e=>`${_d}${e}`,cw=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),dw=(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=cw(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],k=M("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${S} ${x} ${y==="hover"?"persona-message-actions-hover":""}`);k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id);let B=($,T,I)=>{let A=Vn({icon:$,label:T,size:14,className:"persona-message-action-btn",chromeless:!0});return A.setAttribute("data-action",I),A};r&&k.appendChild(B("copy","Copy message","copy")),l&&k.appendChild(B("volume-2","Read aloud","read-aloud")),s&&k.appendChild(B("thumbs-up","Upvote","upvote")),a&&k.appendChild(B("thumbs-down","Downvote","downvote")),d&&k.appendChild(B("refresh-cw","Regenerate response","regenerate")),p&&k.appendChild(B("pencil","Edit message","edit")),u&&k.appendChild(B("quote","Quote message","quote"));for(let $ of m)k.appendChild(B($.iconName??"ellipsis",$.label,s0($.id)));return k},yl=(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=hl(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;r0(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 k=VL(e),B=e.content?.trim()??"",T=k.length>0&&B===xi,I=Ld(s?.widgetConfig?.features?.streamAnimation),A=s?.widgetConfig?.features?.streamAnimation?.plugins,D=e.role==="assistant"&&I.type!=="none"?ll(I.type,A):null,G=e.role==="assistant"&&D?.isAnimating?.(e)===!0,se=e.role==="assistant"&&D!==null&&(!!e.streaming||G);se&&D?.bubbleClass&&S.classList.add(D.bubbleClass);let ne=document.createElement("div");ne.classList.add("persona-message-content"),e.streaming&&ne.classList.add("persona-content-streaming"),se&&D&&(D.containerClass&&ne.classList.add(D.containerClass),ne.style.setProperty("--persona-stream-step",`${I.speed}ms`),ne.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let E=se?Rd(e.content??"",I.buffer,D,e,!!e.streaming):e.content??"",_=()=>{let be=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent});return se&&D?.wrap==="char"?cl(be,"char",e.id,{skipTags:D.skipTags}):se&&D?.wrap==="word"?cl(be,"word",e.id,{skipTags:D.skipTags}):be},W=null;if(T?(W=document.createElement("div"),W.innerHTML=_(),W.style.display="none",ne.appendChild(W)):e.contentSegments?.length?JL(ne,e.contentSegments,be=>t({text:be,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):ne.innerHTML=_(),se&&D?.useCaret&&!T&&B){let be=Hd(),j=ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),De=j[j.length-1];if(De?.parentNode)De.parentNode.insertBefore(be,De.nextSibling);else{let Ne=ne.lastElementChild;Ne?Ne.appendChild(be):ne.appendChild(be)}}if(m&&h==="inline"&&e.createdAt){let be=sw(e,p,"span");be.classList.add("persona-timestamp-inline");let j=ne.lastElementChild;j?j.appendChild(be):ne.appendChild(be)}if(k.length>0){let be=ZL(k,!T&&!!B,()=>{T&&W&&(W.style.display="")});be?S.appendChild(be):T&&W&&(W.style.display="")}let L=KL(e);if(L.length>0){let be=e0(L);be&&S.appendChild(be)}let Y=GL(e);if(Y.length>0){let be=t0(Y);be&&S.appendChild(be)}let K=QL(e);if(K.length>0){let be=n0(K);be&&S.appendChild(be)}let le=e.contentSegments?.length?null:YL(e.contextMentions);if(le&&S.appendChild(le),S.appendChild(ne),m&&h==="below"&&e.createdAt){let be=sw(e,p);be.classList.add("persona-mt-1"),S.appendChild(be)}let de=e.role==="assistant"?jL(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let be=!!(E&&E.trim()),j=I.placeholder==="skeleton",De=j&&I.buffer==="line"&&be;if(be)De&&S.appendChild(dl());else if(j)S.appendChild(dl());else{let Ne=lw("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);Ne&&S.appendChild(Ne)}}de&&e.stopReason&&!e.streaming&&(B||(ne.style.display="none"),S.appendChild(qL(e.stopReason,de)));let ge=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1,Ae=s?.actionEligibility,fe=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ae?.canEdit===!0||o?.showQuote===!0&&Ae?.canQuote===!0||cw(o,"user").length>0);if((ge||fe)&&o){let be=dw(e,fe?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Ae);S.appendChild(be)}if(!u||e.role==="system")return S;let _e=M("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),it=o0(d,e.role);return y==="right"||y==="left"&&e.role==="user"?_e.append(S,it):_e.append(it,S),_e},i0=(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}):yl(e,t,n,o,r,s)};var a0=40,l0=(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,a0);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},pw=(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}},_i=(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)},Nd=(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==="",l0(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")},c0="data-persona-welcome-plugin",uw="data-persona-welcome-overlay",Dd="persona-welcome-overlay-active",fm=new WeakMap,hm=(e,t,n)=>{n.setAttribute(c0,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(uw,""),e.classList.contains(Dd)||(fm.set(e,e.scrollTop),e.classList.add(Dd),e.scrollTop=0)},ym=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(uw),e.classList.contains(Dd)&&(e.classList.remove(Dd),e.scrollTop=fm.get(e)??e.scrollTop,fm.delete(e))},gw=()=>{let e=Q("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Fd=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Q("div",{className:hl("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},mw=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,fw=(e,t)=>{if(mw()||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,B=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-B),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},hw=(e,t,n)=>{if(t<=1||mw()||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 d0="Hello \u{1F44B}",p0="I can answer questions and help you get things done here.",yw=new WeakSet,Cn=(e,t)=>!!e&&e[t]!==void 0,u0=(e,t)=>{!e||e.debug!==!0||!t.length||yw.has(e)||(yw.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Do=e=>{let t=e?.welcome,n=e?.copy,o=Cn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":Cn(t,"dismiss")?t.dismiss:"never",s=[];Cn(t,"title")&&Cn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Cn(t,"subtitle")&&Cn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Cn(t,"variant")&&Cn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&Cn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&Cn(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=rl(t?.anchorComposerTop)!==null;return Cn(t,"anchorComposerTop")&&!l&&s.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),a!=="center"&&(Cn(t,"anchorComposerTop")||Cn(t,"composerGap"))&&s.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),u0(e,s),{title:Cn(t,"title")?t.title:n?.welcomeTitle??d0,kicker:t?.kicker??"",subtitle:Cn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??p0,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()||Md}},bw=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Bs=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var vw="16px",vm="10px",Cm="14px",Cw=e=>{let t=e?.launcher?.enabled??!0,n=Et(e);if($r(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??rn);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??rn),{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&&zn[r.position]?zn[r.position]:zn["bottom-right"],a=M("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??rn);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}},wm=e=>{let t=Q("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":im(e)}});return t.hidden=!0,t},ww=(e,t)=>{let n=wm("starter"),o=pw(e,n,{flatShadow:Et(e)}),r=Do(e);Nd(o,r),_i(t,o.host,Bs(r,e?.initialMessages));let s=gw();return Fd(s,r.message,e),{welcome:o,greetingHost:s}},g0=(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}=Ii(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:vw,iconSize:vm});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 D=Ri(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:vw,iconSize:Cm});a=D.button,l=D.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}=ww(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"),k=wm("followUp"),B=Nr(e,!0);B&&(x.style.maxWidth=B,x.style.marginLeft="auto",x.style.marginRight="auto",x.style.width="100%"),p.append(y,m,x,k);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=Bd({config:e}),{root:I,textNode:A}=nw();return n.append(d,r,p,$),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:x,starterSuggestions:S,transcriptSuggestions:k,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:I,peekTextNode:A}},xw=(e,t=!0)=>{if($r(e))return g0(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?fl(e,o,{showClose:t}):Ur({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}=ww(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=wm("followUp"),S=Nr(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=Oi({config:e}),k=e?.layout?.showFooter!==!1;r?Hi(n,s,e):(s.header.style.display="none",Hi(n,s,e)),n.append(a);let B=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 k||(x.footer.style.display="none"),n.append(x.footer),n.append(B),{container:n,body:a,messagesWrapper:h,starterSuggestions:y,transcriptSuggestions:C,composerOverlay:B,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 xm=(e,t)=>{let n=M("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 Ag=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=Et(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,I=pe(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 $=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 I=parseFloat($)||24,A=Math.max(I-T,8),_=pe(a.callToActionIconName,A,"currentColor",1.5);_?h.appendChild(_):h.textContent=a.callToActionIconText??"\u2197"}else h.textContent=a.callToActionIconText??"\u2197"}let C=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",S="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?S:`${x} ${C}`,l||(n.style.zIndex=String(a.zIndex??rn));let k="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",B="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:B,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}},l0="teaser-dismissed",ww=new Set,Cw=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${l0}`},c0=(e,t)=>{if(ww.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},d0=(e,t)=>{if(ww.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},p0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,u0=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Et(e??{})?null:t},xw=(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)},x=()=>{!s||!p||(p=!1,s.hidden=!0)},S=Y=>{C(),m=!0,x(),d0(Cw(o),Y&&h())},k=Y=>{!r||m||S(Y==="user"&&p)},B=()=>{d=null,!(!s||m||y)&&(u=!0,p=!0,s.hidden=!1,!(p0()||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||c0(Cw(o),h())||(C(),d=setTimeout(B,Math.max(0,r.delayMs??0)))},T=()=>{S(h()),t()},I=Y=>{Y.stopPropagation(),S(h())},_=vm(e,()=>{k("user"),t()}),G=()=>{C(),l?.removeEventListener("click",T),a?.removeEventListener("click",I),s?.remove(),s=null,l=null,a=null,p=!1},ie=()=>{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",I),s=Q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,_.element)},ne=()=>{let Y=o.launcher?.position??"bottom-right",K=zn[Y]??zn["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",_.element.style.position="";return}n.className=fn("persona-launcher-surface",K),n.setAttribute("data-teaser",Y),n.style.zIndex=String(o.launcher?.zIndex??rn),_.element.style.position="static"},E=Y=>{let K=u0(Y);if(r=K,!K){G();return}s||ie(),l.textContent=K.text,a.hidden=K.dismissible===!1,a.setAttribute("aria-label",K.dismissLabel??"Dismiss message"),$()},D=Y=>{o=Y,_.update(Y),E(Y),ne()},W=(Y,K="user")=>{y=Y,Y&&k(K)},L=()=>{G(),_.destroy(),n.remove()};return n.appendChild(_.element),e&&(E(e),ne()),{element:n,launcher:_,get teaser(){return s?{element:s,show:B,dismiss:S}:null},setPanelOpen:W,update:D,destroy:L}};var Sw=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=yw(e),s=vw(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}}},Cm=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>vm(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=xw(e,n);return{instance:r,element:r.element}};var g0=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},m0=(e,t,n)=>`${g0(e)}plugin:${t}:${n}`,Aw=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=>m0(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=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 f0,ChevronUp as h0}from"lucide";var y0=["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"],b0="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",v0="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",C0=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Fd=(e,t)=>{let n=M("div",["persona-message-bubble",e,...y0].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},$d=e=>{let t=M("button",e.expandable?b0:v0);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},wm=(e,t,n)=>{e.innerHTML="";let o=Ht(t?h0:f0,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=M("div","persona-flex persona-items-center");wm(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},jd=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?.();C0(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&&wm(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&&wm(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,w0=(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
- `):""},Mw=(e,t)=>{zd(e,t,{stateSet:Di,previewKind:"reasoning",iconColor:"currentColor"})},xm=(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=w0(e,r.previewMaxLines??3),p=$d({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()),x=()=>{let L=M("span","");return L.setAttribute("data-tool-elapsed",C),L.textContent=Jc(n),L},S=h.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:y,previewText:d,isActive:l,config:t??{},elapsed:Jc(n),createElapsedElement:x});typeof S=="string"&&S.trim()?(m.textContent=S,u.appendChild(m)):S instanceof HTMLElement?u.appendChild(S):(m.textContent=y,u.appendChild(m));let k=M("span","persona-text-xs persona-text-persona-primary");k.textContent=Fb(n),u.appendChild(k);let B=r.loadingAnimation??"none",$=h.activeTextTemplate,T=h.completeTextTemplate,I=l?$:T,A=S instanceof HTMLElement,_=(L,Y)=>{m.textContent="";let K=Zc(L,""),le=0;for(let de of K){let ge=de.styles.length>0?(()=>{let Me=M("span",de.styles.map(fe=>`persona-tool-text-${fe}`).join(" "));return m.appendChild(Me),Me})():m;if(de.isDuration&&l)ge.appendChild(x());else{let Me=de.isDuration?Jc(n):de.text;Y?le=_i(ge,Me,le):ge.appendChild(document.createTextNode(Me))}}};if(!A&&I)if(k.style.display="none",m.style.display="",l&&B!=="none"){let L=h.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),B==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${L}ms`),_(I,!1)):(m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${L}ms`),B==="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&&B!=="none"){m.style.display="";let L=h.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),B==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${L}ms`);else{m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${L}ms`),B==="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 Y=m.textContent||y;m.textContent="",_i(m,Y,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"),Y=pe(r.iconName,16,"currentColor",2);Y&&(L.appendChild(Y),p.appendChild(L))}let G="currentColor",ie=Ud(p,u,{expandable:s,expanded:a,iconColor:G,metaGap:!1}),ne=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,ne),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 D=n.chunks.join(""),W=M("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return W.textContent=D||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),E.appendChild(W),qd({expanded:a,header:p,toggleIcon:ie,content:E,collapsedPreview:ne,iconColor:G}),o.append(p,ne,E),o};var Ni=new Set,Ew=e=>e.toggleTextColor||e.headerTextColor||"var(--persona-primary, #171717)",x0=(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(`
36
+ `,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=Et(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,I=pe(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 $=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 I=parseFloat($)||24,A=Math.max(I-T,8),D=pe(a.callToActionIconName,A,"currentColor",1.5);D?h.appendChild(D):h.textContent=a.callToActionIconText??"\u2197"}else h.textContent=a.callToActionIconText??"\u2197"}let C=a.position&&zn[a.position]?zn[a.position]:zn["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??rn));let k="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",B="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:B,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}},m0="teaser-dismissed",Aw=new Set,Sw=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${m0}`},f0=(e,t)=>{if(Aw.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},h0=(e,t)=>{if(Aw.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},y0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,b0=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Et(e??{})?null:t},Mw=(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=Y=>{C(),m=!0,S(),h0(Sw(o),Y&&h())},k=Y=>{!r||m||x(Y==="user"&&p)},B=()=>{d=null,!(!s||m||y)&&(u=!0,p=!0,s.hidden=!1,!(y0()||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||f0(Sw(o),h())||(C(),d=setTimeout(B,Math.max(0,r.delayMs??0)))},T=()=>{x(h()),t()},I=Y=>{Y.stopPropagation(),x(h())},D=xm(e,()=>{k("user"),t()}),G=()=>{C(),l?.removeEventListener("click",T),a?.removeEventListener("click",I),s?.remove(),s=null,l=null,a=null,p=!1},se=()=>{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",I),s=Q("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,D.element)},ne=()=>{let Y=o.launcher?.position??"bottom-right",K=zn[Y]??zn["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",D.element.style.position="";return}n.className=hn("persona-launcher-surface",K),n.setAttribute("data-teaser",Y),n.style.zIndex=String(o.launcher?.zIndex??rn),D.element.style.position="static"},E=Y=>{let K=b0(Y);if(r=K,!K){G();return}s||se(),l.textContent=K.text,a.hidden=K.dismissible===!1,a.setAttribute("aria-label",K.dismissLabel??"Dismiss message"),$()},_=Y=>{o=Y,D.update(Y),E(Y),ne()},W=(Y,K="user")=>{y=Y,Y&&k(K)},L=()=>{G(),D.destroy(),n.remove()};return n.appendChild(D.element),e&&(E(e),ne()),{element:n,launcher:D,get teaser(){return s?{element:s,show:B,dismiss:x}:null},setPanelOpen:W,update:_,destroy:L}};var Ew=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Cw(e),s=xw(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}}},Sm=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>xm(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Mw(e,n);return{instance:r,element:r.element}};var v0=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},C0=(e,t,n)=>`${v0(e)}plugin:${t}:${n}`,Tw=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=>C0(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 Di=(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 w0,ChevronUp as x0}from"lucide";var S0=["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"],A0="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",M0="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",E0=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),$d=(e,t)=>{let n=M("div",["persona-message-bubble",e,...S0].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},Ud=e=>{let t=M("button",e.expandable?A0:M0);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},Am=(e,t,n)=>{e.innerHTML="";let o=Ht(t?x0:w0,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},jd=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=M("div","persona-flex persona-items-center");Am(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},qd=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?.();E0(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},zd=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&Am(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"},Vd=(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&&Am(d,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};var Ni=new Set,T0=(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
+ `):""},Pw=(e,t)=>{Vd(e,t,{stateSet:Ni,previewKind:"reasoning",iconColor:"currentColor"})},Mm=(e,t)=>{let n=e.reasoning,o=$d("persona-reasoning-bubble",e.id);if(!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&Ni.has(e.id),l=n.status!=="complete",d=T0(e,r.previewMaxLines??3),p=Ud({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=Jc(n),L},x=h.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:y,previewText:d,isActive:l,config:t??{},elapsed:Jc(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 k=M("span","persona-text-xs persona-text-persona-primary");k.textContent=qb(n),u.appendChild(k);let B=r.loadingAnimation??"none",$=h.activeTextTemplate,T=h.completeTextTemplate,I=l?$:T,A=x instanceof HTMLElement,D=(L,Y)=>{m.textContent="";let K=Zc(L,""),le=0;for(let de of K){let ge=de.styles.length>0?(()=>{let Ae=M("span",de.styles.map(fe=>`persona-tool-text-${fe}`).join(" "));return m.appendChild(Ae),Ae})():m;if(de.isDuration&&l)ge.appendChild(S());else{let Ae=de.isDuration?Jc(n):de.text;Y?le=Di(ge,Ae,le):ge.appendChild(document.createTextNode(Ae))}}};if(!A&&I)if(k.style.display="none",m.style.display="",l&&B!=="none"){let L=h.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),B==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${L}ms`),D(I,!1)):(m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${L}ms`),B==="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)),D(I,!0))}else D(I,!1);else if(!A&&l&&B!=="none"){m.style.display="";let L=h.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),B==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${L}ms`);else{m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${L}ms`),B==="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 Y=m.textContent||y;m.textContent="",Di(m,Y,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"),Y=pe(r.iconName,16,"currentColor",2);Y&&(L.appendChild(Y),p.appendChild(L))}let G="currentColor",se=jd(p,u,{expandable:s,expanded:a,iconColor:G,metaGap:!1}),ne=qd({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,ne),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 _=n.chunks.join(""),W=M("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return W.textContent=_||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),E.appendChild(W),zd({expanded:a,header:p,toggleIcon:se,content:E,collapsedPreview:ne,iconColor:G}),o.append(p,ne,E),o};var Fi=new Set,kw=e=>e.toggleTextColor||e.headerTextColor||"var(--persona-primary, #171717)",P0=(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
38
  `);let r=Yc(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
39
- `):""},Sm=(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)"},S0=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=x0(e,o?.previewMaxLines??3),a=n?$b(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=lg(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=lg(n,d.completeTextTemplate,p)),{summary:p,previewText:s,isActive:l}},Tw=(e,t,n)=>{zd(e,t,{stateSet:Ni,previewKind:"tool",iconColor:Ew(n?.toolCall??{})})},Am=(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}=S0(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=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()),x=()=>{let E=M("span","");return E.setAttribute("data-tool-elapsed",C),E.textContent=za(n),E},S=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:t??{},elapsed:za(n),createElapsedElement:x});typeof S=="string"&&S.trim()?(h.textContent=S,y.appendChild(h)):S instanceof HTMLElement?y.appendChild(S):(h.textContent=d,y.appendChild(h));let k=s.loadingAnimation??"none",B=o.activeTextTemplate,$=o.completeTextTemplate,T=u?B:$,I=S instanceof HTMLElement,A=(E,D)=>{h.textContent="";let W=n.name?.trim()||"tool",L=Zc(E,W),Y=0;for(let K of L){let le=K.styles.length>0?(()=>{let de=M("span",K.styles.map(ge=>`persona-tool-text-${ge}`).join(" "));return h.appendChild(de),de})():h;if(K.isDuration&&u)le.appendChild(x());else{let de=K.isDuration?za(n):K.text;D?Y=_i(le,de,Y):le.appendChild(document.createTextNode(de))}}};if(!I)if(u&&k!=="none"){let E=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",`${E}ms`),T&&A(T,!1);else if(h.classList.add(`persona-tool-loading-${k}`),h.style.setProperty("--persona-tool-anim-duration",`${E}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 D=h.textContent||d;h.textContent="",_i(h,D,0)}}else T&&A(T,!1);let _=Ew(o),G=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 ne=M("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(ne.style.display=l?"":"none",o.contentBackgroundColor&&(ne.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(ne.style.color=o.contentTextColor),o.contentPaddingX&&(ne.style.paddingLeft=o.contentPaddingX,ne.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(ne.style.paddingTop=o.contentPaddingY,ne.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,ne.appendChild(E)}if(n.args!==void 0){let E=M("div","persona-space-y-1"),D=M("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(D.style.color=o.labelTextColor),D.textContent="Arguments";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",Sm(W,o),W.textContent=Yc(n.args),E.append(D,W),ne.appendChild(E)}if(n.chunks&&n.chunks.length){let E=M("div","persona-space-y-1"),D=M("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(D.style.color=o.labelTextColor),D.textContent="Activity";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",Sm(W,o),W.textContent=n.chunks.join(""),E.append(D,W),ne.appendChild(E)}if(n.status==="complete"&&n.result!==void 0){let E=M("div","persona-space-y-1"),D=M("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(D.style.color=o.labelTextColor),D.textContent="Result";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",Sm(W,o),W.textContent=Yc(n.result),E.append(D,W),ne.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`,ne.appendChild(E)}return qd({expanded:l,header:m,toggleIcon:G,content:ne,collapsedPreview:ie,iconColor:_}),r.append(m,ie,ne),r};var{setLoader:KD,load:A0,provide:GD,getSync:M0}=ht({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var Pw=A0;var kw=M0;var{setLoader:XD,load:E0}=ht({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var Mm=E0;var Em=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)})}},Do=new Em;var Tm=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:rN,load:T0,provide:sN,getSync:P0}=ht({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),Fi=null,Vd=new Set,Lw=e=>{if(Fi)return Fi;Fi=e,e.initArtifactsUi({componentRegistry:Do});for(let o of Tm)Do.has(o)||Do.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Ho();t?e.__provideMarkdownParsers(t):_a(()=>{let o=Ho();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>Dc());let n=[...Vd];Vd.clear();for(let o of n)try{o()}catch{}return e};var Kd=()=>T0().then(Lw);var ar=()=>{if(Fi)return Fi;let e=P0();return e?Lw(e):null},Pm=e=>Fi?()=>{}:(Vd.add(e),()=>{Vd.delete(e)});function Cn(e){return e?.features?.artifacts?.enabled===!0}function Iw(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"),!Cn(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 k0(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 Rw=["panel","seamless","detached"];function km(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Rw.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Lm(e){return!e||!Cn(e)?!1:km(e)==="detached"}function bl(e,t){if(!Cn(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"),k0(e),Iw(e,t);return}let n=t.features?.artifacts?.layout,o=km(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)}Iw(e,t)}function vl(e,t){for(let l of Rw)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"),!Cn(t))return;let n=t.features?.artifacts?.layout,o=km(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 Hw(e,t){return!t||!Cn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var L0=new Set(["__proto__","prototype","constructor"]),I0=new Set(["collapsed","card","panel","inline"]),Ww=new Set(["markdown","component"]),R0=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,_s=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qd=e=>!L0.has(e),Im=e=>typeof e=="string"&&I0.has(e),Ds=e=>Object.keys(e).length>0;function No(e,t,n,o){e.push({path:t,code:n,message:o})}var H0="Ignored because this key is not part of the persisted preference schema.",Gd="Ignored an unsupported value.",W0="Expected collapsed, panel, or inline.",O0='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Ow={kind:"mode",message:Gd},$i={kind:"string",message:"Expected a CSS length string."},lr={kind:"boolean"},B0={paneWidth:$i,paneMaxWidth:$i,paneMinWidth:$i,expandedPanelWidth:$i,resizableMinWidth:$i,resizableMaxWidth:$i,expandLauncherPanelWhenOpen:lr,resizable:lr},_0={kind:"object",message:"Expected a preference object.",children:{showToolCalls:lr,showReasoning:lr,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:lr,grouped:lr}},reasoningDisplay:{kind:"object",children:{expandable:lr,activePreview:lr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Ow,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Ow,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Ww,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Ww}}},filePreview:{kind:"object",children:{enabled:lr}},layout:{kind:"object",children:B0}}}}};function Bw(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:No(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:No(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:No(o,n,"invalid_value",t.message);case"mode":return Im(e)?Un(e):No(o,n,"invalid_value",t.message);case"modeMap":{if(!_s(e))return No(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:Ps(a);Qd(a)&&(r?r.has(a):R0.test(d))?Im(l)?s[d]=Un(l):No(o,`${n}.${a}`,"invalid_value",W0):No(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":O0)}return Ds(s)?s:void 0}case"object":{if(t.bareMode&&Im(e))return Un(e);if(!_s(e))return No(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))(!Qd(l)||!r.includes(l))&&No(o,s(l),"unknown_key",H0);let a={};for(let l of r){let d=t.children[l],p=Bw(e[l],d,s(l),o);if(d.deprecated&&e[l]!==void 0&&No(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=_s(m)&&_s(p)?{...m,...p}:p}return Ds(a)?a:void 0}}}function _w(e){let t=[];return{preferences:(e===null?void 0:Bw(e,_0,"",t))??{},issues:t}}function Ui(e){if(Array.isArray(e))return e.map(Ui);if(!_s(e))return e;let t={};for(let[n,o]of Object.entries(e))Qd(n)&&o!==void 0&&(t[n]=Ui(o));return t}function Dw(e,t){let n=Ui(e);for(let[o,r]of Object.entries(t)){if(!Qd(o)||r===void 0)continue;let s=n[o];n[o]=_s(s)&&_s(r)?Dw(s,r):Ui(r)}return n}function D0(e){let t={},n;for(let r of e){let s=_w(r).preferences;n=Nw(n,s.artifacts?.display),t=Dw(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function N0(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}:{},...Ds(r)?{byMediaType:r}:{}};return Ds(s)?s:void 0}function Nw(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=N0(n.files,t.files),a={...o?{default:o}:{},...Ds(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Ds(a)?a:void 0}function Fw(e={},t){let n=D0(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=Nw(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 Yd(e){let t=e.preferences;return!t||!Ds(t)?e:{...e,features:Fw(e.features??{},[t])}}function F0(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 $0(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 U0(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function j0(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Rm(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 $w(e,t,n,o,r,s,a=200){let l=F0(r,200),d=j0(t,n,o,a);d=Math.max(l,d);let p=$0(s);return p!==null&&(d=Math.min(d,p)),U0(e,l,d)}var{setLoader:uN,load:q0,provide:gN,getSync:z0}=ht({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var Uw=q0;var jw=z0;var Hm=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 Hm;var qw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),V0=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),zw=(e,t,n)=>{if(!qw(e)||!qw(t)||V0.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]=zw(e[r],t[r],s)}return o};function Jd(e,t){let n=zw(e,t,"");return el(n)}var Vw=()=>{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 K0=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},G0=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=K0(e),n=G0(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}},Wm=e=>typeof e=="string"?e:e==null?"":String(e),ji={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Wm(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Wm(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:Wm(n.text)}}},Kw=e=>Array.isArray(e)?e.map(t=>String(t)):[],ep=e=>{let t=new Set(Kw(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Kw(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 Q0=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}},Y0=e=>e.map(t=>({...t,streaming:!1})),X0=e=>e.map(t=>({...t,status:"complete"})),Om=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Q0(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Y0(n.messages):void 0,artifacts:n.artifacts?X0(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 J0=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")},Gw=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 J0(e)},Z0=async(e,t)=>{let n=await Gw(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await Gw(`${e}\0${t}`)}`}};var Qw=(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,_)=>{if(l||A===p)return;let G=p;p=A,d+=1;let ie={previousToken:G,token:A,source:_,revision:d};for(let ne of m)ne(ie)},x=A=>{l||A.key!==null&&A.key!==o||C(A.key===null?null:A.newValue??null,"external")},S=(async()=>{let A=await Z0(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)),B=()=>{let A=y();if(!A)return null;try{let _=A.getItem(r);if(!_)return null;let G=JSON.parse(_);return typeof G?.expiresAt=="number"&&typeof G?.ownerNonce=="string"?G:null}catch{return null}},$=A=>{let _=y();if(_)try{B()?.ownerNonce===A&&_.removeItem(r)}catch{}},T=A=>new Promise(_=>{let G=setTimeout(ie,A);function ie(){clearTimeout(G),window.removeEventListener("storage",ne),_()}function ne(E){(E.key===null||E.key===r)&&ie()}window.addEventListener("storage",ne)}),I=async A=>{let _=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;Date.now()<G;){let ie=y();if(!ie)break;let ne=Date.now(),E=B();if(E&&E.expiresAt>ne&&E.ownerNonce!==_){await T(Math.min(E.expiresAt-ne,500));continue}try{ie.setItem(r,JSON.stringify({ownerNonce:_,expiresAt:ne+1e4}))}catch{a=!0;break}if(await k(20+Math.random()*40),B()?.ownerNonce!==_){await T(500);continue}u=_;try{return await A()}finally{u=null,$(_)}}return A()};return{ready:S,async get(){return await S,C(h(),"external"),p},async set(A){await S;let _=y();if(_)try{_.setItem(o,A)}catch{a=!0}C(A,"local")},async clear(){await S;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 S;let _=globalThis.navigator?.locks;return _?.request?_.request(s,()=>A()):y()?I(A):A()},matches(A,_,G){return A===e&&_===t&&G===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",x),u&&$(u)}}};var{setLoader:SN,load:eI}=ht({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var Bm=eI;var _m=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},cr=e=>Object.freeze({...e}),Yw=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),Xw=e=>e?cr(e):null;function Jw(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){_m("renderHistoryView cleanup",I)}},u=(T,I)=>{for(let A of t){let _=A[T];if(_)try{let G=_(I);if(G)return G}catch(G){_m(T,G)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),y={header:T=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:cr(T.identityStatus),pendingAction:Xw(T.pendingAction),copy:cr(T.copy),actions:Object.freeze({close:x.close,startNewConversation:x.startNewConversation}),defaultRenderer:T.defaultRenderer})):null,conversation:T=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:Yw(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:cr(T.state),identityStatus:cr(T.identityStatus),copy:cr(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}))}))),C=e.createView({slots:y,renderDom:!1,onModelChange:()=>$(),railSections:h}),x=Object.freeze({...C.operations,close:e.close}),S=()=>(a=!0,C.setDomRenderEnabled(!0),C.element),k=T=>Object.freeze({conversations:Object.freeze(T.conversations.map(Yw)),activeConversationId:T.activeConversationId,state:cr(T.state),pendingAction:Xw(T.pendingAction),identityStatus:cr(T.identityStatus),nextCursor:T.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:cr(C.copy),actions:x,defaultRenderer:S,requestRender:()=>$(),onCleanup:I=>{d.push(I)}}),B=()=>{a=!1;let T=null;for(let A of t)if(A.renderHistoryView){try{T=A.renderHistoryView(k(C.getModel()))}catch(_){_m("renderHistoryView",_),T=null}if(T)break}let I=!T||T.contains(C.element);return a=I,C.setDomRenderEnabled(I),T??C.element};function $(){if(!(!s||o||r)){r=!0;try{p();let T=B();if(T===l)return;let I=l;l=T,e.onElementChanged(T,I)}finally{r=!1}}}return s=!0,$(),{view:C,get element(){return l??C.element},requestRender:$,dispose:()=>{o=!0,p()}}}var tI=null;function Zw(){return tI}var nI=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"]]),oI=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."]]),Dm=e=>oI.get(e)??"Conversation history is unavailable right now.";function rI(e){if(e instanceof fo)return e;if(e instanceof je){let t=nI.get(e.code)??"unavailable";return new fo(t,Dm(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new fo("unavailable",Dm("unavailable"))}function ex(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",Dm("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw rI(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=Qb(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:Qa([],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 sI=["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"],tx={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 Nm(e){if(!e)return tx;let t={...tx};for(let n of sI){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var iI="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=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(iI));if(C.length===0)return;let x=C[0],S=C[C.length-1],k=document.activeElement;h.shiftKey&&(k===x||!l.contains(k))?(h.preventDefault(),S.focus()):!h.shiftKey&&k===S&&(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 lI,OBJ as cI}from"partial-json";function dI(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(!dI(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 Fm(){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,lI|cI),s=pI(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function uI(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function $m(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Do.get(e.component);if(!s){if(Tm.includes(e.component)){Kd().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 gI(){let e=Fm();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function nx(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=nx(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 Um(e){let t=nx(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 mI=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function jm(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=mI}=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 x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,h.appendChild(x),y.appendChild(h);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let 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=`
39
+ `):""},Em=(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)"},k0=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=P0(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=dg(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=dg(n,d.completeTextTemplate,p)),{summary:p,previewText:s,isActive:l}},Lw=(e,t,n)=>{Vd(e,t,{stateSet:Fi,previewKind:"tool",iconColor:kw(n?.toolCall??{})})},Tm=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=$d("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&&Fi.has(e.id),{summary:d,previewText:p,isActive:u}=k0(e,t),m=Ud({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=za(n),E},x=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:t??{},elapsed:za(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 k=s.loadingAnimation??"none",B=o.activeTextTemplate,$=o.completeTextTemplate,T=u?B:$,I=x instanceof HTMLElement,A=(E,_)=>{h.textContent="";let W=n.name?.trim()||"tool",L=Zc(E,W),Y=0;for(let K of L){let le=K.styles.length>0?(()=>{let de=M("span",K.styles.map(ge=>`persona-tool-text-${ge}`).join(" "));return h.appendChild(de),de})():h;if(K.isDuration&&u)le.appendChild(S());else{let de=K.isDuration?za(n):K.text;_?Y=Di(le,de,Y):le.appendChild(document.createTextNode(de))}}};if(!I)if(u&&k!=="none"){let E=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",`${E}ms`),T&&A(T,!1);else if(h.classList.add(`persona-tool-loading-${k}`),h.style.setProperty("--persona-tool-anim-duration",`${E}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 _=h.textContent||d;h.textContent="",Di(h,_,0)}}else T&&A(T,!1);let D=kw(o),G=jd(m,y,{expandable:a,expanded:l,iconColor:D,metaGap:!0}),se=qd({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,se),r;let ne=M("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(ne.style.display=l?"":"none",o.contentBackgroundColor&&(ne.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(ne.style.color=o.contentTextColor),o.contentPaddingX&&(ne.style.paddingLeft=o.contentPaddingX,ne.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(ne.style.paddingTop=o.contentPaddingY,ne.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,ne.appendChild(E)}if(n.args!==void 0){let E=M("div","persona-space-y-1"),_=M("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Arguments";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",Em(W,o),W.textContent=Yc(n.args),E.append(_,W),ne.appendChild(E)}if(n.chunks&&n.chunks.length){let E=M("div","persona-space-y-1"),_=M("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Activity";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",Em(W,o),W.textContent=n.chunks.join(""),E.append(_,W),ne.appendChild(E)}if(n.status==="complete"&&n.result!==void 0){let E=M("div","persona-space-y-1"),_=M("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Result";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",Em(W,o),W.textContent=Yc(n.result),E.append(_,W),ne.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`,ne.appendChild(E)}return zd({expanded:l,header:m,toggleIcon:G,content:ne,collapsedPreview:se,iconColor:D}),r.append(m,se,ne),r};var{setLoader:eN,load:L0,provide:tN,getSync:I0}=ht({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var Iw=L0;var Rw=I0;var{setLoader:rN,load:R0}=ht({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var Pm=R0;var km=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)})}},No=new km;var Lm=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:pN,load:H0,provide:uN,getSync:W0}=ht({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),$i=null,Kd=new Set,Hw=e=>{if($i)return $i;$i=e,e.initArtifactsUi({componentRegistry:No});for(let o of Lm)No.has(o)||No.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Wo();t?e.__provideMarkdownParsers(t):_a(()=>{let o=Wo();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>Dc());let n=[...Kd];Kd.clear();for(let o of n)try{o()}catch{}return e};var Gd=()=>H0().then(Hw);var lr=()=>{if($i)return $i;let e=W0();return e?Hw(e):null},Im=e=>$i?()=>{}:(Kd.add(e),()=>{Kd.delete(e)});function wn(e){return e?.features?.artifacts?.enabled===!0}function Ww(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"),!wn(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 O0(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 Ow=["panel","seamless","detached"];function Rm(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Ow.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Hm(e){return!e||!wn(e)?!1:Rm(e)==="detached"}function bl(e,t){if(!wn(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"),O0(e),Ww(e,t);return}let n=t.features?.artifacts?.layout,o=Rm(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)}Ww(e,t)}function vl(e,t){for(let l of Ow)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"),!wn(t))return;let n=t.features?.artifacts?.layout,o=Rm(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 Bw(e,t){return!t||!wn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var B0=new Set(["__proto__","prototype","constructor"]),_0=new Set(["collapsed","card","panel","inline"]),_w=new Set(["markdown","component"]),D0=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,_s=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yd=e=>!B0.has(e),Wm=e=>typeof e=="string"&&_0.has(e),Ds=e=>Object.keys(e).length>0;function Fo(e,t,n,o){e.push({path:t,code:n,message:o})}var N0="Ignored because this key is not part of the persisted preference schema.",Qd="Ignored an unsupported value.",F0="Expected collapsed, panel, or inline.",$0='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Dw={kind:"mode",message:Qd},Ui={kind:"string",message:"Expected a CSS length string."},cr={kind:"boolean"},U0={paneWidth:Ui,paneMaxWidth:Ui,paneMinWidth:Ui,expandedPanelWidth:Ui,resizableMinWidth:Ui,resizableMaxWidth:Ui,expandLauncherPanelWhenOpen:cr,resizable:cr},j0={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:Qd},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Qd},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Qd},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:Dw,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Dw,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:cr}},layout:{kind:"object",children:U0}}}}};function Nw(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Fo(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Fo(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Fo(o,n,"invalid_value",t.message);case"mode":return Wm(e)?Un(e):Fo(o,n,"invalid_value",t.message);case"modeMap":{if(!_s(e))return Fo(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:Ps(a);Yd(a)&&(r?r.has(a):D0.test(d))?Wm(l)?s[d]=Un(l):Fo(o,`${n}.${a}`,"invalid_value",F0):Fo(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":$0)}return Ds(s)?s:void 0}case"object":{if(t.bareMode&&Wm(e))return Un(e);if(!_s(e))return Fo(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))&&Fo(o,s(l),"unknown_key",N0);let a={};for(let l of r){let d=t.children[l],p=Nw(e[l],d,s(l),o);if(d.deprecated&&e[l]!==void 0&&Fo(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=_s(m)&&_s(p)?{...m,...p}:p}return Ds(a)?a:void 0}}}function Fw(e){let t=[];return{preferences:(e===null?void 0:Nw(e,j0,"",t))??{},issues:t}}function ji(e){if(Array.isArray(e))return e.map(ji);if(!_s(e))return e;let t={};for(let[n,o]of Object.entries(e))Yd(n)&&o!==void 0&&(t[n]=ji(o));return t}function $w(e,t){let n=ji(e);for(let[o,r]of Object.entries(t)){if(!Yd(o)||r===void 0)continue;let s=n[o];n[o]=_s(s)&&_s(r)?$w(s,r):ji(r)}return n}function q0(e){let t={},n;for(let r of e){let s=Fw(r).preferences;n=Uw(n,s.artifacts?.display),t=$w(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function z0(e,t){if(t===void 0)return e===void 0?void 0:ji(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}:{},...Ds(r)?{byMediaType:r}:{}};return Ds(s)?s:void 0}function Uw(e,t){if(t===void 0)return e===void 0?void 0:ji(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=z0(n.files,t.files),a={...o?{default:o}:{},...Ds(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Ds(a)?a:void 0}function jw(e={},t){let n=q0(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=Uw(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 Xd(e){let t=e.preferences;return!t||!Ds(t)?e:{...e,features:jw(e.features??{},[t])}}function V0(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 K0(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 G0(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Q0(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Om(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 qw(e,t,n,o,r,s,a=200){let l=V0(r,200),d=Q0(t,n,o,a);d=Math.max(l,d);let p=K0(s);return p!==null&&(d=Math.min(d,p)),G0(e,l,d)}var{setLoader:vN,load:Y0,provide:CN,getSync:X0}=ht({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var zw=Y0;var Vw=X0;var Bm=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()}},Jd=new Bm;var Kw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),J0=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Gw=(e,t,n)=>{if(!Kw(e)||!Kw(t)||J0.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]=Gw(e[r],t[r],s)}return o};function Zd(e,t){let n=Gw(e,t,"");return el(n)}var Qw=()=>{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 Z0=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},eI=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},ep=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Z0(e),n=eI(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),qi={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)}}},Yw=e=>Array.isArray(e)?e.map(t=>String(t)):[],tp=e=>{let t=new Set(Yw(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Yw(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 tI=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}},nI=e=>e.map(t=>({...t,streaming:!1})),oI=e=>e.map(t=>({...t,status:"complete"})),Dm=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?tI(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?nI(n.messages):void 0,artifacts:n.artifacts?oI(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 rI=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")},Xw=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 rI(e)},sI=async(e,t)=>{let n=await Xw(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await Xw(`${e}\0${t}`)}`}};var Jw=(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,D)=>{if(l||A===p)return;let G=p;p=A,d+=1;let se={previousToken:G,token:A,source:D,revision:d};for(let ne of m)ne(se)},S=A=>{l||A.key!==null&&A.key!==o||C(A.key===null?null:A.newValue??null,"external")},x=(async()=>{let A=await sI(e,t);o=A.storageKey,r=A.leaseKey,s=A.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",S)})(),k=A=>new Promise(D=>setTimeout(D,A)),B=()=>{let A=y();if(!A)return null;try{let D=A.getItem(r);if(!D)return null;let G=JSON.parse(D);return typeof G?.expiresAt=="number"&&typeof G?.ownerNonce=="string"?G:null}catch{return null}},$=A=>{let D=y();if(D)try{B()?.ownerNonce===A&&D.removeItem(r)}catch{}},T=A=>new Promise(D=>{let G=setTimeout(se,A);function se(){clearTimeout(G),window.removeEventListener("storage",ne),D()}function ne(E){(E.key===null||E.key===r)&&se()}window.addEventListener("storage",ne)}),I=async A=>{let D=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;Date.now()<G;){let se=y();if(!se)break;let ne=Date.now(),E=B();if(E&&E.expiresAt>ne&&E.ownerNonce!==D){await T(Math.min(E.expiresAt-ne,500));continue}try{se.setItem(r,JSON.stringify({ownerNonce:D,expiresAt:ne+1e4}))}catch{a=!0;break}if(await k(20+Math.random()*40),B()?.ownerNonce!==D){await T(500);continue}u=D;try{return await A()}finally{u=null,$(D)}}return A()};return{ready:x,async get(){return await x,C(h(),"external"),p},async set(A){await x;let D=y();if(D)try{D.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 D=globalThis.navigator?.locks;return D?.request?D.request(s,()=>A()):y()?I(A):A()},matches(A,D,G){return A===e&&D===t&&G===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",S),u&&$(u)}}};var{setLoader:LN,load:iI}=ht({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var Nm=iI;var Fm=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},dr=e=>Object.freeze({...e}),Zw=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),ex=e=>e?dr(e):null;function tx(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){Fm("renderHistoryView cleanup",I)}},u=(T,I)=>{for(let A of t){let D=A[T];if(D)try{let G=D(I);if(G)return G}catch(G){Fm(T,G)}}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:ex(T.pendingAction),copy:dr(T.copy),actions:Object.freeze({close:S.close,startNewConversation:S.startNewConversation}),defaultRenderer:T.defaultRenderer})):null,conversation:T=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:Zw(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: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),k=T=>Object.freeze({conversations:Object.freeze(T.conversations.map(Zw)),activeConversationId:T.activeConversationId,state:dr(T.state),pendingAction:ex(T.pendingAction),identityStatus:dr(T.identityStatus),nextCursor:T.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:dr(C.copy),actions:S,defaultRenderer:x,requestRender:()=>$(),onCleanup:I=>{d.push(I)}}),B=()=>{a=!1;let T=null;for(let A of t)if(A.renderHistoryView){try{T=A.renderHistoryView(k(C.getModel()))}catch(D){Fm("renderHistoryView",D),T=null}if(T)break}let I=!T||T.contains(C.element);return a=I,C.setDomRenderEnabled(I),T??C.element};function $(){if(!(!s||o||r)){r=!0;try{p();let T=B();if(T===l)return;let I=l;l=T,e.onElementChanged(T,I)}finally{r=!1}}}return s=!0,$(),{view:C,get element(){return l??C.element},requestRender:$,dispose:()=>{o=!0,p()}}}var aI=null;function nx(){return aI}var lI=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."]]),$m=e=>cI.get(e)??"Conversation history is unavailable right now.";function dI(e){if(e instanceof ho)return e;if(e instanceof Ue){let t=lI.get(e.code)??"unavailable";return new ho(t,$m(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new ho("unavailable",$m("unavailable"))}function ox(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 ho("unsupported_scope",$m("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw dI(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=Zb(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:Qa([],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 pI=["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"],rx={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 Um(e){if(!e)return rx;let t={...rx};for(let n of pI){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var uI="button:not([disabled])";function np(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(uI));if(C.length===0)return;let S=C[0],x=C[C.length-1],k=document.activeElement;h.shiftKey&&(k===S||!l.contains(k))?(h.preventDefault(),x.focus()):!h.shiftKey&&k===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 gI,STR as mI,OBJ as fI}from"partial-json";function hI(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function yI(e,t){if(!hI(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 jm(){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=gI(n,mI|fI),s=yI(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function bI(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function qm(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=No.get(e.component);if(!s){if(Lm.includes(e.component)){Gd().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 vI(){let e=jm();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function sx(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 op(e){let t=sx(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 zm(e){let t=sx(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 CI=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Vm(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=CI}=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 k=[];for(let A=1;A<=5;A++){let D=document.createElement("button");D.type="button",D.className="persona-feedback-rating-btn persona-feedback-star-btn",D.setAttribute("role","radio"),D.setAttribute("aria-checked","false"),D.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${p[A-1]}`),D.title=p[A-1],D.dataset.rating=String(A),D.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
- `,_.addEventListener("click",()=>{m=A,k.forEach((G,ie)=>{let ne=ie<A;G.classList.toggle("selected",ne),G.setAttribute("aria-checked",ie===A-1?"true":"false")})}),k.push(_),S.appendChild(_)}y.appendChild(S);let B=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=s,B.rows=3,B.setAttribute("aria-label","Additional comments"),A.appendChild(B),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 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){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let A=B?.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)}}),$.appendChild(T),$.appendChild(I),y.appendChild($),u.appendChild(y),u}function qm(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 x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,C.appendChild(x);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,C.appendChild(S),h.appendChild(C);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 B=document.createElement("div");B.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,B.appendChild($),B.appendChild(T);let I=document.createElement("div");I.className="persona-feedback-numbers";let A=[];for(let E=0;E<=10;E++){let D=document.createElement("button");D.type="button",D.className="persona-feedback-rating-btn persona-feedback-number-btn",D.setAttribute("role","radio"),D.setAttribute("aria-checked","false"),D.setAttribute("aria-label",`Rating ${E} out of 10`),D.textContent=String(E),D.dataset.rating=String(E),E<=6?D.classList.add("persona-feedback-detractor"):E<=8?D.classList.add("persona-feedback-passive"):D.classList.add("persona-feedback-promoter"),D.addEventListener("click",()=>{y=E,A.forEach((W,L)=>{W.classList.toggle("selected",L===E),W.setAttribute("aria-checked",L===E?"true":"false")})}),A.push(D),I.appendChild(D)}k.appendChild(B),k.appendChild(I),h.appendChild(k);let _=null;if(d){let E=document.createElement("div");E.className="persona-feedback-comment-container",_=document.createElement("textarea"),_.className="persona-feedback-comment",_.placeholder=s,_.rows=3,_.setAttribute("aria-label","Additional comments"),E.appendChild(_),h.appendChild(E)}let G=document.createElement("div");G.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 ne=document.createElement("button");return ne.type="button",ne.className="persona-feedback-btn persona-feedback-btn-submit",ne.textContent=a,ne.addEventListener("click",async()=>{if(y===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}ne.disabled=!0,ne.textContent="Submitting...";try{let E=_?.value.trim()||void 0;await t(y,E),m.remove()}catch(E){ne.disabled=!1,ne.textContent=a,console.error("[NPS Feedback] Failed to submit:",E)}}),G.appendChild(ie),G.appendChild(ne),h.appendChild(G),m.appendChild(h),m}var qi="persona-chat-history",yI=30*1e3,bI=641,zi="data-persona-composer-reason",vI={"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 CI(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=vI[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 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 xI(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var zm=e=>!e||typeof e!="object"?{}:{...e},ix=e=>e.map(t=>({...t,streaming:!1})),ax=(e,t,n)=>{let o=e?.markdown?$c(e.markdown):null,r=Ju(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=Ho()!==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?sb(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 lx(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 SI=(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},AI=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:SI(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Vm=(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=el(t),r=()=>{Ev({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=Yd(o);let a=Xd.getForInstance(o.plugins),l=PC(e),d=[],p=!1,u=Aw(()=>o),m=null,y=null,h=null,C=!1,x=null,S=i=>{m=i,i.initApprovalUi({webMcpToolTitle:yi});let c=i.createBuiltInApprovalPlugin();y=c.plugin,h=c.teardown},k=()=>{if(m)return m;let i=kw();return i?(S(i),i):(Pw().then(c=>{C||m||(S(c),x?.())}).catch(()=>{}),null)},B=!1,$=!1,T=null,I=(i,c,g,f)=>{if(!i.querySelector("[data-tv-form]"))return;let b=jw();if(b){b.enhanceWithForms(i,c,g,f);return}Uw().then(()=>{B||$||!T||($=!0,T())}).catch(()=>{})};o.components&&Do.registerAll(o.components);let A=Vw(),G=o.persistState===!1?null:o.storageAdapter??Om(),ie={},ne=null,E,D=new Promise(i=>{E=i}),W,L=!1,Y=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&&(L=!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")ne=i.then(c=>Y(c??{messages:[],metadata:{}}));else{let g=Y(i??{messages:[],metadata:{}});g.metadata&&(ie=zm(g.metadata)),g.messages?.length&&(o={...o,initialMessages:g.messages}),g.artifacts?.length&&(o={...o,initialArtifacts:g.artifacts,initialSelectedArtifactId:g.selectedArtifactId??null}),W=g.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=Y({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}ne||E();let K=()=>ie,le=i=>{ie=i({...ie})??{},ia()},de=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zd],ge=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ji.message,ji.messageAndClick],Me=ep({parsers:de,handlers:ge,getSessionMetadata:K,updateSessionMetadata:le,emit:A.emit,documentRef:typeof document<"u"?document:null});Me.syncFromMetadata();let fe=o.launcher?.enabled??!0,_e=o.launcher?.autoExpand??!1,it=o.autoFocusInput??!1,be=_e,j=fe,De=o.layout?.header?.layout,Ne=!1,we=()=>Fr(o),ke=()=>fe||we(),he=we()?!1:fe?_e:!0,dt=!1,Ie=null,Ut=()=>{dt=!0,Ie&&clearTimeout(Ie),Ie=setTimeout(()=>{dt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),dt=!1)},1e4)},at=ax(o,Me,Ut),nn=o.features?.showReasoning??!0,wn=o.features?.showToolCalls??!0,Wt=o.features?.showEventStreamToggle??!1,jr=o.features?.scrollToBottom??{},xn=o.features?.scrollBehavior??{},bo=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",qr=`${bo()}event-stream`,pn=null,Ki=o.features?.eventStream?.maxEvents??2e3,Tt=null,gt=null,ro=null,Sl=!1,R=null,ee=!1,v=null,N=0,F=(i,c)=>{Tt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},U=(i,c)=>{gt?.processEvent(i,c),Tt?F(i,c):ro&&(ro.length>=Ki&&ro.shift(),ro.push({type:i,payload:c}))},Z=()=>{Tt||!Wt||(ro??(ro=[]),Mm().then(i=>{if(Sl||Tt||!Wt)return;pn=new i.EventStreamStore(qr),Tt=new i.EventStreamBuffer(Ki,pn),gt=gt??new i.ThroughputTracker,pn.open().then(()=>Tt?.restore()).catch(g=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",g)});let c=ro??[];ro=null;for(let g of c)gt?.processEvent(g.type,g.payload),F(g.type,g.payload)}).catch(()=>{}))};Wt&&Z();let te=!1,ae=null,Se=()=>{},yt=()=>{},qe=()=>{},Ot=()=>{},St=()=>{},zr=()=>ee||te&&ae==="panel",In={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)}},jt=o.statusIndicator??{},un=i=>i==="idle"?jt.idleText??$t.idle:i==="connecting"?jt.connectingText??$t.connecting:i==="connected"?jt.connectedText??$t.connected:i==="error"?jt.errorText??$t.error:i==="paused"?jt.pausedText??$t.paused:i==="resuming"?jt.resumingText??$t.resuming:$t[i];function sn(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 Rn=Sw({config:o,showClose:ke()}),{wrapper:Ge,panel:Ae,pillRoot:Yt}=Rn.shell,Fe=Rn.panelElements,{container:ue,body:oe,messagesWrapper:Le,starterSuggestions:fp,transcriptSuggestions:Gi,suggestions:pr,textarea:ce,sendButton:Ee,composerForm:so,statusText:ot,welcomeHost:Sn,welcomeIconHolder:Kx,greetingHost:Hn,introKicker:Gx,introTitle:Qx,introSubtitle:Yx,closeButton:Ue,iconHolder:Pt,headerTitle:ur,headerSubtitle:Vr,header:Te,footer:Re,actionsRow:Xx}=Fe,hp=Fe.leftActions,Al=Fe.rightActions,vo=Fe.sendButtonWrapper,af=Fe.setSendButtonMode,re=Fe.micButton,Wn=Fe.micButtonWrapper,At=Fe.attachmentButton,An=Fe.attachmentButtonWrapper,bt=Fe.attachmentInput,Mn=Fe.attachmentPreviewsContainer;ue.classList.add("persona-relative"),oe.classList.add("persona-relative");let Jx=12,Qi=()=>jr.label??"",Zx=()=>jr.iconName??"arrow-down",eS=()=>jr.enabled!==!1,On=()=>xn.mode??"anchor-top",gr=()=>On()==="follow"||On()==="anchor-top"&&sa,Yi=()=>xn.anchorTopOffset??16,tS=()=>xn.restorePosition??"bottom",lf=()=>xn.pauseOnInteraction===!0,cf=()=>xn.showActivityWhilePinned!==!1,df=()=>xn.announce===!0,yp=()=>xn.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 Xi=M("span","persona-flex persona-items-center"),bp=M("span",""),Kr=M("span","");Kr.setAttribute("data-persona-scroll-to-bottom-count",""),Kr.style.display="none",_t.append(Xi,bp,Kr),ue.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",oe.appendChild(Kn);let $o=M("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"}),ue.appendChild($o);let Ji=null,Ml=null,El=i=>{!df()||!i||(Ml=i,Ji===null&&(Ji=setTimeout(()=>{Ji=null,Ml&&df()&&($o.textContent=Ml),Ml=null},400)))},Tl="empty",Pl=0,vp=()=>Pl||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,Gr=()=>{let c=Re.style.display==="none"?0:Re.offsetHeight;_t.style.bottom=`${c+vp()+Jx}px`};Gr();let Cp=()=>{qs||(Re.style.marginBottom=Pl>0?`${Pl}px`:"")},kl=()=>{let i=Qg(o,we()),c=_o(o),f=Re.style.display==="none"?0:Re.offsetHeight,b=c.anchor==="center"&&Tl==="empty"?rl(c.anchorComposerTop)??rl("44%"):null,w=b===null||we()?0:MC({columnHeight:ue.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`),Pl=i==="block"?w:0,Cp(),Gr()},pf=()=>{let i=!!Qi();_t.setAttribute("aria-label",Qi()||"Jump to latest"),_t.title=Qi(),_t.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Xi.innerHTML="";let c=pe(Zx(),"14px","currentColor",2);c?(Xi.appendChild(c),Xi.style.display=""):Xi.style.display="none",bp.textContent=Qi(),bp.style.display=i?"":"none"};pf();let Je=null,Bt=null,xe=Cv(),nS=i=>{try{ue.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};xe.subscribe(nS);let Co=()=>{xe.setText(ce?.value??"")},Qr=()=>{xe.setMentionRefs(Bt?.getMentionRefs()??[])},oS=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}),uf=i=>{let c=Object.freeze(i.map(oS));xe.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(g){console.error("[AgentWidget] attachments.onChange failed:",g)}Vp()};xe.setSelectedModelId(o.composer?.selectedModelId);let Zi=()=>o.composer?.modes??[],Fs=()=>Kv(Zi(),o.composer?.modeGroups);{let i=vd(o.composer?.defaultActiveModeIds??[],Zi());i.length&&xe.setActiveModeIds(i)}function gf(i){if(xe.getState().selectedModelId!==i){xe.setSelectedModelId(i),mr?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function Ll(i){xe.setActiveModeIds(i),Uo?.render(i,Fs()),$s.forEach(c=>c.repaint()),xo?.resolve(),tc(),io()}function wp(i){Ll(Gv(xe.getState().activeModeIds,i,Zi(),o.composer?.modeGroups))}let mr=null,xp=null,Uo=null,$s=new Map,fr=null;function wo(i){xe.setQuote(i),fr?.render(xe.getState().quote),io(),sh()}let mf=!1;function Sp(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!mf&&o.debug===!0&&(mf=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let hr=null;function Us(i){xe.setPendingSubmission(i),hr?.render(xe.getState().pendingSubmission),io()}let rS=i=>{let c=$s.get(i);if(c)return c;let g=Xv({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===i),getModes:()=>Zi().filter(f=>f.groupId===i),getActiveIds:()=>xe.getState().activeModeIds,onSelect:f=>wp(f)});return $s.set(i,g),g},sS=()=>{let i=[],c=xe.getState().activeModeIds,g=new Set;if(Zi().forEach((f,b)=>{if(bd(f.groupId,o.composer?.modeGroups)){let w=f.groupId;if(g.has(w))return;g.add(w);let O=rS(w);O.action.order=Ug(b),O.action.label=o.composer?.modeGroups?.find(z=>z.id===w)?.label??w,i.push(O.action);return}i.push({id:zv(f.id),kind:"button",placement:"start",order:Ug(b),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:c.includes(f.id),onSelect:()=>wp(f.id)})}),o.composer?.models?.length&&!a.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!mr||xp!==f)&&(xp=f,mr=jv({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>xe.getState().selectedModelId,onSelect:b=>gf(b),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(mr.action)}return i},Ap=null,ff=a.find(i=>i.renderHeader);if(ff?.renderHeader){let i=ff.renderHeader({config:o,defaultRenderer:()=>{let c=$r({config:o,showClose:ke()});return Ri(ue,c,o),c.header},onClose:()=>pt(!1,"user")});if(i){let c=Te;c&&(c.replaceWith(i),Te=i,Rn.header.element=i)}}let hf=()=>{R&&(oe.style.display="none",Re.parentNode?.insertBefore(R.element,Re),R.update())},Mp=()=>{if(!Tt){Z();return}if(ee=!0,R?hf():Mm().then(c=>{R||!ee||!Tt||(R=c.createEventStreamView({buffer:Tt,getFullHistory:()=>Tt.getAllFromStore(),onClose:()=>js(),config:o,plugins:a,getThroughput:()=>gt?.getMetric()??{status:"idle"},renderIconByName:pe}),hf())}).catch(()=>{js()}),et){et.style.boxShadow=`inset 0 0 0 1.5px ${bn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(g=>g&&et.classList.add(g))}let i=()=>{if(!ee)return;let c=Date.now();c-N>=200&&(R?.update(),N=c),v=requestAnimationFrame(i)};N=0,v=requestAnimationFrame(i),zt(),A.emit("eventStream:opened",{timestamp:Date.now()})},js=()=>{if(ee){if(ee=!1,R&&R.element.remove(),oe.style.display="",et){et.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&et.classList.remove(c))}v!==null&&(cancelAnimationFrame(v),v=null),zt(),A.emit("eventStream:closed",{timestamp:Date.now()})}},et=null;if(Wt){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:"");et=M("button",c),et.style.width="28px",et.style.height="28px",et.style.color=bn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let g=Ht(ox,"18px","currentColor",1.5);g&&et.appendChild(g);let f=Fe.clearChatButtonWrapper,b=Fe.closeButtonWrapper,w=f||b;w&&w.parentNode===Te?Te.insertBefore(et,w):Te.appendChild(et),et.addEventListener("click",()=>{ee?js():Mp()})}let yf=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??ir).join(","),b.multiple=(c.maxFiles??4)>1,b.style.display="none",b.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(b)}},qs=!1,bf=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:()=>Ly(),storage:u(c.id),onSubmit:b=>{!P||P.isStreaming()||Pc(b.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{Sr()||bt?.click()},models:g?.models,selectedModelId:xe.getState().selectedModelId??g?.selectedModelId,onModelChange:b=>gf(b),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Ap?.()}:void 0})},vf=bf(()=>Wi({config:o}).footer);vf&&(Rn.replaceComposer(vf),Re=Rn.composer.footer,qs=!0);let tt=null,iS=i=>{so=i.form,ce=i.input,vo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Ee=i.sendButton),i.micButton&&(re=i.micButton,Wn=i.micButton.parentElement),i.found.status&&(ot=i.found.status),i.found.suggestions&&(pr=i.found.suggestions),i.attachmentButton&&(At=i.attachmentButton,An=i.attachmentButton.parentElement),bt=i.attachmentInput??null,Mn=i.attachmentPreviews??null,i.found.actionsRow&&(Xx=i.found.actionsRow),hp=i.found.actionsStart,Al=i.found.actionsEnd};function Ep(){let i=ce;if(!i)return;let c=o.composer?.inputAttributes,g=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;dd(i,c),g&&i.setAttribute("aria-label",g),cd(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:tl(i)}),Iv(i,ld(o.composer?.maxLines,we()?5:3))}let Cf=i=>{tt=xv(i,{debug:o.debug===!0}),tt&&iS(tt),Ep()};yf(Re),Cf(Re),Co();let ea=Dr(o,we());ea&&(Le.style.maxWidth=ea,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%",Hn.style.maxWidth=ea,Hn.style.marginLeft="auto",Hn.style.marginRight="auto",Hn.style.width="100%",fp.style.maxWidth=ea,Gi.style.maxWidth=ea,Gi.style.marginLeft="auto",Gi.style.marginRight="auto",Gi.style.width="100%");let wf=()=>{let i=Dr(o,we());if(!(!i||we()))for(let c of[so,pr,Mn,ot])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};wf();let xf=()=>{!o.attachments?.enabled||!bt||!Mn||(Je?Je.remountPreviews(Mn):(Je=Mi.fromConfig(o.attachments,uf),Je.setPreviewsContainer(Mn)),tt?.addListener(bt,"change",i=>{let c=i.target;Je?.handleFileSelect(c.files),c.value=""}),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(lx(o.attachments.dropOverlay)))};xf();let aS=()=>Bt?.prefetch(),Sf=()=>{if(!o.contextMentions?.enabled||!ce)return;let i=tt?.header??null,c=i?$g(i):void 0;if(Bt=yC({config:o,textarea:ce,anchor:so??ce,getMessages:()=>P.getMessages(),liveRegionHost:ue,chipRow:c}),Bt&&!c){let g=ce;g.parentElement?.insertBefore(Bt.contextRow,g)}};Sf();let xo=null,lS={getState:()=>xe.getState(),getValue:()=>ce?.value??"",setValue:i=>{ce&&(ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),Co())},submit:()=>{aC(tt?.form??null)},openAttachmentPicker:()=>{Sr()||bt?.click()},toggleVoice:()=>{Ap?.()},requestRender:()=>xo?.resolve()},cS=()=>{let i=[];return(Bt?.affordanceButtons??[]).forEach((g,f)=>{i.push({id:`core:mention-${f}`,placement:"start",order:Oo.mention+f,element:g,managed:!0})}),An&&i.push({id:"core:attachment",placement:"start",order:Oo.attachment,element:An}),Wn&&i.push({id:"core:mic",placement:"end",order:Oo.mic,element:Wn}),vo&&i.push({id:"core:send",placement:"end",order:Oo.send,element:vo}),i},Af=()=>{xo?.destroy(),xo=Fv({getBindings:()=>tt,collect:()=>({builtIns:cS(),configActions:[...sS(),...o.composer?.actions??[]],plugins:a,contributionContext:{config:o,getState:()=>xe.getState(),requestRender:()=>xo?.resolve()},debug:o.debug===!0}),actionContext:lS,getState:()=>xe.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),xo.resolve()};Af();let Tp=()=>{if(Uo?.destroy(),Uo=null,!Fs().length)return;let i=tt?.header;i&&(Uo=qv({row:$g(i),onRemove:c=>wp(c),initialIds:xe.getState().activeModeIds}),Uo.render(xe.getState().activeModeIds,Fs()))};Tp();let Mf=()=>{fr?.destroy(),fr=null,hr?.destroy(),hr=null;let i=tt?.header;i&&(fr=Jv({onDismiss:()=>wo(void 0)}),i.appendChild(fr.element),fr.render(xe.getState().quote),Sp()==="defer-one"&&(hr=Zv({onEdit:()=>BA(),onRemove:()=>Us(void 0)}),i.appendChild(hr.element),hr.render(xe.getState().pendingSubmission)))};Mf();let Pp=sC(),dS=()=>{let i=tt?.header?.querySelector(Fg);if(i)return i.childElementCount>0;let c=xe.getState();return c.mentionRefs.length>0||vd(c.activeModeIds,Fs()).length>0},Ef=()=>!1;function io(){let i=xe.getState(),c=Pp.observe(iC(ce),i.text);Re.toggleAttribute("data-persona-composer-compact",rC({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:dS(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0,dictationActive:Ef()}))}function Tf(){o.composer?.layout==="single-row"&&!we()?Re.setAttribute("data-persona-composer-layout","single-row"):Re.removeAttribute("data-persona-composer-layout")}Tf(),xe.subscribe(()=>{xo?.sync(),Vp(),Zl(),io(),sh()}),Zl();let Pf=!1,pS=i=>{if(Pf||o.debug!==!0)return;let c=["messages","composer"].filter(g=>i[g]);c.length&&(Pf=!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??{};pS(i);let c=f=>{switch(f){case"body-top":return oe.querySelector("[data-persona-intro-card]");case"messages":return Le;case"footer-top":return pr;case"composer":return so;case"footer-bottom":return ot;default:return null}},g=(f,b)=>{switch(f){case"header-left":case"header-center":case"header-right":if(f==="header-left")Te.insertBefore(b,Te.firstChild);else if(f==="header-right")Te.appendChild(b);else{let w=Te.querySelector(".persona-flex-col");w?w.parentNode?.insertBefore(b,w.nextSibling):Te.appendChild(b)}break;case"body-top":{let w=oe.querySelector("[data-persona-intro-card]");w?w.replaceWith(b):oe.insertBefore(b,oe.firstChild);break}case"body-bottom":oe.appendChild(b);break;case"footer-top":pr.replaceWith(b);break;case"footer-bottom":ot.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 kf=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")Di.has(b)?Di.delete(b):Di.add(b),Mw(b,f);else if(w==="tool")Ni.has(b)?Ni.delete(b):Ni.add(b),Tw(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)};Le.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),kf(i))}),Le.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),kf(i))}),Le.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let g=Le.getRootNode(),f=typeof g.getSelection=="function"?g.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let b=f.toString(),w=kC(b);!w||w===b||(c.setData("text/plain",w),i.preventDefault())});let kp=new Map,Lf=null,If="idle",uS={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},gS=(i,c)=>{let{icon:g,label:f}=uS[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))},Rf=()=>{Le.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let f=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;gS(c,f&&f===Lf?If:"idle")})};Le.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=P.getMessages().find(q=>q.id===b);if(z&&In.onCopy){let q=z.content||"";navigator.clipboard.writeText(q).then(()=>{g.classList.add("persona-message-action-success");let V=Ht(rx,14,"currentColor",2);V&&(g.innerHTML="",g.appendChild(V)),setTimeout(()=>{g.classList.remove("persona-message-action-success");let X=Ht(sx,14,"currentColor",2);X&&(g.innerHTML="",g.appendChild(X))},2e3)}).catch(V=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",V)}),In.onCopy(z)}}else if(w==="read-aloud")P.toggleReadAloud(b);else if(w==="upvote"||w==="downvote"){let z=(kp.get(b)??null)===w,q=w==="upvote"?"thumbs-up":"thumbs-down";if(z){kp.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",X=f.querySelector(`[data-action="${V}"]`);if(X){X.classList.remove("persona-message-action-active");let ut=pe(V==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ut&&(X.innerHTML="",X.appendChild(ut))}kp.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=P.getMessages().find(ct=>ct.id===b);Xe&&In.onFeedback&&In.onFeedback({type:w,messageId:Xe.id,message:Xe})}}else if(w==="regenerate")Il?.regenerate(b);else if(w==="edit")Il?.edit(b);else if(w==="quote")Il?.quote(b);else if(w?.startsWith(Bd)){let O=w.slice(Bd.length),z=o.messageActions?.custom?.find(V=>V.id===O),q=P.getMessages().find(V=>V.id===b);if(!z||!q)return;try{z.onSelect(q)}catch(V){console.error(`[AgentWidget] messageActions.custom "${O}" onSelect failed:`,V)}}});let Il=null;Le.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 O=w==="approve"?"approved":"denied",q=P.getMessages().find(X=>X.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"?P.resolveWebMcpApproval(b,O):P.resolveApproval(q.approval,O)});let ze=null,Hf=!1,ta=null,Yr=()=>{},na="none",Rl=null,Gn={artifacts:[],selectedId:null},jo=!1,ao=!1,oa=!1,zs=!1,Wf=()=>zs||Gn.artifacts.some(i=>or(o.features?.artifacts,i)==="panel"),Hl=()=>Gn.artifacts.length>0&&!jo&&Wf(),lt={current:null},Lp=(i,c)=>{let g=P.getArtifactById(c),f=g?.markdown,b=g?.title||"artifact",w=g?.file,O=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=P.getMessages().find(me=>me.id===V);if(se?.rawContent)try{let me=JSON.parse(se.rawContent);f=me?.props?.markdown,b=me?.props?.title||b,me?.props?.file&&typeof me.props.file=="object"&&(w=me.props.file),!g&&typeof me?.props?.artifactType=="string"&&(O=me.props.artifactType)}catch{}}}return{markdown:f,title:b,file:w,artifactType:O}};Le.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:O,file:z}=Lp(g,f);if(!w)return;let q=ar();q&&q.triggerArtifactDownload(q.downloadInfoFor({title:O,markdown:w,file:z}))}),Le.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]"),O=b?b.getAttribute("data-artifact-inline"):w?.getAttribute("data-open-artifact")??null,q=(b?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ct=>ct.id===f);if(!q)return;let{markdown:V,title:X,file:se,artifactType:me}=Lp(g,O??""),Xe={artifactId:O,title:X,artifactType:me,markdown:V,file:se};try{Promise.resolve(q.onClick(Xe)).catch(()=>{})}catch{}}),Le.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),w=ar();if(!w)return;let O="";if(b)O=w.artifactCopyText(b);else{let{markdown:z,file:q,artifactType:V}=Lp(g,f);V==="markdown"&&(O=w.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:z??"",...q?{file:q}:{}}))}O&&navigator.clipboard.writeText(O).then(()=>{let z=Ht(rx,16,"currentColor",2);z&&(g.replaceChildren(z),setTimeout(()=>{let q=Ht(sx,16,"currentColor",2);q&&g.replaceChildren(q)},1500))}).catch(()=>{})}),Le.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,zs=!0,ao=!0,oa=!0,P.selectArtifact(f),lo())}),Le.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,zs=!0,P.selectArtifact(f),lo())}),Le.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 Vs=Fe.composerOverlay,Ks=(i,c,g)=>{let f=c.trim();if(!f||!lt.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})),Is(Vs,b);let O=lt.current.getMessages().find(z=>z.toolCall?.id===b);O?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(O,g.structured??f):lt.current.sendMessage(f)},Xr=i=>{let c=lt.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:Kc(i,f),currentIndex:no(i)})},Of=i=>Object.entries(i).map(([c,g])=>`${c}: ${Array.isArray(g)?g.join(", "):g}`).join(" | "),Ip=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=no(i),g=vi(i);if(c>=g-1)return;let f=lt.current?.getMessages().find(b=>b.toolCall?.id===i.getAttribute("data-tool-call-id"));f&&(Gc(i,f,o,c+1),Xr(i))};Vs.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})),Is(Vs,w);let O=lt.current?.getMessages().find(z=>z.toolCall?.id===w);O?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(O),lt.current?.resolveAskUserQuestion(O,"(dismissed)"));return}if(b==="pick"){let w=g.getAttribute("data-option-label");if(!w)return;let O=f.getAttribute("data-multi-select")==="true",z=Wr(f);if(z&&O){let q=Ls(f)[no(f)],V=new Set(Array.isArray(q)?q:[]);V.has(w)?V.delete(w):V.add(w),Or(f,Array.from(V)),Xr(f);return}if(z){Or(f,w),Xr(f),Ip(f);return}if(O){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=sg(f).length===0);return}Ks(f,w,{source:"pick",values:[w]});return}if(b==="submit-multi"){let w=sg(f);if(w.length===0)return;Ks(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 O=f.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!O.trim())return;if(Wr(f)){Or(f,O.trim()),Xr(f),Ip(f);return}Ks(f,O,{source:"free-text"});return}if(b==="next"||b==="back"){if(!lt.current)return;let w=f.getAttribute("data-tool-call-id")??"",O=lt.current.getMessages().find(se=>se.toolCall?.id===w);if(!O)return;let q=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(q){let se=Ls(f)[no(f)];(typeof se!="string"||se!==q)&&Or(f,q)}let V=b==="next"?1:-1,X=no(f)+V;Gc(f,O,o,X),Xr(f);return}if(b==="submit-all"){if(!lt.current)return;let w=f.getAttribute("data-tool-call-id")??"",O=lt.current.getMessages().find(se=>se.toolCall?.id===w);if(!O)return;let q=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";q&&Or(f,q);let V=Kc(f,O);lt.current.persistAskUserQuestionProgress(O,{answers:V,currentIndex:no(f)});let X=Of(V);Ks(f,X||"(submitted)",{source:"submit-all",structured:V});return}if(b==="skip"){if(!lt.current)return;let w=f.getAttribute("data-tool-call-id")??"",O=lt.current.getMessages().find(me=>me.toolCall?.id===w);if(!O)return;let z=Wr(f),q=no(f),V=vi(f),X=q>=V-1;if(!z){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:w},bubbles:!0,composed:!0})),Is(Vs,w),O.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(O),lt.current.resolveAskUserQuestion(O,"(dismissed)"));return}Or(f,"");let se=f.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),X){let me=Kc(f,O),Xe=Of(me);Ks(f,Xe||"(skipped)",{source:"submit-all",structured:me});return}Gc(f,O,o,q+1),Xr(f);return}}),Vs.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()),Xr(f),Ip(f);return}Ks(f,b,{source:"free-text"})}});let Bf=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=Vs.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",Bf);let So=null,vt=null,ra=null,Wl=null,Ol=()=>{},_f=!1,Bl="",_l="";function Rp(){Wl?.(),Wl=null}let mS=()=>{let i=ri&&bs?.isConnected?bs:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},Df=()=>{if(!So||!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=So.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 w=Rm(So,c),O=f.offsetWidth+w/2-b/2;vt.style.left=`${Math.max(0,O)}px`},Dl=()=>{},fS=()=>{let i=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,g=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>g?!1:fe||Et(o)},Nl=()=>!Cn(o)||!Hl()||e.classList.contains("persona-artifact-narrow-host")||fS()||(e.ownerDocument.defaultView??window).innerWidth<bI?"none":Lm(o)?"detached":"welded",lo=()=>{if(!ze||!Cn(o))return;bl(e,o),vl(e,o),Dl();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=Ae.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let g=Hl();ze.setVisible(g),ze.update(Gn),jo?(ze.setMobileOpen(!1),ze.element.classList.add("persona-hidden"),ze.backdrop?.classList.add("persona-hidden"),ao=!1,oa=!1):Gn.artifacts.length>0&&Wf()?(ze.element.classList.remove("persona-hidden"),ze.setMobileOpen(!0)):(ze.setMobileOpen(!1),ze.element.classList.add("persona-hidden"),ze.backdrop?.classList.add("persona-hidden"),ao=!1,oa=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(ze.setExpandToggleVisible(f),ze.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),ze.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),ze.setCustomActions(o.features?.artifacts?.toolbarActions??[]),ze.setTabFade(o.features?.artifacts?.layout?.tabFade),ze.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!oa&&(ao=!1),ao!==_f){let w=ze.element;ao?(Bl=w.style.width,_l=w.style.maxWidth,w.style.removeProperty("width"),w.style.removeProperty("max-width")):(Bl&&(w.style.width=Bl),_l&&(w.style.maxWidth=_l),Bl="",_l=""),_f=ao}e.classList.toggle("persona-artifact-expanded",ao),ze.setExpanded(ao);let b=Nl();b!==na&&(na=b,Yr()),Ol()};if(Cn(o)){Ae.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(ue),So=c,c.appendChild(i),Ae.appendChild(c);let g=b=>{Hf||ze||(ze=b.createArtifactPane(o,{onSelect:w=>lt.current?.selectArtifact(w),onDismiss:()=>{jo=!0,lo()},onToggleExpand:()=>{let w=!ao,O=Gn.selectedId??Gn.artifacts[Gn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:O,expanded:w})!==!0&&(ao=w,w||(oa=!1),lo())}}),ze.element.classList.add("persona-hidden"),c.appendChild(ze.element),ze.backdrop&&Ae.appendChild(ze.backdrop),Ol(),lo())},f=ar();f?g(f):(Pm(()=>{let b=ar();b&&g(b)}),Kd().catch(()=>{})),Ol=()=>{if(!So||!ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){ra?.(),ra=null,Rp(),vt&&(vt.remove(),vt=null),ze.element.style.removeProperty("width"),ze.element.style.removeProperty("maxWidth");return}if(!vt){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 O=e.ownerDocument,z=O.defaultView??window,q=V=>{if(!ze||V.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||z.innerWidth<=640)return;V.preventDefault(),Rp();let X=V.clientX,se=ze.element.getBoundingClientRect().width,me=o.features?.artifacts?.layout,Xe=ut=>{let Xt=So.getBoundingClientRect().width,Ft=e.classList.contains("persona-artifact-welded-split"),It=Rm(So,z),an=Ft?0:w.getBoundingClientRect().width||6,Ze=se-(ut.clientX-X),ln=$w(Ze,Xt,It,an,me?.resizableMinWidth,me?.resizableMaxWidth,mS());ze.element.style.width=`${ln}px`,ze.element.style.maxWidth="none",Df()},ct=()=>{O.removeEventListener("pointermove",Xe),O.removeEventListener("pointerup",ct),O.removeEventListener("pointercancel",ct),Wl=null;try{w.releasePointerCapture(V.pointerId)}catch{}};Wl=ct,O.addEventListener("pointermove",Xe),O.addEventListener("pointerup",ct),O.addEventListener("pointercancel",ct);try{w.setPointerCapture(V.pointerId)}catch{}};w.addEventListener("pointerdown",q),vt=w,So.insertBefore(w,ze.element),ra=()=>{w.removeEventListener("pointerdown",q)}}if(vt){let w=Hl();vt.classList.toggle("persona-hidden",!w),Df()}},Dl=()=>{if(!fe||!ze||(o.launcher?.sidebarMode??!1)||Et(o)&&qn(o).reveal==="emerge")return;let w=e.ownerDocument.defaultView??window,O=o.launcher?.mobileFullscreen??!0,z=o.launcher?.mobileBreakpoint??640;if(O&&w.innerWidth<=z||!Hw(o,fe))return;let q=o.launcher?.width??o.launcherWidth??oo,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Hl()?(Ae.style.width=V,Ae.style.maxWidth=V):(Ae.style.width=q,Ae.style.maxWidth=q)},typeof ResizeObserver<"u"&&(ta=new ResizeObserver(()=>{lo()}),ta.observe(Ae))}else Ae.appendChild(ue);we()&&Yt&&(Fe.peekBanner&&Yt.appendChild(Fe.peekBanner),Yt.appendChild(Re)),e.appendChild(Ge),Yt&&e.appendChild(Yt);let Hp=()=>{if(we()){Ae.style.width="100%",Ae.style.maxWidth="100%";let Ce=o.launcher?.composerBar??{},$e=Ge.dataset.state==="expanded",ft=Ce.expandedSize??"anchored";if(!($e&&ft!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Qt=o.theme?.components?.panel,$n=Hs(o),As=(Ms,Wc)=>Ms==null||Ms===""?Wc:yn($n,Ms)??Ms,Fy="1px solid var(--persona-border)",Mt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Vu="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=As(Qt?.border,Fy),ue.style.borderRadius=As(Qt?.borderRadius,Vu),ue.style.boxShadow=As(Qt?.shadow,Mt),ue.style.overflow="hidden";return}let i=Et(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,O=Hs(o),z=(Ce,$e)=>Ce==null||Ce===""?$e:yn(O,Ce)??Ce,q=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,se=q.innerWidth<=X,me=V&&se&&fe,Xe=i&&V&&se,ct=o.launcher?.position??"bottom-left",ut=ct==="bottom-left"||ct==="top-left",Xt=o.launcher?.zIndex??rn,Ft="var(--persona-panel-border, 1px solid var(--persona-border))",It="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",an="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ze=b&&!me&&!Xe;Ze?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let ln=Ze?Ft:c||me?"none":Ft,nr=Ze?It:me?"none":c?ut?"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":It;i&&!me&&!Ze&&(nr="none",ln="none");let ko=Ze?an:c||me?"0":an,Lo=z(w?.border,ln),H=z(w?.shadow,nr),We=z(w?.borderRadius,ko),Be=Nl(),ye=Be==="detached",mt=Be==="welded";e.classList.toggle("persona-artifact-detached-split",ye),e.classList.toggle("persona-artifact-welded-split",mt);let Vt="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)))))",Rt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Cn(o)&&Lm(o)&&f&&!i;e.classList.toggle("persona-artifact-chat-flush",Rt);let Pe=ye||Rt?"none":H,Kt=ye?Ft:mt?"none":Lo,Gt=ye?an:We;Rt&&(Kt="none",Gt="0");let to=w?.borderRadius!=null&&w.borderRadius!=="",He=Rt&&!to?"0":We,wt=oe.scrollTop;e.style.cssText="",Ge.style.cssText="",Ae.style.cssText="",ue.style.cssText="",oe.style.cssText="",qs||(Re.style.cssText=""),ee&&(oe.style.display="none"),(g||f)&&(e.style.minWidth="0");let Io=()=>{if(wt<=0)return;(oe.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(oe.scrollTop===wt)return;let $e=oe.scrollHeight-oe.clientHeight;$e<=0||(oe.scrollTop=Math.min(wt,$e))})};if(me){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=`
43
+ `,D.addEventListener("click",()=>{m=A,k.forEach((G,se)=>{let ne=se<A;G.classList.toggle("selected",ne),G.setAttribute("aria-checked",se===A-1?"true":"false")})}),k.push(D),x.appendChild(D)}y.appendChild(x);let B=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",B=document.createElement("textarea"),B.className="persona-feedback-comment",B.placeholder=s,B.rows=3,B.setAttribute("aria-label","Additional comments"),A.appendChild(B),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 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){x.classList.add("persona-feedback-shake"),setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let A=B?.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)}}),$.appendChild(T),$.appendChild(I),y.appendChild($),u.appendChild(y),u}function Km(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 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 B=document.createElement("div");B.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,B.appendChild($),B.appendChild(T);let I=document.createElement("div");I.className="persona-feedback-numbers";let A=[];for(let E=0;E<=10;E++){let _=document.createElement("button");_.type="button",_.className="persona-feedback-rating-btn persona-feedback-number-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`Rating ${E} out of 10`),_.textContent=String(E),_.dataset.rating=String(E),E<=6?_.classList.add("persona-feedback-detractor"):E<=8?_.classList.add("persona-feedback-passive"):_.classList.add("persona-feedback-promoter"),_.addEventListener("click",()=>{y=E,A.forEach((W,L)=>{W.classList.toggle("selected",L===E),W.setAttribute("aria-checked",L===E?"true":"false")})}),A.push(_),I.appendChild(_)}k.appendChild(B),k.appendChild(I),h.appendChild(k);let D=null;if(d){let E=document.createElement("div");E.className="persona-feedback-comment-container",D=document.createElement("textarea"),D.className="persona-feedback-comment",D.placeholder=s,D.rows=3,D.setAttribute("aria-label","Additional comments"),E.appendChild(D),h.appendChild(E)}let G=document.createElement("div");G.className="persona-feedback-actions";let se=document.createElement("button");se.type="button",se.className="persona-feedback-btn persona-feedback-btn-skip",se.textContent=l,se.addEventListener("click",()=>{n?.(),m.remove()});let ne=document.createElement("button");return ne.type="button",ne.className="persona-feedback-btn persona-feedback-btn-submit",ne.textContent=a,ne.addEventListener("click",async()=>{if(y===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}ne.disabled=!0,ne.textContent="Submitting...";try{let E=D?.value.trim()||void 0;await t(y,E),m.remove()}catch(E){ne.disabled=!1,ne.textContent=a,console.error("[NPS Feedback] Failed to submit:",E)}}),G.appendChild(se),G.appendChild(ne),h.appendChild(G),m.appendChild(h),m}var zi="persona-chat-history",SI=30*1e3,AI=641,Vi="data-persona-composer-reason",MI={"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 EI(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=MI[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 rp(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 TI(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 PI(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Gm=e=>!e||typeof e!="object"?{}:{...e},cx=e=>e.map(t=>({...t,streaming:!1})),dx=(e,t,n)=>{let o=e?.markdown?$c(e.markdown):null,r=eg(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=Wo()!==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?cb(d):d,h=o(y);m=r&&u?r(h):h}else m=Rr(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)),Rr(l.text??"")}}};function px(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 kI=(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},LI=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:kI(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Qm=(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=el(t),r=()=>{kv({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=Xd(o);let a=Jd.getForInstance(o.plugins),l=IC(e),d=[],p=!1,u=Tw(()=>o),m=null,y=null,h=null,C=!1,S=null,x=i=>{m=i,i.initApprovalUi({webMcpToolTitle:bi});let c=i.createBuiltInApprovalPlugin();y=c.plugin,h=c.teardown},k=()=>{if(m)return m;let i=Rw();return i?(x(i),i):(Iw().then(c=>{C||m||(x(c),S?.())}).catch(()=>{}),null)},B=!1,$=!1,T=null,I=(i,c,g,f)=>{if(!i.querySelector("[data-tv-form]"))return;let b=Vw();if(b){b.enhanceWithForms(i,c,g,f);return}zw().then(()=>{B||$||!T||($=!0,T())}).catch(()=>{})};o.components&&No.registerAll(o.components);let A=Qw(),G=o.persistState===!1?null:o.storageAdapter??Dm(),se={},ne=null,E,_=new Promise(i=>{E=i}),W,L=!1,Y=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&&(L=!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")ne=i.then(c=>Y(c??{messages:[],metadata:{}}));else{let g=Y(i??{messages:[],metadata:{}});g.metadata&&(se=Gm(g.metadata)),g.messages?.length&&(o={...o,initialMessages:g.messages}),g.artifacts?.length&&(o={...o,initialArtifacts:g.artifacts,initialSelectedArtifactId:g.selectedArtifactId??null}),W=g.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=Y({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}ne||E();let K=()=>se,le=i=>{se=i({...se})??{},aa()},de=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ep],ge=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[qi.message,qi.messageAndClick],Ae=tp({parsers:de,handlers:ge,getSessionMetadata:K,updateSessionMetadata:le,emit:A.emit,documentRef:typeof document<"u"?document:null});Ae.syncFromMetadata();let fe=o.launcher?.enabled??!0,_e=o.launcher?.autoExpand??!1,it=o.autoFocusInput??!1,be=_e,j=fe,De=o.layout?.header?.layout,Ne=!1,xe=()=>$r(o),ke=()=>fe||xe(),he=xe()?!1:fe?_e:!0,dt=!1,Ie=null,Ut=()=>{dt=!0,Ie&&clearTimeout(Ie),Ie=setTimeout(()=>{dt&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),dt=!1)},1e4)},at=dx(o,Ae,Ut),nn=o.features?.showReasoning??!0,pn=o.features?.showToolCalls??!0,Wt=o.features?.showEventStreamToggle??!1,qr=o.features?.scrollToBottom??{},xn=o.features?.scrollBehavior??{},vo=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",zr=`${vo()}event-stream`,un=null,Gi=o.features?.eventStream?.maxEvents??2e3,Tt=null,gt=null,ro=null,Sl=!1,R=null,Z=!1,v=null,N=0,F=(i,c)=>{Tt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},U=(i,c)=>{gt?.processEvent(i,c),Tt?F(i,c):ro&&(ro.length>=Gi&&ro.shift(),ro.push({type:i,payload:c}))},ee=()=>{Tt||!Wt||(ro??(ro=[]),Pm().then(i=>{if(Sl||Tt||!Wt)return;un=new i.EventStreamStore(zr),Tt=new i.EventStreamBuffer(Gi,un),gt=gt??new i.ThroughputTracker,un.open().then(()=>Tt?.restore()).catch(g=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",g)});let c=ro??[];ro=null;for(let g of c)gt?.processEvent(g.type,g.payload),F(g.type,g.payload)}).catch(()=>{}))};Wt&&ee();let te=!1,ae=null,we=()=>{},yt=()=>{},qe=()=>{},Ot=()=>{},St=()=>{},Vr=()=>Z||te&&ae==="panel",In={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)}},jt=o.statusIndicator??{},gn=i=>i==="idle"?jt.idleText??$t.idle:i==="connecting"?jt.connectingText??$t.connecting:i==="connected"?jt.connectedText??$t.connected:i==="error"?jt.errorText??$t.error:i==="paused"?jt.pausedText??$t.paused:i==="resuming"?jt.resumingText??$t.resuming:$t[i];function sn(i,c,g,f){if(!i.hasAttribute(Vi))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 Rn=Ew({config:o,showClose:ke()}),{wrapper:Ge,panel:Me,pillRoot:Yt}=Rn.shell,Fe=Rn.panelElements,{container:ue,body:oe,messagesWrapper:Le,starterSuggestions:hp,transcriptSuggestions:Qi,suggestions:ur,textarea:ce,sendButton:Ee,composerForm:so,statusText:ot,welcomeHost:Sn,welcomeIconHolder:Yx,greetingHost:Hn,introKicker:Xx,introTitle:Jx,introSubtitle:Zx,closeButton:je,iconHolder:Pt,headerTitle:gr,headerSubtitle:Kr,header:Te,footer:Re,actionsRow:eS}=Fe,yp=Fe.leftActions,Al=Fe.rightActions,Co=Fe.sendButtonWrapper,df=Fe.setSendButtonMode,re=Fe.micButton,Wn=Fe.micButtonWrapper,At=Fe.attachmentButton,An=Fe.attachmentButtonWrapper,bt=Fe.attachmentInput,Mn=Fe.attachmentPreviewsContainer;ue.classList.add("persona-relative"),oe.classList.add("persona-relative");let tS=12,Yi=()=>qr.label??"",nS=()=>qr.iconName??"arrow-down",oS=()=>qr.enabled!==!1,On=()=>xn.mode??"anchor-top",mr=()=>On()==="follow"||On()==="anchor-top"&&ia,Xi=()=>xn.anchorTopOffset??16,rS=()=>xn.restorePosition??"bottom",pf=()=>xn.pauseOnInteraction===!0,uf=()=>xn.showActivityWhilePinned!==!1,gf=()=>xn.announce===!0,bp=()=>xn.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 Ji=M("span","persona-flex persona-items-center"),vp=M("span",""),Gr=M("span","");Gr.setAttribute("data-persona-scroll-to-bottom-count",""),Gr.style.display="none",_t.append(Ji,vp,Gr),ue.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",oe.appendChild(Kn);let Uo=M("div","persona-sr-only");Uo.setAttribute("aria-live","polite"),Uo.setAttribute("aria-atomic","true"),Uo.setAttribute("role","status"),Uo.setAttribute("data-persona-live-region",""),Object.assign(Uo.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"}),ue.appendChild(Uo);let Zi=null,Ml=null,El=i=>{!gf()||!i||(Ml=i,Zi===null&&(Zi=setTimeout(()=>{Zi=null,Ml&&gf()&&(Uo.textContent=Ml),Ml=null},400)))},Tl="empty",Pl=0,Cp=()=>Pl||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,Qr=()=>{let c=Re.style.display==="none"?0:Re.offsetHeight;_t.style.bottom=`${c+Cp()+tS}px`};Qr();let wp=()=>{qs||(Re.style.marginBottom=Pl>0?`${Pl}px`:"")},kl=()=>{let i=Jg(o,xe()),c=Do(o),f=Re.style.display==="none"?0:Re.offsetHeight,b=c.anchor==="center"&&Tl==="empty"?rl(c.anchorComposerTop)??rl("44%"):null,w=b===null||xe()?0:PC({columnHeight:ue.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`),Pl=i==="block"?w:0,wp(),Qr()},mf=()=>{let i=!!Yi();_t.setAttribute("aria-label",Yi()||"Jump to latest"),_t.title=Yi(),_t.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Ji.innerHTML="";let c=pe(nS(),"14px","currentColor",2);c?(Ji.appendChild(c),Ji.style.display=""):Ji.style.display="none",vp.textContent=Yi(),vp.style.display=i?"":"none"};mf();let Je=null,Bt=null,Se=Sv(),sS=i=>{try{ue.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};Se.subscribe(sS);let wo=()=>{Se.setText(ce?.value??"")},Yr=()=>{Se.setMentionRefs(Bt?.getMentionRefs()??[])},iS=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}),ff=i=>{let c=Object.freeze(i.map(iS));Se.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(g){console.error("[AgentWidget] attachments.onChange failed:",g)}Kp()};Se.setSelectedModelId(o.composer?.selectedModelId);let ea=()=>o.composer?.modes??[],Fs=()=>Yv(ea(),o.composer?.modeGroups);{let i=Cd(o.composer?.defaultActiveModeIds??[],ea());i.length&&Se.setActiveModeIds(i)}function hf(i){if(Se.getState().selectedModelId!==i){Se.setSelectedModelId(i),fr?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function Ll(i){Se.setActiveModeIds(i),jo?.render(i,Fs()),$s.forEach(c=>c.repaint()),So?.resolve(),tc(),io()}function xp(i){Ll(Xv(Se.getState().activeModeIds,i,ea(),o.composer?.modeGroups))}let fr=null,Sp=null,jo=null,$s=new Map,hr=null;function xo(i){Se.setQuote(i),hr?.render(Se.getState().quote),io(),lh()}let yf=!1;function Ap(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!yf&&o.debug===!0&&(yf=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let yr=null;function Us(i){Se.setPendingSubmission(i),yr?.render(Se.getState().pendingSubmission),io()}let aS=i=>{let c=$s.get(i);if(c)return c;let g=eC({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===i),getModes:()=>ea().filter(f=>f.groupId===i),getActiveIds:()=>Se.getState().activeModeIds,onSelect:f=>xp(f)});return $s.set(i,g),g},lS=()=>{let i=[],c=Se.getState().activeModeIds,g=new Set;if(ea().forEach((f,b)=>{if(vd(f.groupId,o.composer?.modeGroups)){let w=f.groupId;if(g.has(w))return;g.add(w);let O=aS(w);O.action.order=zg(b),O.action.label=o.composer?.modeGroups?.find(z=>z.id===w)?.label??w,i.push(O.action);return}i.push({id:Gv(f.id),kind:"button",placement:"start",order:zg(b),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:c.includes(f.id),onSelect:()=>xp(f.id)})}),o.composer?.models?.length&&!a.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!fr||Sp!==f)&&(Sp=f,fr=Vv({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Se.getState().selectedModelId,onSelect:b=>hf(b),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(fr.action)}return i},Mp=null,bf=a.find(i=>i.renderHeader);if(bf?.renderHeader){let i=bf.renderHeader({config:o,defaultRenderer:()=>{let c=Ur({config:o,showClose:ke()});return Hi(ue,c,o),c.header},onClose:()=>pt(!1,"user")});if(i){let c=Te;c&&(c.replaceWith(i),Te=i,Rn.header.element=i)}}let vf=()=>{R&&(oe.style.display="none",Re.parentNode?.insertBefore(R.element,Re),R.update())},Ep=()=>{if(!Tt){ee();return}if(Z=!0,R?vf():Pm().then(c=>{R||!Z||!Tt||(R=c.createEventStreamView({buffer:Tt,getFullHistory:()=>Tt.getAllFromStore(),onClose:()=>js(),config:o,plugins:a,getThroughput:()=>gt?.getMetric()??{status:"idle"},renderIconByName:pe}),vf())}).catch(()=>{js()}),et){et.style.boxShadow=`inset 0 0 0 1.5px ${vn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(g=>g&&et.classList.add(g))}let i=()=>{if(!Z)return;let c=Date.now();c-N>=200&&(R?.update(),N=c),v=requestAnimationFrame(i)};N=0,v=requestAnimationFrame(i),zt(),A.emit("eventStream:opened",{timestamp:Date.now()})},js=()=>{if(Z){if(Z=!1,R&&R.element.remove(),oe.style.display="",et){et.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&et.classList.remove(c))}v!==null&&(cancelAnimationFrame(v),v=null),zt(),A.emit("eventStream:closed",{timestamp:Date.now()})}},et=null;if(Wt){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:"");et=M("button",c),et.style.width="28px",et.style.height="28px",et.style.color=vn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let g=Ht(ix,"18px","currentColor",1.5);g&&et.appendChild(g);let f=Fe.clearChatButtonWrapper,b=Fe.closeButtonWrapper,w=f||b;w&&w.parentNode===Te?Te.insertBefore(et,w):Te.appendChild(et),et.addEventListener("click",()=>{Z?js():Ep()})}let Cf=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??ar).join(","),b.multiple=(c.maxFiles??4)>1,b.style.display="none",b.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(b)}},qs=!1,wf=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:()=>Wy(),storage:u(c.id),onSubmit:b=>{!P||P.isStreaming()||Pc(b.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{Ar()||bt?.click()},models:g?.models,selectedModelId:Se.getState().selectedModelId??g?.selectedModelId,onModelChange:b=>hf(b),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Mp?.()}:void 0})},xf=wf(()=>Oi({config:o}).footer);xf&&(Rn.replaceComposer(xf),Re=Rn.composer.footer,qs=!0);let tt=null,cS=i=>{so=i.form,ce=i.input,Co=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Ee=i.sendButton),i.micButton&&(re=i.micButton,Wn=i.micButton.parentElement),i.found.status&&(ot=i.found.status),i.found.suggestions&&(ur=i.found.suggestions),i.attachmentButton&&(At=i.attachmentButton,An=i.attachmentButton.parentElement),bt=i.attachmentInput??null,Mn=i.attachmentPreviews??null,i.found.actionsRow&&(eS=i.found.actionsRow),yp=i.found.actionsStart,Al=i.found.actionsEnd};function Tp(){let i=ce;if(!i)return;let c=o.composer?.inputAttributes,g=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;dd(i,c),g&&i.setAttribute("aria-label",g),cd(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:tl(i)}),Wv(i,ld(o.composer?.maxLines,xe()?5:3))}let Sf=i=>{tt=Mv(i,{debug:o.debug===!0}),tt&&cS(tt),Tp()};Cf(Re),Sf(Re),wo();let ta=Nr(o,xe());ta&&(Le.style.maxWidth=ta,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%",Hn.style.maxWidth=ta,Hn.style.marginLeft="auto",Hn.style.marginRight="auto",Hn.style.width="100%",hp.style.maxWidth=ta,Qi.style.maxWidth=ta,Qi.style.marginLeft="auto",Qi.style.marginRight="auto",Qi.style.width="100%");let Af=()=>{let i=Nr(o,xe());if(!(!i||xe()))for(let c of[so,ur,Mn,ot])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};Af();let Mf=()=>{!o.attachments?.enabled||!bt||!Mn||(Je?Je.remountPreviews(Mn):(Je=Ei.fromConfig(o.attachments,ff),Je.setPreviewsContainer(Mn)),tt?.addListener(bt,"change",i=>{let c=i.target;Je?.handleFileSelect(c.files),c.value=""}),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(px(o.attachments.dropOverlay)))};Mf();let dS=()=>Bt?.prefetch(),Ef=()=>{if(!o.contextMentions?.enabled||!ce)return;let i=tt?.header??null,c=i?qg(i):void 0;if(Bt=CC({config:o,textarea:ce,anchor:so??ce,getMessages:()=>P.getMessages(),liveRegionHost:ue,chipRow:c}),Bt&&!c){let g=ce;g.parentElement?.insertBefore(Bt.contextRow,g)}};Ef();let So=null,pS={getState:()=>Se.getState(),getValue:()=>ce?.value??"",setValue:i=>{ce&&(ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),wo())},submit:()=>{dC(tt?.form??null)},openAttachmentPicker:()=>{Ar()||bt?.click()},toggleVoice:()=>{Mp?.()},requestRender:()=>So?.resolve()},uS=()=>{let i=[];return(Bt?.affordanceButtons??[]).forEach((g,f)=>{i.push({id:`core:mention-${f}`,placement:"start",order:Bo.mention+f,element:g,managed:!0})}),An&&i.push({id:"core:attachment",placement:"start",order:Bo.attachment,element:An}),Wn&&i.push({id:"core:mic",placement:"end",order:Bo.mic,element:Wn}),Co&&i.push({id:"core:send",placement:"end",order:Bo.send,element:Co}),i},Tf=()=>{So?.destroy(),So=jv({getBindings:()=>tt,collect:()=>({builtIns:uS(),configActions:[...lS(),...o.composer?.actions??[]],plugins:a,contributionContext:{config:o,getState:()=>Se.getState(),requestRender:()=>So?.resolve()},debug:o.debug===!0}),actionContext:pS,getState:()=>Se.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),So.resolve()};Tf();let Pp=()=>{if(jo?.destroy(),jo=null,!Fs().length)return;let i=tt?.header;i&&(jo=Kv({row:qg(i),onRemove:c=>xp(c),initialIds:Se.getState().activeModeIds}),jo.render(Se.getState().activeModeIds,Fs()))};Pp();let Pf=()=>{hr?.destroy(),hr=null,yr?.destroy(),yr=null;let i=tt?.header;i&&(hr=tC({onDismiss:()=>xo(void 0)}),i.appendChild(hr.element),hr.render(Se.getState().quote),Ap()==="defer-one"&&(yr=nC({onEdit:()=>NA(),onRemove:()=>Us(void 0)}),i.appendChild(yr.element),yr.render(Se.getState().pendingSubmission)))};Pf();let kp=lC(),gS=()=>{let i=tt?.header?.querySelector(jg);if(i)return i.childElementCount>0;let c=Se.getState();return c.mentionRefs.length>0||Cd(c.activeModeIds,Fs()).length>0},kf=()=>!1;function io(){let i=Se.getState(),c=kp.observe(cC(ce),i.text);Re.toggleAttribute("data-persona-composer-compact",aC({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:gS(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0,dictationActive:kf()}))}function Lf(){o.composer?.layout==="single-row"&&!xe()?Re.setAttribute("data-persona-composer-layout","single-row"):Re.removeAttribute("data-persona-composer-layout")}Lf(),Se.subscribe(()=>{So?.sync(),Kp(),Zl(),io(),lh()}),Zl();let If=!1,mS=i=>{if(If||o.debug!==!0)return;let c=["messages","composer"].filter(g=>i[g]);c.length&&(If=!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??{};mS(i);let c=f=>{switch(f){case"body-top":return oe.querySelector("[data-persona-intro-card]");case"messages":return Le;case"footer-top":return ur;case"composer":return so;case"footer-bottom":return ot;default:return null}},g=(f,b)=>{switch(f){case"header-left":case"header-center":case"header-right":if(f==="header-left")Te.insertBefore(b,Te.firstChild);else if(f==="header-right")Te.appendChild(b);else{let w=Te.querySelector(".persona-flex-col");w?w.parentNode?.insertBefore(b,w.nextSibling):Te.appendChild(b)}break;case"body-top":{let w=oe.querySelector("[data-persona-intro-card]");w?w.replaceWith(b):oe.insertBefore(b,oe.firstChild);break}case"body-bottom":oe.appendChild(b);break;case"footer-top":ur.replaceWith(b);break;case"footer-bottom":ot.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 Rf=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")Ni.has(b)?Ni.delete(b):Ni.add(b),Pw(b,f);else if(w==="tool")Fi.has(b)?Fi.delete(b):Fi.add(b),Lw(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)};Le.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Rf(i))}),Le.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Rf(i))}),Le.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let g=Le.getRootNode(),f=typeof g.getSelection=="function"?g.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let b=f.toString(),w=RC(b);!w||w===b||(c.setData("text/plain",w),i.preventDefault())});let Lp=new Map,Hf=null,Wf="idle",fS={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},hS=(i,c)=>{let{icon:g,label:f}=fS[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))},Of=()=>{Le.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let f=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;hS(c,f&&f===Hf?Wf:"idle")})};Le.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=P.getMessages().find(q=>q.id===b);if(z&&In.onCopy){let q=z.content||"";navigator.clipboard.writeText(q).then(()=>{g.classList.add("persona-message-action-success");let V=Ht(ax,14,"currentColor",2);V&&(g.innerHTML="",g.appendChild(V)),setTimeout(()=>{g.classList.remove("persona-message-action-success");let X=Ht(lx,14,"currentColor",2);X&&(g.innerHTML="",g.appendChild(X))},2e3)}).catch(V=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",V)}),In.onCopy(z)}}else if(w==="read-aloud")P.toggleReadAloud(b);else if(w==="upvote"||w==="downvote"){let z=(Lp.get(b)??null)===w,q=w==="upvote"?"thumbs-up":"thumbs-down";if(z){Lp.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",X=f.querySelector(`[data-action="${V}"]`);if(X){X.classList.remove("persona-message-action-active");let ut=pe(V==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ut&&(X.innerHTML="",X.appendChild(ut))}Lp.set(b,w),g.classList.add("persona-message-action-active");let ie=pe(q,14,"currentColor",2);ie&&(ie.setAttribute("fill","currentColor"),g.innerHTML="",g.appendChild(ie)),g.classList.remove("persona-message-action-pop"),g.offsetWidth,g.classList.add("persona-message-action-pop");let Xe=P.getMessages().find(ct=>ct.id===b);Xe&&In.onFeedback&&In.onFeedback({type:w,messageId:Xe.id,message:Xe})}}else if(w==="regenerate")Il?.regenerate(b);else if(w==="edit")Il?.edit(b);else if(w==="quote")Il?.quote(b);else if(w?.startsWith(_d)){let O=w.slice(_d.length),z=o.messageActions?.custom?.find(V=>V.id===O),q=P.getMessages().find(V=>V.id===b);if(!z||!q)return;try{z.onSelect(q)}catch(V){console.error(`[AgentWidget] messageActions.custom "${O}" onSelect failed:`,V)}}});let Il=null;Le.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 O=w==="approve"?"approved":"denied",q=P.getMessages().find(X=>X.id===b);if(!q?.approval)return;let V=f.querySelector("[data-approval-buttons]");V&&V.querySelectorAll("button").forEach(ie=>{ie.disabled=!0,ie.style.opacity="0.5",ie.style.cursor="not-allowed"}),q.approval.toolType==="webmcp"?P.resolveWebMcpApproval(b,O):P.resolveApproval(q.approval,O)});let ze=null,Bf=!1,na=null,Xr=()=>{},oa="none",Rl=null,Gn={artifacts:[],selectedId:null},qo=!1,ao=!1,ra=!1,zs=!1,_f=()=>zs||Gn.artifacts.some(i=>sr(o.features?.artifacts,i)==="panel"),Hl=()=>Gn.artifacts.length>0&&!qo&&_f(),lt={current:null},Ip=(i,c)=>{let g=P.getArtifactById(c),f=g?.markdown,b=g?.title||"artifact",w=g?.file,O=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 ie=P.getMessages().find(me=>me.id===V);if(ie?.rawContent)try{let me=JSON.parse(ie.rawContent);f=me?.props?.markdown,b=me?.props?.title||b,me?.props?.file&&typeof me.props.file=="object"&&(w=me.props.file),!g&&typeof me?.props?.artifactType=="string"&&(O=me.props.artifactType)}catch{}}}return{markdown:f,title:b,file:w,artifactType:O}};Le.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:O,file:z}=Ip(g,f);if(!w)return;let q=lr();q&&q.triggerArtifactDownload(q.downloadInfoFor({title:O,markdown:w,file:z}))}),Le.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]"),O=b?b.getAttribute("data-artifact-inline"):w?.getAttribute("data-open-artifact")??null,q=(b?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ct=>ct.id===f);if(!q)return;let{markdown:V,title:X,file:ie,artifactType:me}=Ip(g,O??""),Xe={artifactId:O,title:X,artifactType:me,markdown:V,file:ie};try{Promise.resolve(q.onClick(Xe)).catch(()=>{})}catch{}}),Le.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),w=lr();if(!w)return;let O="";if(b)O=w.artifactCopyText(b);else{let{markdown:z,file:q,artifactType:V}=Ip(g,f);V==="markdown"&&(O=w.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:z??"",...q?{file:q}:{}}))}O&&navigator.clipboard.writeText(O).then(()=>{let z=Ht(ax,16,"currentColor",2);z&&(g.replaceChildren(z),setTimeout(()=>{let q=Ht(lx,16,"currentColor",2);q&&g.replaceChildren(q)},1500))}).catch(()=>{})}),Le.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||(qo=!1,zs=!0,ao=!0,ra=!0,P.selectArtifact(f),lo())}),Le.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(),qo=!1,zs=!0,P.selectArtifact(f),lo())}),Le.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 Vs=Fe.composerOverlay,Ks=(i,c,g)=>{let f=c.trim();if(!f||!lt.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})),Is(Vs,b);let O=lt.current.getMessages().find(z=>z.toolCall?.id===b);O?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(O,g.structured??f):lt.current.sendMessage(f)},Jr=i=>{let c=lt.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:Kc(i,f),currentIndex:no(i)})},Df=i=>Object.entries(i).map(([c,g])=>`${c}: ${Array.isArray(g)?g.join(", "):g}`).join(" | "),Rp=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=no(i),g=Ci(i);if(c>=g-1)return;let f=lt.current?.getMessages().find(b=>b.toolCall?.id===i.getAttribute("data-tool-call-id"));f&&(Gc(i,f,o,c+1),Jr(i))};Vs.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})),Is(Vs,w);let O=lt.current?.getMessages().find(z=>z.toolCall?.id===w);O?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(O),lt.current?.resolveAskUserQuestion(O,"(dismissed)"));return}if(b==="pick"){let w=g.getAttribute("data-option-label");if(!w)return;let O=f.getAttribute("data-multi-select")==="true",z=Or(f);if(z&&O){let q=Ls(f)[no(f)],V=new Set(Array.isArray(q)?q:[]);V.has(w)?V.delete(w):V.add(w),Br(f,Array.from(V)),Jr(f);return}if(z){Br(f,w),Jr(f),Rp(f);return}if(O){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=ag(f).length===0);return}Ks(f,w,{source:"pick",values:[w]});return}if(b==="submit-multi"){let w=ag(f);if(w.length===0)return;Ks(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 O=f.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!O.trim())return;if(Or(f)){Br(f,O.trim()),Jr(f),Rp(f);return}Ks(f,O,{source:"free-text"});return}if(b==="next"||b==="back"){if(!lt.current)return;let w=f.getAttribute("data-tool-call-id")??"",O=lt.current.getMessages().find(ie=>ie.toolCall?.id===w);if(!O)return;let q=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(q){let ie=Ls(f)[no(f)];(typeof ie!="string"||ie!==q)&&Br(f,q)}let V=b==="next"?1:-1,X=no(f)+V;Gc(f,O,o,X),Jr(f);return}if(b==="submit-all"){if(!lt.current)return;let w=f.getAttribute("data-tool-call-id")??"",O=lt.current.getMessages().find(ie=>ie.toolCall?.id===w);if(!O)return;let q=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";q&&Br(f,q);let V=Kc(f,O);lt.current.persistAskUserQuestionProgress(O,{answers:V,currentIndex:no(f)});let X=Df(V);Ks(f,X||"(submitted)",{source:"submit-all",structured:V});return}if(b==="skip"){if(!lt.current)return;let w=f.getAttribute("data-tool-call-id")??"",O=lt.current.getMessages().find(me=>me.toolCall?.id===w);if(!O)return;let z=Or(f),q=no(f),V=Ci(f),X=q>=V-1;if(!z){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:w},bubbles:!0,composed:!0})),Is(Vs,w),O.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(O),lt.current.resolveAskUserQuestion(O,"(dismissed)"));return}Br(f,"");let ie=f.querySelector('[data-ask-free-text-input="true"]');if(ie&&(ie.value=""),X){let me=Kc(f,O),Xe=Df(me);Ks(f,Xe||"(skipped)",{source:"submit-all",structured:me});return}Gc(f,O,o,q+1),Jr(f);return}}),Vs.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(Or(f)){Br(f,b.trim()),Jr(f),Rp(f);return}Ks(f,b,{source:"free-text"})}});let Nf=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=Vs.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",Nf);let Ao=null,vt=null,sa=null,Wl=null,Ol=()=>{},Ff=!1,Bl="",_l="";function Hp(){Wl?.(),Wl=null}let yS=()=>{let i=si&&bs?.isConnected?bs:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},$f=()=>{if(!Ao||!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=Ao.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 w=Om(Ao,c),O=f.offsetWidth+w/2-b/2;vt.style.left=`${Math.max(0,O)}px`},Dl=()=>{},bS=()=>{let i=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,g=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>g?!1:fe||Et(o)},Nl=()=>!wn(o)||!Hl()||e.classList.contains("persona-artifact-narrow-host")||bS()||(e.ownerDocument.defaultView??window).innerWidth<AI?"none":Hm(o)?"detached":"welded",lo=()=>{if(!ze||!wn(o))return;bl(e,o),vl(e,o),Dl();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=Me.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let g=Hl();ze.setVisible(g),ze.update(Gn),qo?(ze.setMobileOpen(!1),ze.element.classList.add("persona-hidden"),ze.backdrop?.classList.add("persona-hidden"),ao=!1,ra=!1):Gn.artifacts.length>0&&_f()?(ze.element.classList.remove("persona-hidden"),ze.setMobileOpen(!0)):(ze.setMobileOpen(!1),ze.element.classList.add("persona-hidden"),ze.backdrop?.classList.add("persona-hidden"),ao=!1,ra=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(ze.setExpandToggleVisible(f),ze.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),ze.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),ze.setCustomActions(o.features?.artifacts?.toolbarActions??[]),ze.setTabFade(o.features?.artifacts?.layout?.tabFade),ze.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!ra&&(ao=!1),ao!==Ff){let w=ze.element;ao?(Bl=w.style.width,_l=w.style.maxWidth,w.style.removeProperty("width"),w.style.removeProperty("max-width")):(Bl&&(w.style.width=Bl),_l&&(w.style.maxWidth=_l),Bl="",_l=""),Ff=ao}e.classList.toggle("persona-artifact-expanded",ao),ze.setExpanded(ao);let b=Nl();b!==oa&&(oa=b,Xr()),Ol()};if(wn(o)){Me.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(ue),Ao=c,c.appendChild(i),Me.appendChild(c);let g=b=>{Bf||ze||(ze=b.createArtifactPane(o,{onSelect:w=>lt.current?.selectArtifact(w),onDismiss:()=>{qo=!0,lo()},onToggleExpand:()=>{let w=!ao,O=Gn.selectedId??Gn.artifacts[Gn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:O,expanded:w})!==!0&&(ao=w,w||(ra=!1),lo())}}),ze.element.classList.add("persona-hidden"),c.appendChild(ze.element),ze.backdrop&&Me.appendChild(ze.backdrop),Ol(),lo())},f=lr();f?g(f):(Im(()=>{let b=lr();b&&g(b)}),Gd().catch(()=>{})),Ol=()=>{if(!Ao||!ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){sa?.(),sa=null,Hp(),vt&&(vt.remove(),vt=null),ze.element.style.removeProperty("width"),ze.element.style.removeProperty("maxWidth");return}if(!vt){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 O=e.ownerDocument,z=O.defaultView??window,q=V=>{if(!ze||V.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||z.innerWidth<=640)return;V.preventDefault(),Hp();let X=V.clientX,ie=ze.element.getBoundingClientRect().width,me=o.features?.artifacts?.layout,Xe=ut=>{let Xt=Ao.getBoundingClientRect().width,Ft=e.classList.contains("persona-artifact-welded-split"),It=Om(Ao,z),an=Ft?0:w.getBoundingClientRect().width||6,Ze=ie-(ut.clientX-X),ln=qw(Ze,Xt,It,an,me?.resizableMinWidth,me?.resizableMaxWidth,yS());ze.element.style.width=`${ln}px`,ze.element.style.maxWidth="none",$f()},ct=()=>{O.removeEventListener("pointermove",Xe),O.removeEventListener("pointerup",ct),O.removeEventListener("pointercancel",ct),Wl=null;try{w.releasePointerCapture(V.pointerId)}catch{}};Wl=ct,O.addEventListener("pointermove",Xe),O.addEventListener("pointerup",ct),O.addEventListener("pointercancel",ct);try{w.setPointerCapture(V.pointerId)}catch{}};w.addEventListener("pointerdown",q),vt=w,Ao.insertBefore(w,ze.element),sa=()=>{w.removeEventListener("pointerdown",q)}}if(vt){let w=Hl();vt.classList.toggle("persona-hidden",!w),$f()}},Dl=()=>{if(!fe||!ze||(o.launcher?.sidebarMode??!1)||Et(o)&&qn(o).reveal==="emerge")return;let w=e.ownerDocument.defaultView??window,O=o.launcher?.mobileFullscreen??!0,z=o.launcher?.mobileBreakpoint??640;if(O&&w.innerWidth<=z||!Bw(o,fe))return;let q=o.launcher?.width??o.launcherWidth??oo,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Hl()?(Me.style.width=V,Me.style.maxWidth=V):(Me.style.width=q,Me.style.maxWidth=q)},typeof ResizeObserver<"u"&&(na=new ResizeObserver(()=>{lo()}),na.observe(Me))}else Me.appendChild(ue);xe()&&Yt&&(Fe.peekBanner&&Yt.appendChild(Fe.peekBanner),Yt.appendChild(Re)),e.appendChild(Ge),Yt&&e.appendChild(Yt);let Wp=()=>{if(xe()){Me.style.width="100%",Me.style.maxWidth="100%";let Ce=o.launcher?.composerBar??{},$e=Ge.dataset.state==="expanded",ft=Ce.expandedSize??"anchored";if(!($e&&ft!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Qt=o.theme?.components?.panel,$n=Hs(o),As=(Ms,Wc)=>Ms==null||Ms===""?Wc:bn($n,Ms)??Ms,qy="1px solid var(--persona-border)",Mt="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Gu="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=As(Qt?.border,qy),ue.style.borderRadius=As(Qt?.borderRadius,Gu),ue.style.boxShadow=As(Qt?.shadow,Mt),ue.style.overflow="hidden";return}let i=Et(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,O=Hs(o),z=(Ce,$e)=>Ce==null||Ce===""?$e:bn(O,Ce)??Ce,q=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,ie=q.innerWidth<=X,me=V&&ie&&fe,Xe=i&&V&&ie,ct=o.launcher?.position??"bottom-left",ut=ct==="bottom-left"||ct==="top-left",Xt=o.launcher?.zIndex??rn,Ft="var(--persona-panel-border, 1px solid var(--persona-border))",It="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",an="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ze=b&&!me&&!Xe;Ze?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let ln=Ze?Ft:c||me?"none":Ft,rr=Ze?It:me?"none":c?ut?"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":It;i&&!me&&!Ze&&(rr="none",ln="none");let Lo=Ze?an:c||me?"0":an,Io=z(w?.border,ln),H=z(w?.shadow,rr),We=z(w?.borderRadius,Lo),Be=Nl(),ye=Be==="detached",mt=Be==="welded";e.classList.toggle("persona-artifact-detached-split",ye),e.classList.toggle("persona-artifact-welded-split",mt);let Vt="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)))))",Rt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&wn(o)&&Hm(o)&&f&&!i;e.classList.toggle("persona-artifact-chat-flush",Rt);let Pe=ye||Rt?"none":H,Kt=ye?Ft:mt?"none":Io,Gt=ye?an:We;Rt&&(Kt="none",Gt="0");let to=w?.borderRadius!=null&&w.borderRadius!=="",He=Rt&&!to?"0":We,wt=oe.scrollTop;e.style.cssText="",Ge.style.cssText="",Me.style.cssText="",ue.style.cssText="",oe.style.cssText="",qs||(Re.style.cssText=""),Z&&(oe.style.display="none"),(g||f)&&(e.style.minWidth="0");let Ro=()=>{if(wt<=0)return;(oe.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(oe.scrollTop===wt)return;let $e=oe.scrollHeight-oe.clientHeight;$e<=0||(oe.scrollTop=Math.min(wt,$e))})};if(me){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;
@@ -52,7 +52,7 @@ _Details: ${n.message}_`:o}var Ag=e=>({isError:!0,content:[{type:"text",text:e}]
52
52
  flex-direction: column !important;
53
53
  z-index: ${Xt} !important;
54
54
  background-color: var(--persona-surface, #ffffff) !important;
55
- `,Ae.style.cssText=`
55
+ `,Me.style.cssText=`
56
56
  position: relative !important;
57
57
  display: flex !important;
58
58
  flex-direction: column !important;
@@ -76,7 +76,7 @@ _Details: ${n.message}_`:o}var Ag=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
- `,oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",Re.style.flexShrink="0",Cp(),Ne=!0,Io();return}let Oe=o?.launcher?.width??o?.launcherWidth??oo;if(!c&&!i)f&&g?(Ae.style.width="100%",Ae.style.maxWidth="100%"):(Ae.style.width=Oe,Ae.style.maxWidth=Oe);else if(i)if(qn(o).reveal==="emerge"&&!b){let $e=qn(o).width;Ae.style.width=$e,Ae.style.maxWidth=$e}else Ae.style.width="100%",Ae.style.maxWidth="100%";if(Dl(),Ae.style.boxShadow=Pe,Ae.style.borderRadius=He,ye?Ae.style.border="none":mt&&(Ae.style.border=Lo),ue.style.border=Kt,ue.style.borderRadius=Gt,ue.style.boxShadow=ye&&!Rt?Vt:"",Rt&&(ue.style.background="transparent",oe.style.background="transparent",Re.style.background="transparent",Re.style.borderTop="none"),mt){let Ce=o.features?.artifacts?.layout;Rl=Ce?.unifiedSplitOuterRadius?.trim()||Ce?.paneBorderRadius?.trim()||We}else Rl=null;if(i&&!me&&!Ze&&!ye&&!mt&&w?.border===void 0&&(ue.style.border="none",qn(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),i&&!me&&mt&&w?.border===void 0&&(qn(o).side==="right"?Ae.style.borderLeft="1px solid var(--persona-border)":Ae.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"),Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1 1 0%",Ae.style.minHeight="0",Ae.style.maxHeight="100%",Ae.style.height="100%",ye||(Ae.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",Re.style.flexShrink="0"),f&&(Ze||ye||Rt)&&!i&&(Rt||(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[ct]??zn["bottom-right"]).split(" ").forEach($e=>Ge.classList.add($e)),c){let Ce=o.launcher?.sidebarWidth??"420px";b?Ge.style.cssText=`
79
+ `,oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",Re.style.flexShrink="0",wp(),Ne=!0,Ro();return}let Oe=o?.launcher?.width??o?.launcherWidth??oo;if(!c&&!i)f&&g?(Me.style.width="100%",Me.style.maxWidth="100%"):(Me.style.width=Oe,Me.style.maxWidth=Oe);else if(i)if(qn(o).reveal==="emerge"&&!b){let $e=qn(o).width;Me.style.width=$e,Me.style.maxWidth=$e}else Me.style.width="100%",Me.style.maxWidth="100%";if(Dl(),Me.style.boxShadow=Pe,Me.style.borderRadius=He,ye?Me.style.border="none":mt&&(Me.style.border=Io),ue.style.border=Kt,ue.style.borderRadius=Gt,ue.style.boxShadow=ye&&!Rt?Vt:"",Rt&&(ue.style.background="transparent",oe.style.background="transparent",Re.style.background="transparent",Re.style.borderTop="none"),mt){let Ce=o.features?.artifacts?.layout;Rl=Ce?.unifiedSplitOuterRadius?.trim()||Ce?.paneBorderRadius?.trim()||We}else Rl=null;if(i&&!me&&!Ze&&!ye&&!mt&&w?.border===void 0&&(ue.style.border="none",qn(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),i&&!me&&mt&&w?.border===void 0&&(qn(o).side==="right"?Me.style.borderLeft="1px solid var(--persona-border)":Me.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"),Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.maxHeight="100%",Me.style.height="100%",ye||(Me.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",Re.style.flexShrink="0"),f&&(Ze||ye||Rt)&&!i&&(Rt||(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[ct]??zn["bottom-right"]).split(" ").forEach($e=>Ge.classList.add($e)),c){let Ce=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;
@@ -102,7 +102,7 @@ _Details: ${n.message}_`:o}var Ag=e=>({isError:!0,content:[{type:"text",text:e}]
102
102
  flex-direction: column !important;
103
103
  z-index: ${Xt} !important;
104
104
  ${ut?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
105
- `,Ae.style.cssText=`
105
+ `,Me.style.cssText=`
106
106
  position: relative !important;
107
107
  display: flex !important;
108
108
  flex-direction: column !important;
@@ -115,8 +115,8 @@ _Details: ${n.message}_`:o}var Ag=e=>({isError:!0,content:[{type:"text",text:e}]
115
115
  padding: 0 !important;
116
116
  box-shadow: ${Pe} !important;
117
117
  border-radius: ${He} !important;
118
- ${ye?"border: none !important;":mt?`border: ${Lo} !important;`:""}
119
- `,Ae.style.setProperty("width","100%","important"),Ae.style.setProperty("max-width","100%","important"),ue.style.cssText=`
118
+ ${ye?"border: none !important;":mt?`border: ${Io} !important;`:""}
119
+ `,Me.style.setProperty("width","100%","important"),Me.style.setProperty("max-width","100%","important"),ue.style.cssText=`
120
120
  display: flex !important;
121
121
  flex-direction: column !important;
122
122
  flex: 1 1 0% !important;
@@ -134,23 +134,23 @@ _Details: ${n.message}_`:o}var Ag=e=>({isError:!0,content:[{type:"text",text:e}]
134
134
  border-top: none !important;
135
135
  padding: 8px 16px 12px 16px !important;
136
136
  ${Rt?"background: transparent !important;":""}
137
- `)}if(!f&&!i){let Ce="max-height: -moz-available !important; max-height: stretch !important;",$e=c?"":"padding-top: 1.25em !important;",ft=c?"":`z-index: ${o.launcher?.zIndex??rn} !important;`;Ge.style.cssText+=Ce+$e+ft}Cp(),Io()},Wp=()=>{e.style.setProperty("--persona-content-max-width",Dr(o,we()))},Nf=!1,Ff=()=>{let i=Qg(o,we());we()&&o.composer?.placement&&o.debug===!0&&!Nf&&(Nf=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=_o(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()},$f=()=>{if(we())return;let i=Et(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!fe)return;let f=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640;if(b&&f.innerWidth<=w)return;let O=f.innerHeight,z=64,q=o.launcher?.heightOffset??0,V=Math.max(200,O-z),X=Math.min(640,V);Ae.style.height=`${Math.max(200,X-q)}px`};Hp(),ki(e,o),bl(e,o),vl(e,o),Wp(),Ff(),Yr=()=>{Hp(),$f(),ki(e,o),bl(e,o),vl(e,o),Wp(),Ff(),Rl?e.style.setProperty("--persona-artifact-welded-outer-radius",Rl):e.style.removeProperty("--persona-artifact-welded-outer-radius"),yt(),Se()};let ve=[];ve.push(()=>{Hf=!0}),ve.push(()=>{d.forEach(i=>i()),l.destroy()}),ve.push(()=>{document.removeEventListener("keydown",Bf)}),ve.push(()=>{Ji!==null&&clearTimeout(Ji)});let Ao=null,Mo=null;ve.push(()=>{Ao?.(),Ao=null,Mo?.(),Mo=null}),ta&&ve.push(()=>{ta?.disconnect(),ta=null}),ve.push(()=>{ra?.(),ra=null,Rp(),vt&&(vt.remove(),vt=null),ze?.element.style.removeProperty("width"),ze?.element.style.removeProperty("maxWidth"),ze?.destroy()}),Wt&&ve.push(()=>{Sl=!0,ro=null,v!==null&&(cancelAnimationFrame(v),v=null),R?.destroy(),R=null,Tt?.destroy(),Tt=null,pn=null});let Jr=null,Uf=()=>{Jr&&(Jr(),Jr=null),o.colorScheme==="auto"&&(Jr=ol(()=>{ki(e,o)}))};Uf(),ve.push(()=>{Jr&&(Jr(),Jr=null)}),ve.push(()=>{C=!0,h?.()}),ve.push(()=>{B=!0});let jf=!1;ve.push(()=>{jf=!0});let Op=(i,c)=>{let g=ll(i,c);return g||!qC.includes(i)?g:(VC().then(f=>{if(jf)return;Ld(f.wipe),Ld(f.glyphCycle);let b=ll(i,c);b&&pl(b,e)}).catch(()=>{}),null)},Fl=o.features?.streamAnimation;if(Fl?.type&&Fl.type!=="none"){let i=Op(Fl.type,Fl.plugins);i&&pl(i,e),ve.push(()=>zC(e))}let qo=ml(pr),qf=ml(fp),zf=ml(Gi),Zr=[qo,qf,zf];ve.push(()=>{Zr.forEach(i=>i.destroy())});let es=null,P,ts=null,Vf=!1,Kf=0,Gf=null,Qf=i=>i.reduce((c,g)=>g.role==="user"?c+1:c,0),Yf=i=>{for(let c=i.length-1;c>=0;c--)if(Ci(i[c]))return i[c].id??null;return null},Xf=!1,hS=()=>{Xf||o.debug!==!0||(Xf=!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".'))},Jf=!1,Zf=!1,eh=(i,c)=>{Jf||o.debug!==!0||!c.enabled||c.expose||Vf||Zf&&(P.isStreaming()||i.some(Ci)||(Jf=!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.")))},Gs=i=>{if(!P)return;let c=i??P.getMessages(),g=V=>{V.render([],P,ce,c)},f=V=>{Zr.forEach(X=>{X!==V&&g(X)})};ts&&(Qf(c)>Kf||Yf(c)!==Gf)&&(ts=null);let b=Br(o);eh(c,b);let w=b.enabled?ag(c):null,O=ts??w,z=ts?"host":"agent";if(O){let V=o.suggestions?.followUps,X=V?.placement??(V?"auto":"composer"),me=(X==="auto"?we()?"composer":"after-message":X)==="after-message"?zf:qo;f(me),me.render(O,P,ce,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:Tc});return}if(c.some(V=>V.role==="user")){Zr.forEach(g);return}let q=o.suggestions?.starters;if(q){let V=Bs(_o(o),c),X=q.placement??"auto",se=X==="auto"?V?"welcome":"composer":X;if(se==="welcome"&&!V){hS(),Zr.forEach(g);return}let me=se==="welcome"?qf:qo;f(me),me.render(q.items??o.suggestionChips,P,ce,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:Tc});return}f(qo),qo.render(o.suggestionChips,P,ce,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a,submitPrompt:Tc})},th=()=>{ts&&(ts=null,Gs())},yS=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){th();return}let g=P?P.getMessages():[];ts=c,Vf=!0,Kf=Qf(g),Gf=Yf(g),Gs(g)},Bn=!1,Dt=RC(),Qs=new Map,ns=new Map,yr=new Map,os=null,br=null;function rs(){if(!os)return;let i=os;os=null,br?.destroy(),br=null,Dt.delete(i),ue.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),P&&Qn(Le,P.getMessages(),at)}let ss=0,bS=Ho()!==null,_n=_C(),Dn=0,vr=null,En=!1,$l=!1,Cr=0,qt=null,is=null,Bp=!1,Ys=!1,as=null,sa=!0,Ul=!1,Xs=null,jl=!1,ls=()=>{jl=!0,xS()},_p=null,vS=4,zo=24,CS=80,wS=1e3,Vo=null,nh=()=>{e.setAttribute("data-persona-scrollbar",yp()),yp()!=="on-scroll"&&(Vo!==null&&clearTimeout(Vo),Vo=null,oe.removeAttribute("data-persona-scrollbar-visible"))},xS=()=>{yp()==="on-scroll"&&(oe.setAttribute("data-persona-scrollbar-visible",""),Vo!==null&&clearTimeout(Vo),Vo=setTimeout(()=>{Vo=null,Ws(oe,zo)&&oe.removeAttribute("data-persona-scrollbar-visible")},wS))};nh(),ve.push(()=>{Vo!==null&&clearTimeout(Vo)});let Dp=new Map,Ve={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};Ef=()=>Ve.active,io();let oh=o.voiceRecognition?.autoResume??!1,Ko=i=>{A.emit("voice:state",{active:Ve.active,source:i,timestamp:Date.now()})},co=()=>{le(i=>({...i,voiceState:{active:Ve.active,timestamp:Date.now(),manuallyDeactivated:Ve.manuallyDeactivated}}))},SS=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=zm(ie.voiceState),c=!!i.active,g=Number(i.timestamp??0);Ve.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-g<yI&&setTimeout(()=>{Ve.active||(Ve.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?P.toggleVoice().then(()=>{Ve.active=P.isVoiceActive(),Ko("restore"),P.isVoiceActive()&&gi()}):Lc("restore"))},1e3)},AS=()=>P?ix(P.getMessages()).filter(i=>!i.__skipPersist):[],ql=null,rh=(i,c)=>{typeof console<"u"&&console.error(i,c)},zl=(i,c)=>{let g=()=>{try{let O=i();return!O||typeof O.then!="function"?null:Promise.resolve(O).catch(z=>{rh(c,z)})}catch(O){return rh(c,O),null}},f=ql,b=f?f.then(()=>g()??void 0):g();if(!b)return;let w=b.finally(()=>{ql===w&&(ql=null)});ql=w};function ia(i){if(!G?.save)return;let g={messages:i?ix(i):P?AS():[],metadata:ie,artifacts:Gn.artifacts,selectedArtifactId:Gn.selectedId,...cs?{draft:cs}:{}};zl(()=>G.save(g),"[AgentWidget] Failed to persist state:")}let cs,Vl=()=>!G?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,aa=oC({write:()=>{if(!Vl())return;let i=xe.getState(),c=tC({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Ru(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(cs)&&(cs=c,ia())}});function sh(){Vl()&&aa.schedule()}function Np(){aa.flush()}function ih(i){if(!Vl())return;let c=nC(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(g=>g.id),modelIds:(o.composer?.models??[]).map(g=>g.id),modes:o.composer?.modes??[]});c&&(cs=i,ce&&!ce.value&&(ce.value=c.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),Co()),c.selectedModelId&&(xe.setSelectedModelId(c.selectedModelId),mr?.repaint()),Ll(c.activeModeIds??[]),c.quote&&wo(c.quote),aa.cancel())}function Kl(){aa.cancel(),cs&&(cs=void 0,Vl()&&ia())}let Js=null,ah=()=>Ge.querySelector("#persona-scroll-container")||oe,Zs=()=>{Js!==null&&(cancelAnimationFrame(Js),Js=null),En=!1},lh=()=>{vr!==null&&(cancelAnimationFrame(vr),vr=null),$l=!1,Zs()},MS=()=>Bn&&$p()&&(On()!=="anchor-top"||cf()),Fp=()=>{let i=Qi()||"Jump to latest",c=MS();_t.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Cr>0?(Kr.textContent=String(Cr),Kr.style.display="",_t.setAttribute("aria-label",`${i} (${Cr} new)`)):(Kr.textContent="",Kr.style.display="none",_t.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},ch=()=>{Cr!==0&&(Cr=0,Fp())},ES=()=>{let i=qt?.spacerHeight??0;return i<=0?Ws(oe,zo):Xl(i)-oe.scrollTop-oe.clientHeight<=zo},$p=()=>gr()?!_n.isFollowing():!ES(),Up=()=>!!P&&P.getMessages().length>0,zt=()=>{if(!eS()||zr()){_t.parentNode&&_t.remove(),_t.style.display="none";return}_t.parentNode!==ue&&ue.appendChild(_t),Gr();let c=Bo(oe)>0&&$p()&&Up();c?Fp():ch(),_t.style.display=c?"":"none"},la=()=>{_n.pause()&&(lh(),zt())},Tn=()=>{_n.resume(),ch(),zt()},wr=(i=!1)=>{gr()&&Up()&&_n.isFollowing()&&(!i&&!Bn||(vr!==null&&(cancelAnimationFrame(vr),vr=null),$l=!0,vr=requestAnimationFrame(()=>{vr=null,$l=!1,_n.isFollowing()&&TS(ah(),i?220:140)})))},dh=(i,c,g,f=()=>!0)=>{let b=i.scrollTop,w=c(),O=w-b;if(Zs(),Math.abs(O)<1){En=!0,i.scrollTop=w,Dn=i.scrollTop,En=!1;return}let z=performance.now();En=!0;let q=X=>1-Math.pow(1-X,3),V=X=>{if(!f()){Zs();return}let se=c();se!==w&&(w=se,O=w-b);let me=X-z,Xe=Math.min(me/g,1),ct=q(Xe),ut=b+O*ct;i.scrollTop=ut,Dn=i.scrollTop,Xe<1?Js=requestAnimationFrame(V):(i.scrollTop=w,Dn=i.scrollTop,Js=null,En=!1)};Js=requestAnimationFrame(V)},TS=(i,c=500)=>{let g=Bo(i)-i.scrollTop;if(Math.abs(g)<1){Dn=i.scrollTop;return}if(Math.abs(g)>=CS){Zs(),En=!0,i.scrollTop=Bo(i),Dn=i.scrollTop,En=!1;return}dh(i,()=>Bo(i),c,()=>_n.isFollowing())},Gl=()=>{if(!Up()){zt();return}let i=ah();En=!0,i.scrollTop=Bo(i),Dn=i.scrollTop,En=!1,zt()},ds=i=>{let c=0,g=i;for(;g&&g!==oe;)c+=g.offsetTop,g=g.offsetParent;return c},PS=()=>{let i=oe.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??oe.ownerDocument.getSelection()},Ql=()=>FC(PS(),oe),jp=()=>{if(tS()!=="last-user-turn")return!1;let i=P?.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=oe.querySelector(`[data-message-id="${g}"]`);if(!f)return!1;let b=Math.min(Math.max(0,ds(f)-Yi()),Bo(oe));return En=!0,oe.scrollTop=b,Dn=oe.scrollTop,En=!1,On()==="follow"&&!Ws(oe,zo)&&_n.pause(),zt(),!0},Yl=i=>{let c=Math.max(0,Math.round(i));Kn.style.height=`${c}px`,Kn.style.display=c>0?"":"none",qt&&(qt.spacerHeight=Math.max(0,i))},Xl=i=>{let c=parseFloat(getComputedStyle(oe).paddingBottom)||0,g=0;for(let b of Array.from(oe.children)){if(b===Kn||b.offsetHeight===0)continue;let w=ds(b)+b.offsetHeight;w>g&&(g=w)}let f=oe.scrollHeight-i;return g>0?Math.min(g+c,f):f},kS=()=>{if(!qt||qt.spacerHeight<=0)return;let i=Xl(qt.spacerHeight),c=Math.max(0,Math.round(oe.scrollTop)+oe.clientHeight-i+zo);c<qt.spacerHeight&&(Yl(c),zt())},po=()=>{is!==null&&(cancelAnimationFrame(is),is=null),Zs(),qt=null,Kn.style.height="0px",Kn.style.display="none"},ph=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),qp=i=>oe.querySelector(`[data-message-id="${ph(i)}"]`),uh=i=>{is!==null&&cancelAnimationFrame(is),is=requestAnimationFrame(()=>{is=null;let c=ph(i),g=oe.querySelector(`[data-message-id="${c}"]`);if(!g)return;let f=ds(g),b=qt?.spacerHeight??0,w=Xl(b),{targetScrollTop:O,spacerHeight:z}=Jg({anchorOffsetTop:f,topOffset:Yi(),viewportHeight:oe.clientHeight,contentHeight:w,slack:zo});qt={initialSpacerHeight:z,contentHeightAtAnchor:w,spacerHeight:z},Yl(z),dh(oe,()=>g.isConnected?Math.max(0,ds(g)-Yi()):O,220)})},Pn=()=>{if(On()!=="anchor-top"||!qt||!Xs)return;let i=qp(Xs);if(!i)return;Zs();let c=qt.spacerHeight,g=Xl(c),{targetScrollTop:f,spacerHeight:b}=Jg({anchorOffsetTop:ds(i),topOffset:Yi(),viewportHeight:oe.clientHeight,contentHeight:g,slack:zo});qt={initialSpacerHeight:b,contentHeightAtAnchor:g,spacerHeight:b},Yl(b),En=!0,oe.scrollTop=f,Dn=oe.scrollTop,En=!1,zt()},LS=()=>{if(gr()){if(!_n.isFollowing()||Ws(oe,1))return;wr(!Bn);return}if(qt&&qt.initialSpacerHeight>0){let i=oe.scrollHeight-qt.spacerHeight,c=$C({initialSpacerHeight:qt.initialSpacerHeight,contentHeightAtAnchor:qt.contentHeightAtAnchor,currentContentHeight:i});c!==qt.spacerHeight&&Yl(c)}zt()},IS=i=>{let c=On();c==="follow"?(Tn(),wr(!0)):c==="anchor-top"&&(sa=!1,Ul=!0,jl=!1,Xs=i,uh(i))},RS=()=>{if(On()==="anchor-top"){if(Ul){sa=!1;return}sa=!0,po(),Tn(),wr(!0)}},HS=96,WS=i=>{if(as===null)return!0;let c=qp(as),g=qp(i);if(!c||!g)return!0;let f=ds(g)-ds(c);return Yi()+f>oe.clientHeight-HS},OS=i=>{if(On()!=="anchor-top"||!Ul||jl||Ql())return;let c=as===null;for(let g of i){if(!c){g.id===as&&(c=!0);continue}if(BC(g)){if(g.id===Xs||!WS(g.id))return;Xs=g.id,uh(g.id);return}}},BS=i=>{let c=new Map;i.forEach(g=>{let f=Dp.get(g.id);c.set(g.id,{streaming:g.streaming,role:g.role}),!f&&g.role==="assistant"&&(A.emit("assistant:message",g),!Ys&&(On()!=="anchor-top"||cf())&&$p()&&(Cr+=1,Fp(),zt(),El(Cr===1?"1 new message below.":`${Cr} 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}))}),Dp.clear(),c.forEach((g,f)=>{Dp.set(f,g)})},ca=(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")},Go=(i,c)=>{let g=document.createElement("div");return g.className="persona-flex",g.id=`wrapper-${i}`,g.setAttribute("data-wrapper-id",i),ca(g,c),g},_S=(i,c,g)=>{let f=document.createElement("div"),w=(()=>{let H=a.find(We=>We.renderLoadingIndicator);if(H?.renderLoadingIndicator)return H.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),O=(H,We)=>We==null?!1:typeof We=="string"?(H.textContent=We,!0):(H.appendChild(We),!0),z=new Set,q=new Map,V=new Set,X=a.some(H=>H.renderAskUserQuestion),se=[],me=[],Xe=o.enableComponentStreaming!==!1,ct=o.approval!==!1,ut=[],Xt=o.messageActions,Ft=Xt?.showRegenerate===!0&&Xt.enabled!==!1&&lt.current?.isStreaming()!==!0?cv(c):null,It=Xt?.showEdit===!0&&Xt.enabled!==!1,an=Xt?.showQuote===!0&&Xt.enabled!==!1,Ze=null,ln=o.features?.reasoningDisplay?.completedVisibility==="removed";if(c.forEach(H=>{if(ln&&H.variant==="reasoning"&&H.reasoning?.status==="complete")return;if(z.add(H.id),q.set(H.id,H.role),os===H.id&&br){let He=Go(H.id,H.role);He.setAttribute("data-persona-message-edit-stub","true"),He.setAttribute("data-preserve-runtime","true"),f.appendChild(He),Ze={messageId:H.id,element:br.element};return}let We=X&&Rr(H),Be=ct&&H.variant==="approval"&&!!H.approval,ye=!We&&H.role==="assistant"&&!H.variant&&Xe&&np(H);!Be&&yr.has(H.id)&&(i.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),yr.delete(H.id)),!ye&&ns.has(H.id)&&(i.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),ns.delete(H.id));let mt=Rr(H)?`:${H.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${H.agentMetadata?.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",Vt={canRegenerate:Ft===H.id,canEdit:It&&bg(H),canQuote:an&&!H.variant&&(H.content?.trim().length??0)>0},cn=`${Vt.canRegenerate?"r":""}${Vt.canEdit?"e":""}${Vt.canQuote?"q":""}`,dn=IC(H,ss)+mt+`:${cn}`,Rt=We||Be||ye?null:HC(Dt,H.id,dn);if(Rt){f.appendChild(Rt.cloneNode(!0)),Rr(H)&&H.toolCall?.id&&H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(V.add(H.toolCall.id),Ua(H,o,Fe.composerOverlay));return}let Pe=null,Kt=a.find(He=>!!(H.variant==="reasoning"&&He.renderReasoning||H.variant==="tool"&&He.renderToolCall||!H.variant&&He.renderMessage)),Gt=o.layout?.messages;if(Rr(H)&&H.agentMetadata?.askUserQuestionAnswered===!0){Qs.delete(H.id),i.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ci(H)&&Br(o).enabled)return;if(Rr(H)&&o.features?.askUserQuestion?.enabled!==!1){let He=a.find(wt=>typeof wt.renderAskUserQuestion=="function");if(He&&lt.current){let wt=Qs.get(H.id),Io=wt!==dn,uo=null;if(Io){let{payload:$e,complete:ft}=Hr(H),kr=H.id,Qt=()=>lt.current?.getMessages().find($n=>$n.id===kr);uo=He.renderAskUserQuestion({message:H,payload:$e,complete:ft,resolve:$n=>{let As=Qt();As&&lt.current?.resolveAskUserQuestion(As,$n)},dismiss:()=>{let $n=Qt();$n?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved($n),lt.current?.resolveAskUserQuestion($n,"(dismissed)"))},config:o})}let Oe=wt!=null;if(Io&&uo===null&&!Oe){H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(V.add(H.toolCall.id),Ua(H,o,Fe.composerOverlay));return}let Ce=Go(H.id,H.role);Ce.setAttribute("data-ask-plugin-stub","true"),Ce.setAttribute("data-preserve-runtime","true"),f.appendChild(Ce),se.push({messageId:H.id,fingerprint:dn,bubble:uo});return}else{H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(V.add(H.toolCall.id),Ua(H,o,Fe.composerOverlay));return}}else if(Be){let He=k();if(!He){f.appendChild(Go(H.id,H.role));return}let wt=a.find(Ce=>typeof Ce.renderApproval=="function")??y,uo=yr.get(H.id)!==dn,Oe=null;if(uo&&wt?.renderApproval){let Ce=H.id,$e=(ft,kr)=>{let Qt=lt.current?.getMessages().find($n=>$n.id===Ce);Qt?.approval&&(Qt.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(Qt.id,ft):lt.current?.resolveApproval(Qt.approval,ft,kr))};Oe=wt.renderApproval({message:H,defaultRenderer:()=>He.createApprovalBubble(H,o),config:o,approve:ft=>$e("approved",ft),deny:ft=>$e("denied",ft)})}if(uo&&Oe===null)i.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),yr.delete(H.id),Pe=He.createApprovalBubble(H,o);else{let Ce=Go(H.id,H.role);Ce.setAttribute("data-approval-plugin-stub","true"),Ce.setAttribute("data-preserve-runtime","true"),f.appendChild(Ce),ut.push({messageId:H.id,fingerprint:dn,bubble:Oe});return}}else if(Kt)if(H.variant==="reasoning"&&H.reasoning&&Kt.renderReasoning){if(!nn)return;Pe=Kt.renderReasoning({message:H,defaultRenderer:()=>xm(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&Kt.renderToolCall){if(!wn)return;Pe=Kt.renderToolCall({message:H,defaultRenderer:()=>Am(H,o),config:o})}else Kt.renderMessage&&(Pe=Kt.renderMessage({message:H,defaultRenderer:()=>{let He=yl(H,g,Gt,o.messageActions,In,{loadingIndicatorRenderer:w,widgetConfig:o,actionEligibility:Vt});return H.role!=="user"&&I(He,H,o,P),He},config:o}));if(!Pe&&ye){let He=Um(H);if(He){let wt=ns.get(H.id),Io=wt!==dn,uo=o.wrapComponentDirectiveInBubble!==!1&&Do.getOptions(He.component)?.bubbleChrome!==!1,Oe=null;if(Io){let Ce=$m(He,{config:o,message:H,transform:g});if(Ce&&He.component==="PersonaArtifactInline"){let $e=Ce.hasAttribute("data-artifact-inline")?Ce:Ce.querySelector("[data-artifact-inline]"),ft=$e?.getAttribute("data-artifact-inline")??"",kr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(ft):ft,Qt=ft?i.querySelector(`#wrapper-${H.id}`)?.querySelector(`[data-artifact-inline="${kr}"]`)??null:null;$e&&Qt&&Qt!==$e&&ar()?.hasLiveInlineArtifactBlock(Qt)&&($e===Ce?Ce=Qt:$e.replaceWith(Qt))}if(Ce)if(uo){let $e=document.createElement("div");if($e.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),$e.id=`bubble-${H.id}`,$e.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let ft=document.createElement("div");ft.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ft.innerHTML=g({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),$e.appendChild(ft)}$e.appendChild(Ce),Oe=$e}else{let $e=document.createElement("div");if($e.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$e.id=`bubble-${H.id}`,$e.setAttribute("data-message-id",H.id),$e.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let ft=document.createElement("div");ft.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",ft.innerHTML=g({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),$e.appendChild(ft)}$e.appendChild(Ce),Oe=$e}}if(Oe||wt!=null){let Ce=Go(H.id,H.role);Ce.setAttribute("data-component-directive-stub","true"),Ce.setAttribute("data-preserve-runtime","true"),f.appendChild(Ce),me.push({messageId:H.id,fingerprint:dn,bubble:Oe});return}}}if(!Pe)if(H.variant==="reasoning"&&H.reasoning){if(!nn)return;Pe=xm(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!wn)return;Pe=Am(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;let He=k();if(!He)return;Pe=He.createApprovalBubble(H,o)}else{let He=o.layout?.messages;He?.renderUserMessage&&H.role==="user"?Pe=He.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):He?.renderAssistantMessage&&H.role==="assistant"?Pe=He.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):Pe=yl(H,g,He,o.messageActions,In,{loadingIndicatorRenderer:w,widgetConfig:o,actionEligibility:Vt}),H.role!=="user"&&Pe&&I(Pe,H,o,P)}let to=Go(H.id,H.role);to.appendChild(Pe),WC(Dt,H.id,dn,to),f.appendChild(to)}),Fe.composerOverlay&&Fe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(We=>{let Be=We.getAttribute("data-persona-ask-sheet-for");Be&&!V.has(Be)&&Is(Fe.composerOverlay,Be)}),o.features?.toolCallDisplay?.grouped){let H=[],We=[],Be=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(ye=>{if(ye.variant==="tool"&&ye.toolCall&&wn){We.push(ye);return}ye.variant==="reasoning"&&(!nn||ln&&ye.reasoning?.status==="complete")||((We.length>1||Be&&We.length>0)&&H.push(We),We=[])}),(We.length>1||Be&&We.length>0)&&H.push(We),H.forEach(ye=>{let mt=ye.map(Gt=>Array.from(f.children).find(to=>to instanceof HTMLElement&&to.getAttribute("data-wrapper-id")===Gt.id)).filter(Gt=>!!Gt);if(mt.length<(Be?1:2))return;let Vt=Go(`tool-group-${ye[0].id}`,"assistant");Vt.setAttribute("data-persona-tool-group-row","true");let cn=document.createElement("div");cn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",cn.setAttribute("data-persona-tool-group","true");let dn=document.createElement("div");dn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",dn.id=`tool-group-summary-${ye[0].id}`;let Rt=`Called ${ye.length} ${ye.length===1?"tool":"tools"}`,Pe=o.toolCall?.renderGroupedSummary?.({messages:ye,toolCalls:ye.map(Gt=>Gt.toolCall).filter(Gt=>!!Gt),defaultSummary:Rt,config:o});O(dn,Pe)||(dn.textContent=Rt);let Kt=document.createElement("div");Kt.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.id=`tool-group-stack-${ye[0].id}`,Kt.setAttribute("data-persona-tool-group-stack","true"),cn.appendChild(dn),Be||cn.appendChild(Kt),Vt.appendChild(cn),mt[0].before(Vt),mt.forEach((Gt,to)=>{if(Be){Gt.remove();return}Gt.style.setProperty("--persona-message-row-max-width","100%");let He=document.createElement("div");He.className="persona-tool-group-item persona-relative",He.setAttribute("data-persona-tool-group-item","true"),to<mt.length-1&&He.setAttribute("data-persona-tool-group-connector","true"),He.appendChild(Gt),Kt.appendChild(He)})})}OC(Dt,z);let nr=c.some(H=>H.role==="assistant"&&H.streaming),ko=c[c.length-1],Lo=ko?.role==="assistant"&&!ko.streaming&&ko.variant!=="approval";if(Bn&&c.some(H=>H.role==="user")&&!nr&&!Lo){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:Oi},We=a.find(ye=>ye.renderLoadingIndicator),Be=null;if(We?.renderLoadingIndicator&&(Be=We.renderLoadingIndicator(H)),Be===null&&o.loadingIndicator?.render&&(Be=o.loadingIndicator.render(H)),Be===null&&(Be=Oi()),Be){let ye=document.createElement("div"),mt=o.loadingIndicator?.showBubble!==!1,Vt=o.layout?.messages?.layout??"bubble";ye.className=mt?hl("assistant",Vt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),ye.setAttribute("data-typing-indicator","true"),mt&&(ye.style.color="var(--persona-message-assistant-text, var(--persona-text))",Vt!=="flat"&&(ye.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),ye.appendChild(Be);let cn=Go("typing-indicator","assistant");cn.appendChild(ye),f.appendChild(cn)}}if(!Bn&&c.length>0){let H=c[c.length-1],We={config:o,lastMessage:H,messageCount:c.length},Be=a.find(mt=>mt.renderIdleIndicator),ye=null;if(Be?.renderIdleIndicator&&(ye=Be.renderIdleIndicator(We)),ye===null&&o.loadingIndicator?.renderIdle&&(ye=o.loadingIndicator.renderIdle(We)),ye){let mt=document.createElement("div"),Vt=o.loadingIndicator?.showBubble!==!1;mt.className=Vt?["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(" "),mt.setAttribute("data-idle-indicator","true"),mt.appendChild(ye);let cn=Go("idle-indicator","assistant");cn.appendChild(mt),f.appendChild(cn)}}if(cb(f),Pd(i,f),Zu(i),Ze){let{messageId:H,element:We}=Ze,Be=i.querySelector(`#wrapper-${H}`);Be&&We.parentElement!==Be&&(ca(Be,q.get(H)??"user"),Be.replaceChildren(We))}if(se.length>0)for(let{messageId:H,fingerprint:We,bubble:Be}of se){let ye=i.querySelector(`#wrapper-${H}`);ye&&(ca(ye,q.get(H)??"assistant"),Be!==null&&(ye.replaceChildren(Be),ye.setAttribute("data-bubble-fp",We),Qs.set(H,We)))}if(Qs.size>0)for(let H of Qs.keys())z.has(H)||Qs.delete(H);if(me.length>0)for(let{messageId:H,fingerprint:We,bubble:Be}of me){let ye=i.querySelector(`#wrapper-${H}`);ye&&(ca(ye,q.get(H)??"assistant"),Be!==null&&(ye.replaceChildren(Be),ye.setAttribute("data-bubble-fp",We),ns.set(H,We)))}if(ns.size>0)for(let H of ns.keys())z.has(H)||ns.delete(H);if(ut.length>0)for(let{messageId:H,fingerprint:We,bubble:Be}of ut){let ye=i.querySelector(`#wrapper-${H}`);ye&&(ca(ye,q.get(H)??"assistant"),Be!==null&&(ye.replaceChildren(Be),ye.setAttribute("data-bubble-fp",We),yr.set(H,We)))}if(yr.size>0)for(let H of yr.keys())z.has(H)||yr.delete(H)},zp=!1,Jl=()=>{zp||(zp=!0,Gu().catch(()=>{zp=!1}))},Qn=(i,c,g)=>{c.length>0&&Jl(),_S(i,c,g),Rf()},da=null,DS=()=>{if(da)return;let i=g=>{let f=g.composedPath();f.includes(Ge)||Yt&&f.includes(Yt)||pt(!1,"user")};da=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},gh=()=>{if(!da)return;(e.ownerDocument??document).removeEventListener("pointerdown",da,!0),da=null};ve.push(()=>gh());let pa=null,NS=()=>{if(pa)return;let i=g=>{g.key==="Escape"&&(g.isComposing||pt(!1,"user"))};pa=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},mh=()=>{if(!pa)return;(e.ownerDocument??document).removeEventListener("keydown",pa,!0),pa=null};ve.push(()=>mh());let ua=!1,fh=new Set,FS=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},ei=()=>{if(!we())return;let i=Fe.peekBanner,c=Fe.peekTextNode;if(!i||!c)return;if(he){i.classList.remove("persona-pill-peek--visible");return}let g=P?.getMessages()??[],f;for(let Ft=g.length-1;Ft>=0;Ft--){let It=g[Ft];if(It.role==="assistant"&&It.content){f=It;break}}if(!f){i.classList.remove("persona-pill-peek--visible");return}let b=f.content,w=!!f.streaming,O=FS(),z=kd(O),q=z.type!=="none"?Op(z.type,O?.plugins):null,V=q?.isAnimating?.(f)===!0,X=q!==null&&(w||V);X&&q&&!fh.has(q.name)&&(pl(q,e),fh.add(q.name));let se=X&&q?.containerClass?q.containerClass:null,me=c.dataset.personaPeekStreamClass??null;me&&me!==se&&(c.classList.remove(me),delete c.dataset.personaPeekStreamClass),se&&me!==se&&(c.classList.add(se),c.dataset.personaPeekStreamClass=se),X?(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=X?Id(b,z.buffer,q,f,w):b;if(X&&z.placeholder==="skeleton"&&w&&(!Xe||!Xe.trim())){let Ft=document.createElement("div"),It=dl();It.classList.add("persona-pill-peek__skeleton"),Ft.appendChild(It),Pd(c,Ft)}else{let Ft=Math.max(0,Xe.length-100),It=Xe.length>100?Xe.slice(-100):Xe,an=Ir(It);if(!X||!q){let Ze=Xe.length>100?`\u2026${It}`:It;c.textContent!==Ze&&(c.textContent=Ze)}else{let Ze=an;(q.wrap==="char"||q.wrap==="word")&&(Ze=cl(an,q.wrap,`peek-${f.id}`,{skipTags:q.skipTags,startIndex:Ft}));let ln=document.createElement("div");if(ln.innerHTML=Ze,q.useCaret&&It.length>0){let nr=Rd(),ko=ln.querySelectorAll(".persona-stream-char, .persona-stream-word"),Lo=ko[ko.length-1];Lo?.parentNode?Lo.parentNode.insertBefore(nr,Lo.nextSibling):ln.appendChild(nr)}Pd(c,ln),q.onAfterRender?.({container:c,bubble:i,messageId:f.id,message:f,speed:z.speed,duration:z.duration})}}let Xt=Bn||ua;i.classList.toggle("persona-pill-peek--visible",Xt)};if(we()){let i=Fe.peekBanner;if(i){let f=b=>{b.preventDefault(),b.stopPropagation(),pt(!0,"user")};i.addEventListener("pointerdown",f),ve.push(()=>{i.removeEventListener("pointerdown",f)})}let c=()=>{ua||(ua=!0,ei())},g=()=>{ua&&(ua=!1,ei())};Ae.addEventListener("pointerenter",c),Ae.addEventListener("pointerleave",g),ve.push(()=>{Ae.removeEventListener("pointerenter",c),Ae.removeEventListener("pointerleave",g)}),Yt&&(Yt.addEventListener("pointerenter",c),Yt.addEventListener("pointerleave",g),ve.push(()=>{Yt.removeEventListener("pointerenter",c),Yt.removeEventListener("pointerleave",g)}))}let $S=i=>{let c=o.launcher?.composerBar??{},g=c.expandedSize??"anchored",f=c.bottomOffset??"16px",b=c.collapsedMaxWidth,w=c.expandedMaxWidth??"880px",O=c.expandedTopOffset??"5vh",z=c.modalMaxWidth??"880px",q=c.modalMaxHeight??"min(90vh, 800px)",V="calc(100vw - 32px)",X="var(--persona-pill-area-height, 80px)",se=Ge.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",Yt){let me=Yt.style;me.bottom=f,me.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} + ${X})`,se.top=O,se.width=w,se.maxWidth=V}},ga=()=>{if(he&&Jl(),!ke())return;if(we()){let V=(o.launcher?.composerBar??{}).expandedSize??"anchored",X=he?"expanded":"collapsed";Ge.dataset.state=X,Ge.dataset.expandedSize=V,Yt&&(Yt.dataset.state=X,Yt.dataset.expandedSize=V),Ge.style.removeProperty("display"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),$S(he),ue.style.display=he?"flex":"none",Yr(),he?(DS(),NS()):(gh(),mh()),ei();return}let i=Et(o),c=e.ownerDocument.defaultView??window,g=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,b=c.innerWidth<=g,w=f&&b&&fe,O=qn(o).reveal;he?(Ge.style.removeProperty("display"),Ge.style.display=i?"flex":"",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.classList.remove("persona-scale-95","persona-opacity-0"),Ae.classList.add("persona-scale-100","persona-opacity-100"),kt?(kt.setPanelOpen(!0),kt.element.style.display="none"):mn&&(mn.style.display="none")):(i?i&&(O==="overlay"||O==="push")&&!w?(Ge.style.removeProperty("display"),Ge.style.display="flex",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ae.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"),Ae.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"),Ae.classList.remove("persona-scale-100","persona-opacity-100"),Ae.classList.add("persona-scale-95","persona-opacity-0")),kt?(kt.setPanelOpen(!1),kt.element.style.display=i?"none":""):mn&&(mn.style.display=i?"none":""))},pt=(i,c="user")=>{if(!ke()||he===i)return;let g=he;he=i,ga();let f=(()=>{let w=o.launcher?.sidebarMode??!1,O=e.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,q=o.launcher?.mobileBreakpoint??640,V=O.innerWidth<=q,X=Et(o)&&z&&V,se=we()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return w||z&&V&&fe||X||se})();if(he&&f){if(!Ao){let w=e.getRootNode(),O=w instanceof ShadowRoot?w.host:e.closest(".persona-host");O&&(Ao=tm(O,o.launcher?.zIndex??rn))}Mo||(Mo=nm(e.ownerDocument))}else he||(Ao?.(),Ao=null,Mo?.(),Mo=null);he&&(Ia(),jp()||(On()==="follow"?wr(!0):Gl()));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:fe,voiceActive:Ve.active,streaming:P.isStreaming()})},xr={inputDisabled:!1,sendDisabled:!1},Sr=()=>xr.inputDisabled,ps=()=>xr.inputDisabled||xr.sendDisabled,US=()=>(xr.inputDisabled?xr.inputReason:void 0)??(xr.sendDisabled?xr.sendReason:void 0);function Vp(){if(!Ee)return;if(xe.getState().phase==="streaming"){Ee.disabled=!1;return}let i=Je?!Je.isReady():!1;Ee.disabled=ps()||i}function Zl(){if(!vo)return;let i=xe.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;vo.toggleAttribute("data-persona-send-hidden",c)}function jS(){let i=US();if(we()){let c=so??Re;i?c.setAttribute("title",i):c.removeAttribute("title"),Re.toggleAttribute(zi,!!i);return}if(i){ot.setAttribute("role","status"),ot.setAttribute("aria-live","polite"),ot.setAttribute(zi,""),ot.textContent=i;return}if(ot.hasAttribute(zi)&&(ot.removeAttribute("role"),ot.removeAttribute("aria-live"),ot.removeAttribute(zi),p)){let c=P.getStatus();sn(ot,un(c),o.statusIndicator??{},c)}}function Kp(){let i=Rg(o.composer?.inputDisabled),c=Rg(o.composer?.sendDisabled);xr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},xe.setInputDisabled(i.disabled),xe.setSendDisabled(c.disabled);let g=xe.getState().phase==="streaming",f=i.disabled,b=g||f;ce&&(ce instanceof HTMLTextAreaElement?ce.disabled=f:ce.setAttribute("contenteditable",f?"false":"true"),ce.setAttribute("aria-disabled",f?"true":"false")),At&&(At.disabled=f),bt&&(bt.disabled=f);for(let w of Bt?.affordanceButtons??[])w.querySelectorAll("button").forEach(O=>{O.disabled=f});re&&(re.disabled=b),Zr.forEach(w=>{w.elements.forEach(O=>{O.toggleAttribute("data-disabled",b),O instanceof HTMLButtonElement||O.setAttribute("aria-disabled",b?"true":"false")}),w.buttons.forEach(O=>{O.disabled=b})}),Jp.forEach(w=>{w.toggleAttribute("data-disabled",b),w instanceof HTMLButtonElement?w.disabled=b:w.setAttribute("aria-disabled",b?"true":"false"),w.querySelectorAll("button").forEach(O=>{O.disabled=b})}),Re.dataset.personaComposerStreaming=g?"true":"false",Re.dataset.personaComposerInputDisabled=f?"true":"false",Re.dataset.personaComposerSendDisabled=ps()?"true":"false",Re.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(w=>{(w instanceof HTMLButtonElement||w instanceof HTMLInputElement||w instanceof HTMLTextAreaElement||w instanceof HTMLSelectElement)&&(w.disabled=g)}),Vp(),jS()}let ma=i=>{xe.setStreaming(i),af(i?"stop":"send"),Kp()},us=()=>{Ve.active||ce&&ce.focus()};A.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>us(),200)});let gs=null,fa=!1,Gp=!Sn.hidden,Ar=null,Qp=!ne,ec=null;ve.push(()=>{ec?.cancel(),ec=null});let qS=i=>{let c=fw(i);if(c===Tl)return;Tl=c,e.setAttribute("data-persona-conversation-state",c);let g=vp();kl(),Qp&&(ec?.cancel(),ec=gw(Re,c==="active"?g:vp(),c==="active"?"drop":"rise")),Pn()},hh=null,yh,bh=null,ti=null,Yp=!1,ha=i=>{let c=_o(o),g=`${c.variant}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(g!==hh||c.icon!==yh)&&(hh=g,yh=c.icon,Dd({host:Sn,iconHolder:Kx,kicker:Gx,title:Qx,subtitle:Yx,starterSuggestions:fp},c));let f=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;f!==bh&&(bh=f,Nd(Hn,c.message,o));let b=i??(P?P.getMessages():o.initialMessages);qS(b);let w=fa,O=!w&&Bs(c,b),z=O!==Gp;if(Gp=O,ti){Ar?.cancel(),Ar=null,w!==Yp&&(Yp=w,w?mm(oe,Sn,null):gm(oe,Sn,ti)),Bi(oe,Sn,!w);return}if(z&&!O&&!w&&c.dismiss==="on-first-message"&&Qp){Ar=uw(Sn,V=>{Ar===V&&(Ar=null),!Gp&&!ti&&(Bi(oe,Sn,!1),Pn()),V?.cancel()});return}if(Ar){if(!O&&!w)return;Ar.cancel(),Ar=null}let q=!Sn.hidden;Bi(oe,Sn,O),!O&&q&&Pn()},Xp=[],Jp=[],Zp=!1,vh=null,Ch,wh=()=>{Jp.length=0;let i=Xp.splice(0,Xp.length);for(let c of i)try{c()}catch(g){console.warn("[persona] renderWelcome cleanup threw",g)}};ve.push(wh);let zS=(i,c)=>{let g=rm(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=sm({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:()=>ce,eventTarget:Sn,submitPrompt:Tc});return Jp.push(b),b},eu=()=>{if(Zp)return;Zp=!0;let i=_o(o);vh=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,Ch=i.icon;try{wh(),mm(oe,Sn,ti),ti=null,Yp=!1;let c=P?P.getMessages():o.initialMessages,g=Bs(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:()=>Sn,sendMessage:O=>{if(!P||P.isStreaming())return;let z=O.trim();z&&P.sendMessage(z)},requestRender:()=>eu(),renderStarter:O=>zS(O,f++),storage:u(w.id),onCleanup:O=>{Xp.push(O)}}),b))break;b&&b!==Sn&&(ti=b,gm(oe,Sn,b))}finally{Zp=!1}ha()},VS=()=>{let i=_o(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===vh&&i.icon===Ch||eu()},tc=()=>{ha(),qs||(ce.placeholder=Yv(xe.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!P?.isStreaming()&&(Ee.textContent=o.copy?.sendButtonLabel??"Send")),ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ce.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},KS=!!o.setStoredConversationId,ya=i=>le(c=>{let g={...c};return delete g[i],g}),nc=i=>{let c=ie[i];return typeof c=="string"?c:null};o.clientToken&&(o={...o,getStoredSessionId:()=>nc("sessionId"),setStoredSessionId:i=>{le(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ya("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>nc("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{le(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ya("conversationId"))});let xh=()=>o.features?.history?.enabled===!0?o.clientToken??null:null,Sh=i=>Qw(i,bo(),o.persistState===!1),Ah=xh(),Qo=Ah?Sh(Ah):null,ms={...Qo?{visitorStore:Qo}:{},historyBootstrapReady:D,getStoredMessageCursor:()=>nc("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){ya("historyMessageCursor");return}le(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=ie.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){ya("pendingDisplayProjections");return}le(c=>({...c,pendingDisplayProjections:i}))},...KS?{}:{getStoredConversationRevision:()=>nc("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){ya("conversationRevision");return}le(c=>({...c,conversationRevision:i}))}}},GS=()=>{let i=xh();if(i&&Qo?.matches(i,bo(),o.persistState===!1)||!i&&!Qo)return;Qo?.destroy(),Qo=i?Sh(i):null;let c={...ms};Qo?c.visitorStore=Qo:delete c.visitorStore,ms=c,P.setHistoryInternals(ms)},fs=null,QS=()=>{fs==null&&(fs=setInterval(()=>{let i=Le.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(fs),fs=null;return}let c=Date.now();i.forEach(g=>{let f=Number(g.getAttribute("data-tool-elapsed"));f&&(g.textContent=Xc(c-f))})},100))},tu=(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((O,z)=>tu(O,c[z]));let g=i,f=c,b=Object.keys(g),w=Object.keys(f);return b.length===w.length&&b.every(O=>Object.prototype.hasOwnProperty.call(f,O)&&tu(g[O],f[O]))},Mh=i=>{let{content:c,rawContent:g,llmContent:f,...b}=i;return b},nu=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!np(i),YS=(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))&&nu(f)&&nu(b)&&tu(Mh(f),Mh(b))},ou=null,ni=null,hs=null,Yo=null,oc=i=>{ou=i;let c,g;ni=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),!ni&&nu(w)&&(ni={index:b,id:w.id}),c&&g&&ni)break}Qn(Le,i,at),ar()?.updateInlineArtifactBlocks(Le,Gn.artifacts,{suppressTransition:Bn}),QS(),ha(i),Gs(i),wr(!Bn),BS(i),i.length===0&&(po(),sa=!0,Ul=!1,Xs=null,jl=!1),!Bp||Ys?(Bp=!0,as=c?.id??null,_p=g?.id??null):c&&c.id!==as?(as=c.id,IS(c.id)):g&&g.id!==_p&&RS(),g&&(_p=g.id),OS(i);let f=Ve.lastUserMessageId;c&&c.id!==f&&(Ve.lastUserMessageId=c.id,A.emit("user:message",c)),Ve.lastUserMessageWasVoice=!!c?.viaVoice,ia(i),ei()},ru=()=>{Yo!==null&&(cancelAnimationFrame(Yo),Yo=null);let i=hs;hs=null,i&&oc(i)},Eh=()=>{Yo!==null&&cancelAnimationFrame(Yo),Yo=null,hs=null},XS=i=>{let c=hs??ou;if(Bn&&c&&ni&&YS(c,i,ni)){hs=i,Yo===null&&(Yo=requestAnimationFrame(()=>{Yo=null;let g=hs;hs=null,g&&oc(g)}));return}if(i.length===0){Eh(),oc(i);return}ru(),oc(i)};P=new Xa(o,{onMessagesChanged(i){XS(i)},onStatusChanged(i){let c=o.statusIndicator??{};sn(ot,(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),St()},onStreamingChanged(i){i||(P?.getMessages().length===0?Eh():ru()),Bn=i,ma(i),St(),P&&Qn(Le,P.getMessages(),at),i||(wr(!0),kS(),Zf=!0,P&&eh(P.getMessages(),Br(o))),zt(),El(i?"Responding\u2026":"Response complete."),ei()},onVoiceStatusChanged(i){if(A.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":tr(),gi();break;case"processing":tr(),ZA();break;case"speaking":tr(),eM();break;default:i==="idle"&&P.isBargeInActive()?(tr(),gi(),re?.setAttribute("aria-label","End voice session")):(Ve.active=!1,tr(),Ko("system"),co());break}},onArtifactsState(i){Gn=i,i.artifacts.length===0&&(zs=!1),ar()?.updateInlineArtifactBlocks(Le,i.artifacts,{suppressTransition:Bn}),lo(),ia()},onHistoryStateChanged(i){qe(i)},onHistoryNotice(i){Ot(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})}},ms),lt.current=P,ve.push(()=>P.cancel()),ve.push(()=>{P.destroy(),Qo?.destroy()});let su=null;if(P.onReadAloudChange((i,c)=>{Lf=i,If=c,Rf();let g=i??su;i&&(su=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"&&(su=null)}),p=!0,Bp=!0,o.voiceRecognition?.provider?.type==="runtype")try{P.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let JS=720,ZS=250,Ye=Nm(o.features?.history?.copy),Nn=null,iu=!1,rt=null,rc=null,sc="conversation",au=null,gn=null,Eo=null,ic=P.getHistoryState(),lu=null,ba=0,cu=null,ac=null,lc=null,du=`persona-history-${Math.random().toString(36).slice(2,8)}`,pu=()=>o.features?.history?.enabled===!0,To=()=>pu()&&!!Nn&&!iu,Th=()=>{let i=P.getStatus();return Bn||i==="paused"||i==="resuming"},uu=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",g=Nn?.capabilities.scopes;return!g||g.includes(c)?c:g[0]??c},oi=()=>rc?.scope??uu(),Ph=()=>P.getClientSession()?.targetId??null,kh=i=>`${i.state}:${"reason"in i?i.reason:""}`,eA=i=>{let c=kh(i);c!==lu&&(lu=c,A.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},cc=i=>{i&&($o.textContent="",$o.textContent=i)},Lh=null,Ih=null,tA=()=>{if(!pu())return null;let i=Zw();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(Lh!==c&&(Lh=c,Ih=c()),Ih):P.isClientTokenMode()?ex({client:P.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:g=>P.bindActivatedSession(g),getClient:()=>P.getClient()}):null},Rh=()=>{ac?.(),ac=null,lc?.(),lc=null,iu=!1,Nn=tA();let i={...ms};Nn?i.historyProvider=Nn:delete i.historyProvider,ms=i,P.setHistoryInternals(ms),Nn&&(ac=Nn.subscribeAvailability?.(c=>{iu=!c,c||kn({restoreFocus:!1}),Er()})??null,lc=Nn.subscribeIdentityStatus(c=>eA(c)),lu=kh(Nn.getIdentityStatus()))},gu=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!fe||Et(o)))return"panel";let c=So??ue;return(c.getBoundingClientRect().width||c.clientWidth)>=JS?"rail":"panel"},Yn=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},dc="data-persona-history-suppressed",Fn=null,Mr=null,ys=null,va=null,mu=null,Hh="",Wh=()=>Te===mu?Hh:o.layout?.showHeader===!1?"none":"",nA=()=>ae==="panel"&&!!ys&&va===ys.element&&o.layout?.showHeader!==!1&&Wh()!=="none",oA=()=>{for(let i of Array.from(Te.children))i!==Fn&&i.setAttribute(dc,"")},rA=()=>{for(let i of Array.from(ue.querySelectorAll(`[${dc}]`)))i.removeAttribute(dc)},sA=()=>{let i=ys;if(!i)return;if(Array.from(Te.children).some(f=>f!==Fn&&!f.hasAttribute(dc))){Mr&&Mr!==Te&&(Mr.style.removeProperty("min-height"),Mr=null);let f=Te.offsetHeight;f>0&&(Te.style.minHeight=`${f}px`,Mr=Te)}Fn||(Fn=M("div","persona-history-header-host")),i.setHeaderPlacement("external");let g=i.getHeaderElement();g.parentNode!==Fn&&Fn.replaceChildren(g),Fn.parentNode!==Te&&Te.appendChild(Fn),oA()},Oh=()=>{Mr&&(Mr.style.removeProperty("min-height"),Mr=null),Fn&&(ys?.setHeaderPlacement("inline"),Fn.remove(),Fn=null,rA())},pc=null,fu=()=>{if(pc){if(oe.style.display="none",Yn(oe,!0),Re.hidden=!0,Yn(Re,!0),nA()){sA(),Te.style.display=Wh(),Yn(Te,!1);return}Oh(),Te.style.display="none",Yn(Te,!0)}};Se=fu;let iA=i=>{let c=oe.style.display,g=Re.hidden,f=Re,b=Te,w=Te.style.display;mu=b,Hh=w,pc=()=>{pc=null,Oh(),mu=null,oe.style.display=c,Yn(oe,!1),f.hidden=g,Yn(f,!1),Re!==f&&(Re.hidden=!1,Yn(Re,!1)),b.style.display=w,Yn(b,!1),Te!==b&&(Te.style.display=o.layout?.showHeader===!1?"none":"",Yn(Te,!1))},Re.parentNode?.insertBefore(i,Re),fu()},ri=null,bs=null,Ca=null,si=null,Bh=()=>[Te,Fe.closeButtonWrapper,Fe.clearChatButtonWrapper,oe,Re],aA=52,uc=()=>o.features?.history?.rail?.collapsible!==!1,ii=()=>o.features?.history?.rail?.side==="right"?"right":"left",hu=200,yu=400,bu=i=>Math.min(yu,Math.max(hu,Math.round(i))),lA=()=>o.features?.history?.rail?.resizable===!0,wa,cA=()=>{if(wa===void 0&&(wa=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${bo()}rail-width`));i&&(wa=i)}catch{}return wa},xa=()=>bu(cA()??o.features?.history?.rail?.width??260),dA=i=>{if(wa=i,o.persistState!==!1)try{window.localStorage.setItem(`${bo()}rail-width`,String(i))}catch{}},gc=()=>uc()&&o.features?.history?.rail?.collapsedBehavior==="overlay",Nt=!1,_h=i=>{let c=M("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},pA=()=>{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=_h(i.iconUrl):g=i.icon?pe(i.icon,20):null),g?g.cloneNode(!0):null}},uA=()=>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=_h(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)}}}})}})??[],gA=i=>{let c=uA();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},Sa=null,Dh=()=>`${bo()}rail-collapsed`,vu=()=>{if(Sa===null&&(Sa=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(Dh());i&&(Sa=i==="1")}catch{}return Sa},Cu=i=>{if(Sa=i,o.persistState!==!1)try{window.localStorage.setItem(Dh(),i?"1":"0")}catch{}},Aa=()=>ae==="rail"&&uc()&&!gc()&&vu(),wu=()=>{},Nh=()=>{if(gc()){wu();return}Cu(!vu()),rt?.view.setCollapsed(Aa()),yt(),Pn()},xu=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!Ed(i)?null:{combo:i,hint:Td(i),aria:sl(i)}},Fh=()=>{d.forEach(c=>c()),d=[];let i=xu();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>te&&ae==="rail"&&uc()||li(),run:()=>gc()?wu():Nh()}));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}`}))};Fh();let mA=300,mc="var(--persona-history-overlay-margin,8px)",Xn=null,Xo=null,fc=0,Jo=null,ai=null,vs=!1,Su=0,$h=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,li=()=>To()&&gc()&&(ae??gu())==="rail",fA=()=>te&&!Nt,Ma=()=>{ai!==null&&clearTimeout(ai),ai=null},hA=()=>{Bm().catch(()=>{})},Uh=()=>{Ma(),Nt&&(ai=setTimeout(()=>{ai=null,!(vs||!Nt)&&(Jo?.contains(document.activeElement)||kn({restoreFocus:!1}))},mA))},yA=(i,c)=>{let g=Jo?.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},Au=i=>{Nt&&(vs=yA(i.clientX,i.clientY),vs?Ma():ai===null&&Uh())},jh=i=>{te||!li()||(Nt=!0,Ta({invoker:Xn,keyboard:i?.keyboard===!0}).then(()=>{te?!vs&&document.activeElement!==Xn&&kn():Nt=!1}))},qh=()=>{let i=va?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",Nt?Ye.expandLabel:Ye.collapseLabel),i.setAttribute("aria-expanded",Nt?"false":"true"))},zh=()=>{Cu(!1);let i=rt;if(!Nt||!i){Ta({invoker:Xn});return}let c=document.activeElement===Xn;Nt=!1,hc(),i.element.remove(),Eu(i.element),qh(),c&&bc(),Pn(),Er()},bA=()=>{Cu(!0),kn()};wu=()=>{!te||Nt?zh():bA()};let vA=()=>{let i=xu(),c=Os({ariaLabel:Ye.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":du,...i?{"aria-keyshortcuts":i.aria}:{}}}),g=c.button;g.addEventListener("mouseenter",()=>{vs=!0,Ma(),!($h()||Date.now()<Su)&&jh()}),g.addEventListener("mouseleave",()=>{vs=!1,Su=0,Uh()}),g.addEventListener("focus",()=>{te||hA()}),g.addEventListener("click",f=>{To()&&(f.detail!==0&&$h()&&!te?jh():zh())}),Xn=g,Xo=c.wrapper},Ea=()=>{if(Xo&&!Xo.isConnected&&(Xo=null,Xn=null),!li()){Xo?.remove(),Xo=null,Xn=null;return}Xn||vA();let i=Xo,c=Xn;if(!i||!c)return;let g=ii()!=="right"?Te.firstChild:null;(g??Te.lastChild)!==i&&Te.insertBefore(i,g),i.style.display=fA()||fc>0?"none":"",c.setAttribute("aria-label",Ye.expandLabel),c.setAttribute("aria-expanded",te?"true":"false"),Jo&&yt()},Vh=i=>{if(!Nt)return;let c=i.target;c instanceof Node&&(Jo?.contains(c)||Xo?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||kn({restoreFocus:!1}))};document.addEventListener("pointerdown",Vh,!0),ve.push(()=>{document.removeEventListener("pointerdown",Vh,!0),document.removeEventListener("pointermove",Au),ci?.(),Ma()});let Mu=null,ci=null,Kh=16,Gh=i=>{dA(bu(i)),yt(),Pn()},CA=()=>{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(hu)),i.setAttribute("aria-valuemax",String(yu)),i.addEventListener("pointerdown",c=>{let g=bs;if(!g||c.button!==0)return;c.preventDefault(),ci?.();let f=c.clientX,b=g.getBoundingClientRect().width||xa(),w=ii()==="right"?-1:1,O=b,z=e.ownerDocument;g.style.transition="none";let q=X=>{O=bu(b+w*(X.clientX-f)),g.style.flex=`0 0 ${O}px`,i.setAttribute("aria-valuenow",String(O))},V=()=>{ci=null,z.removeEventListener("pointermove",q),z.removeEventListener("pointerup",V),z.removeEventListener("pointercancel",V),g.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}Gh(O)};ci=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=ii()==="right"?-Kh:Kh,f=xa(),b=c.key==="ArrowRight"?f+g:c.key==="ArrowLeft"?f-g:c.key==="Home"?hu:c.key==="End"?yu:null;b!==null&&(c.preventDefault(),Gh(b))}),i},wA=(i,c)=>{if(!lA()||Aa()){ci?.(),Mu?.remove();return}let g=Mu??CA();Mu=g,g.setAttribute("aria-label",Ye.resizeLabel),g.setAttribute("aria-valuenow",String(xa())),g.nextElementSibling!==c&&i.insertBefore(g,c)};yt=()=>{rt?.view.setRailSide(ii());let i=ii()==="right",c=Jo;if(c){let z=Xn?Xn.getBoundingClientRect().bottom-ue.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(z))}px + ${mc})`,c.style.width=`${xa()}px`,c.style.left=i?"":mc,c.style.right=i?mc:""}let g=bs,f=ri,b=Ca;if(!g||!f||!b)return;g.style.flex=`0 0 ${Aa()?aA:xa()}px`;let w="1px solid var(--persona-divider,#e5e7eb)";g.style.borderRight=i?"":w,g.style.borderLeft=i?w:"";let O=i?b:g;f.firstElementChild!==O&&f.append(O,i?g:b),wA(f,i?g:b)};let Qh=i=>{if(si&&bs){si.replaceWith(i),si=null,yt();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",ue.insertBefore(c,Te.parentNode===ue?Te:oe);for(let b of Bh())b?.parentNode===ue&&g.appendChild(b);c.append(f,g),f.appendChild(i),ri=c,bs=f,Ca=g,yt()},xA=()=>{if(ri)return;let i=M("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",si=i,Qh(i),Pn()},Yh=()=>{si&&(hc(),Pn())},SA=i=>{let c=M("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))`,ue.style.position="relative",ue.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",Au),Jo=c,yt(),qh()},hc=()=>{pc?.(),Jo&&(vs&&(Su=Date.now()+150),document.removeEventListener("pointermove",Au),Jo.remove(),Jo=null);let i=ri;if(i){ci?.();for(let c of Bh())c&&i.contains(c)&&ue.insertBefore(c,i);i.remove(),ri=null,bs=null,Ca=null,si=null}},Xh=i=>{va=i,i.id=du,i.style.flex="1 1 auto",i.style.minHeight="0"},Eu=i=>{Xh(i),(ae!=="rail"||Nt)&&Yh(),ae!=="rail"?iA(i):Nt?SA(i):Qh(i)},yc=()=>{if(Ea(),ly(),!te||!rt)return;let i=gu();if(i===ae)return;let c=document.activeElement,g=c instanceof HTMLElement&&(rt.element.contains(c)||Fn?.contains(c)===!0)?c:null;hc(),rt.element.remove(),rt.view.setHeaderPlacement("inline"),ae=i,rt.view.setPresentation(i),rt.view.setCollapsed(Aa()),rt.requestRender(),rt.element.isConnected||Eu(rt.element),g?.isConnected?g.focus():bc(),zt(),Pn(),Er()},Jh=(i,c)=>Fn?.querySelector(c)??i.querySelector(c),bc=()=>{let i=rt?.element??va;if(!i)return;let c=Jh(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let g=Jh(i,".persona-history-title")??i;g.tabIndex=-1,g.focus()},Ta=async i=>{if(!To()||te)return;let c=Nn;if(!c)return;if(!Nt&&li()&&vu()){Ea();return}vc();let g=++ba;sc=i?.returnSurface??"conversation",au=i?.invoker??gn;let f=li()&&!Nt;f&&(fc+=1,Ea(),xA());let b;try{b=await Bm()}catch{cc(Ye.openHistoryLabel),f&&(fc-=1,g===ba&&(Yh(),Ea()));return}if(f&&(fc-=1),g!==ba||te)return;rc={scope:uu()},ae=gu(),te=!0;let w=ae==="panel"&&o.layout?.showHeader!==!1&&Te.style.display!=="none"?"external":"inline",O=o.features?.history?.rowAvatar,z=xu(),q=z?{hint:z.hint,aria:z.aria}:null,V={provider:c,context:rc,targetId:Ph(),presentation:ae,collapsible:uc(),collapsed:Aa(),railSide:ii(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:pA(),onToggleCollapse:Nh,...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:O===!1?!1:typeof O=="string"?O: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:X=>Pu(X,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:X=>Cs(X),attachTooltip:en,onStartNew:()=>ku({focusComposer:!0}),onClose:()=>kn(),onRequestDeleteConversation:X=>ay(X),onRequestClearHistory:()=>kA(),...c.resetDevice?{onRequestResetIdentity:()=>LA()}:{}};rt=Jw({plugins:a,config:o,getPresentation:()=>ae??"panel",getReturnSurface:()=>sc,close:()=>kn(),createView:({slots:X,renderDom:se,onModelChange:me,railSections:Xe})=>(ys=b.createHistoryView({...V,railSections:gA(Xe),slots:X,renderDom:se,onModelChange:me,onAnnounce:cc}),ys),onElementChanged:(X,se)=>{if(!se?.isConnected)return Eu(X);Xh(X),se.replaceWith(X),fu()}}),rt.view.setNewConversationRequired(ic.recovery==="new_conversation_required"),i?.focus!==!1&&(ae!=="rail"||i?.keyboard===!0)&&bc(),zt(),Pn(),Er(),A.emit("history:opened",{presentation:ae,returnSurface:sc,timestamp:Date.now()})},vc=()=>{},kn=i=>{if(!te)return;ba+=1;let c=sc,g=au,f=rt,b=i?.restoreFocus!==!1;te=!1;let w=!1,O=null,z=()=>{if(!w){if(w=!0,vc=()=>{},O!==null&&clearTimeout(O),Nt=!1,Ma(),hc(),f?.dispose(),f?.view.destroy(),f?.element.remove(),rt===f&&(rt=null,ys=null,va=null,ae=null,rc=null,au=null),zt(),Pn(),Er(),b){let V=g??gn;V?.isConnected?V.focus():us()}A.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},q=f&&f.element===f.view.element?f.view.playExit():null;if(!q){z();return}vc=z,O=setTimeout(z,ZS),q.then(z)},Zh=i=>{if(!(i.key!=="Escape"||!te||!rt)){if(ae==="rail"){let c=i.target;if(!(c instanceof Node)||!(rt.element.contains(c)||Nt&&Xo?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),kn()}};ue.addEventListener("keydown",Zh),ve.push(()=>ue.removeEventListener("keydown",Zh));let Cc=null,ey=!1,Pa=()=>{if(!ur)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&Cc?.trim()||null;ur.textContent=c??o.launcher?.title??"Chat Assistant";let g=ur.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")},AA=i=>{i!==Cc&&(Cc=i,Pa())},Cs=i=>{ey=i?.starred===!0,AA(i&&i.title.trim()||null),Pa()};Pa(),ue.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,g=P.getActiveConversationId();g&&(c==="delete"?ay(g):c==="star"&&P.canUpdateConversations()&&Lu(g,{starred:!ey}).catch(()=>{}))});let wc=0,MA=250,xc=null,Sc=()=>{xc&&clearTimeout(xc),xc=null};ve.push(Sc);let ty=()=>{Sc();let i=gs;i&&(fa=!0,i.hidden=!1,Le.style.display="none",ha())},Ac=()=>{wc+=1,Sc(),gs&&(gs.remove(),gs=null,fa=!1,Le.style.removeProperty("display"),Yn(Re,!1),ha())},EA=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Le.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Tu=(i,c)=>Q("div",{className:fn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),ny=()=>Q("div",{className:"persona-conversation-loading-body"},Tu("58%",!1),Tu("72%",!0),Tu("44%",!1)),oy=i=>{gs?.remove(),gs=i,i.hidden=!fa,oe.insertBefore(i,Le),Sc(),fa||(xc=setTimeout(ty,MA)),Yn(Re,!0)},TA=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:ny},c=null,g=a.find(f=>f.renderLoadingIndicator);g?.renderLoadingIndicator&&(c=g.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),oy(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ye.openConversationLoadingLabel}},c??ny()))},PA=i=>{let c=()=>{Pu(i,{focusComposer:!0}).catch(()=>{})},g=To()?()=>{Ac(),Ta()}: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:Ye.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},f(Ye.openConversationRetryLabel,c),g?f(Ye.openConversationBackLabel,g):null)),w=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Ye.openConversationErrorTitle,retryLabel:Ye.openConversationRetryLabel,backLabel:Ye.openConversationBackLabel}),retry:c,...g?{back:g}:{},defaultRenderer:b}),O=null;for(let z of a)if(z.renderHistoryOpenError){try{O=z.renderHistoryOpenError(w)}catch(q){console.warn("[persona] renderHistoryOpenError threw",q),O=null}if(O)break}oy(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},O??b())),ty()};A.on("history:closed",()=>{gs&&Yn(Re,!0)});let Pu=async(i,{focusComposer:c=!1}={})=>{let g=oi(),f=!!rt;rt?.view.setActiveConversationId(i),Ac();let b=wc;TA(),te&&(ae==="panel"||Nt)&&kn({restoreFocus:!1}),Ys=!0;try{await P.openConversation(i,{scope:g})}catch(w){throw b===wc&&PA(i),w}finally{Ys=!1}b===wc&&(Ac(),Dt.clear(),po(),Tn(),jp()||Gl(),EA(),Zo(),f||Cs(null),A.emit("history:conversationOpened",{conversationId:i,title:Cc,scope:g,timestamp:Date.now()}),c&&us())},ku=async({focusComposer:i=!1}={})=>{Ac(),await P.startNewConversation({scope:oi()}),Cs(null),Dt.clear(),po(),Tn(),Gl(),Zo();let c=P.getActiveConversationId();rt?.view.setActiveConversationId(c),A.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),te&&(ae==="panel"||Nt)&&kn({restoreFocus:!1}),i&&us()},Lu=async(i,c)=>{let g=await P.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return rt?.view.applyConversationSummary(g),!rt&&i===P.getActiveConversationId()&&Cs(g),g},ry=async i=>{let c=oi(),g=P.getActiveConversationId()===i;await P.deleteConversation(i,{scope:c}),rt?.view.removeConversationSummary(i),g&&(Cs(null),Dt.clear(),po(),Tn(),Zo()),A.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:g,timestamp:Date.now()})},sy=async i=>{let c=i?.scope??oi(),g=i?.allTargets?null:i?.targetId??Ph(),f=await P.clearConversationHistory({...g?{targetId:g}:{},scope:c});return Cs(null),Dt.clear(),po(),Tn(),Zo(),A.emit("history:cleared",{deleted:f.deleted,scope:c,targetId:g,timestamp:Date.now()}),f},iy=async()=>{if(!Nn?.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{Cs(null),P.clearArtifacts(),Dt.clear(),ou=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),ie={},Me.syncFromMetadata(),G?.clear&&zl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),po(),Tn(),Zo(),kn({restoreFocus:!1}),us(),he||kt?.launcher.element.focus()}return cc(i?Ye.identityResetNotice:Ye.identityResetUnconfirmedNotice),A.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},Iu=()=>So?Ae:ue,ay=async i=>await tp({host:Iu(),title:Ye.deleteConversationConfirmTitle,description:Ye.deleteConversationConfirm,confirmLabel:Ye.deleteConversationConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await ry(i),"deleted"):"cancelled",kA=async()=>{let i=oi()==="verified-user";return await tp({host:Iu(),title:Ye.clearHistoryConfirmTitle,description:i?Ye.clearHistoryVerifiedConfirm:Ye.clearHistoryConfirm,confirmLabel:Ye.clearHistoryConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await sy(),"cleared"):"cancelled"},LA=async()=>{if(!await tp({host:Iu(),title:Ye.resetIdentityConfirmTitle,description:Ye.resetIdentityConfirm,confirmLabel:Ye.resetIdentityConfirmLabel,cancelLabel:Ye.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await iy();return{outcome:"reset",remoteRevocationConfirmed:c}},Jn=M("button","persona-history-earlier");Jn.type="button",Jn.textContent=Ye.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 Zo=()=>{if(!(To()&&!!ic.nextMessageCursor&&!!P.getActiveConversationId())){Jn.remove();return}Jn.textContent=Ye.showEarlierMessagesLabel,Jn.parentNode!==oe&&oe.insertBefore(Jn,oe.firstChild)};Jn.addEventListener("click",()=>{let i=P.getActiveConversationId(),c=ic.nextMessageCursor;if(!i||!c||Jn.disabled)return;Jn.disabled=!0;let g=oe.scrollHeight,f=oe.scrollTop;P.loadOlderMessages(i,c,{scope:oi()}).then(()=>{oe.scrollTop=f+(oe.scrollHeight-g),Pn()}).catch(()=>{}).finally(()=>{Jn.disabled=!1,Zo()})});let IA=()=>{let i=Os({ariaLabel:Ye.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()||Th())){if(te){kn();return}Ta({invoker:i.button,keyboard:c.detail===0})}}),i},ly=()=>{if(!To()){Eo?.remove(),gn=null,Eo=null;return}if(Eo&&!Eo.isConnected&&(gn=null,Eo=null),!gn&&Te){let f=IA();gn=f.button,Eo=f.wrapper;let b=Fe.clearChatButtonWrapper||Fe.closeButtonWrapper;b?.parentNode&&Te.contains(b)?b.parentNode.insertBefore(Eo,b):Te.appendChild(Eo)}if(!gn||!Eo)return;let i=li()||te&&ae==="rail";if(Eo.style.display=i?"none":"",i){document.activeElement===gn&&bc();return}let c=Th();gn.disabled=c,gn.setAttribute("aria-disabled",c?"true":"false");let g=c?Ye.openHistoryBusyLabel:Ye.openHistoryLabel;gn.setAttribute("aria-label",g),(o.features?.history?.presentation??"panel")==="panel"?(gn.removeAttribute("aria-expanded"),gn.removeAttribute("aria-controls")):(gn.setAttribute("aria-expanded",te?"true":"false"),gn.setAttribute("aria-controls",du))},Mc=!1,RA=()=>{let i=Fe.clearChatButton;if(i){if(To()){Mc||(cu=i.getAttribute("aria-label")??"",Mc=!0),i.setAttribute("aria-label",Ye.newConversationLabel),i.removeAttribute("title");return}Mc&&(Mc=!1,cu&&i.setAttribute("aria-label",cu))}},Er=()=>{Ye=Nm(o.features?.history?.copy),ly(),Ea(),RA(),Zo()};St=Er,qe=i=>{ic=i,rt?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),ma(i.sendBlocked||Bn),Zo()},Ot=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(Dt.clear(),po(),Tn()),cc(i.message),rt?.view.refresh()},Rh(),Er(),ve.push(()=>{ac?.(),lc?.(),ba+=1,vc(),rt?.dispose(),rt?.view.destroy(),rt=null}),o.clientToken&&P.initClientSession().then(()=>{if(To())return P.reconcileBootConversation({scope:uu()})}).then(()=>{Zo()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Wt||o.onSSEEvent)&&P.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),U(i,c)});let cy=()=>{o.resume&&typeof o.reconnectStream=="function"&&P.resumeFromHandle(o.resume)};ne?ne.then(i=>{if(i){if(i.metadata&&(ie=zm(i.metadata),Me.syncFromMetadata()),i.messages?.length){Ys=!0;try{P.hydrateMessages(i.messages)}finally{Ys=!1}Jl()}i.artifacts?.length&&P.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),ih(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{Qp=!0,E(),cy()}):(ih(W),cy());let HA=()=>{!we()||he||!(o.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},WA=(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),AI(b)}}:i:c,Ru=()=>{let c=ce.getInlineMessageFields?.();return c&&c.contentSegments.some(f=>f.kind==="mention")?c.contentSegments:void 0},er=!1,ws=null,Ec=()=>{ce.value="",ce.style.height="auto",Co(),La()},Hu="data-persona-composer-notice",di=null;function OA(i){El(i),!(we()||!ot)&&(ot.hasAttribute(zi)||(ot.setAttribute(Hu,""),ot.setAttribute("role","status"),ot.setAttribute("aria-live","polite"),ot.textContent=i,di&&clearTimeout(di),di=setTimeout(()=>{if(di=null,!!ot?.hasAttribute(Hu)&&(ot.removeAttribute(Hu),ot.removeAttribute("role"),ot.removeAttribute("aria-live"),p)){let c=P.getStatus();sn(ot,un(c),o.statusIndicator??{},c)}},4e3)))}function BA(){let i=xe.getState().pendingSubmission;i&&(Us(void 0),ce&&(ce.value=i.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),Co()),i.options.selectedModelId&&(xe.setSelectedModelId(i.options.selectedModelId),mr?.repaint()),i.options.activeModeIds?.length&&Ll(i.options.activeModeIds),i.options.quote&&wo(i.options.quote),ce?.focus())}let _A=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},dy=(i={})=>{let c=(i.overrideText??ce?.value??"").trim();return i.resolveInlineCommand&&c?(Bt?.takeInlineCommand(c)??Promise.resolve(null)).then(g=>py(i,c,g)):py(i,c,null)},py=(i,c,g)=>{if(g?.kind==="action"){Ec(),Bt?.clear(),Qr();return}let f=g?.kind==="server"?g.mentions:null,b=g?.kind==="prompt"?g.sendText:c,w=i.pending?.contentParts,O=(Je?.hasAttachments()??!1)||(w?.length??0)>0;if(!cC({text:b,hasAttachments:O,attachmentsReady:Je?.isReady()??!0,hasMentions:Bt?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:Sr(),sendDisabled:ps()}))return;let z=P.isStreaming()?Sp():"block";if(z==="defer-one"&&!i.pending){if(xe.getState().pendingSubmission){OA("One message is already queued. Edit or remove it first.");return}DA({intent:i,sendText:b,serverMentions:f});return}let q={text:b,mentionRefs:[...Bt?.getMentionRefs()??[],...f?.refs??[]],contentSegments:g?.kind==="prompt"?void 0:Ru(),options:{...xe.getState().selectedModelId&&{selectedModelId:xe.getState().selectedModelId},...xe.getState().activeModeIds.length>0&&{activeModeIds:[...xe.getState().activeModeIds]},...xe.getState().quote&&{quote:{...xe.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 ut=[...Je.getContentParts()];return q.text&&ut.push(mo(q.text)),ut};q.contentParts=V();let X=()=>{rs(),HA();let ut=Bt?.collectForSubmit()??null,Xt=WA(ut,f),Ft=V();i.consumeDraft!==!1&&Ec();let It={selectedModelId:q.options.selectedModelId,activeModeIds:q.options.activeModeIds},an=z==="interrupt";an&&P.cancel(),P.sendMessage(q.text,{contentParts:Ft,mentions:Xt??void 0,contentSegments:q.contentSegments,viaVoice:q.viaVoice,composerOptions:It,...q.options.quote&&{quote:q.options.quote},...an&&{interrupt:!0}}),Je?.hasAttachments()&&Je.clearAttachments(),ut&&Bt?.clear(),Qr();let Ze=xe.getState().activeModeIds,ln=Qv(Ze,o.composer?.modes);ln.length!==Ze.length&&Ll(ln),xe.getState().quote&&wo(void 0),Kl(),Pp.release(),io()},se=o.composer?.onBeforeSend;if(!se){X();return}let me=new AbortController;ws=me;let Xe=ut=>{if(ws=null,ut.status==="error"){_A(ut.error);return}ut.status==="proceed"&&X()},ct=dC(se,q,me.signal);if(!(ct instanceof Promise)){Xe(ct);return}return xe.setPreparing(!0),ct.then(Xe).finally(()=>xe.setPreparing(!1))};function DA(i){let c=xe.getState(),g=Je?.hasAttachments()??!1,f=g?[...Je.getContentParts()]:[];g&&i.sendText&&f.push(mo(i.sendText));let b=jg({text:i.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Bt?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Ru(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});Us(b),i.intent.consumeDraft!==!1&&Ec(),g&&Je.clearAttachments(),Bt?.clear(),Qr(),c.quote&&wo(void 0),Kl(),Pp.release(),io(),El("Message queued. It sends when the response finishes.")}function NA(){let i=xe.getState().pendingSubmission;i&&(Us(void 0),Pc(i.text,{consumeDraft:!1,pending:i}))}function FA(i){if(o.messageActions?.showEdit!==!0)return;let c=P.getMessages().find(g=>g.id===i);!c||!bg(c)||os!==i&&(rs(),os=i,br=eC({messageId:i,initialText:c.content,onSave:g=>$A(i,g),onCancel:()=>rs()}),Dt.delete(i),Qn(Le,P.getMessages(),at),br.focus())}function $A(i,c){let g=br;if(os=null,br=null,g?.destroy(),Dt.delete(i),!P.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){Qn(Le,P.getMessages(),at);return}Pn()}function UA(i){if(P.isStreaming())return;let c=yg(P.getMessages(),i);c&&(rs(),P.resubmitFrom(c,{reason:"retry"})&&Pn())}Il={regenerate:UA,edit:FA,quote:i=>{let g=P.getMessages().find(f=>f.id===i)?.content?.trim();g&&(wo({text:g,messageId:i}),ce?.focus())}};let ka=async i=>{if(!er){er=!0;try{await dy({resolveInlineCommand:!0,...i})}finally{er=!1}}};function Tc(i){ps()||(Ec(),Pc(i,{consumeDraft:!1}))}let Pc=(i,c)=>{if(er)return;er=!0;let g=()=>{er=!1};try{let f=dy({...c,overrideText:i});f instanceof Promise?f.finally(g):g()}catch(f){throw g(),f}},jA=i=>{if(i.preventDefault(),P.isStreaming()){P.cancel(),gt?.reset(),R?.update();return}er||ka()},qA=()=>o.features?.composerHistory!==!1,Wu={...Xg},Ou=!1,La=()=>{Wu={...Xg}},zA=()=>P.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),VA=i=>{if(!ce)return;Ou=!0,ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),Ou=!1;let c=ce.value.length;ce.setSelectionRange(c,c)},KA=i=>{Ou||(i.isComposing||Bt?.handleInput(i.inputType??void 0),La())},GA=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:tl(ce)}),QA=i=>{if(ce&&!Sr()&&!(!i.isComposing&&Bt?.handleKeydown(i))){if(qA()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let c=ce.selectionStart===0&&ce.selectionEnd===0,g=LC({direction:i.key==="ArrowUp"?"up":"down",history:zA(),currentValue:ce.value,atStart:c,state:Wu});if(Wu=g.state,g.handled){i.preventDefault(),g.value!==void 0&&VA(g.value);return}}if(Hv(i,GA())){if(P.isStreaming()){if(i.preventDefault(),Sp()==="block"||er||ps())return;La(),ka();return}if(er){i.preventDefault();return}if(ps()){i.preventDefault();return}La(),i.preventDefault(),Ee.click()}}},uy=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(ue)){if(ws){ws.abort(),ws=null,i.preventDefault(),i.stopImmediatePropagation();return}P.isStreaming()&&(P.cancel(),gt?.reset(),R?.update(),La(),i.preventDefault(),i.stopImmediatePropagation())}},YA=async i=>{if(o.attachments?.enabled!==!0||!Je||Sr())return;let c=CI(i.clipboardData);c.length!==0&&(i.preventDefault(),await Je.handleFiles(c))},Zn=null,Po=!1,pi=null,Ct=null,Bu=()=>o.voiceRecognition?.completionBehavior==="review";function xs(i){re?.setAttribute("data-state",i),i==="recording"?JA():Fu()}let gy="--persona-voice-level",_u=.5,ui=null,Du=-1,kc=0,my=()=>{let i=[],c=Wn??re?.parentElement??null;return c&&i.push(c),Re&&i.push(Re),i},Nu=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==Du){Du=c;for(let g of my())g.style.setProperty(gy,String(c))}},XA=()=>{Du=-1,kc=0;for(let i of my())i.style.removeProperty(gy)};function JA(){if(ui!==null)return;if(typeof requestAnimationFrame!="function"){Nu(p?P.getVoiceLevel()??_u:_u);return}let i=()=>{ui=requestAnimationFrame(i);let c=p?P.getVoiceLevel():null;if(c===null){Nu(_u);return}kc+=(c-kc)*.3,Nu(kc)};ui=requestAnimationFrame(i)}function Fu(){ui!==null&&(cancelAnimationFrame(ui),ui=null),XA()}let fy=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Lc=(i="user")=>{if(Po||P.isStreaming())return;let c=fy();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=ce.value;Zn.onresult=w=>{let O="",z="";for(let V=0;V<w.results.length;V++){let X=w.results[V],se=X[0].transcript;X.isFinal?O+=se+" ":z=se}let q=b+O+z;ce.value=q,Co(),pi&&clearTimeout(pi),(O||z)&&(pi=window.setTimeout(()=>{if(ce.value.trim()&&Zn&&Po){if(Tr(),Bu())return;ka({viaVoice:!0})}},f))},Zn.onerror=w=>{w.error!=="no-speech"&&Tr()},Zn.onend=()=>{if(Po){let w=ce.value.trim();!Bu()&&w&&w!==b.trim()&&ka({viaVoice:!0}),Tr()}};try{if(Zn.start(),Po=!0,Ve.active=!0,i!=="system"&&(Ve.manuallyDeactivated=!1),Ko(i),co(),io(),re){let w=o.voiceRecognition??{};Ct={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:w.iconName??"mic",iconSize:parseFloat(w.iconSize??"")||hn};let O=w.recordingBackgroundColor,z=w.recordingIconColor,q=w.recordingBorderColor;if(re.classList.add("persona-voice-recording"),xs("recording"),re.style.backgroundColor=O??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=z??"var(--persona-voice-recording-indicator, #ffffff)",z){let V=re.querySelector("svg");V&&V.setAttribute("stroke",z)}q&&(re.style.borderColor=q),re.setAttribute("aria-label","Stop voice recognition")}}catch{Tr("system")}},Tr=(i="user")=>{if(Po){if(Po=!1,pi&&(clearTimeout(pi),pi=null),Zn){try{Zn.stop()}catch{}Zn=null}if(Ve.active=!1,Ko(i),co(),io(),re){if(re.classList.remove("persona-voice-recording"),xs("idle"),Ct){re.style.backgroundColor=Ct.backgroundColor,re.style.color=Ct.color,re.style.borderColor=Ct.borderColor;let c=re.querySelector("svg");c&&c.setAttribute("stroke",Ct.color||"currentColor"),Ct=null}re.setAttribute("aria-label","Start voice recognition")}}},$u=()=>{if(!re||Ct)return;let i=o.voiceRecognition??{};Ct={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||hn}},Uu=(i,c)=>{if(!re)return;let g=re.querySelector("svg");g&&g.remove();let f=Ct?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||hn),b=pe(i,f,c,1.5);b&&re.appendChild(b)},Ic=()=>{re&&re.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},gi=()=>{if(!re)return;$u();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,g=i.recordingIconColor,f=i.recordingBorderColor;if(Ic(),re.classList.add("persona-voice-recording"),xs("recording"),re.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=g??"var(--persona-voice-recording-indicator, #ffffff)",g){let b=re.querySelector("svg");b&&b.setAttribute("stroke",g)}f&&(re.style.borderColor=f),re.setAttribute("aria-label","Stop voice recognition")},ZA=()=>{if(!re)return;$u();let i=o.voiceRecognition??{},c=P.getVoiceInterruptionMode(),g=i.processingIconName??"loader",f=i.processingIconColor??Ct?.color??"",b=i.processingBackgroundColor??Ct?.backgroundColor??"",w=i.processingBorderColor??Ct?.borderColor??"";Ic(),re.classList.add("persona-voice-processing"),xs("processing"),re.style.backgroundColor=b,re.style.borderColor=w;let O=f||"currentColor";re.style.color=O,Uu(g,O),re.setAttribute("aria-label","Processing voice input"),c==="none"&&(re.style.cursor="default")},eM=()=>{if(!re)return;$u();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??""),w=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Ct?.backgroundColor??""),O=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":Ct?.borderColor??"");Ic(),re.classList.add("persona-voice-speaking"),xs("speaking"),re.style.backgroundColor=w,re.style.borderColor=O;let z=b||"currentColor";re.style.color=z,Uu(f,z);let q=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";re.setAttribute("aria-label",q),c==="none"&&(re.style.cursor="default"),c==="barge-in"&&re.classList.add("persona-voice-recording")},tr=()=>{re&&(Ic(),xs("idle"),Ct&&(re.style.backgroundColor=Ct.backgroundColor??"",re.style.color=Ct.color??"",re.style.borderColor=Ct.borderColor??"",Uu(Ct.iconName,Ct.color||"currentColor"),Ct=null),re.style.cursor="",re.setAttribute("aria-label","Start voice recognition"))},ju=()=>{if(!Sr()){if(o.voiceRecognition?.provider?.type==="runtype"){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(()=>{Ve.active=!1,Ve.manuallyDeactivated=!0,co(),Ko("user"),tr()});return}P.toggleVoice().then(()=>{Ve.active=P.isVoiceActive(),Ve.manuallyDeactivated=!P.isVoiceActive(),co(),Ko("user"),P.isVoiceActive()?gi():tr()});return}if(Po){let i=ce.value.trim();Ve.manuallyDeactivated=!0,co(),Tr("user"),i&&!Bu()&&ka()}else Ve.manuallyDeactivated=!1,co(),Lc("user")}};Ap=ju,re&&ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(P.isVoiceActive()&&P.toggleVoice(),tr()):Tr("system")});let tM=A.on("assistant:complete",()=>{xe.getState().pendingSubmission&&setTimeout(()=>{P.isStreaming()||NA()},0)});ve.push(tM);let nM=A.on("assistant:complete",()=>{oh&&(Ve.active||Ve.manuallyDeactivated||oh==="assistant"&&!Ve.lastUserMessageWasVoice||setTimeout(()=>{!Ve.active&&!Ve.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?P.toggleVoice().then(()=>{Ve.active=P.isVoiceActive(),Ko("auto"),P.isVoiceActive()&&gi()}):Lc("auto"))},600))});ve.push(nM);let oM=A.on("action:resubmit",()=>{setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)});ve.push(oM);let hy=()=>{pt(!he,"user")},kt=null,mn=null;if(fe&&!we()){let{instance:i,element:c}=Cm({config:o,plugins:a,onToggle:hy});kt=i,i||(mn=c)}kt?e.appendChild(kt.element):mn&&e.appendChild(mn),ga(),Gs(),tc(),eu(),ma(P.isStreaming()),jp()||(On()==="follow"?wr(!0):Gl()),SS(),it&&(!fe||we()?setTimeout(()=>us(),0):he&&setTimeout(()=>us(),200));let Ss=null,yy=()=>{Ss&&(Ss.disconnect(),Ss.observe(Re),Ss.observe(ue))},Ia=()=>{if(we()){Gr(),ga();return}let i=Et(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,O=f&&w&&fe;try{if(O){Yr(),na=Nl();return}let z=!1;Ne&&(Ne=!1,Yr(),z=!0);let q=Nl();if(!z&&q!==na&&(Yr(),z=!0),na=q,z&&Ol(),!fe&&!i){Ae.style.height="",Ae.style.width="";return}if(!c&&!i){let X=o?.launcher?.width??o?.launcherWidth??oo;Ae.style.width=X,Ae.style.maxWidth=X}Dl(),$f()}finally{if(Gr(),kl(),ga(),he&&fe){let q=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),V=o.launcher?.sidebarMode??!1,X=o.launcher?.mobileFullscreen??!0,se=Et(o)&&X&&q,me=V||X&&q&&fe||se;if(me&&!Mo){let Xe=e.getRootNode(),ct=Xe instanceof ShadowRoot?Xe.host:e.closest(".persona-host");ct&&!Ao&&(Ao=tm(ct,o.launcher?.zIndex??rn)),Mo=nm(e.ownerDocument)}else me||(Ao?.(),Ao=null,Mo?.(),Mo=null)}}};Ia();let Rc=e.ownerDocument.defaultView??window;if(Rc.addEventListener("resize",Ia),ve.push(()=>Rc.removeEventListener("resize",Ia)),typeof ResizeObserver<"u"){Ss=new ResizeObserver(()=>{kl()}),yy(),ve.push(()=>{Ss?.disconnect(),Ss=null});let i=new ResizeObserver(()=>{yc()});i.observe(ue),ve.push(()=>i.disconnect())}Rc.addEventListener("resize",yc),ve.push(()=>Rc.removeEventListener("resize",yc)),Dn=oe.scrollTop;let by=Bo(oe),vy=()=>{let i=oe.scrollTop,c=Bo(oe),g=c<by;if(by=c,!gr()){Dn=i,zt();return}let{action:f,nextLastScrollTop:b}=DC({following:_n.isFollowing(),currentScrollTop:i,lastScrollTop:Dn,nearBottom:Ws(oe,zo),userScrollThreshold:vS,isAutoScrolling:En||$l||g,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Dn=b,f==="resume"){Ql()||Tn();return}f==="pause"&&la()};if(oe.addEventListener("scroll",vy,{passive:!0}),ve.push(()=>oe.removeEventListener("scroll",vy)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{LS(),Zu(Le)});i.observe(Le),i.observe(oe),ve.push(()=>i.disconnect())}let Cy=()=>{gr()&&_n.isFollowing()&&Ql()&&la()},wy=oe.ownerDocument;wy.addEventListener("selectionchange",Cy),ve.push(()=>{wy.removeEventListener("selectionchange",Cy)});let rM=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),xy=i=>{rM.has(i.key)&&(ls(),lf()&&gr()&&_n.isFollowing()&&la())},Sy=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(ls(),lf()&&gr()&&_n.isFollowing()&&la())};oe.addEventListener("keydown",xy),oe.addEventListener("focusin",Sy),ve.push(()=>{oe.removeEventListener("keydown",xy),oe.removeEventListener("focusin",Sy)});let Ay=i=>{if(i.deltaY!==0&&ls(),!gr())return;let c=NC({following:_n.isFollowing(),deltaY:i.deltaY,nearBottom:Ws(oe,zo),resumeWhenNearBottom:!0});c==="pause"?la():c==="resume"&&!Ql()&&Tn()};oe.addEventListener("wheel",Ay,{passive:!0}),oe.addEventListener("touchmove",ls,{passive:!0}),oe.addEventListener("pointerdown",ls,{passive:!0}),ve.push(()=>{oe.removeEventListener("touchmove",ls),oe.removeEventListener("pointerdown",ls)}),ve.push(()=>oe.removeEventListener("wheel",Ay)),_t.addEventListener("click",()=>{po(),oe.scrollTop=oe.scrollHeight,Dn=oe.scrollTop,Tn(),wr(!0),zt()}),ve.push(()=>_t.remove()),ve.push(()=>{lh(),po()});let My=()=>{Ue&&(es&&(Ue.removeEventListener("click",es),es=null),ke()?(Ue.style.display="",es=()=>{pt(!1,"user")},Ue.addEventListener("click",es)):Ue.style.display="none")};My(),(()=>{let{clearChatButton:i}=Fe;i&&i.addEventListener("click",()=>{if(To()){ku({focusComposer:!0}).catch(g=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",g)});return}P.clearMessages(),Dt.clear(),Tn(),Is(Fe.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&&zl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ie={},Me.syncFromMetadata(),Je?.clearAttachments(),Kl(),Us(void 0),wo(void 0),rs(),Tt?.clear(),gt?.reset(),R?.update()})})();let Ey=[["keydown",QA],["input",KA],["input",Co],["input",Qr],["keyup",Qr],["paste",YA],["focus",aS]],Ty=i=>{if(i)for(let[c,g]of Ey)tt?.addListener(i,c,g)},sM=i=>{if(i)for(let[c,g]of Ey)tt?.removeListener(i,c,g)},Py=()=>{tt&&(tt.addListener(tt.form,"submit",jA),tt.addListener(tt.footer,"click",Qr),Ty(ce),re&&tt.addListener(re,"click",ju))};Py();let ky=()=>{Bt?.onComposerSwap((i,c)=>{sM(c),ce=i,tt&&(tt.input=i),Ty(i),Ep(),Kp(),Co()})};ky();let qu=!1;function Ly(){if(!qu){qu=!0;try{let i=ce?.value??"",c=Re.ownerDocument??document,g=ce?c.activeElement===ce:!1;Fu(),tt?.destroy(),tt=null,Bt?.destroy(),Bt=null;let f=null,b=()=>(f=we()?Od({config:o}):Wi({config:o}),f.footer),w=bf(b)??b();Rn.replaceComposer(w),Re=Rn.composer.footer;let O=f!==null&&w===f.footer;qs=!O,af=O?f.setSendButtonMode:()=>{},yf(Re),Cf(Re),wf(),xf(),Sf(),ky(),Af(),Tp(),Mf(),Py();let z=Zr.indexOf(qo);qo.destroy(),qo=ml(pr),z>=0&&(Zr[z]=qo),ce&&(ce.value=i),Co(),Qr(),tc(),Gs(),ma(P.isStreaming()),Ve.active&&xs("recording"),Yr(),yy(),Gr(),io(),Zl(),g&&ce?.focus()}finally{qu=!1}}}let Ra=e.ownerDocument??document;Ra.addEventListener("keydown",uy,!0);let Iy=()=>{Np()},Ry=()=>{Ra.visibilityState==="hidden"&&Np()};typeof window<"u"&&(window.addEventListener("pagehide",Iy),Ra.addEventListener("visibilitychange",Ry),ve.push(()=>{window.removeEventListener("pagehide",Iy),Ra.removeEventListener("visibilitychange",Ry)}));let Hy="persona-attachment-drop-active",Ha=0,zu=()=>{Ha=0,ue.classList.remove(Hy)},mi=()=>o.attachments?.enabled===!0&&Je!==null&&!Sr(),Wy=i=>{!op(i.dataTransfer)||!mi()||(Ha++,Ha===1&&ue.classList.add(Hy))},Oy=i=>{!op(i.dataTransfer)||!mi()||(Ha--,Ha<=0&&zu())},By=i=>{!op(i.dataTransfer)||!mi()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},_y=i=>{if(!op(i.dataTransfer)||!mi())return;i.preventDefault(),i.stopPropagation(),zu();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&Je.handleFiles(c)},Pr=!0;ue.addEventListener("dragenter",Wy,Pr),ue.addEventListener("dragleave",Oy,Pr),e.addEventListener("dragover",By,Pr),e.addEventListener("drop",_y,Pr);let Hc=e.ownerDocument,Dy=i=>{mi()&&i.preventDefault()},Ny=i=>{mi()&&i.preventDefault()};Hc.addEventListener("dragover",Dy),Hc.addEventListener("drop",Ny),ve.push(()=>{tt?.destroy(),tt=null,Fu(),xo?.destroy(),xo=null,Uo?.destroy(),Uo=null,fr?.destroy(),fr=null,hr?.destroy(),hr=null,mr=null,xp=null,Np(),aa.destroy(),di&&clearTimeout(di),rs(),ws?.abort(),ws=null,Je?.destroy(),Je=null,xe.destroy(),Ra.removeEventListener("keydown",uy,!0),Bt?.destroy()}),ve.push(()=>{ue.removeEventListener("dragenter",Wy,Pr),ue.removeEventListener("dragleave",Oy,Pr),e.removeEventListener("dragover",By,Pr),e.removeEventListener("drop",_y,Pr),Hc.removeEventListener("dragover",Dy),Hc.removeEventListener("drop",Ny),zu()}),ve.push(()=>{P.cancel()}),kt?ve.push(()=>{kt?.destroy()}):mn&&ve.push(()=>{mn?.remove()});let Lt={update(i){let c=o.toolCall,g=o.messageActions,f=o.layout?.messages,b=o.colorScheme,w=o.loadingIndicator,O=o.iterationDisplay,z=o.features?.showReasoning,q=o.features?.showToolCalls,V=o.features?.toolCallDisplay,X=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type,me=o.features?.history?.enabled===!0,Xe=o.features?.history?.provider,ct=o.getIdentityProof,ut=o.clientToken,Xt=o.contextMentions;o=Jd({...o,features:s},i),s=o.features,o=Yd(o),r(),Hp(),ki(e,o),bl(e,o),vl(e,o),yt(),lo(),o.colorScheme!==b&&Uf();let Ft=Xd.getForInstance(o.plugins);a.length=0,a.push(...Ft),Fh(),fe=o.launcher?.enabled??!0,_e=o.launcher?.autoExpand??!1,nn=o.features?.showReasoning??!0,wn=o.features?.showToolCalls??!0,jr=o.features?.scrollToBottom??{};let It=On();xn=o.features?.scrollBehavior??{},It!==On()&&(po(),Tn()),nh(),pf(),zt();let an=Wt;if(Wt=o.features?.showEventStreamToggle??!1,Wt&&!an){if(Tt||(Z(),P.setSSEEventCallback((J,Ke)=>{o.onSSEEvent?.(J,Ke),U(J,Ke)})),!et&&Te){let J=o.features?.eventStream?.classNames,Ke="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"+(J?.toggleButton?" "+J.toggleButton:"");et=M("button",Ke),et.style.width="28px",et.style.height="28px",et.style.color=bn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let Qe=Ht(ox,"18px","currentColor",1.5);Qe&&et.appendChild(Qe);let nt=Fe.clearChatButtonWrapper,xt=Fe.closeButtonWrapper,on=nt||xt;on&&on.parentNode===Te?Te.insertBefore(et,on):Te.appendChild(et),et.addEventListener("click",()=>{ee?js():Mp()})}}else!Wt&&an&&(js(),et&&(et.remove(),et=null),Tt?.clear(),pn?.destroy(),Tt=null,pn=null,gt?.reset(),gt=null,ro=null);if(o.launcher?.enabled===!1&&kt&&(kt.destroy(),kt=null),o.launcher?.enabled===!1&&mn&&(mn.remove(),mn=null),o.launcher?.enabled!==!1&&!kt&&!mn){let{instance:J,element:Ke}=Cm({config:o,plugins:a,onToggle:hy});kt=J,J||(mn=Ke),e.appendChild(Ke)}kt&&kt.update(o),Pa(),Vr&&o.launcher?.subtitle!==void 0&&(Vr.textContent=o.launcher.subtitle);let Ze=o.layout?.header;if(Ze?.layout!==De&&Te){let J=Ze?fl(o,Ze,{showClose:ke(),onClose:()=>pt(!1,"user")}):$r({config:o,showClose:ke(),onClose:()=>pt(!1,"user")});Rn.replaceHeader(J),Te=Rn.header.element,Pt=Rn.header.iconHolder,ur=Rn.header.headerTitle,Vr=Rn.header.headerSubtitle,Ue=Rn.header.closeButton,De=Ze?.layout,Pa()}else if(Ze){if(Pt&&(Pt.style.display=Ze.showIcon===!1?"none":""),ur&&(ur.style.display=Ze.showTitle===!1?"none":""),Vr&&(Vr.style.display=Ze.showSubtitle===!1?"none":""),Ue){let J=ke()&&Ze.showCloseButton!==!1;Ue.style.display=J?"":"none"}if(Fe.clearChatButtonWrapper){let J=Ze.showClearChat;if(J!==void 0){Fe.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:Ke}=Fe;Ke&&!Ke.classList.contains("persona-absolute")&&(J?Ke.classList.remove("persona-ml-auto"):Ke.classList.add("persona-ml-auto"))}}}let nr=o.layout?.showHeader!==!1;Te&&(Te.style.display=nr?"":"none");let ko=o.layout?.showFooter!==!1;Re&&(Re.style.display=ko?"":"none"),Gr(),zt(),fe!==j?fe?pt(_e,"auto"):(he=!0,ga()):_e!==be&&pt(_e,"auto"),be=_e,j=fe,Ia(),My();let We=JSON.stringify(o.toolCall)!==JSON.stringify(c),Be=JSON.stringify(o.messageActions)!==JSON.stringify(g),ye=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),mt=o.loadingIndicator?.render!==w?.render||o.loadingIndicator?.renderIdle!==w?.renderIdle||o.loadingIndicator?.showBubble!==w?.showBubble,Vt=o.iterationDisplay!==O,cn=(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(X);(We||Be||ye||mt||Vt||cn)&&P&&(ss++,Qn(Le,P.getMessages(),at));let Rt=o.features?.streamAnimation?.type;if(Rt!==se&&Rt&&Rt!=="none"){let J=Op(Rt,o.features?.streamAnimation?.plugins);J&&pl(J,e)}let Pe=o.launcher??{},Kt=Pe.headerIconHidden??!1,Gt=o.layout?.header?.showIcon,to=Kt||Gt===!1,He=Pe.headerIconName,wt=Pe.headerIconSize??"48px";if(Pt){let J=Te,Ke=J?.querySelector(".persona-flex-col");if(to)Pt.style.display="none",J&&Ke&&!J.contains(Ke)&&J.insertBefore(Ke,J.firstChild);else{if(Pt.style.display="",Pt.style.height=wt,Pt.style.width=wt,J&&Ke&&(J.contains(Pt)?Pt.nextSibling!==Ke&&(Pt.remove(),J.insertBefore(Pt,Ke)):J.insertBefore(Pt,Ke)),He){let nt=parseFloat(wt)||24,xt=pe(He,nt*.6,"currentColor",1);xt?Pt.replaceChildren(xt):Pt.textContent=Pe.agentIconText??"\u{1F4AC}"}else if(Pe.iconUrl){let nt=Pt.querySelector("img");if(nt)nt.src=Pe.iconUrl,nt.style.height=wt,nt.style.width=wt;else{let xt=document.createElement("img");xt.src=Pe.iconUrl,xt.alt="",xt.className="persona-rounded-xl persona-object-cover",xt.style.height=wt,xt.style.width=wt,Pt.replaceChildren(xt)}}else{let nt=Pt.querySelector("svg"),xt=Pt.querySelector("img");(nt||xt)&&Pt.replaceChildren(),Pt.textContent=Pe.agentIconText??"\u{1F4AC}"}let Qe=Pt.querySelector("img");Qe&&(Qe.style.height=wt,Qe.style.width=wt)}}let Io=o.layout?.header?.showTitle,uo=o.layout?.header?.showSubtitle;if(ur&&(ur.style.display=Io===!1?"none":""),Vr&&(Vr.style.display=uo===!1?"none":""),Ue){let J=ke()&&o.layout?.header?.showCloseButton!==!1;if(Ue.style.display=J?"":"none",!we()){let Jt=Pe.closeButtonSize??"";Ue.style.height=Jt,Ue.style.width=Jt,Ue.style.minWidth=Jt,Ue.style.minHeight=Jt}let Ke=Pe.closeButtonPlacement??"inline",{closeButtonWrapper:Qe}=Fe,nt=Ke==="top-right",xt=Qe?.classList.contains("persona-absolute");if(Qe&&nt!==xt)if(Qe.remove(),nt){Qe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Jt=Ca??ue;Jt.style.position="relative",Jt.appendChild(Qe)}else{let Jt=Pe.clearChat?.placement??"inline",Zt=Pe.clearChat?.enabled??!0;Qe.className=Zt&&Jt==="inline"?"":"persona-ml-auto",Te&&Te.appendChild(Qe)}if(Ue.style.color=Pe.closeButtonColor||bn.actionIconColor,Pe.closeButtonBackgroundColor?(Ue.style.backgroundColor=Pe.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),Pe.closeButtonBorderWidth||Pe.closeButtonBorderColor){let Jt=Pe.closeButtonBorderWidth||"0px",Zt=Pe.closeButtonBorderColor||"transparent";Ue.style.border=`${Jt} solid ${Zt}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");Pe.closeButtonBorderRadius?(Ue.style.borderRadius=Pe.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),Pe.closeButtonPaddingX?(Ue.style.paddingLeft=Pe.closeButtonPaddingX,Ue.style.paddingRight=Pe.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),Pe.closeButtonPaddingY?(Ue.style.paddingTop=Pe.closeButtonPaddingY,Ue.style.paddingBottom=Pe.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom=""),Hd(Ue,Pe.closeButtonIconName??"x",{iconSize:we()?hm:void 0,iconText:Pe.closeButtonIconText??"\xD7"});let on=Pe.closeButtonTooltipText??"Close chat",go=Pe.closeButtonShowTooltip??!0;Ue.setAttribute("aria-label",on),Qe&&en({anchor:Ue,trigger:Qe,text:()=>Ue?.getAttribute("aria-label")??on,enabled:go})}let{clearChatButton:Oe,clearChatButtonWrapper:Ce}=Fe;if(Oe){let J=Pe.clearChat??{},Ke=J.enabled??!0,Qe=o.layout?.header?.showClearChat,nt=Qe!==void 0?Qe:Ke,xt=J.placement??"inline";if(Ce){Ce.style.display=nt?"":"none";let{closeButtonWrapper:on}=Fe;!we()&&on&&!on.classList.contains("persona-absolute")&&(nt?on.classList.remove("persona-ml-auto"):on.classList.add("persona-ml-auto"));let go=xt==="top-right",Jt=Ce.classList.contains("persona-absolute");if(!we()&&go!==Jt&&nt){if(Ce.remove(),go){Ce.className="persona-absolute persona-top-4 persona-z-50",Ce.style.right="48px";let Ro=Ca??ue;Ro.style.position="relative",Ro.appendChild(Ce)}else{Ce.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ce.style.right="";let Ro=Fe.closeButtonWrapper;Te&&Ro&&Ro.parentElement===Te?Te.insertBefore(Ce,Ro):Te&&Te.appendChild(Ce)}let Zt=Fe.closeButtonWrapper;Zt&&!Zt.classList.contains("persona-absolute")&&(go?Zt.classList.add("persona-ml-auto"):Zt.classList.remove("persona-ml-auto"))}}if(nt){if(!we()){let Zt=J.size??"";Oe.style.height=Zt,Oe.style.width=Zt,Oe.style.minWidth=Zt,Oe.style.minHeight=Zt}let on=J.iconColor??"";if(Oe.style.color=on||bn.actionIconColor,Hd(Oe,J.iconName??"refresh-cw",{iconSize:we()?ym:void 0}),J.backgroundColor?(Oe.style.backgroundColor=J.backgroundColor,Oe.classList.remove("hover:persona-bg-gray-100")):(Oe.style.backgroundColor="",Oe.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let Zt=J.borderWidth||"0px",Ro=J.borderColor||"transparent";Oe.style.border=`${Zt} solid ${Ro}`,Oe.classList.remove("persona-border-none")}else Oe.style.border="",Oe.classList.add("persona-border-none");J.borderRadius?(Oe.style.borderRadius=J.borderRadius,Oe.classList.remove("persona-rounded-full")):(Oe.style.borderRadius="",Oe.classList.add("persona-rounded-full")),J.paddingX?(Oe.style.paddingLeft=J.paddingX,Oe.style.paddingRight=J.paddingX):(Oe.style.paddingLeft="",Oe.style.paddingRight=""),J.paddingY?(Oe.style.paddingTop=J.paddingY,Oe.style.paddingBottom=J.paddingY):(Oe.style.paddingTop="",Oe.style.paddingBottom="");let go=J.tooltipText??"Clear chat",Jt=J.showTooltip??!0;Oe.setAttribute("aria-label",go),Ce&&en({anchor:Oe,trigger:Ce,text:()=>Oe?.getAttribute("aria-label")??go,enabled:Jt})}}let $e=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zd],ft=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ji.message,ji.messageAndClick];Me=ep({parsers:$e,handlers:ft,getSessionMetadata:K,updateSessionMetadata:le,emit:A.emit,documentRef:typeof document<"u"?document:null}),at=ax(o,Me,Ut),GS(),P.updateConfig(o),(o.features?.history?.enabled===!0!==me||o.features?.history?.provider!==Xe||o.getIdentityProof!==ct||o.clientToken!==ut)&&(kn({restoreFocus:!1}),Rh()),Er(),yc(),Qn(Le,P.getMessages(),at),Gs(),tc(),VS(),ma(P.isStreaming()),Xt!==o.contextMentions&&Ly();let kr=o.voiceRecognition?.enabled===!0,Qt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),$n=o.voiceRecognition?.provider?.type==="runtype";if(kr&&(Qt||$n))if(!re||!Wn){let J=Pi(o);if(J){re=J.button,Wn=J.wrapper;let Ke=vo&&vo.parentElement===Al?vo:null;Al?Al.insertBefore(Wn,Ke):so?.appendChild(Wn),tt&&(tt.micButton=re),tt?.addListener(re,"click",ju),re.disabled=P.isStreaming()}}else{let J=o.voiceRecognition??{},Ke=o.sendButton??{},Qe=J.iconName??"mic",nt=J.iconSize,xt=parseFloat(nt??"")||hn;re.classList.add(jn),re.classList.toggle(ho,!nt),re.style.width=nt??"",re.style.height=nt??"",re.style.minWidth=nt??"",re.style.minHeight=nt??"";let on=J.iconColor??Ke.textColor;re.innerHTML="";let go=pe(Qe,xt,on||"currentColor",1.5);go?re.appendChild(go):re.textContent="\u{1F3A4}";let Jt=J.backgroundColor??Ke.backgroundColor;Jt?re.style.backgroundColor=Jt:re.style.backgroundColor="",on?re.style.color=on:re.style.color="var(--persona-text, #111827)",J.borderWidth?(re.style.borderWidth=J.borderWidth,re.style.borderStyle="solid"):(re.style.borderWidth="",re.style.borderStyle=""),J.borderColor?re.style.borderColor=J.borderColor:re.style.borderColor="",J.paddingX?(re.style.paddingLeft=J.paddingX,re.style.paddingRight=J.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),J.paddingY?(re.style.paddingTop=J.paddingY,re.style.paddingBottom=J.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let Zt=J.tooltipText??"Start voice recognition",Ro=J.showTooltip??!1;re.setAttribute("aria-label",Zt),Wn&&en({anchor:re,trigger:Wn,text:()=>re?.getAttribute("aria-label")??Zt,enabled:Ro}),Wn.style.display="",re.disabled=P.isStreaming()}else re&&Wn&&(Wn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?P.isVoiceActive()&&P.toggleVoice():Po&&Tr());if(o.attachments?.enabled===!0){if(!An||!At){let J=o.attachments??{};Mn||(Mn=M("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Mn.style.display="none",(ce.parentElement??so).insertBefore(Mn,ce)),bt||(bt=document.createElement("input"),bt.type="file",bt.accept=(J.allowedTypes??ir).join(","),bt.multiple=(J.maxFiles??4)>1,bt.style.display="none",bt.setAttribute("aria-label","Attach files"),(ce.parentElement??so).insertBefore(bt,ce)),An=M("div","persona-send-button-wrapper"),At=M("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${jn} ${ho}`),At.type="button",At.setAttribute("aria-label",J.buttonTooltipText??"Attach file");let Ke=J.buttonIconName??"paperclip";At.style.fontSize="18px",At.style.lineHeight="1";let Qe=pe(Ke,hn,"currentColor",1.5);Qe?At.appendChild(Qe):At.textContent="\u{1F4CE}",At.addEventListener("click",xt=>{xt.preventDefault(),bt?.click()}),An.appendChild(At);let nt=J.buttonTooltipText??"Attach file";en({anchor:At,trigger:An,text:()=>At?.getAttribute("aria-label")??nt}),hp?hp.append(An):so.appendChild(An),tt&&(tt.attachmentButton=At,tt.attachmentInput=bt??void 0,tt.attachmentPreviews=Mn??void 0),!Je&&bt&&Mn&&(Je=Mi.fromConfig(J,uf),Je.setPreviewsContainer(Mn),tt?.addListener(bt,"change",async()=>{Je&&bt?.files&&(await Je.handleFileSelect(bt.files),bt.value="")}))}else{An.style.display="";let J=o.attachments??{};bt&&(bt.accept=(J.allowedTypes??ir).join(","),bt.multiple=(J.maxFiles??4)>1),Je&&Je.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles,adapter:J.adapter})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(lx(o.attachments?.dropOverlay)),At){let J=o.attachments??{},Ke=J.buttonTooltipText??"Attach file";At.setAttribute("aria-label",Ke),At.textContent="";let Qe=pe(J.buttonIconName??"paperclip",hn,"currentColor",1.5);Qe?At.appendChild(Qe):At.textContent="\u{1F4CE}",An&&en({anchor:At,trigger:An,text:()=>At?.getAttribute("aria-label")??Ke})}}else An&&(An.style.display="none"),Je&&Je.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Mt=o.sendButton??{},Vu=Mt.useIcon??!1,Ms=Mt.iconText??"\u2191",Wc=Mt.iconName,$y=Mt.tooltipText??"Send message",lM=Mt.showTooltip??!1,Wa=Mt.size,cM=parseFloat(Wa??"")||Wg,Oc=Mt.backgroundColor,Oa=Mt.textColor;if(Vu){if(Ee.style.width=Wa??"",Ee.style.height=Wa??"",Ee.style.minWidth=Wa??"",Ee.style.minHeight=Wa??"",Ee.style.fontSize="18px",Ee.style.lineHeight="1",Oa?Ee.style.color=Oa:Ee.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!P.isStreaming())if(Ee.innerHTML="",Wc){let J=parseFloat(Mt.iconSize??"")||Math.round(cM*.5),Ke=Oa?.trim()||"currentColor",Qe=Mt.iconStrokeWidth??2,nt=pe(Wc,J,Ke,Qe),xt=pe(Mt.stopIconName??"square",J,Ke,Qe);nt&&xt?Ee.appendChild(Og(nt,xt)):nt?Ee.appendChild(nt):Ee.textContent=Ms}else Ee.textContent=Ms;Ee.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${jn}`,Oc?(Ee.style.backgroundColor=Oc,Ee.classList.remove("persona-bg-persona-primary")):(Ee.style.backgroundColor="",Ee.classList.add("persona-bg-persona-primary"))}else Ee.textContent=o.copy?.sendButtonLabel??"Send",Ee.style.width="",Ee.style.height="",Ee.style.minWidth="",Ee.style.minHeight="",Ee.style.fontSize="",Ee.style.lineHeight="",Ee.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",Oc?(Ee.style.backgroundColor=Oc,Ee.classList.remove("persona-bg-persona-accent")):Ee.classList.add("persona-bg-persona-accent"),Oa?Ee.style.color=Oa:Ee.classList.add("persona-text-white");Mt.borderWidth?(Ee.style.borderWidth=Mt.borderWidth,Ee.style.borderStyle="solid"):(Ee.style.borderWidth="",Ee.style.borderStyle=""),Mt.borderColor?Ee.style.borderColor=Mt.borderColor:Ee.style.borderColor="",Mt.paddingX?(Ee.style.paddingLeft=Mt.paddingX,Ee.style.paddingRight=Mt.paddingX):(Ee.style.paddingLeft="",Ee.style.paddingRight=""),Mt.paddingY?(Ee.style.paddingTop=Mt.paddingY,Ee.style.paddingBottom=Mt.paddingY):(Ee.style.paddingTop="",Ee.style.paddingBottom=""),P.isStreaming()||Ee.setAttribute("aria-label",$y),Zl(),vo&&en({anchor:Ee,trigger:vo,text:()=>Ee.getAttribute("aria-label")??$y,enabled:lM}),Tf();let Uy=vd(xe.getState().activeModeIds,o.composer?.modes);xe.setActiveModeIds(Uy),Fs().length>0!==!!Uo&&Tp(),Uo?.render(Uy,Fs());for(let J of[...$s.keys()])bd(J,o.composer?.modeGroups)||$s.delete(J);$s.forEach(J=>J.repaint()),mr?.repaint(),xo?.resolve();let Bc=Dr(o,we());if(Wp(),Bc){Le.style.maxWidth=Bc,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%",Hn.style.maxWidth=Bc,Hn.style.marginLeft="auto",Hn.style.marginRight="auto",Hn.style.width="100%";for(let J of[so,pr,Mn,ot])J&&(J.style.maxWidth=Bc,J.style.marginLeft="auto",J.style.marginRight="auto",J.style.width="100%")}else{Le.style.maxWidth="",Le.style.marginLeft="",Le.style.marginRight="",Le.style.width="",Hn.style.maxWidth="",Hn.style.marginLeft="",Hn.style.marginRight="",Hn.style.width="";for(let J of[so,pr,Mn,ot])J&&(J.style.maxWidth="",J.style.marginLeft="",J.style.marginRight="",J.style.width="")}let Lr=o.statusIndicator??{},dM=Lr.visible??!0;if(ot.style.display=dM?"":"none",P){let J=P.getStatus();sn(ot,(Qe=>Qe==="idle"?Lr.idleText??$t.idle:Qe==="connecting"?Lr.connectingText??$t.connecting:Qe==="connected"?Lr.connectedText??$t.connected:Qe==="error"?Lr.errorText??$t.error:$t[Qe])(J),Lr,J)}ot.classList.remove("persona-text-left","persona-text-center","persona-text-right");let pM=Lr.align==="left"?"persona-text-left":Lr.align==="center"?"persona-text-center":"persona-text-right";ot.classList.add(pM),Ep(),Kp(),io(),Se()},open(){ke()&&pt(!0,"api")},close(){ke()&&pt(!1,"api")},toggle(){ke()&&pt(!he,"api")},reconnect(){P.reconnectNow()},clearChat(){jo=!1,P.clearMessages(),Dt.clear(),Tn();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&&zl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ie={},Me.syncFromMetadata(),Je?.clearAttachments(),Kl(),Us(void 0),wo(void 0),rs(),Tt?.clear(),gt?.reset(),R?.update()},setMessage(i){return!ce||P.isStreaming()||Sr()?!1:(!he&&ke()&&pt(!0,"system"),ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(P.isStreaming()||ps())return!1;let c=i?.trim()||ce.value.trim();return c?(!he&&ke()&&pt(!0,"system"),ce.value="",ce.style.height="auto",Co(),Pc(c,{consumeDraft:!1}),!0):!1},getComposerState(){return xe.getState()},setQuote(i){let c=i?.text?.trim();c&&wo({...i,text:c})},clearQuote(){wo(void 0)},startVoiceRecognition(){return P.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(P.isVoiceActive()||(!he&&ke()&&pt(!0,"system"),Ve.manuallyDeactivated=!1,co(),P.toggleVoice().then(()=>{Ve.active=P.isVoiceActive(),Ko("user"),P.isVoiceActive()&&gi()})),!0):Po?!0:fy()?(!he&&ke()&&pt(!0,"system"),Ve.manuallyDeactivated=!1,co(),Lc("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?P.isVoiceActive()?(P.toggleVoice().then(()=>{Ve.active=!1,Ve.manuallyDeactivated=!0,co(),Ko("user"),tr()}),!0):!1:Po?(Ve.manuallyDeactivated=!0,co(),Tr("user"),!0):!1},injectMessage(i){return!he&&ke()&&pt(!0,"system"),P.injectMessage(i)},injectAssistantMessage(i){!he&&ke()&&pt(!0,"system");let c=P.injectAssistantMessage(i);return dt&&(dt=!1,Ie&&(clearTimeout(Ie),Ie=null),setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)),c},injectUserMessage(i){return!he&&ke()&&pt(!0,"system"),P.injectUserMessage(i)},injectSystemMessage(i){return!he&&ke()&&pt(!0,"system"),P.injectSystemMessage(i)},injectMessageBatch(i){return!he&&ke()&&pt(!0,"system"),P.injectMessageBatch(i)},injectComponentDirective(i){return!he&&ke()&&pt(!0,"system"),P.injectComponentDirective(i)},injectTestMessage(i){!he&&ke()&&pt(!0,"system"),P.injectTestEvent(i)},async connectStream(i,c){return P.connectStream(i,c)},__pushEventStreamEvent(i){Wt&&(Z(),U(i.type,i.payload))},showEventStream(){Wt&&Mp()},hideEventStream(){ee&&js()},isEventStreamVisible(){return ee},listConversations(i){return P.listConversations(i)},getActiveConversationId(){return P.getActiveConversationId()},openConversation(i,c){return Pu(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return ku({focusComposer:i?.focus===!0})},deleteConversation(i){return ry(i)},renameConversation(i,c){return Lu(i,{title:c})},setConversationStarred(i,c){return Lu(i,{starred:c})},clearConversationHistory(i){return sy(i)},resetHistoryIdentity(){return iy()},getHistoryIdentityStatus(){return Nn?Nn.getIdentityStatus():pu()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return Ta({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){kn(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return te},showArtifacts(){Cn(o)&&(jo=!1,zs=!0,lo(),ze?.setMobileOpen(!0))},hideArtifacts(){Cn(o)&&(jo=!0,lo())},upsertArtifact(i){return Cn(o)?(or(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(jo=!1,zs=!0),P.upsertArtifact(i)):null},selectArtifact(i){Cn(o)&&P.selectArtifact(i)},clearArtifacts(){Cn(o)&&P.clearArtifacts()},getArtifacts(){return P?.getArtifacts()??[]},getSelectedArtifactId(){return P?.getSelectedArtifactId()??null},focusInput(){return fe&&!he&&!we()||!ce?!1:(ce.focus(),!0)},async resolveApproval(i,c,g){let b=P.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"){P.resolveWebMcpApproval(b.id,c);return}return P.resolveApproval(b.approval,c,g)},setFollowUpSuggestions(i){yS(i)},clearFollowUpSuggestions(){th()},getMessages(){return P.getMessages()},getStatus(){return P.getStatus()},getPersistentMetadata(){return{...ie}},updatePersistentMetadata(i){le(i)},on(i,c){return A.on(i,c)},off(i,c){A.off(i,c)},isOpen(){return ke()&&he},isVoiceActive(){return Ve.active},toggleReadAloud(i){P.toggleReadAloud(i)},stopReadAloud(){P.stopSpeaking()},getReadAloudState(i){return P.getReadAloudState(i)},onReadAloudChange(i){return P.onReadAloudChange(i)},getState(){return{open:ke()&&he,launcherEnabled:fe,voiceActive:Ve.active,streaming:P.isStreaming()}},showCSATFeedback(i){!he&&ke()&&pt(!0,"system");let c=Le.querySelector(".persona-feedback-container");c&&c.remove();let g=jm({onSubmit:async(f,b)=>{P.isClientTokenMode()&&await P.submitCSATFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});Le.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!he&&ke()&&pt(!0,"system");let c=Le.querySelector(".persona-feedback-container");c&&c.remove();let g=qm({onSubmit:async(f,b)=>{P.isClientTokenMode()&&await P.submitNPSFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});Le.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(){ru(),fs!=null&&(clearInterval(fs),fs=null),ve.forEach(i=>i()),Ge.remove(),Yt?.remove(),kt?.destroy(),mn?.remove(),es&&Ue.removeEventListener("click",es)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:g=>g?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,ve.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 X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",c),ve.push(()=>{window.removeEventListener("persona:focusInput",c)}),Wt){let V=se=>{let me=se.detail;(!me?.instanceId||me.instanceId===i)&&Lt.showEventStream()},X=se=>{let me=se.detail;(!me?.instanceId||me.instanceId===i)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",X),ve.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",X)})}let g=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.showHistory()},f=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.hideHistory()};window.addEventListener("persona:showHistory",g),window.addEventListener("persona:hideHistory",f),ve.push(()=>{window.removeEventListener("persona:showHistory",g),window.removeEventListener("persona:hideHistory",f)});let b=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.showArtifacts()},w=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.hideArtifacts()},O=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||X?.artifact&&Lt.upsertArtifact(X.artifact)},z=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||typeof X?.id=="string"&&Lt.selectArtifact(X.id)},q=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",w),window.addEventListener("persona:upsertArtifact",O),window.addEventListener("persona:selectArtifact",z),window.addEventListener("persona:clearArtifacts",q),ve.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",w),window.removeEventListener("persona:upsertArtifact",O),window.removeEventListener("persona:selectArtifact",z),window.removeEventListener("persona:clearArtifacts",q)})}let eo=wI(o.persistState);if(eo&&ke()){let i=xI(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",O=eo.persist?.voiceState&&i.getItem(f)==="true";if(b&&(kt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Lt.open(),setTimeout(()=>{if(w||O)Lt.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),ve.push(()=>{window.removeEventListener("persona:clear-chat",q)})}}}if(L&&ke()&&(kt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Lt.open()},0)),ei(),!bS){let i=_a(()=>{P&&(ss++,Dt.clear(),Qn(Le,P.getMessages(),at))});ve.push(i)}x=()=>{P&&(ss++,Dt.clear(),Qn(Le,P.getMessages(),at))},P.getMessages().length>0&&Jl(),T=()=>{P&&(ss++,Dt.clear(),Qn(Le,P.getMessages(),at))};let iM=Qy(()=>{P&&(ss++,Dt.clear(),Qn(Le,P.getMessages(),at))});ve.push(iM);let aM=Pm(()=>{P&&(ss++,Dt.clear(),Qn(Le,P.getMessages(),at),ar()?.updateInlineArtifactBlocks(Le,Gn.artifacts,{suppressTransition:!0}),lo())});return ve.push(aM),Lt};var cx=(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},MI=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},EI=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},TI=(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.")},dx=(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"},Ym=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=""},px=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Ym(e)},Km=e=>{e.style.transition=""},Gm=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=""},Qm=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=""},PI=(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))},kI=(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)},LI=e=>{let t=Hs(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:yn(t,r)??r;return{inset:o(n?.inset,Cd),canvasBackground:o(n?.canvasBackground,wd)}},ux=(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},II=(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??"";PI(e,t,n,o,p),kI(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,x=s?.launcher?.mobileBreakpoint??640,S=h!=null?h.innerWidth<=x:!1;if(C&&S&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Gm(t),Km(o),px(o),Qm(n),rp(r,o),ux(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"),px(o),MI(o,d.maxHeight),ux(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",Gm(t),Km(o),Qm(n),rp(r,o);let B=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=B,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",Km(o),Ym(o),rp(r,o);let B=cx(d.width,e.clientWidth),$=Math.max(0,e.clientWidth),T=d.animate?"margin-left 180ms ease":"none",I=d.side==="right"?a?-B:0:a?0:-B;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=`${$+B}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=`${$}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="",Gm(t),Ym(o),Qm(n),rp(r,o);let B=d.reveal==="emerge";B?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",I=!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",EI(o,d.maxHeight),o.style.overflow=B||I?"hidden":"visible",o.style.transition=T,B){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let A=u?`calc(${cx(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"}}},RI=(e,t)=>{let n=e.ownerDocument.createElement("div");return dx(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){dx(n,o)},destroy(){n.remove()}}},HI=(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,x=()=>{C=t?.launcher?.detachedPanel===!0?LI(t):null};x();let S=()=>{II(a,l,d,p,u,t,m,C)},k=null,B=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=ol(()=>{x(),S()}))},$=()=>{h(),qn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{S()}),y.observe(a)))},T=!1,I=()=>{S(),$(),m&&!T&&a.dataset.personaDockMobileFullscreen!=="true"&&(T=!0,TI(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(),B(),{mode:"docked",host:u,shell:a,syncWidgetState(G){let ie=G.launcherEnabled?G.open:!0;m!==ie&&(m=ie,I())},updateConfig(G){t=G,(t?.launcher?.enabled??!0)===!1&&(m=!0),x(),I(),B()},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)=>Et(t)?HI(e,t):RI(e,t);var WI=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},gx=(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)},mx=e=>{let t=WI(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=sp(t,r),a,l=[],d=(S,k)=>{let $=!(k?.launcher?.enabled??!0)||Et(k),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 I=S.attachShadow({mode:"open"});I.appendChild(T),gx(I,o)}else S.appendChild(T),gx(S,o);return t.id&&T.setAttribute("data-persona-instance",t.id),T},p=()=>{s.syncWidgetState(a.getState())},u=()=>{l.forEach(S=>S()),l=[a.on("widget:opened",p),a.on("widget:closed",p)],p()},m=()=>{let S=d(s.host,r);a=Vm(S,r,{debugTools:e.debugTools}),u()},y=()=>{l.forEach(S=>S()),l=[],a.destroy()};m(),e.onChatReady?.();let h=S=>{y(),s.destroy(),s=sp(t,S),r=S,m()},C={update(S){let k=Jd(r??{},S),B=Et(r),$=Et(k),T=Fr(r),I=Fr(k);if(B!==$||T!==I){h(k);return}r=k,s.updateConfig(r),a.update(S),p()},destroy(){y(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},x=new Proxy(C,{get(S,k,B){if(k==="host")return s.host;if(k in S)return Reflect.get(S,k,B);let $=a[k];return typeof $=="function"?$.bind(a):$}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=x),x};var vx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),OI=new Set(["button","a","input","select","textarea","details","summary"]),BI=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Xm=/\b(product|card|item|listing|result)\b/i,Zm=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,_I=3e3,DI=100;function Cx(e){let t=typeof e.className=="string"?e.className:"";if(Xm.test(t)||e.id&&Xm.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Xm.test(o.value))return!0}return!1}function wx(e){return Zm.test((e.textContent??"").trim())}function xx(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 NI(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function fx(e){let t=e.match(Zm);return t?t[0]:null}function hx(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 FI(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 $I="commerce-card",UI="result-card";function yx(e){return!Cx(e)||!wx(e)||!xx(e)&&!NI(e)?0:5200}function bx(e){return!Cx(e)||wx(e)||!xx(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Sx=[{id:$I,scoreElement(e){return yx(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||Zm.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(yx(e)===0)return null;let{title:n,href:o}=hx(e),r=fx((e.textContent??"").trim())??fx(t.text)??"",s=FI(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:UI,scoreElement(e){return bx(e)},formatSummary(e,t){if(bx(e)===0)return null;let{title:n,href:o}=hx(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
139
- `)}}];function jI(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function qI(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??Sx;return l==="simple"&&e.rules&&e.rules.length>0?(jI(),p=[]):l==="simple"&&(p=[]),{mode:l,maxElements:n,maxCandidates:d,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:p}}function Jm(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var zI=["data-testid","data-product","data-action","data-id","data-name","data-type"];function VI(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"||OI.has(t)||n&&BI.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Ax(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 KI(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 Mx(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Jm(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of zI){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${Jm(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=>Jm(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 GI(e){return e==="static"?DI:_I}function Ex(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Mx(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:VI(e),attributes:KI(e)}}function QI(e,t,n,o){let r=GI(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 YI(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 XI(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(vx.has(u)){l=a.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){l=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Ax(p)){l=a.nextNode();continue}let m=Ex(p,e.maxTextLength),y=m.text.length>0,h=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(S=>S==="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:x}=QI(p,m,e.rules,n);r.push({el:p,domIndex:s,enriched:m,score:C,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;YI(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 JI(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(vx.has(p)){s=r.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Ax(d)){s=r.nextNode();continue}let u=Ex(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 ZI(e={}){let t=qI(e),n=t.root??document.body;return n?t.mode==="simple"?JI(t,n):XI(t,n):[]}var ip=100;function eR(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:
137
+ `)}if(!f&&!i){let Ce="max-height: -moz-available !important; max-height: stretch !important;",$e=c?"":"padding-top: 1.25em !important;",ft=c?"":`z-index: ${o.launcher?.zIndex??rn} !important;`;Ge.style.cssText+=Ce+$e+ft}wp(),Ro()},Op=()=>{e.style.setProperty("--persona-content-max-width",Nr(o,xe()))},Uf=!1,jf=()=>{let i=Jg(o,xe());xe()&&o.composer?.placement&&o.debug===!0&&!Uf&&(Uf=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=Do(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??Md),kl()},qf=()=>{if(xe())return;let i=Et(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!fe)return;let f=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640;if(b&&f.innerWidth<=w)return;let O=f.innerHeight,z=64,q=o.launcher?.heightOffset??0,V=Math.max(200,O-z),X=Math.min(640,V);Me.style.height=`${Math.max(200,X-q)}px`};Wp(),Li(e,o),bl(e,o),vl(e,o),Op(),jf(),Xr=()=>{Wp(),qf(),Li(e,o),bl(e,o),vl(e,o),Op(),jf(),Rl?e.style.setProperty("--persona-artifact-welded-outer-radius",Rl):e.style.removeProperty("--persona-artifact-welded-outer-radius"),yt(),we()};let ve=[];ve.push(()=>{Bf=!0}),ve.push(()=>{d.forEach(i=>i()),l.destroy()}),ve.push(()=>{document.removeEventListener("keydown",Nf)}),ve.push(()=>{Zi!==null&&clearTimeout(Zi)});let Mo=null,Eo=null;ve.push(()=>{Mo?.(),Mo=null,Eo?.(),Eo=null}),na&&ve.push(()=>{na?.disconnect(),na=null}),ve.push(()=>{sa?.(),sa=null,Hp(),vt&&(vt.remove(),vt=null),ze?.element.style.removeProperty("width"),ze?.element.style.removeProperty("maxWidth"),ze?.destroy()}),Wt&&ve.push(()=>{Sl=!0,ro=null,v!==null&&(cancelAnimationFrame(v),v=null),R?.destroy(),R=null,Tt?.destroy(),Tt=null,un=null});let Zr=null,zf=()=>{Zr&&(Zr(),Zr=null),o.colorScheme==="auto"&&(Zr=ol(()=>{Li(e,o)}))};zf(),ve.push(()=>{Zr&&(Zr(),Zr=null)}),ve.push(()=>{C=!0,h?.()}),ve.push(()=>{B=!0});let Vf=!1;ve.push(()=>{Vf=!0});let Bp=(i,c)=>{let g=ll(i,c);return g||!KC.includes(i)?g:(QC().then(f=>{if(Vf)return;Id(f.wipe),Id(f.glyphCycle);let b=ll(i,c);b&&pl(b,e)}).catch(()=>{}),null)},Fl=o.features?.streamAnimation;if(Fl?.type&&Fl.type!=="none"){let i=Bp(Fl.type,Fl.plugins);i&&pl(i,e),ve.push(()=>GC(e))}let zo=ml(ur),Kf=ml(hp),Gf=ml(Qi),es=[zo,Kf,Gf];ve.push(()=>{es.forEach(i=>i.destroy())});let ts=null,P,ns=null,Qf=!1,Yf=0,Xf=null,Jf=i=>i.reduce((c,g)=>g.role==="user"?c+1:c,0),Zf=i=>{for(let c=i.length-1;c>=0;c--)if(wi(i[c]))return i[c].id??null;return null},eh=!1,vS=()=>{eh||o.debug!==!0||(eh=!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".'))},th=!1,nh=!1,oh=(i,c)=>{th||o.debug!==!0||!c.enabled||c.expose||Qf||nh&&(P.isStreaming()||i.some(wi)||(th=!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.")))},Gs=i=>{if(!P)return;let c=i??P.getMessages(),g=V=>{V.render([],P,ce,c)},f=V=>{es.forEach(X=>{X!==V&&g(X)})};ns&&(Jf(c)>Yf||Zf(c)!==Xf)&&(ns=null);let b=_r(o);oh(c,b);let w=b.enabled?cg(c):null,O=ns??w,z=ns?"host":"agent";if(O){let V=o.suggestions?.followUps,X=V?.placement??(V?"auto":"composer"),me=(X==="auto"?xe()?"composer":"after-message":X)==="after-message"?Gf:zo;f(me),me.render(O,P,ce,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:Tc});return}if(c.some(V=>V.role==="user")){es.forEach(g);return}let q=o.suggestions?.starters;if(q){let V=Bs(Do(o),c),X=q.placement??"auto",ie=X==="auto"?V?"welcome":"composer":X;if(ie==="welcome"&&!V){vS(),es.forEach(g);return}let me=ie==="welcome"?Kf:zo;f(me),me.render(q.items??o.suggestionChips,P,ce,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:Tc});return}f(zo),zo.render(o.suggestionChips,P,ce,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a,submitPrompt:Tc})},rh=()=>{ns&&(ns=null,Gs())},CS=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){rh();return}let g=P?P.getMessages():[];ns=c,Qf=!0,Yf=Jf(g),Xf=Zf(g),Gs(g)},Bn=!1,Dt=OC(),Qs=new Map,os=new Map,br=new Map,rs=null,vr=null;function ss(){if(!rs)return;let i=rs;rs=null,vr?.destroy(),vr=null,Dt.delete(i),ue.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),P&&Qn(Le,P.getMessages(),at)}let is=0,wS=Wo()!==null,_n=FC(),Dn=0,Cr=null,En=!1,$l=!1,wr=0,qt=null,as=null,_p=!1,Ys=!1,ls=null,ia=!0,Ul=!1,Xs=null,jl=!1,cs=()=>{jl=!0,MS()},Dp=null,xS=4,Vo=24,SS=80,AS=1e3,Ko=null,sh=()=>{e.setAttribute("data-persona-scrollbar",bp()),bp()!=="on-scroll"&&(Ko!==null&&clearTimeout(Ko),Ko=null,oe.removeAttribute("data-persona-scrollbar-visible"))},MS=()=>{bp()==="on-scroll"&&(oe.setAttribute("data-persona-scrollbar-visible",""),Ko!==null&&clearTimeout(Ko),Ko=setTimeout(()=>{Ko=null,Ws(oe,Vo)&&oe.removeAttribute("data-persona-scrollbar-visible")},AS))};sh(),ve.push(()=>{Ko!==null&&clearTimeout(Ko)});let Np=new Map,Ve={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};kf=()=>Ve.active,io();let ih=o.voiceRecognition?.autoResume??!1,Go=i=>{A.emit("voice:state",{active:Ve.active,source:i,timestamp:Date.now()})},co=()=>{le(i=>({...i,voiceState:{active:Ve.active,timestamp:Date.now(),manuallyDeactivated:Ve.manuallyDeactivated}}))},ES=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Gm(se.voiceState),c=!!i.active,g=Number(i.timestamp??0);Ve.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-g<SI&&setTimeout(()=>{Ve.active||(Ve.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?P.toggleVoice().then(()=>{Ve.active=P.isVoiceActive(),Go("restore"),P.isVoiceActive()&&mi()}):Lc("restore"))},1e3)},TS=()=>P?cx(P.getMessages()).filter(i=>!i.__skipPersist):[],ql=null,ah=(i,c)=>{typeof console<"u"&&console.error(i,c)},zl=(i,c)=>{let g=()=>{try{let O=i();return!O||typeof O.then!="function"?null:Promise.resolve(O).catch(z=>{ah(c,z)})}catch(O){return ah(c,O),null}},f=ql,b=f?f.then(()=>g()??void 0):g();if(!b)return;let w=b.finally(()=>{ql===w&&(ql=null)});ql=w};function aa(i){if(!G?.save)return;let g={messages:i?cx(i):P?TS():[],metadata:se,artifacts:Gn.artifacts,selectedArtifactId:Gn.selectedId,...ds?{draft:ds}:{}};zl(()=>G.save(g),"[AgentWidget] Failed to persist state:")}let ds,Vl=()=>!G?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,la=iC({write:()=>{if(!Vl())return;let i=Se.getState(),c=rC({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Wu(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(ds)&&(ds=c,aa())}});function lh(){Vl()&&la.schedule()}function Fp(){la.flush()}function ch(i){if(!Vl())return;let c=sC(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(g=>g.id),modelIds:(o.composer?.models??[]).map(g=>g.id),modes:o.composer?.modes??[]});c&&(ds=i,ce&&!ce.value&&(ce.value=c.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),wo()),c.selectedModelId&&(Se.setSelectedModelId(c.selectedModelId),fr?.repaint()),Ll(c.activeModeIds??[]),c.quote&&xo(c.quote),la.cancel())}function Kl(){la.cancel(),ds&&(ds=void 0,Vl()&&aa())}let Js=null,dh=()=>Ge.querySelector("#persona-scroll-container")||oe,Zs=()=>{Js!==null&&(cancelAnimationFrame(Js),Js=null),En=!1},ph=()=>{Cr!==null&&(cancelAnimationFrame(Cr),Cr=null),$l=!1,Zs()},PS=()=>Bn&&Up()&&(On()!=="anchor-top"||uf()),$p=()=>{let i=Yi()||"Jump to latest",c=PS();_t.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),wr>0?(Gr.textContent=String(wr),Gr.style.display="",_t.setAttribute("aria-label",`${i} (${wr} new)`)):(Gr.textContent="",Gr.style.display="none",_t.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},uh=()=>{wr!==0&&(wr=0,$p())},kS=()=>{let i=qt?.spacerHeight??0;return i<=0?Ws(oe,Vo):Xl(i)-oe.scrollTop-oe.clientHeight<=Vo},Up=()=>mr()?!_n.isFollowing():!kS(),jp=()=>!!P&&P.getMessages().length>0,zt=()=>{if(!oS()||Vr()){_t.parentNode&&_t.remove(),_t.style.display="none";return}_t.parentNode!==ue&&ue.appendChild(_t),Qr();let c=_o(oe)>0&&Up()&&jp();c?$p():uh(),_t.style.display=c?"":"none"},ca=()=>{_n.pause()&&(ph(),zt())},Tn=()=>{_n.resume(),uh(),zt()},xr=(i=!1)=>{mr()&&jp()&&_n.isFollowing()&&(!i&&!Bn||(Cr!==null&&(cancelAnimationFrame(Cr),Cr=null),$l=!0,Cr=requestAnimationFrame(()=>{Cr=null,$l=!1,_n.isFollowing()&&LS(dh(),i?220:140)})))},gh=(i,c,g,f=()=>!0)=>{let b=i.scrollTop,w=c(),O=w-b;if(Zs(),Math.abs(O)<1){En=!0,i.scrollTop=w,Dn=i.scrollTop,En=!1;return}let z=performance.now();En=!0;let q=X=>1-Math.pow(1-X,3),V=X=>{if(!f()){Zs();return}let ie=c();ie!==w&&(w=ie,O=w-b);let me=X-z,Xe=Math.min(me/g,1),ct=q(Xe),ut=b+O*ct;i.scrollTop=ut,Dn=i.scrollTop,Xe<1?Js=requestAnimationFrame(V):(i.scrollTop=w,Dn=i.scrollTop,Js=null,En=!1)};Js=requestAnimationFrame(V)},LS=(i,c=500)=>{let g=_o(i)-i.scrollTop;if(Math.abs(g)<1){Dn=i.scrollTop;return}if(Math.abs(g)>=SS){Zs(),En=!0,i.scrollTop=_o(i),Dn=i.scrollTop,En=!1;return}gh(i,()=>_o(i),c,()=>_n.isFollowing())},Gl=()=>{if(!jp()){zt();return}let i=dh();En=!0,i.scrollTop=_o(i),Dn=i.scrollTop,En=!1,zt()},ps=i=>{let c=0,g=i;for(;g&&g!==oe;)c+=g.offsetTop,g=g.offsetParent;return c},IS=()=>{let i=oe.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??oe.ownerDocument.getSelection()},Ql=()=>jC(IS(),oe),qp=()=>{if(rS()!=="last-user-turn")return!1;let i=P?.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=oe.querySelector(`[data-message-id="${g}"]`);if(!f)return!1;let b=Math.min(Math.max(0,ps(f)-Xi()),_o(oe));return En=!0,oe.scrollTop=b,Dn=oe.scrollTop,En=!1,On()==="follow"&&!Ws(oe,Vo)&&_n.pause(),zt(),!0},Yl=i=>{let c=Math.max(0,Math.round(i));Kn.style.height=`${c}px`,Kn.style.display=c>0?"":"none",qt&&(qt.spacerHeight=Math.max(0,i))},Xl=i=>{let c=parseFloat(getComputedStyle(oe).paddingBottom)||0,g=0;for(let b of Array.from(oe.children)){if(b===Kn||b.offsetHeight===0)continue;let w=ps(b)+b.offsetHeight;w>g&&(g=w)}let f=oe.scrollHeight-i;return g>0?Math.min(g+c,f):f},RS=()=>{if(!qt||qt.spacerHeight<=0)return;let i=Xl(qt.spacerHeight),c=Math.max(0,Math.round(oe.scrollTop)+oe.clientHeight-i+Vo);c<qt.spacerHeight&&(Yl(c),zt())},po=()=>{as!==null&&(cancelAnimationFrame(as),as=null),Zs(),qt=null,Kn.style.height="0px",Kn.style.display="none"},mh=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),zp=i=>oe.querySelector(`[data-message-id="${mh(i)}"]`),fh=i=>{as!==null&&cancelAnimationFrame(as),as=requestAnimationFrame(()=>{as=null;let c=mh(i),g=oe.querySelector(`[data-message-id="${c}"]`);if(!g)return;let f=ps(g),b=qt?.spacerHeight??0,w=Xl(b),{targetScrollTop:O,spacerHeight:z}=tm({anchorOffsetTop:f,topOffset:Xi(),viewportHeight:oe.clientHeight,contentHeight:w,slack:Vo});qt={initialSpacerHeight:z,contentHeightAtAnchor:w,spacerHeight:z},Yl(z),gh(oe,()=>g.isConnected?Math.max(0,ps(g)-Xi()):O,220)})},Pn=()=>{if(On()!=="anchor-top"||!qt||!Xs)return;let i=zp(Xs);if(!i)return;Zs();let c=qt.spacerHeight,g=Xl(c),{targetScrollTop:f,spacerHeight:b}=tm({anchorOffsetTop:ps(i),topOffset:Xi(),viewportHeight:oe.clientHeight,contentHeight:g,slack:Vo});qt={initialSpacerHeight:b,contentHeightAtAnchor:g,spacerHeight:b},Yl(b),En=!0,oe.scrollTop=f,Dn=oe.scrollTop,En=!1,zt()},HS=()=>{if(mr()){if(!_n.isFollowing()||Ws(oe,1))return;xr(!Bn);return}if(qt&&qt.initialSpacerHeight>0){let i=oe.scrollHeight-qt.spacerHeight,c=qC({initialSpacerHeight:qt.initialSpacerHeight,contentHeightAtAnchor:qt.contentHeightAtAnchor,currentContentHeight:i});c!==qt.spacerHeight&&Yl(c)}zt()},WS=i=>{let c=On();c==="follow"?(Tn(),xr(!0)):c==="anchor-top"&&(ia=!1,Ul=!0,jl=!1,Xs=i,fh(i))},OS=()=>{if(On()==="anchor-top"){if(Ul){ia=!1;return}ia=!0,po(),Tn(),xr(!0)}},BS=96,_S=i=>{if(ls===null)return!0;let c=zp(ls),g=zp(i);if(!c||!g)return!0;let f=ps(g)-ps(c);return Xi()+f>oe.clientHeight-BS},DS=i=>{if(On()!=="anchor-top"||!Ul||jl||Ql())return;let c=ls===null;for(let g of i){if(!c){g.id===ls&&(c=!0);continue}if(NC(g)){if(g.id===Xs||!_S(g.id))return;Xs=g.id,fh(g.id);return}}},NS=i=>{let c=new Map;i.forEach(g=>{let f=Np.get(g.id);c.set(g.id,{streaming:g.streaming,role:g.role}),!f&&g.role==="assistant"&&(A.emit("assistant:message",g),!Ys&&(On()!=="anchor-top"||uf())&&Up()&&(wr+=1,$p(),zt(),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}))}),Np.clear(),c.forEach((g,f)=>{Np.set(f,g)})},da=(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")},Qo=(i,c)=>{let g=document.createElement("div");return g.className="persona-flex",g.id=`wrapper-${i}`,g.setAttribute("data-wrapper-id",i),da(g,c),g},FS=(i,c,g)=>{let f=document.createElement("div"),w=(()=>{let H=a.find(We=>We.renderLoadingIndicator);if(H?.renderLoadingIndicator)return H.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),O=(H,We)=>We==null?!1:typeof We=="string"?(H.textContent=We,!0):(H.appendChild(We),!0),z=new Set,q=new Map,V=new Set,X=a.some(H=>H.renderAskUserQuestion),ie=[],me=[],Xe=o.enableComponentStreaming!==!1,ct=o.approval!==!1,ut=[],Xt=o.messageActions,Ft=Xt?.showRegenerate===!0&&Xt.enabled!==!1&&lt.current?.isStreaming()!==!0?uv(c):null,It=Xt?.showEdit===!0&&Xt.enabled!==!1,an=Xt?.showQuote===!0&&Xt.enabled!==!1,Ze=null,ln=o.features?.reasoningDisplay?.completedVisibility==="removed";if(c.forEach(H=>{if(ln&&H.variant==="reasoning"&&H.reasoning?.status==="complete")return;if(z.add(H.id),q.set(H.id,H.role),rs===H.id&&vr){let He=Qo(H.id,H.role);He.setAttribute("data-persona-message-edit-stub","true"),He.setAttribute("data-preserve-runtime","true"),f.appendChild(He),Ze={messageId:H.id,element:vr.element};return}let We=X&&Hr(H),Be=ct&&H.variant==="approval"&&!!H.approval,ye=!We&&H.role==="assistant"&&!H.variant&&Xe&&op(H);!Be&&br.has(H.id)&&(i.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),br.delete(H.id)),!ye&&os.has(H.id)&&(i.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),os.delete(H.id));let mt=Hr(H)?`:${H.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${H.agentMetadata?.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",Vt={canRegenerate:Ft===H.id,canEdit:It&&wg(H),canQuote:an&&!H.variant&&(H.content?.trim().length??0)>0},cn=`${Vt.canRegenerate?"r":""}${Vt.canEdit?"e":""}${Vt.canQuote?"q":""}`,dn=WC(H,is)+mt+`:${cn}`,Rt=We||Be||ye?null:BC(Dt,H.id,dn);if(Rt){f.appendChild(Rt.cloneNode(!0)),Hr(H)&&H.toolCall?.id&&H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(V.add(H.toolCall.id),Ua(H,o,Fe.composerOverlay));return}let Pe=null,Kt=a.find(He=>!!(H.variant==="reasoning"&&He.renderReasoning||H.variant==="tool"&&He.renderToolCall||!H.variant&&He.renderMessage)),Gt=o.layout?.messages;if(Hr(H)&&H.agentMetadata?.askUserQuestionAnswered===!0){Qs.delete(H.id),i.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime");return}if(wi(H)&&_r(o).enabled)return;if(Hr(H)&&o.features?.askUserQuestion?.enabled!==!1){let He=a.find(wt=>typeof wt.renderAskUserQuestion=="function");if(He&&lt.current){let wt=Qs.get(H.id),Ro=wt!==dn,uo=null;if(Ro){let{payload:$e,complete:ft}=Wr(H),Lr=H.id,Qt=()=>lt.current?.getMessages().find($n=>$n.id===Lr);uo=He.renderAskUserQuestion({message:H,payload:$e,complete:ft,resolve:$n=>{let As=Qt();As&&lt.current?.resolveAskUserQuestion(As,$n)},dismiss:()=>{let $n=Qt();$n?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved($n),lt.current?.resolveAskUserQuestion($n,"(dismissed)"))},config:o})}let Oe=wt!=null;if(Ro&&uo===null&&!Oe){H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(V.add(H.toolCall.id),Ua(H,o,Fe.composerOverlay));return}let Ce=Qo(H.id,H.role);Ce.setAttribute("data-ask-plugin-stub","true"),Ce.setAttribute("data-preserve-runtime","true"),f.appendChild(Ce),ie.push({messageId:H.id,fingerprint:dn,bubble:uo});return}else{H.agentMetadata?.awaitingLocalTool===!0&&!H.agentMetadata?.askUserQuestionAnswered&&(V.add(H.toolCall.id),Ua(H,o,Fe.composerOverlay));return}}else if(Be){let He=k();if(!He){f.appendChild(Qo(H.id,H.role));return}let wt=a.find(Ce=>typeof Ce.renderApproval=="function")??y,uo=br.get(H.id)!==dn,Oe=null;if(uo&&wt?.renderApproval){let Ce=H.id,$e=(ft,Lr)=>{let Qt=lt.current?.getMessages().find($n=>$n.id===Ce);Qt?.approval&&(Qt.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(Qt.id,ft):lt.current?.resolveApproval(Qt.approval,ft,Lr))};Oe=wt.renderApproval({message:H,defaultRenderer:()=>He.createApprovalBubble(H,o),config:o,approve:ft=>$e("approved",ft),deny:ft=>$e("denied",ft)})}if(uo&&Oe===null)i.querySelector(`#wrapper-${H.id}`)?.removeAttribute("data-preserve-runtime"),br.delete(H.id),Pe=He.createApprovalBubble(H,o);else{let Ce=Qo(H.id,H.role);Ce.setAttribute("data-approval-plugin-stub","true"),Ce.setAttribute("data-preserve-runtime","true"),f.appendChild(Ce),ut.push({messageId:H.id,fingerprint:dn,bubble:Oe});return}}else if(Kt)if(H.variant==="reasoning"&&H.reasoning&&Kt.renderReasoning){if(!nn)return;Pe=Kt.renderReasoning({message:H,defaultRenderer:()=>Mm(H,o),config:o})}else if(H.variant==="tool"&&H.toolCall&&Kt.renderToolCall){if(!pn)return;Pe=Kt.renderToolCall({message:H,defaultRenderer:()=>Tm(H,o),config:o})}else Kt.renderMessage&&(Pe=Kt.renderMessage({message:H,defaultRenderer:()=>{let He=yl(H,g,Gt,o.messageActions,In,{loadingIndicatorRenderer:w,widgetConfig:o,actionEligibility:Vt});return H.role!=="user"&&I(He,H,o,P),He},config:o}));if(!Pe&&ye){let He=zm(H);if(He){let wt=os.get(H.id),Ro=wt!==dn,uo=o.wrapComponentDirectiveInBubble!==!1&&No.getOptions(He.component)?.bubbleChrome!==!1,Oe=null;if(Ro){let Ce=qm(He,{config:o,message:H,transform:g});if(Ce&&He.component==="PersonaArtifactInline"){let $e=Ce.hasAttribute("data-artifact-inline")?Ce:Ce.querySelector("[data-artifact-inline]"),ft=$e?.getAttribute("data-artifact-inline")??"",Lr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(ft):ft,Qt=ft?i.querySelector(`#wrapper-${H.id}`)?.querySelector(`[data-artifact-inline="${Lr}"]`)??null:null;$e&&Qt&&Qt!==$e&&lr()?.hasLiveInlineArtifactBlock(Qt)&&($e===Ce?Ce=Qt:$e.replaceWith(Qt))}if(Ce)if(uo){let $e=document.createElement("div");if($e.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),$e.id=`bubble-${H.id}`,$e.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let ft=document.createElement("div");ft.className="persona-mb-3 persona-text-sm persona-leading-relaxed",ft.innerHTML=g({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),$e.appendChild(ft)}$e.appendChild(Ce),Oe=$e}else{let $e=document.createElement("div");if($e.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$e.id=`bubble-${H.id}`,$e.setAttribute("data-message-id",H.id),$e.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let ft=document.createElement("div");ft.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",ft.innerHTML=g({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),$e.appendChild(ft)}$e.appendChild(Ce),Oe=$e}}if(Oe||wt!=null){let Ce=Qo(H.id,H.role);Ce.setAttribute("data-component-directive-stub","true"),Ce.setAttribute("data-preserve-runtime","true"),f.appendChild(Ce),me.push({messageId:H.id,fingerprint:dn,bubble:Oe});return}}}if(!Pe)if(H.variant==="reasoning"&&H.reasoning){if(!nn)return;Pe=Mm(H,o)}else if(H.variant==="tool"&&H.toolCall){if(!pn)return;Pe=Tm(H,o)}else if(H.variant==="approval"&&H.approval){if(o.approval===!1)return;let He=k();if(!He)return;Pe=He.createApprovalBubble(H,o)}else{let He=o.layout?.messages;He?.renderUserMessage&&H.role==="user"?Pe=He.renderUserMessage({message:H,config:o,streaming:!!H.streaming}):He?.renderAssistantMessage&&H.role==="assistant"?Pe=He.renderAssistantMessage({message:H,config:o,streaming:!!H.streaming}):Pe=yl(H,g,He,o.messageActions,In,{loadingIndicatorRenderer:w,widgetConfig:o,actionEligibility:Vt}),H.role!=="user"&&Pe&&I(Pe,H,o,P)}let to=Qo(H.id,H.role);to.appendChild(Pe),_C(Dt,H.id,dn,to),f.appendChild(to)}),Fe.composerOverlay&&Fe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(We=>{let Be=We.getAttribute("data-persona-ask-sheet-for");Be&&!V.has(Be)&&Is(Fe.composerOverlay,Be)}),o.features?.toolCallDisplay?.grouped){let H=[],We=[],Be=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(ye=>{if(ye.variant==="tool"&&ye.toolCall&&pn){We.push(ye);return}ye.variant==="reasoning"&&(!nn||ln&&ye.reasoning?.status==="complete")||((We.length>1||Be&&We.length>0)&&H.push(We),We=[])}),(We.length>1||Be&&We.length>0)&&H.push(We),H.forEach(ye=>{let mt=ye.map(Gt=>Array.from(f.children).find(to=>to instanceof HTMLElement&&to.getAttribute("data-wrapper-id")===Gt.id)).filter(Gt=>!!Gt);if(mt.length<(Be?1:2))return;let Vt=Qo(`tool-group-${ye[0].id}`,"assistant");Vt.setAttribute("data-persona-tool-group-row","true");let cn=document.createElement("div");cn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",cn.setAttribute("data-persona-tool-group","true");let dn=document.createElement("div");dn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",dn.id=`tool-group-summary-${ye[0].id}`;let Rt=`Called ${ye.length} ${ye.length===1?"tool":"tools"}`,Pe=o.toolCall?.renderGroupedSummary?.({messages:ye,toolCalls:ye.map(Gt=>Gt.toolCall).filter(Gt=>!!Gt),defaultSummary:Rt,config:o});O(dn,Pe)||(dn.textContent=Rt);let Kt=document.createElement("div");Kt.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.id=`tool-group-stack-${ye[0].id}`,Kt.setAttribute("data-persona-tool-group-stack","true"),cn.appendChild(dn),Be||cn.appendChild(Kt),Vt.appendChild(cn),mt[0].before(Vt),mt.forEach((Gt,to)=>{if(Be){Gt.remove();return}Gt.style.setProperty("--persona-message-row-max-width","100%");let He=document.createElement("div");He.className="persona-tool-group-item persona-relative",He.setAttribute("data-persona-tool-group-item","true"),to<mt.length-1&&He.setAttribute("data-persona-tool-group-connector","true"),He.appendChild(Gt),Kt.appendChild(He)})})}DC(Dt,z);let rr=c.some(H=>H.role==="assistant"&&H.streaming),Lo=c[c.length-1],Io=Lo?.role==="assistant"&&!Lo.streaming&&Lo.variant!=="approval";if(Bn&&c.some(H=>H.role==="user")&&!rr&&!Io){let H={config:o,streaming:!0,location:"standalone",defaultRenderer:Bi},We=a.find(ye=>ye.renderLoadingIndicator),Be=null;if(We?.renderLoadingIndicator&&(Be=We.renderLoadingIndicator(H)),Be===null&&o.loadingIndicator?.render&&(Be=o.loadingIndicator.render(H)),Be===null&&(Be=Bi()),Be){let ye=document.createElement("div"),mt=o.loadingIndicator?.showBubble!==!1,Vt=o.layout?.messages?.layout??"bubble";ye.className=mt?hl("assistant",Vt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),ye.setAttribute("data-typing-indicator","true"),mt&&(ye.style.color="var(--persona-message-assistant-text, var(--persona-text))",Vt!=="flat"&&(ye.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),ye.appendChild(Be);let cn=Qo("typing-indicator","assistant");cn.appendChild(ye),f.appendChild(cn)}}if(!Bn&&c.length>0){let H=c[c.length-1],We={config:o,lastMessage:H,messageCount:c.length},Be=a.find(mt=>mt.renderIdleIndicator),ye=null;if(Be?.renderIdleIndicator&&(ye=Be.renderIdleIndicator(We)),ye===null&&o.loadingIndicator?.renderIdle&&(ye=o.loadingIndicator.renderIdle(We)),ye){let mt=document.createElement("div"),Vt=o.loadingIndicator?.showBubble!==!1;mt.className=Vt?["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(" "),mt.setAttribute("data-idle-indicator","true"),mt.appendChild(ye);let cn=Qo("idle-indicator","assistant");cn.appendChild(mt),f.appendChild(cn)}}if(gb(f),kd(i,f),tg(i),Ze){let{messageId:H,element:We}=Ze,Be=i.querySelector(`#wrapper-${H}`);Be&&We.parentElement!==Be&&(da(Be,q.get(H)??"user"),Be.replaceChildren(We))}if(ie.length>0)for(let{messageId:H,fingerprint:We,bubble:Be}of ie){let ye=i.querySelector(`#wrapper-${H}`);ye&&(da(ye,q.get(H)??"assistant"),Be!==null&&(ye.replaceChildren(Be),ye.setAttribute("data-bubble-fp",We),Qs.set(H,We)))}if(Qs.size>0)for(let H of Qs.keys())z.has(H)||Qs.delete(H);if(me.length>0)for(let{messageId:H,fingerprint:We,bubble:Be}of me){let ye=i.querySelector(`#wrapper-${H}`);ye&&(da(ye,q.get(H)??"assistant"),Be!==null&&(ye.replaceChildren(Be),ye.setAttribute("data-bubble-fp",We),os.set(H,We)))}if(os.size>0)for(let H of os.keys())z.has(H)||os.delete(H);if(ut.length>0)for(let{messageId:H,fingerprint:We,bubble:Be}of ut){let ye=i.querySelector(`#wrapper-${H}`);ye&&(da(ye,q.get(H)??"assistant"),Be!==null&&(ye.replaceChildren(Be),ye.setAttribute("data-bubble-fp",We),br.set(H,We)))}if(br.size>0)for(let H of br.keys())z.has(H)||br.delete(H)},Vp=!1,Jl=()=>{Vp||(Vp=!0,Yu().catch(()=>{Vp=!1}))},Qn=(i,c,g)=>{c.length>0&&Jl(),FS(i,c,g),Of()},pa=null,$S=()=>{if(pa)return;let i=g=>{let f=g.composedPath();f.includes(Ge)||Yt&&f.includes(Yt)||pt(!1,"user")};pa=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},hh=()=>{if(!pa)return;(e.ownerDocument??document).removeEventListener("pointerdown",pa,!0),pa=null};ve.push(()=>hh());let ua=null,US=()=>{if(ua)return;let i=g=>{g.key==="Escape"&&(g.isComposing||pt(!1,"user"))};ua=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},yh=()=>{if(!ua)return;(e.ownerDocument??document).removeEventListener("keydown",ua,!0),ua=null};ve.push(()=>yh());let ga=!1,bh=new Set,jS=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},ei=()=>{if(!xe())return;let i=Fe.peekBanner,c=Fe.peekTextNode;if(!i||!c)return;if(he){i.classList.remove("persona-pill-peek--visible");return}let g=P?.getMessages()??[],f;for(let Ft=g.length-1;Ft>=0;Ft--){let It=g[Ft];if(It.role==="assistant"&&It.content){f=It;break}}if(!f){i.classList.remove("persona-pill-peek--visible");return}let b=f.content,w=!!f.streaming,O=jS(),z=Ld(O),q=z.type!=="none"?Bp(z.type,O?.plugins):null,V=q?.isAnimating?.(f)===!0,X=q!==null&&(w||V);X&&q&&!bh.has(q.name)&&(pl(q,e),bh.add(q.name));let ie=X&&q?.containerClass?q.containerClass:null,me=c.dataset.personaPeekStreamClass??null;me&&me!==ie&&(c.classList.remove(me),delete c.dataset.personaPeekStreamClass),ie&&me!==ie&&(c.classList.add(ie),c.dataset.personaPeekStreamClass=ie),X?(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=X?Rd(b,z.buffer,q,f,w):b;if(X&&z.placeholder==="skeleton"&&w&&(!Xe||!Xe.trim())){let Ft=document.createElement("div"),It=dl();It.classList.add("persona-pill-peek__skeleton"),Ft.appendChild(It),kd(c,Ft)}else{let Ft=Math.max(0,Xe.length-100),It=Xe.length>100?Xe.slice(-100):Xe,an=Rr(It);if(!X||!q){let Ze=Xe.length>100?`\u2026${It}`:It;c.textContent!==Ze&&(c.textContent=Ze)}else{let Ze=an;(q.wrap==="char"||q.wrap==="word")&&(Ze=cl(an,q.wrap,`peek-${f.id}`,{skipTags:q.skipTags,startIndex:Ft}));let ln=document.createElement("div");if(ln.innerHTML=Ze,q.useCaret&&It.length>0){let rr=Hd(),Lo=ln.querySelectorAll(".persona-stream-char, .persona-stream-word"),Io=Lo[Lo.length-1];Io?.parentNode?Io.parentNode.insertBefore(rr,Io.nextSibling):ln.appendChild(rr)}kd(c,ln),q.onAfterRender?.({container:c,bubble:i,messageId:f.id,message:f,speed:z.speed,duration:z.duration})}}let Xt=Bn||ga;i.classList.toggle("persona-pill-peek--visible",Xt)};if(xe()){let i=Fe.peekBanner;if(i){let f=b=>{b.preventDefault(),b.stopPropagation(),pt(!0,"user")};i.addEventListener("pointerdown",f),ve.push(()=>{i.removeEventListener("pointerdown",f)})}let c=()=>{ga||(ga=!0,ei())},g=()=>{ga&&(ga=!1,ei())};Me.addEventListener("pointerenter",c),Me.addEventListener("pointerleave",g),ve.push(()=>{Me.removeEventListener("pointerenter",c),Me.removeEventListener("pointerleave",g)}),Yt&&(Yt.addEventListener("pointerenter",c),Yt.addEventListener("pointerleave",g),ve.push(()=>{Yt.removeEventListener("pointerenter",c),Yt.removeEventListener("pointerleave",g)}))}let qS=i=>{let c=o.launcher?.composerBar??{},g=c.expandedSize??"anchored",f=c.bottomOffset??"16px",b=c.collapsedMaxWidth,w=c.expandedMaxWidth??"880px",O=c.expandedTopOffset??"5vh",z=c.modalMaxWidth??"880px",q=c.modalMaxHeight??"min(90vh, 800px)",V="calc(100vw - 32px)",X="var(--persona-pill-area-height, 80px)",ie=Ge.style;if(ie.left="",ie.right="",ie.top="",ie.bottom="",ie.transform="",ie.width="",ie.maxWidth="",ie.height="",ie.maxHeight="",Yt){let me=Yt.style;me.bottom=f,me.width=b??""}if(i&&g!=="fullscreen"){if(g==="modal"){ie.top="50%",ie.left="50%",ie.transform="translate(-50%, -50%)",ie.bottom="auto",ie.right="auto",ie.width=z,ie.maxWidth=V,ie.maxHeight=q,ie.height=q;return}ie.left="50%",ie.transform="translateX(-50%)",ie.bottom=`calc(${f} + ${X})`,ie.top=O,ie.width=w,ie.maxWidth=V}},ma=()=>{if(he&&Jl(),!ke())return;if(xe()){let V=(o.launcher?.composerBar??{}).expandedSize??"anchored",X=he?"expanded":"collapsed";Ge.dataset.state=X,Ge.dataset.expandedSize=V,Yt&&(Yt.dataset.state=X,Yt.dataset.expandedSize=V),Ge.style.removeProperty("display"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),qS(he),ue.style.display=he?"flex":"none",Xr(),he?($S(),US()):(hh(),yh()),ei();return}let i=Et(o),c=e.ownerDocument.defaultView??window,g=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,b=c.innerWidth<=g,w=f&&b&&fe,O=qn(o).reveal;he?(Ge.style.removeProperty("display"),Ge.style.display=i?"flex":"",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-95","persona-opacity-0"),Me.classList.add("persona-scale-100","persona-opacity-100"),kt?(kt.setPanelOpen(!0),kt.element.style.display="none"):fn&&(fn.style.display="none")):(i?i&&(O==="overlay"||O==="push")&&!w?(Ge.style.removeProperty("display"),Ge.style.display="flex",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.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"),Me.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"),Me.classList.remove("persona-scale-100","persona-opacity-100"),Me.classList.add("persona-scale-95","persona-opacity-0")),kt?(kt.setPanelOpen(!1),kt.element.style.display=i?"none":""):fn&&(fn.style.display=i?"none":""))},pt=(i,c="user")=>{if(!ke()||he===i)return;let g=he;he=i,ma();let f=(()=>{let w=o.launcher?.sidebarMode??!1,O=e.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,q=o.launcher?.mobileBreakpoint??640,V=O.innerWidth<=q,X=Et(o)&&z&&V,ie=xe()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return w||z&&V&&fe||X||ie})();if(he&&f){if(!Mo){let w=e.getRootNode(),O=w instanceof ShadowRoot?w.host:e.closest(".persona-host");O&&(Mo=rm(O,o.launcher?.zIndex??rn))}Eo||(Eo=sm(e.ownerDocument))}else he||(Mo?.(),Mo=null,Eo?.(),Eo=null);he&&(Ia(),qp()||(On()==="follow"?xr(!0):Gl()));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:fe,voiceActive:Ve.active,streaming:P.isStreaming()})},Sr={inputDisabled:!1,sendDisabled:!1},Ar=()=>Sr.inputDisabled,us=()=>Sr.inputDisabled||Sr.sendDisabled,zS=()=>(Sr.inputDisabled?Sr.inputReason:void 0)??(Sr.sendDisabled?Sr.sendReason:void 0);function Kp(){if(!Ee)return;if(Se.getState().phase==="streaming"){Ee.disabled=!1;return}let i=Je?!Je.isReady():!1;Ee.disabled=us()||i}function Zl(){if(!Co)return;let i=Se.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;Co.toggleAttribute("data-persona-send-hidden",c)}function VS(){let i=zS();if(xe()){let c=so??Re;i?c.setAttribute("title",i):c.removeAttribute("title"),Re.toggleAttribute(Vi,!!i);return}if(i){ot.setAttribute("role","status"),ot.setAttribute("aria-live","polite"),ot.setAttribute(Vi,""),ot.textContent=i;return}if(ot.hasAttribute(Vi)&&(ot.removeAttribute("role"),ot.removeAttribute("aria-live"),ot.removeAttribute(Vi),p)){let c=P.getStatus();sn(ot,gn(c),o.statusIndicator??{},c)}}function Gp(){let i=Og(o.composer?.inputDisabled),c=Og(o.composer?.sendDisabled);Sr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},Se.setInputDisabled(i.disabled),Se.setSendDisabled(c.disabled);let g=Se.getState().phase==="streaming",f=i.disabled,b=g||f;ce&&(ce instanceof HTMLTextAreaElement?ce.disabled=f:ce.setAttribute("contenteditable",f?"false":"true"),ce.setAttribute("aria-disabled",f?"true":"false")),At&&(At.disabled=f),bt&&(bt.disabled=f);for(let w of Bt?.affordanceButtons??[])w.querySelectorAll("button").forEach(O=>{O.disabled=f});re&&(re.disabled=b),es.forEach(w=>{w.elements.forEach(O=>{O.toggleAttribute("data-disabled",b),O instanceof HTMLButtonElement||O.setAttribute("aria-disabled",b?"true":"false")}),w.buttons.forEach(O=>{O.disabled=b})}),Zp.forEach(w=>{w.toggleAttribute("data-disabled",b),w instanceof HTMLButtonElement?w.disabled=b:w.setAttribute("aria-disabled",b?"true":"false"),w.querySelectorAll("button").forEach(O=>{O.disabled=b})}),Re.dataset.personaComposerStreaming=g?"true":"false",Re.dataset.personaComposerInputDisabled=f?"true":"false",Re.dataset.personaComposerSendDisabled=us()?"true":"false",Re.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(w=>{(w instanceof HTMLButtonElement||w instanceof HTMLInputElement||w instanceof HTMLTextAreaElement||w instanceof HTMLSelectElement)&&(w.disabled=g)}),Kp(),VS()}let fa=i=>{Se.setStreaming(i),df(i?"stop":"send"),Gp()},gs=()=>{Ve.active||ce&&ce.focus()};A.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>gs(),200)});let ms=null,ha=!1,Qp=!Sn.hidden,Mr=null,Yp=!ne,ec=null;ve.push(()=>{ec?.cancel(),ec=null});let KS=i=>{let c=bw(i);if(c===Tl)return;Tl=c,e.setAttribute("data-persona-conversation-state",c);let g=Cp();kl(),Yp&&(ec?.cancel(),ec=hw(Re,c==="active"?g:Cp(),c==="active"?"drop":"rise")),Pn()},vh=null,Ch,wh=null,ti=null,Xp=!1,ya=i=>{let c=Do(o),g=`${c.variant}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(g!==vh||c.icon!==Ch)&&(vh=g,Ch=c.icon,Nd({host:Sn,iconHolder:Yx,kicker:Xx,title:Jx,subtitle:Zx,starterSuggestions:hp},c));let f=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;f!==wh&&(wh=f,Fd(Hn,c.message,o));let b=i??(P?P.getMessages():o.initialMessages);KS(b);let w=ha,O=!w&&Bs(c,b),z=O!==Qp;if(Qp=O,ti){Mr?.cancel(),Mr=null,w!==Xp&&(Xp=w,w?ym(oe,Sn,null):hm(oe,Sn,ti)),_i(oe,Sn,!w);return}if(z&&!O&&!w&&c.dismiss==="on-first-message"&&Yp){Mr=fw(Sn,V=>{Mr===V&&(Mr=null),!Qp&&!ti&&(_i(oe,Sn,!1),Pn()),V?.cancel()});return}if(Mr){if(!O&&!w)return;Mr.cancel(),Mr=null}let q=!Sn.hidden;_i(oe,Sn,O),!O&&q&&Pn()},Jp=[],Zp=[],eu=!1,xh=null,Sh,Ah=()=>{Zp.length=0;let i=Jp.splice(0,Jp.length);for(let c of i)try{c()}catch(g){console.warn("[persona] renderWelcome cleanup threw",g)}};ve.push(Ah);let GS=(i,c)=>{let g=am(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=lm({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:()=>ce,eventTarget:Sn,submitPrompt:Tc});return Zp.push(b),b},tu=()=>{if(eu)return;eu=!0;let i=Do(o);xh=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,Sh=i.icon;try{Ah(),ym(oe,Sn,ti),ti=null,Xp=!1;let c=P?P.getMessages():o.initialMessages,g=Bs(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:()=>Sn,sendMessage:O=>{if(!P||P.isStreaming())return;let z=O.trim();z&&P.sendMessage(z)},requestRender:()=>tu(),renderStarter:O=>GS(O,f++),storage:u(w.id),onCleanup:O=>{Jp.push(O)}}),b))break;b&&b!==Sn&&(ti=b,hm(oe,Sn,b))}finally{eu=!1}ya()},QS=()=>{let i=Do(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===xh&&i.icon===Sh||tu()},tc=()=>{ya(),qs||(ce.placeholder=Zv(Se.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!P?.isStreaming()&&(Ee.textContent=o.copy?.sendButtonLabel??"Send")),ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ce.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},YS=!!o.setStoredConversationId,ni=i=>le(c=>{let g={...c};return delete g[i],g}),nc=i=>{let c=se[i];return typeof c=="string"?c:null},Mh=()=>{let i=se.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},nu=!!o.clientToken&&typeof o.reconnectStream!="function";o.clientToken&&(o={...o,getStoredSessionId:()=>nc("sessionId"),setStoredSessionId:i=>{le(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ni("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>nc("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{le(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ni("conversationId"))});let Eh=()=>o.clientToken??null,Th=i=>Jw(i,vo(),o.persistState===!1),Ph=Eh(),Yo=Ph?Th(Ph):null,Xo={...Yo?{visitorStore:Yo}:{},historyBootstrapReady:_,getStoredMessageCursor:()=>nc("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){ni("historyMessageCursor");return}le(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=se.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){ni("pendingDisplayProjections");return}le(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:Mh,setStoredResumableHandle:i=>{if(!i){ni("durableResume");return}le(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>nu&&Mh()!==null,...YS?{}:{getStoredConversationRevision:()=>nc("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){ni("conversationRevision");return}le(c=>({...c,conversationRevision:i}))}}};if(nu){let i=o.onExecutionState,c=e.ownerDocument.defaultView,g=!1,f=()=>{g=!0},b=()=>{g=!1};c?.addEventListener("beforeunload",f),c?.addEventListener("pagehide",f),c?.addEventListener("pageshow",b),ve.push(()=>{c?.removeEventListener("beforeunload",f),c?.removeEventListener("pagehide",f),c?.removeEventListener("pageshow",b)}),o={...o,reconnectStream:o.reconnectStream??(w=>P.getClient().reconnectClientTokenStream(w)),onExecutionState:w=>{(w||!g)&&Xo.setStoredResumableHandle?.(w?{executionId:w.executionId,after:w.lastEventId}:null),i?.(w)}}}let XS=()=>{let i=Eh();if(i&&Yo?.matches(i,vo(),o.persistState===!1)||!i&&!Yo)return;Yo?.destroy(),Yo=i?Th(i):null;let c={...Xo};Yo?c.visitorStore=Yo:delete c.visitorStore,Xo=c,P.setHistoryInternals(Xo)},fs=null,JS=()=>{fs==null&&(fs=setInterval(()=>{let i=Le.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(fs),fs=null;return}let c=Date.now();i.forEach(g=>{let f=Number(g.getAttribute("data-tool-elapsed"));f&&(g.textContent=Xc(c-f))})},100))},ou=(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((O,z)=>ou(O,c[z]));let g=i,f=c,b=Object.keys(g),w=Object.keys(f);return b.length===w.length&&b.every(O=>Object.prototype.hasOwnProperty.call(f,O)&&ou(g[O],f[O]))},kh=i=>{let{content:c,rawContent:g,llmContent:f,...b}=i;return b},ru=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!op(i),ZS=(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))&&ru(f)&&ru(b)&&ou(kh(f),kh(b))},su=null,oi=null,hs=null,Jo=null,oc=i=>{su=i;let c,g;oi=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),!oi&&ru(w)&&(oi={index:b,id:w.id}),c&&g&&oi)break}Qn(Le,i,at),lr()?.updateInlineArtifactBlocks(Le,Gn.artifacts,{suppressTransition:Bn}),JS(),ya(i),Gs(i),xr(!Bn),NS(i),i.length===0&&(po(),ia=!0,Ul=!1,Xs=null,jl=!1),!_p||Ys?(_p=!0,ls=c?.id??null,Dp=g?.id??null):c&&c.id!==ls?(ls=c.id,WS(c.id)):g&&g.id!==Dp&&OS(),g&&(Dp=g.id),DS(i);let f=Ve.lastUserMessageId;c&&c.id!==f&&(Ve.lastUserMessageId=c.id,A.emit("user:message",c)),Ve.lastUserMessageWasVoice=!!c?.viaVoice,aa(i),ei()},iu=()=>{Jo!==null&&(cancelAnimationFrame(Jo),Jo=null);let i=hs;hs=null,i&&oc(i)},Lh=()=>{Jo!==null&&cancelAnimationFrame(Jo),Jo=null,hs=null},eA=i=>{let c=hs??su;if(Bn&&c&&oi&&ZS(c,i,oi)){hs=i,Jo===null&&(Jo=requestAnimationFrame(()=>{Jo=null;let g=hs;hs=null,g&&oc(g)}));return}if(i.length===0){Lh(),oc(i);return}iu(),oc(i)};P=new Xa(o,{onMessagesChanged(i){eA(i)},onStatusChanged(i){let c=o.statusIndicator??{};sn(ot,(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),St()},onStreamingChanged(i){i||(P?.getMessages().length===0?Lh():iu()),Bn=i,fa(i),St(),P&&Qn(Le,P.getMessages(),at),i||(xr(!0),RS(),nh=!0,P&&oh(P.getMessages(),_r(o))),zt(),El(i?"Responding\u2026":"Response complete."),ei()},onVoiceStatusChanged(i){if(A.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":or(),mi();break;case"processing":or(),nM();break;case"speaking":or(),oM();break;default:i==="idle"&&P.isBargeInActive()?(or(),mi(),re?.setAttribute("aria-label","End voice session")):(Ve.active=!1,or(),Go("system"),co());break}},onArtifactsState(i){Gn=i,i.artifacts.length===0&&(zs=!1),lr()?.updateInlineArtifactBlocks(Le,i.artifacts,{suppressTransition:Bn}),lo(),aa()},onHistoryStateChanged(i){qe(i)},onHistoryNotice(i){Ot(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})}},Xo),lt.current=P,ve.push(()=>P.cancel()),ve.push(()=>{P.destroy(),Yo?.destroy()});let au=null;if(P.onReadAloudChange((i,c)=>{Hf=i,Wf=c,Of();let g=i??au;i&&(au=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"&&(au=null)}),p=!0,_p=!0,o.voiceRecognition?.provider?.type==="runtype")try{P.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let tA=720,nA=250,Ye=Um(o.features?.history?.copy),Nn=null,lu=!1,rt=null,rc=null,sc="conversation",cu=null,mn=null,To=null,ic=P.getHistoryState(),du=null,ba=0,pu=null,ac=null,lc=null,uu=`persona-history-${Math.random().toString(36).slice(2,8)}`,gu=()=>o.features?.history?.enabled===!0,Po=()=>gu()&&!!Nn&&!lu,Ih=()=>{let i=P.getStatus();return Bn||i==="paused"||i==="resuming"},mu=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",g=Nn?.capabilities.scopes;return!g||g.includes(c)?c:g[0]??c},ri=()=>rc?.scope??mu(),Rh=()=>P.getClientSession()?.targetId??null,Hh=i=>`${i.state}:${"reason"in i?i.reason:""}`,oA=i=>{let c=Hh(i);c!==du&&(du=c,A.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},cc=i=>{i&&(Uo.textContent="",Uo.textContent=i)},Wh=null,Oh=null,rA=()=>{if(!gu())return null;let i=nx();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(Wh!==c&&(Wh=c,Oh=c()),Oh):P.isClientTokenMode()?ox({client:P.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:g=>P.bindActivatedSession(g),getClient:()=>P.getClient()}):null},Bh=()=>{ac?.(),ac=null,lc?.(),lc=null,lu=!1,Nn=rA();let i={...Xo};Nn?i.historyProvider=Nn:delete i.historyProvider,Xo=i,P.setHistoryInternals(Xo),Nn&&(ac=Nn.subscribeAvailability?.(c=>{lu=!c,c||kn({restoreFocus:!1}),Tr()})??null,lc=Nn.subscribeIdentityStatus(c=>oA(c)),du=Hh(Nn.getIdentityStatus()))},fu=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!fe||Et(o)))return"panel";let c=Ao??ue;return(c.getBoundingClientRect().width||c.clientWidth)>=tA?"rail":"panel"},Yn=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},dc="data-persona-history-suppressed",Fn=null,Er=null,ys=null,va=null,hu=null,_h="",Dh=()=>Te===hu?_h:o.layout?.showHeader===!1?"none":"",sA=()=>ae==="panel"&&!!ys&&va===ys.element&&o.layout?.showHeader!==!1&&Dh()!=="none",iA=()=>{for(let i of Array.from(Te.children))i!==Fn&&i.setAttribute(dc,"")},aA=()=>{for(let i of Array.from(ue.querySelectorAll(`[${dc}]`)))i.removeAttribute(dc)},lA=()=>{let i=ys;if(!i)return;if(Array.from(Te.children).some(f=>f!==Fn&&!f.hasAttribute(dc))){Er&&Er!==Te&&(Er.style.removeProperty("min-height"),Er=null);let f=Te.offsetHeight;f>0&&(Te.style.minHeight=`${f}px`,Er=Te)}Fn||(Fn=M("div","persona-history-header-host")),i.setHeaderPlacement("external");let g=i.getHeaderElement();g.parentNode!==Fn&&Fn.replaceChildren(g),Fn.parentNode!==Te&&Te.appendChild(Fn),iA()},Nh=()=>{Er&&(Er.style.removeProperty("min-height"),Er=null),Fn&&(ys?.setHeaderPlacement("inline"),Fn.remove(),Fn=null,aA())},pc=null,yu=()=>{if(pc){if(oe.style.display="none",Yn(oe,!0),Re.hidden=!0,Yn(Re,!0),sA()){lA(),Te.style.display=Dh(),Yn(Te,!1);return}Nh(),Te.style.display="none",Yn(Te,!0)}};we=yu;let cA=i=>{let c=oe.style.display,g=Re.hidden,f=Re,b=Te,w=Te.style.display;hu=b,_h=w,pc=()=>{pc=null,Nh(),hu=null,oe.style.display=c,Yn(oe,!1),f.hidden=g,Yn(f,!1),Re!==f&&(Re.hidden=!1,Yn(Re,!1)),b.style.display=w,Yn(b,!1),Te!==b&&(Te.style.display=o.layout?.showHeader===!1?"none":"",Yn(Te,!1))},Re.parentNode?.insertBefore(i,Re),yu()},si=null,bs=null,Ca=null,ii=null,Fh=()=>[Te,Fe.closeButtonWrapper,Fe.clearChatButtonWrapper,oe,Re],dA=52,uc=()=>o.features?.history?.rail?.collapsible!==!1,ai=()=>o.features?.history?.rail?.side==="right"?"right":"left",bu=200,vu=400,Cu=i=>Math.min(vu,Math.max(bu,Math.round(i))),pA=()=>o.features?.history?.rail?.resizable===!0,wa,uA=()=>{if(wa===void 0&&(wa=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${vo()}rail-width`));i&&(wa=i)}catch{}return wa},xa=()=>Cu(uA()??o.features?.history?.rail?.width??260),gA=i=>{if(wa=i,o.persistState!==!1)try{window.localStorage.setItem(`${vo()}rail-width`,String(i))}catch{}},gc=()=>uc()&&o.features?.history?.rail?.collapsedBehavior==="overlay",Nt=!1,$h=i=>{let c=M("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},mA=()=>{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=$h(i.iconUrl):g=i.icon?pe(i.icon,20):null),g?g.cloneNode(!0):null}},fA=()=>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=$h(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)}}}})}})??[],hA=i=>{let c=fA();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},Sa=null,Uh=()=>`${vo()}rail-collapsed`,wu=()=>{if(Sa===null&&(Sa=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(Uh());i&&(Sa=i==="1")}catch{}return Sa},xu=i=>{if(Sa=i,o.persistState!==!1)try{window.localStorage.setItem(Uh(),i?"1":"0")}catch{}},Aa=()=>ae==="rail"&&uc()&&!gc()&&wu(),Su=()=>{},jh=()=>{if(gc()){Su();return}xu(!wu()),rt?.view.setCollapsed(Aa()),yt(),Pn()},Au=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!Td(i)?null:{combo:i,hint:Pd(i),aria:sl(i)}},qh=()=>{d.forEach(c=>c()),d=[];let i=Au();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>te&&ae==="rail"&&uc()||ci(),run:()=>gc()?Su():jh()}));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}`}))};qh();let yA=300,mc="var(--persona-history-overlay-margin,8px)",Xn=null,Zo=null,fc=0,er=null,li=null,vs=!1,Mu=0,zh=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,ci=()=>Po()&&gc()&&(ae??fu())==="rail",bA=()=>te&&!Nt,Ma=()=>{li!==null&&clearTimeout(li),li=null},vA=()=>{Nm().catch(()=>{})},Vh=()=>{Ma(),Nt&&(li=setTimeout(()=>{li=null,!(vs||!Nt)&&(er?.contains(document.activeElement)||kn({restoreFocus:!1}))},yA))},CA=(i,c)=>{let g=er?.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},Eu=i=>{Nt&&(vs=CA(i.clientX,i.clientY),vs?Ma():li===null&&Vh())},Kh=i=>{te||!ci()||(Nt=!0,Ta({invoker:Xn,keyboard:i?.keyboard===!0}).then(()=>{te?!vs&&document.activeElement!==Xn&&kn():Nt=!1}))},Gh=()=>{let i=va?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",Nt?Ye.expandLabel:Ye.collapseLabel),i.setAttribute("aria-expanded",Nt?"false":"true"))},Qh=()=>{xu(!1);let i=rt;if(!Nt||!i){Ta({invoker:Xn});return}let c=document.activeElement===Xn;Nt=!1,hc(),i.element.remove(),Pu(i.element),Gh(),c&&bc(),Pn(),Tr()},wA=()=>{xu(!0),kn()};Su=()=>{!te||Nt?Qh():wA()};let xA=()=>{let i=Au(),c=Os({ariaLabel:Ye.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":uu,...i?{"aria-keyshortcuts":i.aria}:{}}}),g=c.button;g.addEventListener("mouseenter",()=>{vs=!0,Ma(),!(zh()||Date.now()<Mu)&&Kh()}),g.addEventListener("mouseleave",()=>{vs=!1,Mu=0,Vh()}),g.addEventListener("focus",()=>{te||vA()}),g.addEventListener("click",f=>{Po()&&(f.detail!==0&&zh()&&!te?Kh():Qh())}),Xn=g,Zo=c.wrapper},Ea=()=>{if(Zo&&!Zo.isConnected&&(Zo=null,Xn=null),!ci()){Zo?.remove(),Zo=null,Xn=null;return}Xn||xA();let i=Zo,c=Xn;if(!i||!c)return;let g=ai()!=="right"?Te.firstChild:null;(g??Te.lastChild)!==i&&Te.insertBefore(i,g),i.style.display=bA()||fc>0?"none":"",c.setAttribute("aria-label",Ye.expandLabel),c.setAttribute("aria-expanded",te?"true":"false"),er&&yt()},Yh=i=>{if(!Nt)return;let c=i.target;c instanceof Node&&(er?.contains(c)||Zo?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||kn({restoreFocus:!1}))};document.addEventListener("pointerdown",Yh,!0),ve.push(()=>{document.removeEventListener("pointerdown",Yh,!0),document.removeEventListener("pointermove",Eu),di?.(),Ma()});let Tu=null,di=null,Xh=16,Jh=i=>{gA(Cu(i)),yt(),Pn()},SA=()=>{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(bu)),i.setAttribute("aria-valuemax",String(vu)),i.addEventListener("pointerdown",c=>{let g=bs;if(!g||c.button!==0)return;c.preventDefault(),di?.();let f=c.clientX,b=g.getBoundingClientRect().width||xa(),w=ai()==="right"?-1:1,O=b,z=e.ownerDocument;g.style.transition="none";let q=X=>{O=Cu(b+w*(X.clientX-f)),g.style.flex=`0 0 ${O}px`,i.setAttribute("aria-valuenow",String(O))},V=()=>{di=null,z.removeEventListener("pointermove",q),z.removeEventListener("pointerup",V),z.removeEventListener("pointercancel",V),g.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}Jh(O)};di=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=ai()==="right"?-Xh:Xh,f=xa(),b=c.key==="ArrowRight"?f+g:c.key==="ArrowLeft"?f-g:c.key==="Home"?bu:c.key==="End"?vu:null;b!==null&&(c.preventDefault(),Jh(b))}),i},AA=(i,c)=>{if(!pA()||Aa()){di?.(),Tu?.remove();return}let g=Tu??SA();Tu=g,g.setAttribute("aria-label",Ye.resizeLabel),g.setAttribute("aria-valuenow",String(xa())),g.nextElementSibling!==c&&i.insertBefore(g,c)};yt=()=>{rt?.view.setRailSide(ai());let i=ai()==="right",c=er;if(c){let z=Xn?Xn.getBoundingClientRect().bottom-ue.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(z))}px + ${mc})`,c.style.width=`${xa()}px`,c.style.left=i?"":mc,c.style.right=i?mc:""}let g=bs,f=si,b=Ca;if(!g||!f||!b)return;g.style.flex=`0 0 ${Aa()?dA:xa()}px`;let w="1px solid var(--persona-divider,#e5e7eb)";g.style.borderRight=i?"":w,g.style.borderLeft=i?w:"";let O=i?b:g;f.firstElementChild!==O&&f.append(O,i?g:b),AA(f,i?g:b)};let Zh=i=>{if(ii&&bs){ii.replaceWith(i),ii=null,yt();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",ue.insertBefore(c,Te.parentNode===ue?Te:oe);for(let b of Fh())b?.parentNode===ue&&g.appendChild(b);c.append(f,g),f.appendChild(i),si=c,bs=f,Ca=g,yt()},MA=()=>{if(si)return;let i=M("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",ii=i,Zh(i),Pn()},ey=()=>{ii&&(hc(),Pn())},EA=i=>{let c=M("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${mc};display:flex;overflow:hidden;z-index:${Ti-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))`,ue.style.position="relative",ue.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",Eu),er=c,yt(),Gh()},hc=()=>{pc?.(),er&&(vs&&(Mu=Date.now()+150),document.removeEventListener("pointermove",Eu),er.remove(),er=null);let i=si;if(i){di?.();for(let c of Fh())c&&i.contains(c)&&ue.insertBefore(c,i);i.remove(),si=null,bs=null,Ca=null,ii=null}},ty=i=>{va=i,i.id=uu,i.style.flex="1 1 auto",i.style.minHeight="0"},Pu=i=>{ty(i),(ae!=="rail"||Nt)&&ey(),ae!=="rail"?cA(i):Nt?EA(i):Zh(i)},yc=()=>{if(Ea(),uy(),!te||!rt)return;let i=fu();if(i===ae)return;let c=document.activeElement,g=c instanceof HTMLElement&&(rt.element.contains(c)||Fn?.contains(c)===!0)?c:null;hc(),rt.element.remove(),rt.view.setHeaderPlacement("inline"),ae=i,rt.view.setPresentation(i),rt.view.setCollapsed(Aa()),rt.requestRender(),rt.element.isConnected||Pu(rt.element),g?.isConnected?g.focus():bc(),zt(),Pn(),Tr()},ny=(i,c)=>Fn?.querySelector(c)??i.querySelector(c),bc=()=>{let i=rt?.element??va;if(!i)return;let c=ny(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let g=ny(i,".persona-history-title")??i;g.tabIndex=-1,g.focus()},Ta=async i=>{if(!Po()||te)return;let c=Nn;if(!c)return;if(!Nt&&ci()&&wu()){Ea();return}vc();let g=++ba;sc=i?.returnSurface??"conversation",cu=i?.invoker??mn;let f=ci()&&!Nt;f&&(fc+=1,Ea(),MA());let b;try{b=await Nm()}catch{cc(Ye.openHistoryLabel),f&&(fc-=1,g===ba&&(ey(),Ea()));return}if(f&&(fc-=1),g!==ba||te)return;rc={scope:mu()},ae=fu(),te=!0;let w=ae==="panel"&&o.layout?.showHeader!==!1&&Te.style.display!=="none"?"external":"inline",O=o.features?.history?.rowAvatar,z=Au(),q=z?{hint:z.hint,aria:z.aria}:null,V={provider:c,context:rc,targetId:Rh(),presentation:ae,collapsible:uc(),collapsed:Aa(),railSide:ai(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:mA(),onToggleCollapse:jh,...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:O===!1?!1:typeof O=="string"?O: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:X=>Lu(X,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:X=>Cs(X),attachTooltip:en,onStartNew:()=>Iu({focusComposer:!0}),onClose:()=>kn(),onRequestDeleteConversation:X=>py(X),onRequestClearHistory:()=>RA(),...c.resetDevice?{onRequestResetIdentity:()=>HA()}:{}};rt=tx({plugins:a,config:o,getPresentation:()=>ae??"panel",getReturnSurface:()=>sc,close:()=>kn(),createView:({slots:X,renderDom:ie,onModelChange:me,railSections:Xe})=>(ys=b.createHistoryView({...V,railSections:hA(Xe),slots:X,renderDom:ie,onModelChange:me,onAnnounce:cc}),ys),onElementChanged:(X,ie)=>{if(!ie?.isConnected)return Pu(X);ty(X),ie.replaceWith(X),yu()}}),rt.view.setNewConversationRequired(ic.recovery==="new_conversation_required"),i?.focus!==!1&&(ae!=="rail"||i?.keyboard===!0)&&bc(),zt(),Pn(),Tr(),A.emit("history:opened",{presentation:ae,returnSurface:sc,timestamp:Date.now()})},vc=()=>{},kn=i=>{if(!te)return;ba+=1;let c=sc,g=cu,f=rt,b=i?.restoreFocus!==!1;te=!1;let w=!1,O=null,z=()=>{if(!w){if(w=!0,vc=()=>{},O!==null&&clearTimeout(O),Nt=!1,Ma(),hc(),f?.dispose(),f?.view.destroy(),f?.element.remove(),rt===f&&(rt=null,ys=null,va=null,ae=null,rc=null,cu=null),zt(),Pn(),Tr(),b){let V=g??mn;V?.isConnected?V.focus():gs()}A.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},q=f&&f.element===f.view.element?f.view.playExit():null;if(!q){z();return}vc=z,O=setTimeout(z,nA),q.then(z)},oy=i=>{if(!(i.key!=="Escape"||!te||!rt)){if(ae==="rail"){let c=i.target;if(!(c instanceof Node)||!(rt.element.contains(c)||Nt&&Zo?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),kn()}};ue.addEventListener("keydown",oy),ve.push(()=>ue.removeEventListener("keydown",oy));let Cc=null,ry=!1,Pa=()=>{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")},TA=i=>{i!==Cc&&(Cc=i,Pa())},Cs=i=>{ry=i?.starred===!0,TA(i&&i.title.trim()||null),Pa()};Pa(),ue.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,g=P.getActiveConversationId();g&&(c==="delete"?py(g):c==="star"&&P.canUpdateConversations()&&Ru(g,{starred:!ry}).catch(()=>{}))});let wc=0,PA=250,xc=null,Sc=()=>{xc&&clearTimeout(xc),xc=null};ve.push(Sc);let sy=()=>{Sc();let i=ms;i&&(ha=!0,i.hidden=!1,Le.style.display="none",ya())},Ac=()=>{wc+=1,Sc(),ms&&(ms.remove(),ms=null,ha=!1,Le.style.removeProperty("display"),Yn(Re,!1),ya())},kA=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Le.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},ku=(i,c)=>Q("div",{className:hn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),iy=()=>Q("div",{className:"persona-conversation-loading-body"},ku("58%",!1),ku("72%",!0),ku("44%",!1)),ay=i=>{ms?.remove(),ms=i,i.hidden=!ha,oe.insertBefore(i,Le),Sc(),ha||(xc=setTimeout(sy,PA)),Yn(Re,!0)},LA=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:iy},c=null,g=a.find(f=>f.renderLoadingIndicator);g?.renderLoadingIndicator&&(c=g.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),ay(Q("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ye.openConversationLoadingLabel}},c??iy()))},IA=i=>{let c=()=>{Lu(i,{focusComposer:!0}).catch(()=>{})},g=Po()?()=>{Ac(),Ta()}: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:Ye.openConversationErrorTitle}),Q("div",{className:"persona-conversation-loading-error-actions"},f(Ye.openConversationRetryLabel,c),g?f(Ye.openConversationBackLabel,g):null)),w=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Ye.openConversationErrorTitle,retryLabel:Ye.openConversationRetryLabel,backLabel:Ye.openConversationBackLabel}),retry:c,...g?{back:g}:{},defaultRenderer:b}),O=null;for(let z of a)if(z.renderHistoryOpenError){try{O=z.renderHistoryOpenError(w)}catch(q){console.warn("[persona] renderHistoryOpenError threw",q),O=null}if(O)break}ay(Q("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},O??b())),sy()};A.on("history:closed",()=>{ms&&Yn(Re,!0)});let Lu=async(i,{focusComposer:c=!1}={})=>{let g=ri(),f=!!rt;rt?.view.setActiveConversationId(i),Ac();let b=wc;LA(),te&&(ae==="panel"||Nt)&&kn({restoreFocus:!1}),Ys=!0;try{await P.openConversation(i,{scope:g})}catch(w){throw b===wc&&IA(i),w}finally{Ys=!1}b===wc&&(Ac(),Dt.clear(),po(),Tn(),qp()||Gl(),kA(),tr(),f||Cs(null),A.emit("history:conversationOpened",{conversationId:i,title:Cc,scope:g,timestamp:Date.now()}),c&&gs())},Iu=async({focusComposer:i=!1}={})=>{Ac(),await P.startNewConversation({scope:ri()}),Cs(null),Dt.clear(),po(),Tn(),Gl(),tr();let c=P.getActiveConversationId();rt?.view.setActiveConversationId(c),A.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),te&&(ae==="panel"||Nt)&&kn({restoreFocus:!1}),i&&gs()},Ru=async(i,c)=>{let g=await P.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return rt?.view.applyConversationSummary(g),!rt&&i===P.getActiveConversationId()&&Cs(g),g},ly=async i=>{let c=ri(),g=P.getActiveConversationId()===i;await P.deleteConversation(i,{scope:c}),rt?.view.removeConversationSummary(i),g&&(Cs(null),Dt.clear(),po(),Tn(),tr()),A.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:g,timestamp:Date.now()})},cy=async i=>{let c=i?.scope??ri(),g=i?.allTargets?null:i?.targetId??Rh(),f=await P.clearConversationHistory({...g?{targetId:g}:{},scope:c});return Cs(null),Dt.clear(),po(),Tn(),tr(),A.emit("history:cleared",{deleted:f.deleted,scope:c,targetId:g,timestamp:Date.now()}),f},dy=async()=>{if(!Nn?.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{Cs(null),P.clearArtifacts(),Dt.clear(),su=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),se={},Ae.syncFromMetadata(),G?.clear&&zl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),po(),Tn(),tr(),kn({restoreFocus:!1}),gs(),he||kt?.launcher.element.focus()}return cc(i?Ye.identityResetNotice:Ye.identityResetUnconfirmedNotice),A.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},Hu=()=>Ao?Me:ue,py=async i=>await np({host:Hu(),title:Ye.deleteConversationConfirmTitle,description:Ye.deleteConversationConfirm,confirmLabel:Ye.deleteConversationConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await ly(i),"deleted"):"cancelled",RA=async()=>{let i=ri()==="verified-user";return await np({host:Hu(),title:Ye.clearHistoryConfirmTitle,description:i?Ye.clearHistoryVerifiedConfirm:Ye.clearHistoryConfirm,confirmLabel:Ye.clearHistoryConfirmLabel,cancelLabel:Ye.confirmCancelLabel})?(await cy(),"cleared"):"cancelled"},HA=async()=>{if(!await np({host:Hu(),title:Ye.resetIdentityConfirmTitle,description:Ye.resetIdentityConfirm,confirmLabel:Ye.resetIdentityConfirmLabel,cancelLabel:Ye.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await dy();return{outcome:"reset",remoteRevocationConfirmed:c}},Jn=M("button","persona-history-earlier");Jn.type="button",Jn.textContent=Ye.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 tr=()=>{if(!(Po()&&!!ic.nextMessageCursor&&!!P.getActiveConversationId())){Jn.remove();return}Jn.textContent=Ye.showEarlierMessagesLabel,Jn.parentNode!==oe&&oe.insertBefore(Jn,oe.firstChild)};Jn.addEventListener("click",()=>{let i=P.getActiveConversationId(),c=ic.nextMessageCursor;if(!i||!c||Jn.disabled)return;Jn.disabled=!0;let g=oe.scrollHeight,f=oe.scrollTop;P.loadOlderMessages(i,c,{scope:ri()}).then(()=>{oe.scrollTop=f+(oe.scrollHeight-g),Pn()}).catch(()=>{}).finally(()=>{Jn.disabled=!1,tr()})});let WA=()=>{let i=Os({ariaLabel:Ye.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(!(!Po()||Ih())){if(te){kn();return}Ta({invoker:i.button,keyboard:c.detail===0})}}),i},uy=()=>{if(!Po()){To?.remove(),mn=null,To=null;return}if(To&&!To.isConnected&&(mn=null,To=null),!mn&&Te){let f=WA();mn=f.button,To=f.wrapper;let b=Fe.clearChatButtonWrapper||Fe.closeButtonWrapper;b?.parentNode&&Te.contains(b)?b.parentNode.insertBefore(To,b):Te.appendChild(To)}if(!mn||!To)return;let i=ci()||te&&ae==="rail";if(To.style.display=i?"none":"",i){document.activeElement===mn&&bc();return}let c=Ih();mn.disabled=c,mn.setAttribute("aria-disabled",c?"true":"false");let g=c?Ye.openHistoryBusyLabel:Ye.openHistoryLabel;mn.setAttribute("aria-label",g),(o.features?.history?.presentation??"panel")==="panel"?(mn.removeAttribute("aria-expanded"),mn.removeAttribute("aria-controls")):(mn.setAttribute("aria-expanded",te?"true":"false"),mn.setAttribute("aria-controls",uu))},Mc=!1,OA=()=>{let i=Fe.clearChatButton;if(i){if(Po()){Mc||(pu=i.getAttribute("aria-label")??"",Mc=!0),i.setAttribute("aria-label",Ye.newConversationLabel),i.removeAttribute("title");return}Mc&&(Mc=!1,pu&&i.setAttribute("aria-label",pu))}},Tr=()=>{Ye=Um(o.features?.history?.copy),uy(),Ea(),OA(),tr()};St=Tr,qe=i=>{ic=i,rt?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),fa(i.sendBlocked||Bn),tr()},Ot=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(Dt.clear(),po(),Tn()),cc(i.message),rt?.view.refresh()},Bh(),Tr(),ve.push(()=>{ac?.(),lc?.(),ba+=1,vc(),rt?.dispose(),rt?.view.destroy(),rt=null}),o.clientToken&&P.initClientSession().then(()=>{if(Po())return P.reconcileBootConversation({scope:mu()})}).then(()=>{tr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Wt||o.onSSEEvent)&&P.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),U(i,c)});let gy=()=>{let i=o.resume??(nu?Xo.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&P.resumeFromHandle(i)};ne?ne.then(i=>{if(i){if(i.metadata&&(se=Gm(i.metadata),Ae.syncFromMetadata()),i.messages?.length){Ys=!0;try{P.hydrateMessages(i.messages)}finally{Ys=!1}Jl()}i.artifacts?.length&&P.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),ch(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{Yp=!0,E(),gy()}):(ch(W),gy());let BA=()=>{!xe()||he||!(o.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},_A=(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),LI(b)}}:i:c,Wu=()=>{let c=ce.getInlineMessageFields?.();return c&&c.contentSegments.some(f=>f.kind==="mention")?c.contentSegments:void 0},nr=!1,ws=null,Ec=()=>{ce.value="",ce.style.height="auto",wo(),La()},Ou="data-persona-composer-notice",pi=null;function DA(i){El(i),!(xe()||!ot)&&(ot.hasAttribute(Vi)||(ot.setAttribute(Ou,""),ot.setAttribute("role","status"),ot.setAttribute("aria-live","polite"),ot.textContent=i,pi&&clearTimeout(pi),pi=setTimeout(()=>{if(pi=null,!!ot?.hasAttribute(Ou)&&(ot.removeAttribute(Ou),ot.removeAttribute("role"),ot.removeAttribute("aria-live"),p)){let c=P.getStatus();sn(ot,gn(c),o.statusIndicator??{},c)}},4e3)))}function NA(){let i=Se.getState().pendingSubmission;i&&(Us(void 0),ce&&(ce.value=i.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),wo()),i.options.selectedModelId&&(Se.setSelectedModelId(i.options.selectedModelId),fr?.repaint()),i.options.activeModeIds?.length&&Ll(i.options.activeModeIds),i.options.quote&&xo(i.options.quote),ce?.focus())}let FA=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},my=(i={})=>{let c=(i.overrideText??ce?.value??"").trim();return i.resolveInlineCommand&&c?(Bt?.takeInlineCommand(c)??Promise.resolve(null)).then(g=>fy(i,c,g)):fy(i,c,null)},fy=(i,c,g)=>{if(g?.kind==="action"){Ec(),Bt?.clear(),Yr();return}let f=g?.kind==="server"?g.mentions:null,b=g?.kind==="prompt"?g.sendText:c,w=i.pending?.contentParts,O=(Je?.hasAttachments()??!1)||(w?.length??0)>0;if(!uC({text:b,hasAttachments:O,attachmentsReady:Je?.isReady()??!0,hasMentions:Bt?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:Ar(),sendDisabled:us()}))return;let z=P.isStreaming()?Ap():"block";if(z==="defer-one"&&!i.pending){if(Se.getState().pendingSubmission){DA("One message is already queued. Edit or remove it first.");return}$A({intent:i,sendText:b,serverMentions:f});return}let q={text:b,mentionRefs:[...Bt?.getMentionRefs()??[],...f?.refs??[]],contentSegments:g?.kind==="prompt"?void 0:Wu(),options:{...Se.getState().selectedModelId&&{selectedModelId:Se.getState().selectedModelId},...Se.getState().activeModeIds.length>0&&{activeModeIds:[...Se.getState().activeModeIds]},...Se.getState().quote&&{quote:{...Se.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 ut=[...Je.getContentParts()];return q.text&&ut.push(fo(q.text)),ut};q.contentParts=V();let X=()=>{ss(),BA();let ut=Bt?.collectForSubmit()??null,Xt=_A(ut,f),Ft=V();i.consumeDraft!==!1&&Ec();let It={selectedModelId:q.options.selectedModelId,activeModeIds:q.options.activeModeIds},an=z==="interrupt";an&&P.cancel(),P.sendMessage(q.text,{contentParts:Ft,mentions:Xt??void 0,contentSegments:q.contentSegments,viaVoice:q.viaVoice,composerOptions:It,...q.options.quote&&{quote:q.options.quote},...an&&{interrupt:!0}}),Je?.hasAttachments()&&Je.clearAttachments(),ut&&Bt?.clear(),Yr();let Ze=Se.getState().activeModeIds,ln=Jv(Ze,o.composer?.modes);ln.length!==Ze.length&&Ll(ln),Se.getState().quote&&xo(void 0),Kl(),kp.release(),io()},ie=o.composer?.onBeforeSend;if(!ie){X();return}let me=new AbortController;ws=me;let Xe=ut=>{if(ws=null,ut.status==="error"){FA(ut.error);return}ut.status==="proceed"&&X()},ct=gC(ie,q,me.signal);if(!(ct instanceof Promise)){Xe(ct);return}return Se.setPreparing(!0),ct.then(Xe).finally(()=>Se.setPreparing(!1))};function $A(i){let c=Se.getState(),g=Je?.hasAttachments()??!1,f=g?[...Je.getContentParts()]:[];g&&i.sendText&&f.push(fo(i.sendText));let b=Vg({text:i.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Bt?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Wu(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});Us(b),i.intent.consumeDraft!==!1&&Ec(),g&&Je.clearAttachments(),Bt?.clear(),Yr(),c.quote&&xo(void 0),Kl(),kp.release(),io(),El("Message queued. It sends when the response finishes.")}function UA(){let i=Se.getState().pendingSubmission;i&&(Us(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||!wg(c)||rs!==i&&(ss(),rs=i,vr=oC({messageId:i,initialText:c.content,onSave:g=>qA(i,g),onCancel:()=>ss()}),Dt.delete(i),Qn(Le,P.getMessages(),at),vr.focus())}function qA(i,c){let g=vr;if(rs=null,vr=null,g?.destroy(),Dt.delete(i),!P.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){Qn(Le,P.getMessages(),at);return}Pn()}function zA(i){if(P.isStreaming())return;let c=Cg(P.getMessages(),i);c&&(ss(),P.resubmitFrom(c,{reason:"retry"})&&Pn())}Il={regenerate:zA,edit:jA,quote:i=>{let g=P.getMessages().find(f=>f.id===i)?.content?.trim();g&&(xo({text:g,messageId:i}),ce?.focus())}};let ka=async i=>{if(!nr){nr=!0;try{await my({resolveInlineCommand:!0,...i})}finally{nr=!1}}};function Tc(i){us()||(Ec(),Pc(i,{consumeDraft:!1}))}let Pc=(i,c)=>{if(nr)return;nr=!0;let g=()=>{nr=!1};try{let f=my({...c,overrideText:i});f instanceof Promise?f.finally(g):g()}catch(f){throw g(),f}},VA=i=>{if(i.preventDefault(),P.isStreaming()){P.cancel(),gt?.reset(),R?.update();return}nr||ka()},KA=()=>o.features?.composerHistory!==!1,Bu={...em},_u=!1,La=()=>{Bu={...em}},GA=()=>P.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),QA=i=>{if(!ce)return;_u=!0,ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),_u=!1;let c=ce.value.length;ce.setSelectionRange(c,c)},YA=i=>{_u||(i.isComposing||Bt?.handleInput(i.inputType??void 0),La())},XA=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:tl(ce)}),JA=i=>{if(ce&&!Ar()&&!(!i.isComposing&&Bt?.handleKeydown(i))){if(KA()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let c=ce.selectionStart===0&&ce.selectionEnd===0,g=HC({direction:i.key==="ArrowUp"?"up":"down",history:GA(),currentValue:ce.value,atStart:c,state:Bu});if(Bu=g.state,g.handled){i.preventDefault(),g.value!==void 0&&QA(g.value);return}}if(Bv(i,XA())){if(P.isStreaming()){if(i.preventDefault(),Ap()==="block"||nr||us())return;La(),ka();return}if(nr){i.preventDefault();return}if(us()){i.preventDefault();return}La(),i.preventDefault(),Ee.click()}}},hy=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(ue)){if(ws){ws.abort(),ws=null,i.preventDefault(),i.stopImmediatePropagation();return}P.isStreaming()&&(P.cancel(),gt?.reset(),R?.update(),La(),i.preventDefault(),i.stopImmediatePropagation())}},ZA=async i=>{if(o.attachments?.enabled!==!0||!Je||Ar())return;let c=EI(i.clipboardData);c.length!==0&&(i.preventDefault(),await Je.handleFiles(c))},Zn=null,ko=!1,ui=null,Ct=null,Du=()=>o.voiceRecognition?.completionBehavior==="review";function xs(i){re?.setAttribute("data-state",i),i==="recording"?tM():Uu()}let yy="--persona-voice-level",Nu=.5,gi=null,Fu=-1,kc=0,by=()=>{let i=[],c=Wn??re?.parentElement??null;return c&&i.push(c),Re&&i.push(Re),i},$u=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==Fu){Fu=c;for(let g of by())g.style.setProperty(yy,String(c))}},eM=()=>{Fu=-1,kc=0;for(let i of by())i.style.removeProperty(yy)};function tM(){if(gi!==null)return;if(typeof requestAnimationFrame!="function"){$u(p?P.getVoiceLevel()??Nu:Nu);return}let i=()=>{gi=requestAnimationFrame(i);let c=p?P.getVoiceLevel():null;if(c===null){$u(Nu);return}kc+=(c-kc)*.3,$u(kc)};gi=requestAnimationFrame(i)}function Uu(){gi!==null&&(cancelAnimationFrame(gi),gi=null),eM()}let vy=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Lc=(i="user")=>{if(ko||P.isStreaming())return;let c=vy();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=ce.value;Zn.onresult=w=>{let O="",z="";for(let V=0;V<w.results.length;V++){let X=w.results[V],ie=X[0].transcript;X.isFinal?O+=ie+" ":z=ie}let q=b+O+z;ce.value=q,wo(),ui&&clearTimeout(ui),(O||z)&&(ui=window.setTimeout(()=>{if(ce.value.trim()&&Zn&&ko){if(Pr(),Du())return;ka({viaVoice:!0})}},f))},Zn.onerror=w=>{w.error!=="no-speech"&&Pr()},Zn.onend=()=>{if(ko){let w=ce.value.trim();!Du()&&w&&w!==b.trim()&&ka({viaVoice:!0}),Pr()}};try{if(Zn.start(),ko=!0,Ve.active=!0,i!=="system"&&(Ve.manuallyDeactivated=!1),Go(i),co(),io(),re){let w=o.voiceRecognition??{};Ct={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:w.iconName??"mic",iconSize:parseFloat(w.iconSize??"")||yn};let O=w.recordingBackgroundColor,z=w.recordingIconColor,q=w.recordingBorderColor;if(re.classList.add("persona-voice-recording"),xs("recording"),re.style.backgroundColor=O??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=z??"var(--persona-voice-recording-indicator, #ffffff)",z){let V=re.querySelector("svg");V&&V.setAttribute("stroke",z)}q&&(re.style.borderColor=q),re.setAttribute("aria-label","Stop voice recognition")}}catch{Pr("system")}},Pr=(i="user")=>{if(ko){if(ko=!1,ui&&(clearTimeout(ui),ui=null),Zn){try{Zn.stop()}catch{}Zn=null}if(Ve.active=!1,Go(i),co(),io(),re){if(re.classList.remove("persona-voice-recording"),xs("idle"),Ct){re.style.backgroundColor=Ct.backgroundColor,re.style.color=Ct.color,re.style.borderColor=Ct.borderColor;let c=re.querySelector("svg");c&&c.setAttribute("stroke",Ct.color||"currentColor"),Ct=null}re.setAttribute("aria-label","Start voice recognition")}}},ju=()=>{if(!re||Ct)return;let i=o.voiceRecognition??{};Ct={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||yn}},qu=(i,c)=>{if(!re)return;let g=re.querySelector("svg");g&&g.remove();let f=Ct?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||yn),b=pe(i,f,c,1.5);b&&re.appendChild(b)},Ic=()=>{re&&re.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},mi=()=>{if(!re)return;ju();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,g=i.recordingIconColor,f=i.recordingBorderColor;if(Ic(),re.classList.add("persona-voice-recording"),xs("recording"),re.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=g??"var(--persona-voice-recording-indicator, #ffffff)",g){let b=re.querySelector("svg");b&&b.setAttribute("stroke",g)}f&&(re.style.borderColor=f),re.setAttribute("aria-label","Stop voice recognition")},nM=()=>{if(!re)return;ju();let i=o.voiceRecognition??{},c=P.getVoiceInterruptionMode(),g=i.processingIconName??"loader",f=i.processingIconColor??Ct?.color??"",b=i.processingBackgroundColor??Ct?.backgroundColor??"",w=i.processingBorderColor??Ct?.borderColor??"";Ic(),re.classList.add("persona-voice-processing"),xs("processing"),re.style.backgroundColor=b,re.style.borderColor=w;let O=f||"currentColor";re.style.color=O,qu(g,O),re.setAttribute("aria-label","Processing voice input"),c==="none"&&(re.style.cursor="default")},oM=()=>{if(!re)return;ju();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??""),w=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Ct?.backgroundColor??""),O=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":Ct?.borderColor??"");Ic(),re.classList.add("persona-voice-speaking"),xs("speaking"),re.style.backgroundColor=w,re.style.borderColor=O;let z=b||"currentColor";re.style.color=z,qu(f,z);let q=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";re.setAttribute("aria-label",q),c==="none"&&(re.style.cursor="default"),c==="barge-in"&&re.classList.add("persona-voice-recording")},or=()=>{re&&(Ic(),xs("idle"),Ct&&(re.style.backgroundColor=Ct.backgroundColor??"",re.style.color=Ct.color??"",re.style.borderColor=Ct.borderColor??"",qu(Ct.iconName,Ct.color||"currentColor"),Ct=null),re.style.cursor="",re.setAttribute("aria-label","Start voice recognition"))},zu=()=>{if(!Ar()){if(o.voiceRecognition?.provider?.type==="runtype"){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(()=>{Ve.active=!1,Ve.manuallyDeactivated=!0,co(),Go("user"),or()});return}P.toggleVoice().then(()=>{Ve.active=P.isVoiceActive(),Ve.manuallyDeactivated=!P.isVoiceActive(),co(),Go("user"),P.isVoiceActive()?mi():or()});return}if(ko){let i=ce.value.trim();Ve.manuallyDeactivated=!0,co(),Pr("user"),i&&!Du()&&ka()}else Ve.manuallyDeactivated=!1,co(),Lc("user")}};Mp=zu,re&&ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(P.isVoiceActive()&&P.toggleVoice(),or()):Pr("system")});let rM=A.on("assistant:complete",()=>{Se.getState().pendingSubmission&&setTimeout(()=>{P.isStreaming()||UA()},0)});ve.push(rM);let sM=A.on("assistant:complete",()=>{ih&&(Ve.active||Ve.manuallyDeactivated||ih==="assistant"&&!Ve.lastUserMessageWasVoice||setTimeout(()=>{!Ve.active&&!Ve.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?P.toggleVoice().then(()=>{Ve.active=P.isVoiceActive(),Go("auto"),P.isVoiceActive()&&mi()}):Lc("auto"))},600))});ve.push(sM);let iM=A.on("action:resubmit",()=>{setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)});ve.push(iM);let Cy=()=>{pt(!he,"user")},kt=null,fn=null;if(fe&&!xe()){let{instance:i,element:c}=Sm({config:o,plugins:a,onToggle:Cy});kt=i,i||(fn=c)}kt?e.appendChild(kt.element):fn&&e.appendChild(fn),ma(),Gs(),tc(),tu(),fa(P.isStreaming()),qp()||(On()==="follow"?xr(!0):Gl()),ES(),it&&(!fe||xe()?setTimeout(()=>gs(),0):he&&setTimeout(()=>gs(),200));let Ss=null,wy=()=>{Ss&&(Ss.disconnect(),Ss.observe(Re),Ss.observe(ue))},Ia=()=>{if(xe()){Qr(),ma();return}let i=Et(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,O=f&&w&&fe;try{if(O){Xr(),oa=Nl();return}let z=!1;Ne&&(Ne=!1,Xr(),z=!0);let q=Nl();if(!z&&q!==oa&&(Xr(),z=!0),oa=q,z&&Ol(),!fe&&!i){Me.style.height="",Me.style.width="";return}if(!c&&!i){let X=o?.launcher?.width??o?.launcherWidth??oo;Me.style.width=X,Me.style.maxWidth=X}Dl(),qf()}finally{if(Qr(),kl(),ma(),he&&fe){let q=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),V=o.launcher?.sidebarMode??!1,X=o.launcher?.mobileFullscreen??!0,ie=Et(o)&&X&&q,me=V||X&&q&&fe||ie;if(me&&!Eo){let Xe=e.getRootNode(),ct=Xe instanceof ShadowRoot?Xe.host:e.closest(".persona-host");ct&&!Mo&&(Mo=rm(ct,o.launcher?.zIndex??rn)),Eo=sm(e.ownerDocument)}else me||(Mo?.(),Mo=null,Eo?.(),Eo=null)}}};Ia();let Rc=e.ownerDocument.defaultView??window;if(Rc.addEventListener("resize",Ia),ve.push(()=>Rc.removeEventListener("resize",Ia)),typeof ResizeObserver<"u"){Ss=new ResizeObserver(()=>{kl()}),wy(),ve.push(()=>{Ss?.disconnect(),Ss=null});let i=new ResizeObserver(()=>{yc()});i.observe(ue),ve.push(()=>i.disconnect())}Rc.addEventListener("resize",yc),ve.push(()=>Rc.removeEventListener("resize",yc)),Dn=oe.scrollTop;let xy=_o(oe),Sy=()=>{let i=oe.scrollTop,c=_o(oe),g=c<xy;if(xy=c,!mr()){Dn=i,zt();return}let{action:f,nextLastScrollTop:b}=$C({following:_n.isFollowing(),currentScrollTop:i,lastScrollTop:Dn,nearBottom:Ws(oe,Vo),userScrollThreshold:xS,isAutoScrolling:En||$l||g,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Dn=b,f==="resume"){Ql()||Tn();return}f==="pause"&&ca()};if(oe.addEventListener("scroll",Sy,{passive:!0}),ve.push(()=>oe.removeEventListener("scroll",Sy)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{HS(),tg(Le)});i.observe(Le),i.observe(oe),ve.push(()=>i.disconnect())}let Ay=()=>{mr()&&_n.isFollowing()&&Ql()&&ca()},My=oe.ownerDocument;My.addEventListener("selectionchange",Ay),ve.push(()=>{My.removeEventListener("selectionchange",Ay)});let aM=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Ey=i=>{aM.has(i.key)&&(cs(),pf()&&mr()&&_n.isFollowing()&&ca())},Ty=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(cs(),pf()&&mr()&&_n.isFollowing()&&ca())};oe.addEventListener("keydown",Ey),oe.addEventListener("focusin",Ty),ve.push(()=>{oe.removeEventListener("keydown",Ey),oe.removeEventListener("focusin",Ty)});let Py=i=>{if(i.deltaY!==0&&cs(),!mr())return;let c=UC({following:_n.isFollowing(),deltaY:i.deltaY,nearBottom:Ws(oe,Vo),resumeWhenNearBottom:!0});c==="pause"?ca():c==="resume"&&!Ql()&&Tn()};oe.addEventListener("wheel",Py,{passive:!0}),oe.addEventListener("touchmove",cs,{passive:!0}),oe.addEventListener("pointerdown",cs,{passive:!0}),ve.push(()=>{oe.removeEventListener("touchmove",cs),oe.removeEventListener("pointerdown",cs)}),ve.push(()=>oe.removeEventListener("wheel",Py)),_t.addEventListener("click",()=>{po(),oe.scrollTop=oe.scrollHeight,Dn=oe.scrollTop,Tn(),xr(!0),zt()}),ve.push(()=>_t.remove()),ve.push(()=>{ph(),po()});let ky=()=>{je&&(ts&&(je.removeEventListener("click",ts),ts=null),ke()?(je.style.display="",ts=()=>{pt(!1,"user")},je.addEventListener("click",ts)):je.style.display="none")};ky(),(()=>{let{clearChatButton:i}=Fe;i&&i.addEventListener("click",()=>{if(Po()){Iu({focusComposer:!0}).catch(g=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",g)});return}P.clearMessages(),Dt.clear(),Tn(),Is(Fe.composerOverlay);try{localStorage.removeItem(zi),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zi}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==zi)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&&zl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),se={},Ae.syncFromMetadata(),Je?.clearAttachments(),Kl(),Us(void 0),xo(void 0),ss(),Tt?.clear(),gt?.reset(),R?.update()})})();let Ly=[["keydown",JA],["input",YA],["input",wo],["input",Yr],["keyup",Yr],["paste",ZA],["focus",dS]],Iy=i=>{if(i)for(let[c,g]of Ly)tt?.addListener(i,c,g)},lM=i=>{if(i)for(let[c,g]of Ly)tt?.removeListener(i,c,g)},Ry=()=>{tt&&(tt.addListener(tt.form,"submit",VA),tt.addListener(tt.footer,"click",Yr),Iy(ce),re&&tt.addListener(re,"click",zu))};Ry();let Hy=()=>{Bt?.onComposerSwap((i,c)=>{lM(c),ce=i,tt&&(tt.input=i),Iy(i),Tp(),Gp(),wo()})};Hy();let Vu=!1;function Wy(){if(!Vu){Vu=!0;try{let i=ce?.value??"",c=Re.ownerDocument??document,g=ce?c.activeElement===ce:!1;Uu(),tt?.destroy(),tt=null,Bt?.destroy(),Bt=null;let f=null,b=()=>(f=xe()?Bd({config:o}):Oi({config:o}),f.footer),w=wf(b)??b();Rn.replaceComposer(w),Re=Rn.composer.footer;let O=f!==null&&w===f.footer;qs=!O,df=O?f.setSendButtonMode:()=>{},Cf(Re),Sf(Re),Af(),Mf(),Ef(),Hy(),Tf(),Pp(),Pf(),Ry();let z=es.indexOf(zo);zo.destroy(),zo=ml(ur),z>=0&&(es[z]=zo),ce&&(ce.value=i),wo(),Yr(),tc(),Gs(),fa(P.isStreaming()),Ve.active&&xs("recording"),Xr(),wy(),Qr(),io(),Zl(),g&&ce?.focus()}finally{Vu=!1}}}let Ra=e.ownerDocument??document;Ra.addEventListener("keydown",hy,!0);let Oy=()=>{Fp()},By=()=>{Ra.visibilityState==="hidden"&&Fp()};typeof window<"u"&&(window.addEventListener("pagehide",Oy),Ra.addEventListener("visibilitychange",By),ve.push(()=>{window.removeEventListener("pagehide",Oy),Ra.removeEventListener("visibilitychange",By)}));let _y="persona-attachment-drop-active",Ha=0,Ku=()=>{Ha=0,ue.classList.remove(_y)},fi=()=>o.attachments?.enabled===!0&&Je!==null&&!Ar(),Dy=i=>{!rp(i.dataTransfer)||!fi()||(Ha++,Ha===1&&ue.classList.add(_y))},Ny=i=>{!rp(i.dataTransfer)||!fi()||(Ha--,Ha<=0&&Ku())},Fy=i=>{!rp(i.dataTransfer)||!fi()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},$y=i=>{if(!rp(i.dataTransfer)||!fi())return;i.preventDefault(),i.stopPropagation(),Ku();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&Je.handleFiles(c)},kr=!0;ue.addEventListener("dragenter",Dy,kr),ue.addEventListener("dragleave",Ny,kr),e.addEventListener("dragover",Fy,kr),e.addEventListener("drop",$y,kr);let Hc=e.ownerDocument,Uy=i=>{fi()&&i.preventDefault()},jy=i=>{fi()&&i.preventDefault()};Hc.addEventListener("dragover",Uy),Hc.addEventListener("drop",jy),ve.push(()=>{tt?.destroy(),tt=null,Uu(),So?.destroy(),So=null,jo?.destroy(),jo=null,hr?.destroy(),hr=null,yr?.destroy(),yr=null,fr=null,Sp=null,Fp(),la.destroy(),pi&&clearTimeout(pi),ss(),ws?.abort(),ws=null,Je?.destroy(),Je=null,Se.destroy(),Ra.removeEventListener("keydown",hy,!0),Bt?.destroy()}),ve.push(()=>{ue.removeEventListener("dragenter",Dy,kr),ue.removeEventListener("dragleave",Ny,kr),e.removeEventListener("dragover",Fy,kr),e.removeEventListener("drop",$y,kr),Hc.removeEventListener("dragover",Uy),Hc.removeEventListener("drop",jy),Ku()}),ve.push(()=>{P.cancel()}),kt?ve.push(()=>{kt?.destroy()}):fn&&ve.push(()=>{fn?.remove()});let Lt={update(i){let c=o.toolCall,g=o.messageActions,f=o.layout?.messages,b=o.colorScheme,w=o.loadingIndicator,O=o.iterationDisplay,z=o.features?.showReasoning,q=o.features?.showToolCalls,V=o.features?.toolCallDisplay,X=o.features?.reasoningDisplay,ie=o.features?.streamAnimation?.type,me=o.features?.history?.enabled===!0,Xe=o.features?.history?.provider,ct=o.getIdentityProof,ut=o.clientToken,Xt=o.contextMentions;o=Zd({...o,features:s},i),s=o.features,o=Xd(o),r(),Wp(),Li(e,o),bl(e,o),vl(e,o),yt(),lo(),o.colorScheme!==b&&zf();let Ft=Jd.getForInstance(o.plugins);a.length=0,a.push(...Ft),qh(),fe=o.launcher?.enabled??!0,_e=o.launcher?.autoExpand??!1,nn=o.features?.showReasoning??!0,pn=o.features?.showToolCalls??!0,qr=o.features?.scrollToBottom??{};let It=On();xn=o.features?.scrollBehavior??{},It!==On()&&(po(),Tn()),sh(),mf(),zt();let an=Wt;if(Wt=o.features?.showEventStreamToggle??!1,Wt&&!an){if(Tt||(ee(),P.setSSEEventCallback((J,Ke)=>{o.onSSEEvent?.(J,Ke),U(J,Ke)})),!et&&Te){let J=o.features?.eventStream?.classNames,Ke="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"+(J?.toggleButton?" "+J.toggleButton:"");et=M("button",Ke),et.style.width="28px",et.style.height="28px",et.style.color=vn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let Qe=Ht(ix,"18px","currentColor",1.5);Qe&&et.appendChild(Qe);let nt=Fe.clearChatButtonWrapper,xt=Fe.closeButtonWrapper,on=nt||xt;on&&on.parentNode===Te?Te.insertBefore(et,on):Te.appendChild(et),et.addEventListener("click",()=>{Z?js():Ep()})}}else!Wt&&an&&(js(),et&&(et.remove(),et=null),Tt?.clear(),un?.destroy(),Tt=null,un=null,gt?.reset(),gt=null,ro=null);if(o.launcher?.enabled===!1&&kt&&(kt.destroy(),kt=null),o.launcher?.enabled===!1&&fn&&(fn.remove(),fn=null),o.launcher?.enabled!==!1&&!kt&&!fn){let{instance:J,element:Ke}=Sm({config:o,plugins:a,onToggle:Cy});kt=J,J||(fn=Ke),e.appendChild(Ke)}kt&&kt.update(o),Pa(),Kr&&o.launcher?.subtitle!==void 0&&(Kr.textContent=o.launcher.subtitle);let Ze=o.layout?.header;if(Ze?.layout!==De&&Te){let J=Ze?fl(o,Ze,{showClose:ke(),onClose:()=>pt(!1,"user")}):Ur({config:o,showClose:ke(),onClose:()=>pt(!1,"user")});Rn.replaceHeader(J),Te=Rn.header.element,Pt=Rn.header.iconHolder,gr=Rn.header.headerTitle,Kr=Rn.header.headerSubtitle,je=Rn.header.closeButton,De=Ze?.layout,Pa()}else if(Ze){if(Pt&&(Pt.style.display=Ze.showIcon===!1?"none":""),gr&&(gr.style.display=Ze.showTitle===!1?"none":""),Kr&&(Kr.style.display=Ze.showSubtitle===!1?"none":""),je){let J=ke()&&Ze.showCloseButton!==!1;je.style.display=J?"":"none"}if(Fe.clearChatButtonWrapper){let J=Ze.showClearChat;if(J!==void 0){Fe.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:Ke}=Fe;Ke&&!Ke.classList.contains("persona-absolute")&&(J?Ke.classList.remove("persona-ml-auto"):Ke.classList.add("persona-ml-auto"))}}}let rr=o.layout?.showHeader!==!1;Te&&(Te.style.display=rr?"":"none");let Lo=o.layout?.showFooter!==!1;Re&&(Re.style.display=Lo?"":"none"),Qr(),zt(),fe!==j?fe?pt(_e,"auto"):(he=!0,ma()):_e!==be&&pt(_e,"auto"),be=_e,j=fe,Ia(),ky();let We=JSON.stringify(o.toolCall)!==JSON.stringify(c),Be=JSON.stringify(o.messageActions)!==JSON.stringify(g),ye=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),mt=o.loadingIndicator?.render!==w?.render||o.loadingIndicator?.renderIdle!==w?.renderIdle||o.loadingIndicator?.showBubble!==w?.showBubble,Vt=o.iterationDisplay!==O,cn=(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(X);(We||Be||ye||mt||Vt||cn)&&P&&(is++,Qn(Le,P.getMessages(),at));let Rt=o.features?.streamAnimation?.type;if(Rt!==ie&&Rt&&Rt!=="none"){let J=Bp(Rt,o.features?.streamAnimation?.plugins);J&&pl(J,e)}let Pe=o.launcher??{},Kt=Pe.headerIconHidden??!1,Gt=o.layout?.header?.showIcon,to=Kt||Gt===!1,He=Pe.headerIconName,wt=Pe.headerIconSize??"48px";if(Pt){let J=Te,Ke=J?.querySelector(".persona-flex-col");if(to)Pt.style.display="none",J&&Ke&&!J.contains(Ke)&&J.insertBefore(Ke,J.firstChild);else{if(Pt.style.display="",Pt.style.height=wt,Pt.style.width=wt,J&&Ke&&(J.contains(Pt)?Pt.nextSibling!==Ke&&(Pt.remove(),J.insertBefore(Pt,Ke)):J.insertBefore(Pt,Ke)),He){let nt=parseFloat(wt)||24,xt=pe(He,nt*.6,"currentColor",1);xt?Pt.replaceChildren(xt):Pt.textContent=Pe.agentIconText??"\u{1F4AC}"}else if(Pe.iconUrl){let nt=Pt.querySelector("img");if(nt)nt.src=Pe.iconUrl,nt.style.height=wt,nt.style.width=wt;else{let xt=document.createElement("img");xt.src=Pe.iconUrl,xt.alt="",xt.className="persona-rounded-xl persona-object-cover",xt.style.height=wt,xt.style.width=wt,Pt.replaceChildren(xt)}}else{let nt=Pt.querySelector("svg"),xt=Pt.querySelector("img");(nt||xt)&&Pt.replaceChildren(),Pt.textContent=Pe.agentIconText??"\u{1F4AC}"}let Qe=Pt.querySelector("img");Qe&&(Qe.style.height=wt,Qe.style.width=wt)}}let Ro=o.layout?.header?.showTitle,uo=o.layout?.header?.showSubtitle;if(gr&&(gr.style.display=Ro===!1?"none":""),Kr&&(Kr.style.display=uo===!1?"none":""),je){let J=ke()&&o.layout?.header?.showCloseButton!==!1;if(je.style.display=J?"":"none",!xe()){let Jt=Pe.closeButtonSize??"";je.style.height=Jt,je.style.width=Jt,je.style.minWidth=Jt,je.style.minHeight=Jt}let Ke=Pe.closeButtonPlacement??"inline",{closeButtonWrapper:Qe}=Fe,nt=Ke==="top-right",xt=Qe?.classList.contains("persona-absolute");if(Qe&&nt!==xt)if(Qe.remove(),nt){Qe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Jt=Ca??ue;Jt.style.position="relative",Jt.appendChild(Qe)}else{let Jt=Pe.clearChat?.placement??"inline",Zt=Pe.clearChat?.enabled??!0;Qe.className=Zt&&Jt==="inline"?"":"persona-ml-auto",Te&&Te.appendChild(Qe)}if(je.style.color=Pe.closeButtonColor||vn.actionIconColor,Pe.closeButtonBackgroundColor?(je.style.backgroundColor=Pe.closeButtonBackgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),Pe.closeButtonBorderWidth||Pe.closeButtonBorderColor){let Jt=Pe.closeButtonBorderWidth||"0px",Zt=Pe.closeButtonBorderColor||"transparent";je.style.border=`${Jt} solid ${Zt}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");Pe.closeButtonBorderRadius?(je.style.borderRadius=Pe.closeButtonBorderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),Pe.closeButtonPaddingX?(je.style.paddingLeft=Pe.closeButtonPaddingX,je.style.paddingRight=Pe.closeButtonPaddingX):(je.style.paddingLeft="",je.style.paddingRight=""),Pe.closeButtonPaddingY?(je.style.paddingTop=Pe.closeButtonPaddingY,je.style.paddingBottom=Pe.closeButtonPaddingY):(je.style.paddingTop="",je.style.paddingBottom=""),Wd(je,Pe.closeButtonIconName??"x",{iconSize:xe()?vm:void 0,iconText:Pe.closeButtonIconText??"\xD7"});let on=Pe.closeButtonTooltipText??"Close chat",go=Pe.closeButtonShowTooltip??!0;je.setAttribute("aria-label",on),Qe&&en({anchor:je,trigger:Qe,text:()=>je?.getAttribute("aria-label")??on,enabled:go})}let{clearChatButton:Oe,clearChatButtonWrapper:Ce}=Fe;if(Oe){let J=Pe.clearChat??{},Ke=J.enabled??!0,Qe=o.layout?.header?.showClearChat,nt=Qe!==void 0?Qe:Ke,xt=J.placement??"inline";if(Ce){Ce.style.display=nt?"":"none";let{closeButtonWrapper:on}=Fe;!xe()&&on&&!on.classList.contains("persona-absolute")&&(nt?on.classList.remove("persona-ml-auto"):on.classList.add("persona-ml-auto"));let go=xt==="top-right",Jt=Ce.classList.contains("persona-absolute");if(!xe()&&go!==Jt&&nt){if(Ce.remove(),go){Ce.className="persona-absolute persona-top-4 persona-z-50",Ce.style.right="48px";let Ho=Ca??ue;Ho.style.position="relative",Ho.appendChild(Ce)}else{Ce.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ce.style.right="";let Ho=Fe.closeButtonWrapper;Te&&Ho&&Ho.parentElement===Te?Te.insertBefore(Ce,Ho):Te&&Te.appendChild(Ce)}let Zt=Fe.closeButtonWrapper;Zt&&!Zt.classList.contains("persona-absolute")&&(go?Zt.classList.add("persona-ml-auto"):Zt.classList.remove("persona-ml-auto"))}}if(nt){if(!xe()){let Zt=J.size??"";Oe.style.height=Zt,Oe.style.width=Zt,Oe.style.minWidth=Zt,Oe.style.minHeight=Zt}let on=J.iconColor??"";if(Oe.style.color=on||vn.actionIconColor,Wd(Oe,J.iconName??"refresh-cw",{iconSize:xe()?Cm:void 0}),J.backgroundColor?(Oe.style.backgroundColor=J.backgroundColor,Oe.classList.remove("hover:persona-bg-gray-100")):(Oe.style.backgroundColor="",Oe.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let Zt=J.borderWidth||"0px",Ho=J.borderColor||"transparent";Oe.style.border=`${Zt} solid ${Ho}`,Oe.classList.remove("persona-border-none")}else Oe.style.border="",Oe.classList.add("persona-border-none");J.borderRadius?(Oe.style.borderRadius=J.borderRadius,Oe.classList.remove("persona-rounded-full")):(Oe.style.borderRadius="",Oe.classList.add("persona-rounded-full")),J.paddingX?(Oe.style.paddingLeft=J.paddingX,Oe.style.paddingRight=J.paddingX):(Oe.style.paddingLeft="",Oe.style.paddingRight=""),J.paddingY?(Oe.style.paddingTop=J.paddingY,Oe.style.paddingBottom=J.paddingY):(Oe.style.paddingTop="",Oe.style.paddingBottom="");let go=J.tooltipText??"Clear chat",Jt=J.showTooltip??!0;Oe.setAttribute("aria-label",go),Ce&&en({anchor:Oe,trigger:Ce,text:()=>Oe?.getAttribute("aria-label")??go,enabled:Jt})}}let $e=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ep],ft=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[qi.message,qi.messageAndClick];Ae=tp({parsers:$e,handlers:ft,getSessionMetadata:K,updateSessionMetadata:le,emit:A.emit,documentRef:typeof document<"u"?document:null}),at=dx(o,Ae,Ut),XS(),P.updateConfig(o),(o.features?.history?.enabled===!0!==me||o.features?.history?.provider!==Xe||o.getIdentityProof!==ct||o.clientToken!==ut)&&(kn({restoreFocus:!1}),Bh()),Tr(),yc(),Qn(Le,P.getMessages(),at),Gs(),tc(),QS(),fa(P.isStreaming()),Xt!==o.contextMentions&&Wy();let Lr=o.voiceRecognition?.enabled===!0,Qt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),$n=o.voiceRecognition?.provider?.type==="runtype";if(Lr&&(Qt||$n))if(!re||!Wn){let J=ki(o);if(J){re=J.button,Wn=J.wrapper;let Ke=Co&&Co.parentElement===Al?Co:null;Al?Al.insertBefore(Wn,Ke):so?.appendChild(Wn),tt&&(tt.micButton=re),tt?.addListener(re,"click",zu),re.disabled=P.isStreaming()}}else{let J=o.voiceRecognition??{},Ke=o.sendButton??{},Qe=J.iconName??"mic",nt=J.iconSize,xt=parseFloat(nt??"")||yn;re.classList.add(jn),re.classList.toggle(yo,!nt),re.style.width=nt??"",re.style.height=nt??"",re.style.minWidth=nt??"",re.style.minHeight=nt??"";let on=J.iconColor??Ke.textColor;re.innerHTML="";let go=pe(Qe,xt,on||"currentColor",1.5);go?re.appendChild(go):re.textContent="\u{1F3A4}";let Jt=J.backgroundColor??Ke.backgroundColor;Jt?re.style.backgroundColor=Jt:re.style.backgroundColor="",on?re.style.color=on:re.style.color="var(--persona-text, #111827)",J.borderWidth?(re.style.borderWidth=J.borderWidth,re.style.borderStyle="solid"):(re.style.borderWidth="",re.style.borderStyle=""),J.borderColor?re.style.borderColor=J.borderColor:re.style.borderColor="",J.paddingX?(re.style.paddingLeft=J.paddingX,re.style.paddingRight=J.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),J.paddingY?(re.style.paddingTop=J.paddingY,re.style.paddingBottom=J.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let Zt=J.tooltipText??"Start voice recognition",Ho=J.showTooltip??!1;re.setAttribute("aria-label",Zt),Wn&&en({anchor:re,trigger:Wn,text:()=>re?.getAttribute("aria-label")??Zt,enabled:Ho}),Wn.style.display="",re.disabled=P.isStreaming()}else re&&Wn&&(Wn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?P.isVoiceActive()&&P.toggleVoice():ko&&Pr());if(o.attachments?.enabled===!0){if(!An||!At){let J=o.attachments??{};Mn||(Mn=M("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Mn.style.display="none",(ce.parentElement??so).insertBefore(Mn,ce)),bt||(bt=document.createElement("input"),bt.type="file",bt.accept=(J.allowedTypes??ar).join(","),bt.multiple=(J.maxFiles??4)>1,bt.style.display="none",bt.setAttribute("aria-label","Attach files"),(ce.parentElement??so).insertBefore(bt,ce)),An=M("div","persona-send-button-wrapper"),At=M("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${jn} ${yo}`),At.type="button",At.setAttribute("aria-label",J.buttonTooltipText??"Attach file");let Ke=J.buttonIconName??"paperclip";At.style.fontSize="18px",At.style.lineHeight="1";let Qe=pe(Ke,yn,"currentColor",1.5);Qe?At.appendChild(Qe):At.textContent="\u{1F4CE}",At.addEventListener("click",xt=>{xt.preventDefault(),bt?.click()}),An.appendChild(At);let nt=J.buttonTooltipText??"Attach file";en({anchor:At,trigger:An,text:()=>At?.getAttribute("aria-label")??nt}),yp?yp.append(An):so.appendChild(An),tt&&(tt.attachmentButton=At,tt.attachmentInput=bt??void 0,tt.attachmentPreviews=Mn??void 0),!Je&&bt&&Mn&&(Je=Ei.fromConfig(J,ff),Je.setPreviewsContainer(Mn),tt?.addListener(bt,"change",async()=>{Je&&bt?.files&&(await Je.handleFileSelect(bt.files),bt.value="")}))}else{An.style.display="";let J=o.attachments??{};bt&&(bt.accept=(J.allowedTypes??ar).join(","),bt.multiple=(J.maxFiles??4)>1),Je&&Je.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles,adapter:J.adapter})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(px(o.attachments?.dropOverlay)),At){let J=o.attachments??{},Ke=J.buttonTooltipText??"Attach file";At.setAttribute("aria-label",Ke),At.textContent="";let Qe=pe(J.buttonIconName??"paperclip",yn,"currentColor",1.5);Qe?At.appendChild(Qe):At.textContent="\u{1F4CE}",An&&en({anchor:At,trigger:An,text:()=>At?.getAttribute("aria-label")??Ke})}}else An&&(An.style.display="none"),Je&&Je.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Mt=o.sendButton??{},Gu=Mt.useIcon??!1,Ms=Mt.iconText??"\u2191",Wc=Mt.iconName,zy=Mt.tooltipText??"Send message",pM=Mt.showTooltip??!1,Wa=Mt.size,uM=parseFloat(Wa??"")||_g,Oc=Mt.backgroundColor,Oa=Mt.textColor;if(Gu){if(Ee.style.width=Wa??"",Ee.style.height=Wa??"",Ee.style.minWidth=Wa??"",Ee.style.minHeight=Wa??"",Ee.style.fontSize="18px",Ee.style.lineHeight="1",Oa?Ee.style.color=Oa:Ee.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!P.isStreaming())if(Ee.innerHTML="",Wc){let J=parseFloat(Mt.iconSize??"")||Math.round(uM*.5),Ke=Oa?.trim()||"currentColor",Qe=Mt.iconStrokeWidth??2,nt=pe(Wc,J,Ke,Qe),xt=pe(Mt.stopIconName??"square",J,Ke,Qe);nt&&xt?Ee.appendChild(Dg(nt,xt)):nt?Ee.appendChild(nt):Ee.textContent=Ms}else Ee.textContent=Ms;Ee.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${jn}`,Oc?(Ee.style.backgroundColor=Oc,Ee.classList.remove("persona-bg-persona-primary")):(Ee.style.backgroundColor="",Ee.classList.add("persona-bg-persona-primary"))}else Ee.textContent=o.copy?.sendButtonLabel??"Send",Ee.style.width="",Ee.style.height="",Ee.style.minWidth="",Ee.style.minHeight="",Ee.style.fontSize="",Ee.style.lineHeight="",Ee.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",Oc?(Ee.style.backgroundColor=Oc,Ee.classList.remove("persona-bg-persona-accent")):Ee.classList.add("persona-bg-persona-accent"),Oa?Ee.style.color=Oa:Ee.classList.add("persona-text-white");Mt.borderWidth?(Ee.style.borderWidth=Mt.borderWidth,Ee.style.borderStyle="solid"):(Ee.style.borderWidth="",Ee.style.borderStyle=""),Mt.borderColor?Ee.style.borderColor=Mt.borderColor:Ee.style.borderColor="",Mt.paddingX?(Ee.style.paddingLeft=Mt.paddingX,Ee.style.paddingRight=Mt.paddingX):(Ee.style.paddingLeft="",Ee.style.paddingRight=""),Mt.paddingY?(Ee.style.paddingTop=Mt.paddingY,Ee.style.paddingBottom=Mt.paddingY):(Ee.style.paddingTop="",Ee.style.paddingBottom=""),P.isStreaming()||Ee.setAttribute("aria-label",zy),Zl(),Co&&en({anchor:Ee,trigger:Co,text:()=>Ee.getAttribute("aria-label")??zy,enabled:pM}),Lf();let Vy=Cd(Se.getState().activeModeIds,o.composer?.modes);Se.setActiveModeIds(Vy),Fs().length>0!==!!jo&&Pp(),jo?.render(Vy,Fs());for(let J of[...$s.keys()])vd(J,o.composer?.modeGroups)||$s.delete(J);$s.forEach(J=>J.repaint()),fr?.repaint(),So?.resolve();let Bc=Nr(o,xe());if(Op(),Bc){Le.style.maxWidth=Bc,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%",Hn.style.maxWidth=Bc,Hn.style.marginLeft="auto",Hn.style.marginRight="auto",Hn.style.width="100%";for(let J of[so,ur,Mn,ot])J&&(J.style.maxWidth=Bc,J.style.marginLeft="auto",J.style.marginRight="auto",J.style.width="100%")}else{Le.style.maxWidth="",Le.style.marginLeft="",Le.style.marginRight="",Le.style.width="",Hn.style.maxWidth="",Hn.style.marginLeft="",Hn.style.marginRight="",Hn.style.width="";for(let J of[so,ur,Mn,ot])J&&(J.style.maxWidth="",J.style.marginLeft="",J.style.marginRight="",J.style.width="")}let Ir=o.statusIndicator??{},gM=Ir.visible??!0;if(ot.style.display=gM?"":"none",P){let J=P.getStatus();sn(ot,(Qe=>Qe==="idle"?Ir.idleText??$t.idle:Qe==="connecting"?Ir.connectingText??$t.connecting:Qe==="connected"?Ir.connectedText??$t.connected:Qe==="error"?Ir.errorText??$t.error:$t[Qe])(J),Ir,J)}ot.classList.remove("persona-text-left","persona-text-center","persona-text-right");let mM=Ir.align==="left"?"persona-text-left":Ir.align==="center"?"persona-text-center":"persona-text-right";ot.classList.add(mM),Tp(),Gp(),io(),we()},open(){ke()&&pt(!0,"api")},close(){ke()&&pt(!1,"api")},toggle(){ke()&&pt(!he,"api")},reconnect(){P.reconnectNow()},clearChat(){qo=!1,P.clearMessages(),Dt.clear(),Tn();try{localStorage.removeItem(zi),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zi}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==zi)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&&zl(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),se={},Ae.syncFromMetadata(),Je?.clearAttachments(),Kl(),Us(void 0),xo(void 0),ss(),Tt?.clear(),gt?.reset(),R?.update()},setMessage(i){return!ce||P.isStreaming()||Ar()?!1:(!he&&ke()&&pt(!0,"system"),ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(P.isStreaming()||us())return!1;let c=i?.trim()||ce.value.trim();return c?(!he&&ke()&&pt(!0,"system"),ce.value="",ce.style.height="auto",wo(),Pc(c,{consumeDraft:!1}),!0):!1},getComposerState(){return Se.getState()},setQuote(i){let c=i?.text?.trim();c&&xo({...i,text:c})},clearQuote(){xo(void 0)},startVoiceRecognition(){return P.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(P.isVoiceActive()||(!he&&ke()&&pt(!0,"system"),Ve.manuallyDeactivated=!1,co(),P.toggleVoice().then(()=>{Ve.active=P.isVoiceActive(),Go("user"),P.isVoiceActive()&&mi()})),!0):ko?!0:vy()?(!he&&ke()&&pt(!0,"system"),Ve.manuallyDeactivated=!1,co(),Lc("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?P.isVoiceActive()?(P.toggleVoice().then(()=>{Ve.active=!1,Ve.manuallyDeactivated=!0,co(),Go("user"),or()}),!0):!1:ko?(Ve.manuallyDeactivated=!0,co(),Pr("user"),!0):!1},injectMessage(i){return!he&&ke()&&pt(!0,"system"),P.injectMessage(i)},injectAssistantMessage(i){!he&&ke()&&pt(!0,"system");let c=P.injectAssistantMessage(i);return dt&&(dt=!1,Ie&&(clearTimeout(Ie),Ie=null),setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)),c},injectUserMessage(i){return!he&&ke()&&pt(!0,"system"),P.injectUserMessage(i)},injectSystemMessage(i){return!he&&ke()&&pt(!0,"system"),P.injectSystemMessage(i)},injectMessageBatch(i){return!he&&ke()&&pt(!0,"system"),P.injectMessageBatch(i)},injectComponentDirective(i){return!he&&ke()&&pt(!0,"system"),P.injectComponentDirective(i)},injectTestMessage(i){!he&&ke()&&pt(!0,"system"),P.injectTestEvent(i)},async connectStream(i,c){return P.connectStream(i,c)},__pushEventStreamEvent(i){Wt&&(ee(),U(i.type,i.payload))},showEventStream(){Wt&&Ep()},hideEventStream(){Z&&js()},isEventStreamVisible(){return Z},listConversations(i){return P.listConversations(i)},getActiveConversationId(){return P.getActiveConversationId()},openConversation(i,c){return Lu(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return Iu({focusComposer:i?.focus===!0})},deleteConversation(i){return ly(i)},renameConversation(i,c){return Ru(i,{title:c})},setConversationStarred(i,c){return Ru(i,{starred:c})},clearConversationHistory(i){return cy(i)},resetHistoryIdentity(){return dy()},getHistoryIdentityStatus(){return Nn?Nn.getIdentityStatus():gu()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return Ta({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){kn(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return te},showArtifacts(){wn(o)&&(qo=!1,zs=!0,lo(),ze?.setMobileOpen(!0))},hideArtifacts(){wn(o)&&(qo=!0,lo())},upsertArtifact(i){return wn(o)?(sr(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(qo=!1,zs=!0),P.upsertArtifact(i)):null},selectArtifact(i){wn(o)&&P.selectArtifact(i)},clearArtifacts(){wn(o)&&P.clearArtifacts()},getArtifacts(){return P?.getArtifacts()??[]},getSelectedArtifactId(){return P?.getSelectedArtifactId()??null},focusInput(){return fe&&!he&&!xe()||!ce?!1:(ce.focus(),!0)},async resolveApproval(i,c,g){let b=P.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"){P.resolveWebMcpApproval(b.id,c);return}return P.resolveApproval(b.approval,c,g)},setFollowUpSuggestions(i){CS(i)},clearFollowUpSuggestions(){rh()},getMessages(){return P.getMessages()},getStatus(){return P.getStatus()},getPersistentMetadata(){return{...se}},updatePersistentMetadata(i){le(i)},on(i,c){return A.on(i,c)},off(i,c){A.off(i,c)},isOpen(){return ke()&&he},isVoiceActive(){return Ve.active},toggleReadAloud(i){P.toggleReadAloud(i)},stopReadAloud(){P.stopSpeaking()},getReadAloudState(i){return P.getReadAloudState(i)},onReadAloudChange(i){return P.onReadAloudChange(i)},getState(){return{open:ke()&&he,launcherEnabled:fe,voiceActive:Ve.active,streaming:P.isStreaming()}},showCSATFeedback(i){!he&&ke()&&pt(!0,"system");let c=Le.querySelector(".persona-feedback-container");c&&c.remove();let g=Vm({onSubmit:async(f,b)=>{P.isClientTokenMode()&&await P.submitCSATFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});Le.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!he&&ke()&&pt(!0,"system");let c=Le.querySelector(".persona-feedback-container");c&&c.remove();let g=Km({onSubmit:async(f,b)=>{P.isClientTokenMode()&&await P.submitNPSFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});Le.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(){iu(),fs!=null&&(clearInterval(fs),fs=null),ve.forEach(i=>i()),Ge.remove(),Yt?.remove(),kt?.destroy(),fn?.remove(),ts&&je.removeEventListener("click",ts)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:g=>g?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,ve.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 X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",c),ve.push(()=>{window.removeEventListener("persona:focusInput",c)}),Wt){let V=ie=>{let me=ie.detail;(!me?.instanceId||me.instanceId===i)&&Lt.showEventStream()},X=ie=>{let me=ie.detail;(!me?.instanceId||me.instanceId===i)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",X),ve.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",X)})}let g=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.showHistory()},f=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.hideHistory()};window.addEventListener("persona:showHistory",g),window.addEventListener("persona:hideHistory",f),ve.push(()=>{window.removeEventListener("persona:showHistory",g),window.removeEventListener("persona:hideHistory",f)});let b=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.showArtifacts()},w=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.hideArtifacts()},O=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||X?.artifact&&Lt.upsertArtifact(X.artifact)},z=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||typeof X?.id=="string"&&Lt.selectArtifact(X.id)},q=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",w),window.addEventListener("persona:upsertArtifact",O),window.addEventListener("persona:selectArtifact",z),window.addEventListener("persona:clearArtifacts",q),ve.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",w),window.removeEventListener("persona:upsertArtifact",O),window.removeEventListener("persona:selectArtifact",z),window.removeEventListener("persona:clearArtifacts",q)})}let eo=TI(o.persistState);if(eo&&ke()){let i=PI(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",O=eo.persist?.voiceState&&i.getItem(f)==="true";if(b&&(kt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Lt.open(),setTimeout(()=>{if(w||O)Lt.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),ve.push(()=>{window.removeEventListener("persona:clear-chat",q)})}}}if(L&&ke()&&(kt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Lt.open()},0)),ei(),!wS){let i=_a(()=>{P&&(is++,Dt.clear(),Qn(Le,P.getMessages(),at))});ve.push(i)}S=()=>{P&&(is++,Dt.clear(),Qn(Le,P.getMessages(),at))},P.getMessages().length>0&&Jl(),T=()=>{P&&(is++,Dt.clear(),Qn(Le,P.getMessages(),at))};let cM=Zy(()=>{P&&(is++,Dt.clear(),Qn(Le,P.getMessages(),at))});ve.push(cM);let dM=Im(()=>{P&&(is++,Dt.clear(),Qn(Le,P.getMessages(),at),lr()?.updateInlineArtifactBlocks(Le,Gn.artifacts,{suppressTransition:!0}),lo())});return ve.push(dM),Lt};var ux=(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},II=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},RI=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},HI=(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.")},gx=(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"},Zm=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=""},mx=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Zm(e)},Ym=e=>{e.style.transition=""},Xm=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=""},Jm=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},sp=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},WI=(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))},OI=(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)},BI=e=>{let t=Hs(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:bn(t,r)??r;return{inset:o(n?.inset,wd),canvasBackground:o(n?.canvasBackground,xd)}},fx=(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},_I=(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??"";WI(e,t,n,o,p),OI(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"),Xm(t),Ym(o),mx(o),Jm(n),sp(r,o),fx(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"),mx(o),II(o,d.maxHeight),fx(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",Xm(t),Ym(o),Jm(n),sp(r,o);let B=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=B,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",Ym(o),Zm(o),sp(r,o);let B=ux(d.width,e.clientWidth),$=Math.max(0,e.clientWidth),T=d.animate?"margin-left 180ms ease":"none",I=d.side==="right"?a?-B:0:a?0:-B;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=`${$+B}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=`${$}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="",Xm(t),Zm(o),Jm(n),sp(r,o);let B=d.reveal==="emerge";B?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",I=!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",RI(o,d.maxHeight),o.style.overflow=B||I?"hidden":"visible",o.style.transition=T,B){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let A=u?`calc(${ux(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"}}},DI=(e,t)=>{let n=e.ownerDocument.createElement("div");return gx(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){gx(n,o)},destroy(){n.remove()}}},NI=(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?BI(t):null};S();let x=()=>{_I(a,l,d,p,u,t,m,C)},k=null,B=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=ol(()=>{S(),x()}))},$=()=>{h(),qn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{x()}),y.observe(a)))},T=!1,I=()=>{x(),$(),m&&!T&&a.dataset.personaDockMobileFullscreen!=="true"&&(T=!0,HI(a,qn(t)))},A=a.ownerDocument.defaultView,D=()=>{I()};return A?.addEventListener("resize",D),qn(t).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),I(),B(),{mode:"docked",host:u,shell:a,syncWidgetState(G){let se=G.launcherEnabled?G.open:!0;m!==se&&(m=se,I())},updateConfig(G){t=G,(t?.launcher?.enabled??!0)===!1&&(m=!0),S(),I(),B()},destroy(){A?.removeEventListener("resize",D),k?.(),k=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},ip=(e,t)=>Et(t)?NI(e,t):DI(e,t);var FI=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},hx=(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)},yx=e=>{let t=FI(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=ip(t,r),a,l=[],d=(x,k)=>{let $=!(k?.launcher?.enabled??!0)||Et(k),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 I=x.attachShadow({mode:"open"});I.appendChild(T),hx(I,o)}else x.appendChild(T),hx(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=Qm(x,r,{debugTools:e.debugTools}),u()},y=()=>{l.forEach(x=>x()),l=[],a.destroy()};m(),e.onChatReady?.();let h=x=>{y(),s.destroy(),s=ip(t,x),r=x,m()},C={update(x){let k=Zd(r??{},x),B=Et(r),$=Et(k),T=$r(r),I=$r(k);if(B!==$||T!==I){h(k);return}r=k,s.updateConfig(r),a.update(x),p()},destroy(){y(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},S=new Proxy(C,{get(x,k,B){if(k==="host")return s.host;if(k in x)return Reflect.get(x,k,B);let $=a[k];return typeof $=="function"?$.bind(a):$}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=S),S};var xx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),$I=new Set(["button","a","input","select","textarea","details","summary"]),UI=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ef=/\b(product|card|item|listing|result)\b/i,nf=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,jI=3e3,qI=100;function Sx(e){let t=typeof e.className=="string"?e.className:"";if(ef.test(t)||e.id&&ef.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&ef.test(o.value))return!0}return!1}function Ax(e){return nf.test((e.textContent??"").trim())}function Mx(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 bx(e){let t=e.match(nf);return t?t[0]:null}function vx(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 VI(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 KI="commerce-card",GI="result-card";function Cx(e){return!Sx(e)||!Ax(e)||!Mx(e)&&!zI(e)?0:5200}function wx(e){return!Sx(e)||Ax(e)||!Mx(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Ex=[{id:KI,scoreElement(e){return Cx(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||nf.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Cx(e)===0)return null;let{title:n,href:o}=vx(e),r=bx((e.textContent??"").trim())??bx(t.text)??"",s=VI(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:GI,scoreElement(e){return wx(e)},formatSummary(e,t){if(wx(e)===0)return null;let{title:n,href:o}=vx(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
139
+ `)}}];function QI(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function YI(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??Ex;return l==="simple"&&e.rules&&e.rules.length>0?(QI(),p=[]):l==="simple"&&(p=[]),{mode:l,maxElements:n,maxCandidates:d,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:p}}function tf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var XI=["data-testid","data-product","data-action","data-id","data-name","data-type"];function JI(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"||$I.has(t)||n&&UI.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Tx(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 ZI(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 Px(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${tf(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of XI){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${tf(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=>tf(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 eR(e){return e==="static"?qI:jI}function kx(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Px(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:JI(e),attributes:ZI(e)}}function tR(e,t,n,o){let r=eR(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 nR(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 oR(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(xx.has(u)){l=a.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){l=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Tx(p)){l=a.nextNode();continue}let m=kx(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}=tR(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;nR(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 rR(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(xx.has(p)){s=r.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Tx(d)){s=r.nextNode();continue}let u=kx(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 sR(e={}){let t=YI(e),n=t.root??document.body;return n?t.mode==="simple"?rR(t,n):oR(t,n):[]}var ap=100;function iR(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,ip)}" (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,ip)}" (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,ip)}" (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,ip)}"`);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 tR={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"}}},Tx={components:{panel:{borderRadius:"0",shadow:"none"}}},Px={id:"shop",label:"Shopping Assistant",config:{theme:tR,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"]}},kx={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Tx}},Lx={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Tx}},Ix={shop:Px,minimal:kx,fullscreen:Lx};function nR(e){return Ix[e]}var oR=mx;function rR(){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 iR(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:Fo(e.colors.primary,.95),100:Fo(e.colors.primary,.9),200:Fo(e.colors.primary,.8),300:Fo(e.colors.primary,.7),400:Fo(e.colors.primary,.6),500:e.colors.primary,600:Fo(e.colors.primary,.8),700:Fo(e.colors.primary,.7),800:Fo(e.colors.primary,.6),900:Fo(e.colors.primary,.5),950:Fo(e.colors.primary,.45)}}),{...t,palette:n}}}}function aR(){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 lR(){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 Fo(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 cR(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}function ef(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@${sr}/dist`}function dr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function dR(e){if(e)return{getHeaders:dr(e.getHeaders),onFeedback:dr(e.onFeedback),onCopy:dr(e.onCopy),requestMiddleware:dr(e.requestMiddleware),actionHandlers:dr(e.actionHandlers),actionParsers:dr(e.actionParsers),postprocessMessage:dr(e.postprocessMessage),contextProviders:dr(e.contextProviders),streamParser:dr(e.streamParser)}}var Rx=`({ text, message }: any) => {
153
+ `)}var aR={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"}}},Lx={components:{panel:{borderRadius:"0",shadow:"none"}}},Ix={id:"shop",label:"Shopping Assistant",config:{theme:aR,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"]}},Rx={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Lx}},Hx={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Lx}},Wx={shop:Ix,minimal:Rx,fullscreen:Hx};function lR(e){return Wx[e]}var cR=yx;function dR(){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 pR(){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 uR(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:$o(e.colors.primary,.95),100:$o(e.colors.primary,.9),200:$o(e.colors.primary,.8),300:$o(e.colors.primary,.7),400:$o(e.colors.primary,.6),500:e.colors.primary,600:$o(e.colors.primary,.8),700:$o(e.colors.primary,.7),800:$o(e.colors.primary,.6),900:$o(e.colors.primary,.5),950:$o(e.colors.primary,.45)}}),{...t,palette:n}}}}function gR(){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 mR(){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 $o(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 fR(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}function of(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@${mo}/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 hR(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 Ox=`({ 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
- }`,Hx=`function(ctx) {
166
+ }`,Bx=`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
- }`,Wx=`(action: any, context: any) => {
179
+ }`,_x=`(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
- }`,Ox=`function(action, context) {
196
+ }`,Dx=`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
- }`,pR=`(parsed: any) => {
213
+ }`,yR=`(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
- }`,uR=`function(parsed) {
219
+ }`,bR=`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 gR(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 ap(e){return e.parserType??gR(e.streamParser)??"plain"}function lp(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 cp(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 dp(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 pp(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 up(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 tf(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 Bx(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}: {`),Bx(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}: {`),Bx(e,n,`${o} `),e.push(`${o}},`))}function Cl(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function mR(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:dR(n.hooks)}:void 0;return t==="esm"?fR(o,r):t==="script-installer"?bR(o,r):t==="script-advanced"?CR(o,r):t==="react-component"?hR(o,r):t==="react-advanced"?yR(o,r):vR(o,r)}function fR(e,t){let n=t?.hooks,o=ap(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Cl(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(...pp(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(...lp(e," ")),s.push(...cp(e," ",n)),s.push(...dp(e," ")),s.push(...up(e," ")),s.push(...tf(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 hR(e,t){let n=t?.hooks,o=ap(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: '${Cl(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(...pp(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(...lp(e," ")),s.push(...cp(e," ",n)),s.push(...dp(e," ")),s.push(...up(e," ")),s.push(...tf(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 yR(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: '${Cl(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(...pp(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(...lp(e," ")),o.push(...cp(e," ",n)),o.push(...dp(e," ")),o.push(...up(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(${pR}),`)),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(` ${Rx}`),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(` ${Rx}`),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(` ${Wx}`),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(` ${Wx}`),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 _x(e){let t=ap(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=_x(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="${ef(t)}/install.global.js" data-config='${s}'></script>`}function vR(e,t){let n=t?.hooks,o=ap(e),r=o!=="plain",s=ef(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: '${Cl(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(...pp(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(...lp(e," ")),a.push(...cp(e," ",n)),a.push(...dp(e," ")),a.push(...up(e," ")),a.push(...tf(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 CR(e,t){let n=t?.hooks,o=_x(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
225
+ }`;function vR(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??vR(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 rf(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 Nx(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}: {`),Nx(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function jr(e,t,n,o){n&&(e.push(`${o}${t}: {`),Nx(e,n,`${o} `),e.push(`${o}},`))}function Cl(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function CR(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:hR(n.hooks)}:void 0;return t==="esm"?wR(o,r):t==="script-installer"?AR(o,r):t==="script-advanced"?ER(o,r):t==="react-component"?xR(o,r):t==="react-advanced"?SR(o,r):MR(o,r)}function wR(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: '${Cl(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&&jr(s,"theme",e.theme," "),e.launcher&&jr(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(...rf(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 xR(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: '${Cl(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&&jr(s,"theme",e.theme," "),e.launcher&&jr(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(...rf(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 SR(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: '${Cl(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&&jr(o,"theme",e.theme," "),e.launcher&&jr(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(${yR}),`)),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(` ${Ox}`),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(` ${Ox}`),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 Fx(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 AR(e,t){let n=Fx(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="${of(t)}/install.global.js" data-config='${s}'></script>`}function MR(e,t){let n=t?.hooks,o=lp(e),r=o!=="plain",s=of(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: '${Cl(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&&jr(a,"theme",e.theme," "),e.launcher&&jr(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(...rf(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 ER(e,t){let n=t?.hooks,o=Fx(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 = '${ef(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(${uR});`),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(` ${Hx}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Hx}`),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(` ${Ox}`),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(` ${Ox}`),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: '${Cl(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 wR}from"lucide";var Dx={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Nx=.1,Fx=.15,$x=1.5,nf=24,Ux=40,xR=`
232
+ `)};`,""," // Constants",` var CDN_BASE = '${of(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(${bR});`),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(` ${Bx}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Bx}`),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(` ${Dx}`),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(` ${Dx}`),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: '${Cl(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 TR}from"lucide";var $x={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Ux=.1,jx=.15,qx=1.5,sf=24,zx=40,PR=`
234
234
  /* \u2500\u2500 Root \u2500\u2500 */
235
235
  .persona-dc-root {
236
236
  display: flex;
@@ -381,7 +381,7 @@ ${s.join(`
381
381
  .persona-dc-stage {
382
382
  height: 550px;
383
383
  min-height: 400px;
384
- padding: ${nf}px;
384
+ padding: ${sf}px;
385
385
  overflow: auto;
386
386
  background: #f0f1f3;
387
387
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -471,10 +471,10 @@ ${s.join(`
471
471
  min-height: 300px;
472
472
  }
473
473
  }
474
- `;function SR(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=xR,document.head.appendChild(e)}function AR(e,t){let n=e.clientWidth-nf*2-Ux,o=e.clientHeight-nf*2-Ux;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function MR(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 ER(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");SR();let u=Math.max(0,Math.min(o,n.length-1)),m=r,y=s,h=null,C=1,x=!1,S=M("div","persona-dc-root"),k=M("div","persona-dc-toolbar"),B=M("div","persona-dc-toolbar-lead"),$=M("div","persona-dc-toolbar-trail"),T=Vn({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ne(-1)}),I=M("div");I.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 _=M("span","persona-dc-title-text"),G=M("span","persona-dc-title-chevron"),ie=Ht(wR,12,"currentColor",2);ie&&G.appendChild(ie),A.append(_,G);let ne=M("div","persona-dc-dropdown");ne.setAttribute("role","listbox"),ne.style.display="none";let E=!1;function D(){ne.innerHTML="";for(let Ie=0;Ie<n.length;Ie++){let Ut=n[Ie],at=M("button","persona-dc-dropdown-item");at.type="button",at.setAttribute("role","option"),at.setAttribute("aria-current",Ie===u?"true":"false");let nn=M("span");if(nn.textContent=Ut.title,at.appendChild(nn),Ut.description){let wn=M("span","persona-dc-dropdown-desc");wn.textContent=Ut.description,at.appendChild(wn)}at.addEventListener("click",()=>{L(),we(Ie)}),ne.appendChild(at)}}function W(){E=!E,ne.style.display=E?"":"none",A.setAttribute("aria-expanded",E?"true":"false"),E&&D()}function L(){E&&(E=!1,ne.style.display="none",A.setAttribute("aria-expanded","false"))}A.addEventListener("click",Ie=>{Ie.stopPropagation(),W()});let Y=()=>L();document.addEventListener("click",Y),I.append(A,ne);let K=Vn({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ne(1)}),le=M("span","persona-dc-counter");B.append(T,I,K,le);let de=null;l&&(de=Wd({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:Ie=>{m=Ie,it.dataset.device=m,h=null,ke()}}),$.appendChild(de.element));let ge=null;if(a){let Ie=M("div","persona-dc-zoom-controls"),Ut=Vn({icon:"minus",label:"Zoom out",size:14,onClick:()=>{h=Math.max(Fx,(h??C)-Nx),ke()}});ge=M("span","persona-dc-zoom-level"),ge.title="Reset to 100%",ge.style.cursor="pointer",ge.addEventListener("click",()=>{h=1,ke()});let at=Vn({icon:"plus",label:"Zoom in",size:14,onClick:()=>{h=Math.min($x,(h??C)+Nx),ke()}}),nn=Vn({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{h=null,ke()}});Ie.append(Ut,ge,at,nn),$.appendChild(Ie)}if(d){let Ie=M("div","persona-dc-separator");$.appendChild(Ie);let Ut=Wd({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:at=>{y=at,it.dataset.colorScheme=y,j()}});$.appendChild(Ut.element)}let Me=M("div","persona-dc-separator");$.appendChild(Me);let fe=Vn({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[u].url,"_blank")}});$.appendChild(fe),k.append(B,$);let _e=M("div","persona-dc-stage"),it=M("div","persona-dc-iframe-wrapper");it.dataset.device=m,it.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,it.appendChild(be),_e.appendChild(it),S.append(k,_e),e.appendChild(S);function j(){try{let Ie=be.contentDocument?.body;if(!Ie)return;y==="dark"?Ie.classList.add("theme-dark"):Ie.classList.remove("theme-dark")}catch{}}be.addEventListener("load",()=>j());function De(){let Ie=n[u];_.textContent=Ie.title,le.textContent=`${u+1} / ${n.length}`,be.title=Ie.title}function Ne(Ie){let Ut=((u+Ie)%n.length+n.length)%n.length;we(Ut)}function we(Ie){Ie<0||Ie>=n.length||(u=Ie,be.src=n[u].url,De(),p?.(u,n[u]))}function ke(){if(x)return;let Ie=Dx[m]??Dx.desktop;C=AR(_e,Ie);let Ut=Math.max(Fx,Math.min($x,h??C));MR(it,be,Ie,Ut,m),ge&&(ge.textContent=`${Math.round(Ut*100)}%`)}let he=new ResizeObserver(()=>ke());he.observe(_e),De(),be.src=n[u].url,requestAnimationFrame(()=>ke());function dt(){x||(x=!0,he.disconnect(),document.removeEventListener("click",Y),S.remove())}return{element:S,goTo:we,next:()=>Ne(1),prev:()=>Ne(-1),getIndex:()=>u,setDevice(Ie){m=Ie,it.dataset.device=Ie,de?.setSelected(Ie),h=null,ke()},setColorScheme(Ie){y=Ie,it.dataset.colorScheme=Ie},setZoom(Ie){h=Ie,ke()},destroy:dt}}wg();var jx=16e3,TR=24e3,PR=4096,kR=4,LR=1380533830;function IR(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===LR?new Uint8Array(e,44):new Uint8Array(e)}function RR(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 wl=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:jx,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:jx});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ai(TR);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=`${RR(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(PR,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=IR(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 Ns=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 xl(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new wl(e.runtype);case"browser":if(!Ns.isSupported())throw new Error("Browser speech recognition not supported");return new Ns(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 of(e){if(e?.type==="custom"&&e.custom)return xl({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return xl({type:"runtype",runtype:e.runtype});if(Ns.isSupported())return xl({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function qx(e){try{return of(e),!0}catch{return!1}}var zx="webmcp:",HR=e=>e.startsWith(zx)?e.slice(zx.length):e,gp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},mp=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 gp.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={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=OR(r.inputSchema);return a&&(s.parametersSchema=a),s})}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 C=typeof document<"u"&&!!document.modelContext;return yo(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=HR(t),a;try{a=await r.getTools()}catch(C){let x=C instanceof Error?C.message:String(C);return yo(`Failed to read WebMCP registry: ${x}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(C=>C.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 C=await r.executeTool(l,NR(n),{signal:u.signal});return BR(C)}catch(C){if(m)return yo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return yo("Aborted by cancel()");let x=C instanceof Error?C.message:String(C);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){gp.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,gp.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??_R;try{return await n(t)}catch(o){return gp.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=>WR(t,o))}},WR=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},OR=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},BR=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:FR(t)}]}},yo=e=>({isError:!0,content:[{type:"text",text:e}]}),_R=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=DR(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
474
+ `;function kR(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=PR,document.head.appendChild(e)}function LR(e,t){let n=e.clientWidth-sf*2-zx,o=e.clientHeight-sf*2-zx;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function IR(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 RR(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");kR();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"),k=M("div","persona-dc-toolbar"),B=M("div","persona-dc-toolbar-lead"),$=M("div","persona-dc-toolbar-trail"),T=Vn({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ne(-1)}),I=M("div");I.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 D=M("span","persona-dc-title-text"),G=M("span","persona-dc-title-chevron"),se=Ht(TR,12,"currentColor",2);se&&G.appendChild(se),A.append(D,G);let ne=M("div","persona-dc-dropdown");ne.setAttribute("role","listbox"),ne.style.display="none";let E=!1;function _(){ne.innerHTML="";for(let Ie=0;Ie<n.length;Ie++){let Ut=n[Ie],at=M("button","persona-dc-dropdown-item");at.type="button",at.setAttribute("role","option"),at.setAttribute("aria-current",Ie===u?"true":"false");let nn=M("span");if(nn.textContent=Ut.title,at.appendChild(nn),Ut.description){let pn=M("span","persona-dc-dropdown-desc");pn.textContent=Ut.description,at.appendChild(pn)}at.addEventListener("click",()=>{L(),xe(Ie)}),ne.appendChild(at)}}function W(){E=!E,ne.style.display=E?"":"none",A.setAttribute("aria-expanded",E?"true":"false"),E&&_()}function L(){E&&(E=!1,ne.style.display="none",A.setAttribute("aria-expanded","false"))}A.addEventListener("click",Ie=>{Ie.stopPropagation(),W()});let Y=()=>L();document.addEventListener("click",Y),I.append(A,ne);let K=Vn({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ne(1)}),le=M("span","persona-dc-counter");B.append(T,I,K,le);let de=null;l&&(de=Od({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:Ie=>{m=Ie,it.dataset.device=m,h=null,ke()}}),$.appendChild(de.element));let ge=null;if(a){let Ie=M("div","persona-dc-zoom-controls"),Ut=Vn({icon:"minus",label:"Zoom out",size:14,onClick:()=>{h=Math.max(jx,(h??C)-Ux),ke()}});ge=M("span","persona-dc-zoom-level"),ge.title="Reset to 100%",ge.style.cursor="pointer",ge.addEventListener("click",()=>{h=1,ke()});let at=Vn({icon:"plus",label:"Zoom in",size:14,onClick:()=>{h=Math.min(qx,(h??C)+Ux),ke()}}),nn=Vn({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{h=null,ke()}});Ie.append(Ut,ge,at,nn),$.appendChild(Ie)}if(d){let Ie=M("div","persona-dc-separator");$.appendChild(Ie);let Ut=Od({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:at=>{y=at,it.dataset.colorScheme=y,j()}});$.appendChild(Ut.element)}let Ae=M("div","persona-dc-separator");$.appendChild(Ae);let fe=Vn({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[u].url,"_blank")}});$.appendChild(fe),k.append(B,$);let _e=M("div","persona-dc-stage"),it=M("div","persona-dc-iframe-wrapper");it.dataset.device=m,it.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,it.appendChild(be),_e.appendChild(it),x.append(k,_e),e.appendChild(x);function j(){try{let Ie=be.contentDocument?.body;if(!Ie)return;y==="dark"?Ie.classList.add("theme-dark"):Ie.classList.remove("theme-dark")}catch{}}be.addEventListener("load",()=>j());function De(){let Ie=n[u];D.textContent=Ie.title,le.textContent=`${u+1} / ${n.length}`,be.title=Ie.title}function Ne(Ie){let Ut=((u+Ie)%n.length+n.length)%n.length;xe(Ut)}function xe(Ie){Ie<0||Ie>=n.length||(u=Ie,be.src=n[u].url,De(),p?.(u,n[u]))}function ke(){if(S)return;let Ie=$x[m]??$x.desktop;C=LR(_e,Ie);let Ut=Math.max(jx,Math.min(qx,h??C));IR(it,be,Ie,Ut,m),ge&&(ge.textContent=`${Math.round(Ut*100)}%`)}let he=new ResizeObserver(()=>ke());he.observe(_e),De(),be.src=n[u].url,requestAnimationFrame(()=>ke());function dt(){S||(S=!0,he.disconnect(),document.removeEventListener("click",Y),x.remove())}return{element:x,goTo:xe,next:()=>Ne(1),prev:()=>Ne(-1),getIndex:()=>u,setDevice(Ie){m=Ie,it.dataset.device=Ie,de?.setSelected(Ie),h=null,ke()},setColorScheme(Ie){y=Ie,it.dataset.colorScheme=Ie},setZoom(Ie){h=Ie,ke()},destroy:dt}}Ag();var Vx=16e3,HR=24e3,WR=4096,OR=4,BR=1380533830;function _R(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===BR?new Uint8Array(e,44):new Uint8Array(e)}function DR(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 wl=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:Vx,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:Vx});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Mi(HR);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=`${DR(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(WR,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*OR));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=_R(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 Ns=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 xl(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new wl(e.runtype);case"browser":if(!Ns.isSupported())throw new Error("Browser speech recognition not supported");return new Ns(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 af(e){if(e?.type==="custom"&&e.custom)return xl({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return xl({type:"runtype",runtype:e.runtype});if(Ns.isSupported())return xl({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Kx(e){try{return af(e),!0}catch{return!1}}var Gx="webmcp:",NR=e=>e.startsWith(Gx)?e.slice(Gx.length):e,mp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},fp=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={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=$R(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return bo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let C=typeof document<"u"&&!!document.modelContext;return bo(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=NR(t),a;try{a=await r.getTools()}catch(C){let S=C instanceof Error?C.message:String(C);return bo(`Failed to read WebMCP registry: ${S}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(C=>C.name===s);if(!l)return bo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return bo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return bo("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 bo("User declined the tool call.");if(o?.aborted)return bo("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,zR(n),{signal:u.signal});return UR(C)}catch(C){if(m)return bo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return bo("Aborted by cancel()");let S=C instanceof Error?C.message:String(C);return bo(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){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??jR;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=>FR(t,o))}},FR=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},$R=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},UR=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:VR(t)}]}},bo=e=>({isError:!0,content:[{type:"text",text:e}]}),jR=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=qR(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)},DR=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)}},NR=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},FR=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var rf=class extends mp{constructor(t){super(t,{recordToolDisplayTitles:jc,getToolDisplayTitle:yi,loadPolyfill:qc})}};function $R(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 UR(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:$R(o,n)?2:3}function Vx(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function sf(e,t){let n=t.trim();if(!n)return[...e].sort(Vx);let o=[];for(let r of e){let s=UR(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:Vx(r.item,s.item)),o.map(r=>r.item)}function jR(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 qR(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>sf(e.items,t),resolve:e.resolve}}function zR(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=>sf(t,jR(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 VR(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 x=C===y;h.setAttribute("aria-selected",x?"true":"false"),h.tabIndex=x||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{Bb as ASK_USER_QUESTION_CLIENT_TOOL,Ob as ASK_USER_QUESTION_PARAMETERS_SCHEMA,zc as ASK_USER_QUESTION_TOOL_NAME,xi as AgentWidgetClient,Xa as AgentWidgetSession,Mi as AttachmentManager,Rs as BrowserSpeechEngine,wC as DEFAULT_COMPONENTS,kg as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,oo as DEFAULT_FLOATING_LAUNCHER_WIDTH,vC as DEFAULT_PALETTE,CC as DEFAULT_SEMANTIC,st as DEFAULT_WIDGET_CONFIG,fo as HistoryProviderError,Ix as PRESETS,Lx as PRESET_FULLSCREEN,kx as PRESET_MINIMAL,Px as PRESET_SHOP,Si as ReadAloudController,ig as SUGGEST_REPLIES_CLIENT_TOOL,Rb as SUGGEST_REPLIES_PARAMETERS_SCHEMA,rr as SUGGEST_REPLIES_TOOL_NAME,Jk as THEME_ZONES,sr as VERSION,Uc as WEBMCP_TOOL_PREFIX,rf as WebMcpBridge,rR as accessibilityPlugin,sR as animationsPlugin,Fw as applyFeaturePreferences,ki as applyThemeVariables,Ri as attachHeaderToContainer,iR as brandPlugin,Wi as buildComposer,YC as buildDefaultHeader,$r as buildHeader,fl as buildHeaderWithLayout,XC as buildMinimalHeader,ja as builtInClientToolsForDispatch,Un as canonicalArtifactDisplayMode,ZI as collectEnrichedPageContext,Do as componentRegistry,ep as createActionManager,Vm as createAgentExperience,xP as createAskUserQuestionBubble,of as createBestAvailableVoiceProvider,e0 as createBubbleWithLayout,jm as createCSATFeedback,am as createComboButton,gI as createComponentMiddleware,Fm as createComponentStreamParser,tb as createDefaultSanitizer,ER as createDemoCarousel,DT as createDirectivePostprocessor,Hi as createDropdownMenu,TP as createFlexibleJsonStreamParser,Vn as createIconButton,mg as createImagePart,pg as createJsonStreamParser,QC as createLabelButton,Om as createLocalStorageAdapter,Fc as createMarkdownProcessor,$c as createMarkdownProcessorFromConfig,aw as createMessageActions,qm as createNPSFeedback,cg as createPlainTextParser,cR as createPlugin,dg as createRegexJsonParser,VR as createRovingTablist,zR as createSlashCommandsSource,RL as createSplitButton,yl as createStandardBubble,qR as createStaticMentionSource,mo as createTextPart,xd as createTheme,ol as createThemeObserver,Wd as createToggleGroup,Oi as createTypingIndicator,xl as createVoiceProvider,sp as createWidgetHostLayout,ug as createXmlParser,oR as default,ji as defaultActionHandlers,Zd as defaultJsonActionParser,sf as defaultMentionFilter,Sx as defaultParseRules,Sd as detectColorScheme,NT as directivePostprocessor,Ua as ensureAskUserQuestionSheet,Ir as escapeHtml,Um as extractComponentDirectiveFromMessage,IP as fileToImagePart,eR as formatEnrichedContext,ks as generateAssistantMessageId,mR as generateCodeSnippet,YT as generateMessageId,Mx as generateStableSelector,Na as generateUserMessageId,Hs as getActiveTheme,Gg as getColorScheme,gg as getDisplayText,JC as getHeaderLayout,LP as getImageParts,nR as getPreset,np as hasComponentDirective,Ka as hasImages,lm as headerLayouts,lR as highContrastPlugin,mx as initAgentWidget,Rr as isAskUserQuestionMessage,uI as isComponentDirectiveType,Et as isDockedMountMode,KP as isHistoryProviderError,Ci as isSuggestRepliesMessage,qx as isVoiceSupported,Ts as isWebMcpToolName,Bs as isWelcomeVisible,ag as latestAgentSuggestions,uL as listRegisteredStreamAnimations,Gu as loadMarkdownParsers,Jy as markdownPostprocessor,el as mergeWithDefaults,kP as normalizeContent,Ps as normalizeMediaType,_a as onMarkdownParsersReady,Hr as parseAskUserQuestionPayload,Wb as parseSuggestRepliesPayload,_w as parseWidgetPreferenceSlice,Ya as pickBestVoice,Xd as pluginRegistry,aR as reducedMotionPlugin,HT as registerIcons,Ld as registerStreamAnimationPlugin,Is as removeAskUserQuestionSheet,$m as renderComponentDirective,sw as renderLoadingIndicatorWithFallback,pe as renderLucideIcon,fb as resolveArtifactDisplay,or as resolveArtifactDisplayMode,Yd as resolveConfigPreferences,qn as resolveDockConfig,Ju as resolveSanitizer,Vg as resolveTokens,_o as resolveWelcomeConfig,gb as stripWebMcpPrefix,Kg as themeToCssVariables,pL as unregisterStreamAnimationPlugin,RP as validateImageFile,xC as validateTheme};
479
+ ${e.description}`:"");return window.confirm(n)},qR=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)}},zR=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},VR=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var lf=class extends fp{constructor(t){super(t,{recordToolDisplayTitles:jc,getToolDisplayTitle:bi,loadPolyfill:qc})}};function KR(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 GR(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:KR(o,n)?2:3}function Qx(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function cf(e,t){let n=t.trim();if(!n)return[...e].sort(Qx);let o=[];for(let r of e){let s=GR(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:Qx(r.item,s.item)),o.map(r=>r.item)}function QR(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 YR(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>cf(e.items,t),resolve:e.resolve}}function XR(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=>cf(t,QR(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 JR(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{Fb as ASK_USER_QUESTION_CLIENT_TOOL,Nb as ASK_USER_QUESTION_PARAMETERS_SCHEMA,zc as ASK_USER_QUESTION_TOOL_NAME,Si as AgentWidgetClient,Xa as AgentWidgetSession,Ei as AttachmentManager,Rs as BrowserSpeechEngine,AC as DEFAULT_COMPONENTS,Rg as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,oo as DEFAULT_FLOATING_LAUNCHER_WIDTH,xC as DEFAULT_PALETTE,SC as DEFAULT_SEMANTIC,st as DEFAULT_WIDGET_CONFIG,ho as HistoryProviderError,Wx as PRESETS,Hx as PRESET_FULLSCREEN,Rx as PRESET_MINIMAL,Ix as PRESET_SHOP,Ai as ReadAloudController,lg as SUGGEST_REPLIES_CLIENT_TOOL,Bb as SUGGEST_REPLIES_PARAMETERS_SCHEMA,ir as SUGGEST_REPLIES_TOOL_NAME,rL as THEME_ZONES,mo as VERSION,Uc as WEBMCP_TOOL_PREFIX,lf as WebMcpBridge,dR as accessibilityPlugin,pR as animationsPlugin,jw as applyFeaturePreferences,Li as applyThemeVariables,Hi as attachHeaderToContainer,uR as brandPlugin,Oi as buildComposer,ZC as buildDefaultHeader,Ur as buildHeader,fl as buildHeaderWithLayout,ew as buildMinimalHeader,ja as builtInClientToolsForDispatch,Un as canonicalArtifactDisplayMode,sR as collectEnrichedPageContext,No as componentRegistry,tp as createActionManager,Qm as createAgentExperience,MP as createAskUserQuestionBubble,af as createBestAvailableVoiceProvider,i0 as createBubbleWithLayout,Vm as createCSATFeedback,dm as createComboButton,vI as createComponentMiddleware,jm as createComponentStreamParser,sb as createDefaultSanitizer,RR as createDemoCarousel,$T as createDirectivePostprocessor,Wi as createDropdownMenu,LP as createFlexibleJsonStreamParser,Vn as createIconButton,hg as createImagePart,gg as createJsonStreamParser,JC as createLabelButton,Dm as createLocalStorageAdapter,Fc as createMarkdownProcessor,$c as createMarkdownProcessorFromConfig,dw as createMessageActions,Km as createNPSFeedback,pg as createPlainTextParser,fR as createPlugin,ug as createRegexJsonParser,JR as createRovingTablist,XR as createSlashCommandsSource,DL as createSplitButton,yl as createStandardBubble,YR as createStaticMentionSource,fo as createTextPart,Sd as createTheme,ol as createThemeObserver,Od as createToggleGroup,Bi as createTypingIndicator,xl as createVoiceProvider,ip as createWidgetHostLayout,mg as createXmlParser,cR as default,qi as defaultActionHandlers,ep as defaultJsonActionParser,cf as defaultMentionFilter,Ex as defaultParseRules,Ad as detectColorScheme,UT as directivePostprocessor,Ua as ensureAskUserQuestionSheet,Rr as escapeHtml,zm as extractComponentDirectiveFromMessage,WP as fileToImagePart,iR as formatEnrichedContext,ks as generateAssistantMessageId,CR as generateCodeSnippet,ZT as generateMessageId,Px as generateStableSelector,Na as generateUserMessageId,Hs as getActiveTheme,Xg as getColorScheme,fg as getDisplayText,tw as getHeaderLayout,HP as getImageParts,lR as getPreset,op as hasComponentDirective,Ka as hasImages,pm as headerLayouts,mR as highContrastPlugin,yx as initAgentWidget,Hr as isAskUserQuestionMessage,bI as isComponentDirectiveType,Et as isDockedMountMode,YP as isHistoryProviderError,wi as isSuggestRepliesMessage,Kx as isVoiceSupported,Ts as isWebMcpToolName,Bs as isWelcomeVisible,cg as latestAgentSuggestions,bL as listRegisteredStreamAnimations,Yu as loadMarkdownParsers,nb as markdownPostprocessor,el as mergeWithDefaults,RP as normalizeContent,Ps as normalizeMediaType,_a as onMarkdownParsersReady,Wr as parseAskUserQuestionPayload,Db as parseSuggestRepliesPayload,Fw as parseWidgetPreferenceSlice,Ya as pickBestVoice,Jd as pluginRegistry,gR as reducedMotionPlugin,BT as registerIcons,Id as registerStreamAnimationPlugin,Is as removeAskUserQuestionSheet,qm as renderComponentDirective,lw as renderLoadingIndicatorWithFallback,pe as renderLucideIcon,vb as resolveArtifactDisplay,sr as resolveArtifactDisplayMode,Xd as resolveConfigPreferences,qn as resolveDockConfig,eg as resolveSanitizer,Qg as resolveTokens,Do as resolveWelcomeConfig,yb as stripWebMcpPrefix,Yg as themeToCssVariables,yL as unregisterStreamAnimationPlugin,OP as validateImageFile,MC as validateTheme};
480
480
  //# sourceMappingURL=index.js.map