@runtypelabs/persona 4.23.2 → 4.24.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.
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-CI7OckWI.d.cts → types-Db61aI9J.d.cts} +2 -0
- package/dist/animations/{types-CI7OckWI.d.ts → types-Db61aI9J.d.ts} +2 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/animations-extra.d.cts +2 -0
- package/dist/animations-extra.d.ts +2 -0
- package/dist/approval-ui-3NMYNXBD.js +1 -0
- package/dist/approval-ui.cjs +2 -2
- package/dist/approval-ui.d.cts +215 -37
- package/dist/approval-ui.d.ts +215 -37
- package/dist/approval-ui.js +2 -2
- package/dist/{artifacts-ui-F4N6VMKF.js → artifacts-ui-IGB5YKLO.js} +4 -4
- package/dist/artifacts-ui.d.cts +210 -25
- package/dist/artifacts-ui.d.ts +210 -25
- package/dist/{chunk-NIKYKSNZ.js → chunk-7CO4T5KB.js} +1 -1
- package/dist/codegen.cjs +11 -11
- package/dist/codegen.js +13 -13
- package/dist/context-mentions.d.cts +210 -25
- package/dist/context-mentions.d.ts +210 -25
- package/dist/event-stream-view.d.cts +210 -25
- package/dist/event-stream-view.d.ts +210 -25
- package/dist/forms-ui.d.cts +245 -27
- package/dist/forms-ui.d.ts +245 -27
- package/dist/history-view.d.cts +2 -0
- package/dist/history-view.d.ts +2 -0
- package/dist/index.cjs +70 -69
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +270 -39
- package/dist/index.d.ts +270 -39
- package/dist/index.global.js +57 -54
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +70 -69
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/session-reconnect.d.cts +210 -25
- package/dist/session-reconnect.d.ts +210 -25
- package/dist/smart-dom-reader.d.cts +210 -25
- package/dist/smart-dom-reader.d.ts +210 -25
- package/dist/theme-editor-preview.cjs +74 -73
- package/dist/theme-editor-preview.d.cts +217 -25
- package/dist/theme-editor-preview.d.ts +217 -25
- package/dist/theme-editor-preview.js +51 -50
- package/dist/theme-editor.cjs +10 -10
- package/dist/theme-editor.d.cts +230 -27
- package/dist/theme-editor.d.ts +230 -27
- package/dist/theme-editor.js +10 -10
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +1522 -11
- package/dist/theme-reference.d.ts +1522 -11
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +1 -1
- package/package.json +3 -2
- package/src/__fixtures__/defaults-parity.v4.json +776 -0
- package/src/approval-ui-entry.ts +0 -1
- package/src/approval-ui-loader.ts +5 -4
- package/src/approval-ui.ts +0 -1
- package/src/client-identity-proof.test.ts +193 -0
- package/src/client-session-warm.test.ts +216 -0
- package/src/client-visitor-history.test.ts +6 -0
- package/src/client.ts +122 -30
- package/src/codegen.test.ts +24 -0
- package/src/components/activity-row.test.ts +100 -0
- package/src/components/activity-row.ts +136 -0
- package/src/components/approval-actions.test.ts +8 -5
- package/src/components/approval-actions.ts +19 -6
- package/src/components/approval-bubble.test.ts +56 -9
- package/src/components/approval-bubble.ts +36 -41
- package/src/components/composer-builder.ts +5 -2
- package/src/components/composer-parts.ts +10 -2
- package/src/components/header-builder.test.ts +32 -0
- package/src/components/header-builder.ts +7 -4
- package/src/components/header-layouts.test.ts +12 -0
- package/src/components/header-layouts.ts +3 -2
- package/src/components/launcher.ts +11 -2
- package/src/components/message-bubble.test.ts +22 -0
- package/src/components/message-bubble.ts +7 -3
- package/src/components/panel.test.ts +52 -1
- package/src/components/panel.ts +47 -8
- package/src/components/pill-composer-builder.test.ts +2 -0
- package/src/components/pill-composer-builder.ts +0 -1
- package/src/components/reasoning-bubble.ts +29 -17
- package/src/components/suggestions.test.ts +1 -0
- package/src/components/suggestions.ts +0 -16
- package/src/components/tool-bubble.ts +131 -114
- package/src/components/tool-details.test.ts +87 -0
- package/src/components/tool-details.ts +102 -0
- package/src/components/welcome.test.ts +8 -0
- package/src/components/welcome.ts +4 -2
- package/src/defaults-parity.test.ts +158 -0
- package/src/defaults.test.ts +69 -0
- package/src/defaults.ts +128 -49
- package/src/generated/runtype-openapi-contract.ts +2 -2
- package/src/index-core.ts +2 -0
- package/src/install.test.ts +24 -0
- package/src/install.ts +3 -1
- package/src/launcher-global.ts +2 -1
- package/src/launcher-variants.test.ts +52 -0
- package/src/runtime/init-update-reset.test.ts +21 -0
- package/src/session.ts +29 -6
- package/src/styles/widget-styles.test.ts +19 -0
- package/src/styles/widget.css +295 -23
- package/src/theme-editor/index.ts +2 -0
- package/src/theme-editor/preview-utils.test.ts +8 -0
- package/src/theme-editor/preview-utils.ts +7 -3
- package/src/theme-editor/sections.test.ts +31 -0
- package/src/theme-editor/sections.ts +55 -1
- package/src/theme-editor/state-preferences.test.ts +49 -0
- package/src/theme-editor/state.ts +73 -15
- package/src/theme-reference.test.ts +20 -0
- package/src/theme-reference.ts +11 -5
- package/src/tool-call-display-defaults.test.ts +33 -1
- package/src/types/theme.ts +80 -3
- package/src/types.ts +136 -22
- package/src/ui.activity-row.test.ts +91 -0
- package/src/ui.approval-plugin.test.ts +63 -0
- package/src/ui.composer-compact.test.ts +24 -2
- package/src/ui.composer-placement.test.ts +23 -0
- package/src/ui.detached-panel.test.ts +33 -6
- package/src/ui.docked.test.ts +19 -0
- package/src/ui.header-update-stability.test.ts +25 -0
- package/src/ui.identity-proof.test.ts +58 -0
- package/src/ui.launcher-teaser.test.ts +25 -0
- package/src/ui.message-width.test.ts +17 -2
- package/src/ui.reasoning-display.test.ts +92 -0
- package/src/ui.rebuild-composer.test.ts +20 -3
- package/src/ui.scroll.test.ts +32 -0
- package/src/ui.session-init.test.ts +312 -0
- package/src/ui.status-indicator.test.ts +82 -0
- package/src/ui.suggest-replies.test.ts +11 -0
- package/src/ui.ts +363 -74
- package/src/ui.v5-defaults.test.ts +144 -0
- package/src/ui.welcome.test.ts +92 -3
- package/src/utils/__snapshots__/tokens-parity.test.ts.snap +811 -140
- package/src/utils/code-generators.ts +14 -0
- package/src/utils/composer-compact.test.ts +0 -2
- package/src/utils/composer-compact.ts +2 -4
- package/src/utils/composer-placement.ts +2 -3
- package/src/utils/config-merge.test.ts +81 -5
- package/src/utils/config-merge.ts +13 -3
- package/src/utils/defaults-provenance.ts +67 -0
- package/src/utils/dock.ts +7 -1
- package/src/utils/launcher-variant.ts +16 -0
- package/src/utils/panel-config.ts +97 -0
- package/src/utils/status-indicator.ts +39 -0
- package/src/utils/theme.test.ts +182 -0
- package/src/utils/theme.ts +131 -18
- package/src/utils/tokens.test.ts +122 -1
- package/src/utils/tokens.ts +177 -17
- package/src/welcome.test.ts +23 -0
- package/src/welcome.ts +16 -9
- package/dist/approval-ui-K7R5Q5OC.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
var TM=Object.defineProperty;var Wa=(e,t)=>()=>(e&&(t=e(e=0)),t);var Zy=(e,t)=>{for(var n in t)TM(e,n,{get:t[n],enumerable:!0})};var eb={};Zy(eb,{DOMPurify:()=>kM,Marked:()=>PM});import{Marked as PM}from"marked";import kM from"dompurify";var tb=Wa(()=>{"use strict"});var Ai,kg=Wa(()=>{"use strict";Ai=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of a)l()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function yk(e){return e.replace(/\/+$/,"")}async function bk(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var nd,Mv=Wa(()=>{"use strict";kg();nd=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Ai(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let r=await this.ensurePlayer();if(t!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.generation&&o.onStart?.()}),r.onFinished(()=>{t===this.generation&&o.onEnd?.()});let s=`${yk(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 bk(a));let l=a.body.getReader();for(;;){let{done:d,value:p}=await l.read();if(t!==this.generation){await l.cancel().catch(()=>{});return}if(d)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(t!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var od,Ev=Wa(()=>{"use strict";od=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var Tv={};Zy(Tv,{FallbackSpeechEngine:()=>od,RuntypeSpeechEngine:()=>nd});var Pv=Wa(()=>{"use strict";Mv();Ev()});import{Marked as RM}from"marked";import HM from"dompurify";var ft=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:u=>{o=u,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(m=>(r=m,m)).catch(m=>{throw s=null,m}),s),provide:u=>{r=u},getSync:()=>r}};var{setLoader:PH,load:LM,provide:IM,getSync:Zu}=ft({fallbackImport:()=>Promise.resolve().then(()=>(tb(),eb))}),Bc=new Set,nb=()=>{let e=[...Bc];Bc.clear();for(let t of e)try{t()}catch{}};var eg=()=>{let e=Zu();return e?Promise.resolve(e):LM().then(t=>(nb(),t))},Oa=e=>Zu()?()=>{}:(Bc.add(e),()=>{Bc.delete(e)}),ob=e=>{IM(e),nb()},Ro=Zu;ob({Marked:RM,DOMPurify:HM});import{Ban as WM,Bell as OM,Bookmark as BM,Building as _M,Calendar as DM,CalendarDays as NM,Camera as FM,ChartColumn as $M,CircleCheck as UM,CircleX as jM,Clock as qM,CreditCard as zM,DollarSign as VM,EyeOff as KM,Files as GM,Film as YM,Flag as QM,Folder as XM,FolderOpen as JM,Funnel as ZM,Gift as eE,Globe as tE,Hash as nE,Headphones as oE,Heart as rE,House as sE,Image as iE,Info as aE,Key as lE,Lightbulb as cE,Link as dE,Lock as pE,Mail as uE,MapPin as gE,MessageCircle as mE,Monitor as fE,Moon as hE,Package as yE,Pause as bE,PenLine as vE,Percent as CE,Phone as wE,Play as xE,Receipt as SE,RotateCw as AE,Save as ME,Settings as EE,Share as TE,Shield as PE,ShoppingBag as kE,ShoppingCart as LE,Smartphone as IE,Sparkles as RE,Store as HE,Sun as WE,Tag as OE,Timer as BE,TriangleAlert as _E,Truck as DE,User as NE,VolumeX as FE,Wallet as $E,Zap as UE}from"lucide";var rb={user:NE,mail:uE,phone:wE,calendar:DM,clock:qM,building:_M,"map-pin":gE,lock:pE,key:lE,"credit-card":zM,hash:nE,globe:tE,link:dE,"circle-check":UM,"circle-x":jM,"triangle-alert":_E,info:aE,ban:WM,shield:PE,house:sE,"pen-line":vE,save:ME,share:TE,funnel:ZM,settings:EE,"rotate-cw":AE,"shopping-cart":LE,"shopping-bag":kE,package:yE,truck:DE,tag:OE,gift:eE,receipt:SE,wallet:$E,store:HE,"dollar-sign":VM,percent:CE,play:xE,pause:bE,"volume-x":FE,camera:FM,image:iE,film:YM,headphones:oE,"message-circle":mE,bell:OM,heart:rE,"eye-off":KM,bookmark:BM,"calendar-days":NM,timer:BE,folder:XM,"folder-open":JM,files:GM,"chart-column":$M,sparkles:RE,zap:UE,sun:WE,moon:hE,flag:QM,lightbulb:cE,monitor:fE,smartphone:IE};var It=(e,t=24,n="currentColor",o=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([p,u])=>{p!=="stroke"&&d.setAttribute(p,String(u))}),r.appendChild(d)}),r};var{setLoader:_H,load:jE}=ft({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")});var _c=jE;import{Activity as qE,ArrowDown as zE,ArrowLeft as VE,ArrowRight as KE,ArrowUp as GE,ArrowUpRight as YE,AtSign as QE,Bot as XE,Check as JE,ChevronDown as ZE,ChevronLeft as eT,ChevronRight as tT,ChevronUp as nT,Clipboard as oT,ClipboardCopy as rT,CodeXml as sT,Copy as iT,Download as aT,Ellipsis as lT,EllipsisVertical as cT,ExternalLink as dT,Eye as pT,File as uT,FileCode as gT,FileSpreadsheet as mT,FileText as fT,History as hT,ImagePlus as yT,Loader as bT,LoaderCircle as vT,Maximize as CT,Menu as wT,MessageSquare as xT,Mic as ST,Minimize as AT,Minus as MT,PanelLeft as ET,Paperclip as TT,Pencil as PT,Plus as kT,Quote as LT,RefreshCw as IT,Search as RT,Send as HT,ShieldAlert as WT,ShieldCheck as OT,ShieldX as BT,Square as _T,Star as DT,ThumbsDown as NT,ThumbsUp as FT,Trash as $T,Trash2 as UT,Upload as jT,Volume2 as qT,X as zT}from"lucide";var VT={activity:qE,"arrow-down":zE,"arrow-up":GE,"arrow-up-right":YE,bot:XE,"chevron-down":ZE,"chevron-up":nT,"chevron-right":tT,"chevron-left":eT,check:JE,clipboard:oT,"clipboard-copy":rT,"code-xml":sT,copy:iT,file:uT,"file-code":gT,"file-spreadsheet":mT,"file-text":fT,"image-plus":yT,loader:bT,"loader-circle":vT,mic:ST,paperclip:TT,quote:LT,"refresh-cw":IT,search:RT,send:HT,"shield-alert":WT,"shield-check":OT,"shield-x":BT,square:_T,"thumbs-down":NT,"thumbs-up":FT,upload:jT,"volume-2":qT,x:zT,"at-sign":QE,"arrow-left":VE,"arrow-right":KE,"external-link":dT,ellipsis:lT,"ellipsis-vertical":cT,menu:wT,"panel-left":ET,plus:kT,minus:MT,pencil:PT,trash:$T,"trash-2":UT,download:aT,maximize:CT,minimize:AT,"message-square":xT,star:DT,eye:pT,history:hT},KT=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],ws=new Map(Object.entries(VT)),fi=new Set,hi=!1,Dc=new Set,ng=e=>{let t=[...Dc];e&&Dc.clear();for(let n of t)try{n()}catch{}},sb=e=>hi?()=>{}:(Dc.add(e),()=>{Dc.delete(e)}),og=()=>{let e=0;for(let t of[...fi]){let n=ws.get(t.name);if(!n)continue;fi.delete(t),e++;let o=It(n,t.size,t.color,t.strokeWidth);if(o)for(t.el.removeAttribute("data-persona-icon-pending");o.firstChild;)t.el.appendChild(o.firstChild)}return e},GT=e=>{for(let[t,n]of Object.entries(e))ws.set(t,n);og()>0&&!hi&&ng(!1)},ib=e=>{if(!hi){for(let[t,n]of Object.entries(e))ws.has(t)||ws.set(t,n);hi=!0,og(),ng(!0)}},tg=!1,YT=()=>{_c().then(e=>{if(!hi){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))ws.has(t)||ws.set(t,n);hi=!0,og(),ng(!0)}}).catch(e=>{tg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},QT=(e,t,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},le=(e,t=24,n="currentColor",o=2)=>{let r=ws.get(e);if(r)return It(r,t,n,o);if(KT.includes(e)){tg&&(tg=!1);let s=QT(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}),YT(),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};ib(rb);function ab(e,t){let n=e.voiceRecognition,o=t.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function In(e){return e?.type==="runtype"||e?.type==="custom"}var XT=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function lb(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:XT()}catch{return!1}}var JT=e=>{if(!e)return;let t={},n=e;if(n.heading){let o=n.heading;t.heading=(r,s,a)=>o({type:"heading",raw:a,depth:s,text:r,tokens:[]})}if(n.code){let o=n.code;t.code=(r,s,a)=>o({type:"code",raw:"",text:r,lang:s,escaped:a})}if(n.blockquote){let o=n.blockquote;t.blockquote=r=>o({type:"blockquote",raw:"",text:r,tokens:[]})}if(n.table){let o=n.table;t.table=(r,s)=>o({type:"table",raw:"",header:[],rows:[],align:[],headerHtml:r,bodyHtml:s})}if(n.link){let o=n.link;t.link=(r,s,a)=>o({type:"link",raw:"",href:r,title:s??null,text:a,tokens:[]})}if(n.image){let o=n.image;t.image=(r,s,a)=>o({type:"image",raw:"",href:r,title:s??null,text:a})}if(n.list){let o=n.list;t.list=(r,s,a)=>o({type:"list",raw:"",ordered:s,start:a,loose:!1,items:[],itemsHtml:r})}if(n.listitem){let o=n.listitem;t.listitem=(r,s,a)=>o({type:"list_item",raw:"",task:s,checked:a,loose:!1,text:r,tokens:[]})}if(n.paragraph){let o=n.paragraph;t.paragraph=r=>o({type:"paragraph",raw:"",text:r,tokens:[]})}if(n.codespan){let o=n.codespan;t.codespan=r=>o({type:"codespan",raw:"",text:r})}if(n.strong){let o=n.strong;t.strong=r=>o({type:"strong",raw:"",text:r,tokens:[]})}if(n.em){let o=n.em;t.em=r=>o({type:"em",raw:"",text:r,tokens:[]})}if(n.del){let o=n.del;t.del=r=>o({type:"del",raw:"",text:r,tokens:[]})}if(n.html){let o=n.html;t.html=r=>o({type:"html",raw:r,text:r})}if(n.text){let o=n.text;t.text=r=>o({type:"text",raw:r,text:r})}if(n.checkbox){let o=n.checkbox;t.checkbox=r=>o({checked:r})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},Nc=e=>{let t=null;return n=>{let o=Ro();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=JT(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Fc=e=>e?Nc({markedOptions:e.options,renderer:e.renderer}):Nc(),ZT=Nc(),db=e=>ZT(e),Ir=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),pb=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),cb=e=>`%%FORM_PLACEHOLDER_${e}%%`,ub=(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=cb(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=cb(t.length);return t.push({token:s,type:r}),s}),n},eP=e=>{let t=Fc(e);return n=>{let o=[],r=ub(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="${pb(l)}"></div>`;s=s.replace(d,u)}),s}},tP=e=>{let t=[],n=ub(e,t),o=db(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="${pb(s)}"></div>`;o=o.replace(a,d)}),o};var nP={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"]},oP=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,gb=()=>{let e=null;return t=>{let n=Ro();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:")&&!oP.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,nP)}},rg=e=>e===!1?null:typeof e=="function"?e:gb();var mb=/^\s*\|?[\s:|-]*-[\s:|-]*$/,fb=e=>e.includes("|"),hb=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())},rP=e=>`| ${e.join(" | ")} |`,sP=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,iP=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),yb=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(!
|
|
3
|
-
`):e};var bb="var(--persona-md-table-scroll-fade, 24px)",vb=new WeakSet;function wb(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 Cb(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":bb),e.style.setProperty("--persona-fade-r",r<=1?"0px":bb)}function sg(e){vb.has(e)||(vb.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Cb(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Cb)}var $c="webmcp:",ig=new Map,Uc=e=>{ig.clear();for(let t of e){let n=t.title?.trim();n&&ig.set(t.name,n)}},yi=e=>ig.get(Mb(e)),xb=null;function Ab(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}:${aP(t.join(""))}`}function Sb(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 aP(e){let t=Sb(e,0).toString(36),n=Sb(e,2654435761).toString(36);return`${t}.${n}`}var Mb=e=>e.startsWith($c)?e.slice($c.length):e,xs=e=>e.startsWith($c),jc=()=>xb?xb():import("@mcp-b/webmcp-polyfill");var{setLoader:tW,load:lP}=ft({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var Eb=lP;function Un(e){return e==="card"?"collapsed":e}function Ss(e){return e.split(";",1)[0].trim().toLowerCase()}function cP(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Ss(r)===t)return{mode:Un(s),selector:Ss(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ss(r)===o)return{mode:Un(s),selector:o}}function Tb(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:Un(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Ss(t.file.mimeType):void 0,d=l?cP(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 Tb(e,t).mode}function Ba(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var dP="agent_",pP="flow_";function Pb(e){return e.startsWith(dP)?{kind:"agentId",agentId:e}:e.startsWith(pP)?{kind:"flowId",flowId:e}:null}function kb(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=Pb(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=Pb(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 uP(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function _a(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function As(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Lb(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}import{parse as gP,ARR as mP,OBJ as fP,STR as hP}from"partial-json";var E=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var G=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let l of Object.keys(a)){let d=a[l];d!=null&&(s[l]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},gn=(...e)=>e.filter(Boolean).join(" ");var qc="ask_user_question",Da=8,bi="data-persona-ask-sheet-for",yP="Other",bP="Other\u2026",Rb="Type your own answer here",Hb="Send",vP="Next",CP="Back",wP="Submit all",xP="Skip",SP=3,ag="data-ask-current-index",lg="data-ask-question-count",Wb="data-ask-answers",cg="data-ask-grouped",Ob="data-ask-layout",AP=e=>e.layout==="pills"?"pills":"rows",MP=e=>e.getAttribute(Ob)==="pills"?"pills":"rows",Ib=!1,Bb=e=>e.replace(/["\\]/g,"\\$&"),Rr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===qc,zc=e=>e?.features?.askUserQuestion??{},Hr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=gP(r,hP|fP|mP);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Na=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Da&&!Ib&&(Ib=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Da}.`)),t.slice(0,Da)},EP=e=>Na(e)[0]??null,TP=(e,t)=>Na(e)[t]??null,_b=(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))},Db=(e,t,n)=>{if(e!=="rows")return null;let o=E("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=E("span","persona-ask-row-check");o.appendChild(r)}else{let r=E("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},PP=(e,t,n,o)=>{let s=E("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=E("span","persona-ask-row-content"),l=E("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let p=E("span","persona-ask-row-description");p.textContent=e.description,a.appendChild(p)}s.appendChild(a);let d=Db(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},kP=e=>{let n=E("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},LP=(e,t,n,o)=>{let s=E("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,d=(Array.isArray(e?.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<SP;u++)s.appendChild(kP(o));return s}if(d.forEach((u,m)=>{s.appendChild(PP(u,m,o,a))}),e?.allowFreeText!==!1){let u=o==="rows"?yP:bP;if(o==="rows"){let m=E("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(d.length)),m.setAttribute("data-ask-other-row","true");let y=E("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=t.freeTextPlaceholder??Rb,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??u),y.appendChild(h),m.appendChild(y);let C=Db(o,a,d.length);C&&m.appendChild(C),s.appendChild(m)}else{let m=E("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=t.freeTextLabel??u,s.appendChild(m)}}return s},Nb=(e,t)=>{let o=E("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Rb,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=E("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Hb,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},IP=e=>{let t=E("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=E("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Hb,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},RP=(e,t,n)=>{let o=E("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=E("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??CP,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=E("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=E("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??xP,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=E("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=e===t-1;return l.textContent=d?n.submitAllLabel??wP:n.nextLabel??vP,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ms=e=>{let t=e.getAttribute(Wb);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Fb=(e,t)=>{e.setAttribute(Wb,JSON.stringify(t))},no=e=>{let t=Number(e.getAttribute(ag)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},HP=(e,t)=>{e.setAttribute(ag,String(Math.max(0,Math.floor(t))))},vi=e=>{let t=Number(e.getAttribute(lg)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Wr=e=>e.getAttribute(cg)==="true",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},OP=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Vc=(e,t)=>{let{payload:n}=Hr(t),o=Na(n),r=Ms(e),s={},a=new Set;return o.forEach((l,d)=>{let p=typeof l?.question=="string"?l.question:"";p&&(a.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),a.add(p),Object.prototype.hasOwnProperty.call(r,d)&&(s[p]=r[d]))}),s},$b=e=>{let t=Ms(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="")},Ub=e=>{if(!Wr(e))return;let t=Ms(e),n=no(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},dg=(e,t,n)=>{let o=zc(n),r=MP(e),{payload:s,complete:a}=Hr(t),l=Wr(e),d=no(e),p=vi(e),u=l?TP(s,d):EP(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 I=typeof u?.question=="string"?u.question:"";C.textContent=I,C.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let w=e.querySelector('[data-ask-pill-list="true"]');if(w){let I=LP(u,o,a,r);w.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(Nb(o,r))}let S=e.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!S?e.appendChild(IP(o)):(!m||l)&&S&&S.remove(),e.setAttribute("data-multi-select",m?"true":"false");let P=e.querySelector('[data-ask-nav-row="true"]');if(l){let I=RP(d,p,o);P?P.replaceWith(I):e.appendChild(I)}else P&&P.remove();$b(e),Ub(e)},BP=(e,t,n)=>{let o=zc(t),r=AP(o),s=e.toolCall.id,a=Na(n),l=Math.max(1,a.length),d=l>1,p=WP(e,a),u=d?OP(e,l):0,m=E("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(bi,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",e.id),m.setAttribute(lg,String(l)),m.setAttribute(ag,String(u)),m.setAttribute(cg,d?"true":"false"),m.setAttribute(Ob,r),Fb(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`),_b(m,o);let y=E("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=E("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",y.appendChild(h);let C=E("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",y.appendChild(C),m.appendChild(y);let S=E("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),m.appendChild(S),r!=="rows"&&m.appendChild(Nb(o,r)),dg(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},_P=(e,t,n)=>{let{payload:o}=Hr(t),r=Math.max(1,Na(o).length);r>vi(e)&&(e.setAttribute(lg,String(r)),r>1&&!Wr(e)&&e.setAttribute(cg,"true")),dg(e,t,n)},DP=(e,t)=>{let n=E("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=zc(t);_b(n,o);let r=E("span","persona-ask-stub-label"),{complete:s}=Hr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Fa=(e,t,n)=>{if(!n||!Rr(e)||zc(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${bi}]`).forEach(p=>{p.getAttribute(bi)!==r&&p.remove()});let a=n.querySelector(`[${bi}="${Bb(r)}"]`);if(a){_P(a,e,t);return}let{payload:l}=Hr(e),d=BP(e,t,l);n.appendChild(d)},Es=(e,t)=>{if(!e)return;let n=t?`[${bi}="${Bb(t)}"]`:`[${bi}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},pg=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Or=(e,t)=>{let n=Ms(e),o=no(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Fb(e,n),$b(e),Ub(e)},Kc=(e,t,n,o)=>{let r=vi(e),s=Math.max(0,Math.min(r-1,o));HP(e,s),dg(e,t,n)};var ir="suggest_replies";var qb={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},ug={name:ir,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:qb,origin:"sdk",annotations:{readOnlyHint:!0}},zb=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ci=e=>e.variant==="tool"&&e.toolCall?.name===ir,Vb=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},gg=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ci(n))continue;let o=Vb(n.toolCall?.args);return o.length>0?o:null}return null},jb=new Set,NP=(e,t,n)=>{let o=`${e}:${t}:${n}`;jb.has(o)||(jb.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&&NP(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 Kb={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Da,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Gb={name:qc,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Kb,origin:"sdk",annotations:{readOnlyHint:!0}},$a=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Gb),Br(e).expose&&t.push(ug),t};var FP=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),$P=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),UP=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=FP(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:$P(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},mg=(e,t)=>{let n=[],o=[],r=[],s="",a,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let d of e){let p=UP(d);if(p){let m=d.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(m===void 0||m!==a)&&l(),o.length===0&&(s=d.createdAt,a=m),o.some(y=>y.toolCallId===p.call.toolCallId)||(o.push(p.call),r.push(p.result));continue}let u=t(d);u&&(l(),n.push(u))}return l(),n};import{parse as Yb,STR as Qb,OBJ as Xb}from"partial-json";var Gc=e=>e.replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")
|
|
1
|
+
var kE=Object.defineProperty;var Qa=(e,t)=>()=>(e&&(t=e(e=0)),t);var Yb=(e,t)=>{for(var n in t)kE(e,n,{get:t[n],enumerable:!0})};var Qb={};Yb(Qb,{DOMPurify:()=>IE,Marked:()=>LE});import{Marked as LE}from"marked";import IE from"dompurify";var Xb=Qa(()=>{"use strict"});var qi,vm=Qa(()=>{"use strict";qi=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 O0(e){return e.replace(/\/+$/,"")}async function B0(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 Pd,IC=Qa(()=>{"use strict";vm();Pd=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 qi(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=`${O0(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 B0(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 kd,RC=Qa(()=>{"use strict";kd=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 HC={};Yb(HC,{FallbackSpeechEngine:()=>kd,RuntypeSpeechEngine:()=>Pd});var WC=Qa(()=>{"use strict";IC();RC()});import{Marked as WE}from"marked";import OE from"dompurify";var vt=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:u=>{o=u,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(m=>(r=m,m)).catch(m=>{throw s=null,m}),s),provide:u=>{r=u},getSync:()=>r}};var{setLoader:tO,load:RE,provide:HE,getSync:Rg}=vt({fallbackImport:()=>Promise.resolve().then(()=>(Xb(),Qb))}),td=new Set,Jb=()=>{let e=[...td];td.clear();for(let t of e)try{t()}catch{}};var Hg=()=>{let e=Rg();return e?Promise.resolve(e):RE().then(t=>(Jb(),t))},Xa=e=>Rg()?()=>{}:(td.add(e),()=>{td.delete(e)}),Zb=e=>{HE(e),Jb()},Bo=Rg;Zb({Marked:WE,DOMPurify:OE});import{Ban as BE,Bell as DE,Bookmark as _E,Building as NE,Calendar as FE,CalendarDays as $E,Camera as UE,ChartColumn as jE,CircleCheck as VE,CircleX as qE,Clock as zE,CreditCard as KE,DollarSign as GE,EyeOff as YE,Files as QE,Film as XE,Flag as JE,Folder as ZE,FolderOpen as eT,Funnel as tT,Gift as nT,Globe as oT,Hash as rT,Headphones as sT,Heart as iT,House as aT,Image as lT,Info as cT,Key as dT,Lightbulb as pT,Link as uT,Lock as gT,Mail as mT,MapPin as fT,MessageCircle as hT,Monitor as yT,Moon as bT,Package as vT,Pause as CT,PenLine as wT,Percent as xT,Phone as ST,Play as AT,Receipt as MT,RotateCw as ET,Save as TT,Settings as PT,Share as kT,Shield as LT,ShoppingBag as IT,ShoppingCart as RT,Smartphone as HT,Sparkles as WT,Store as OT,Sun as BT,Tag as DT,Timer as _T,TriangleAlert as NT,Truck as FT,User as $T,VolumeX as UT,Wallet as jT,Zap as VT}from"lucide";var ev={user:$T,mail:mT,phone:ST,calendar:FE,clock:zE,building:NE,"map-pin":fT,lock:gT,key:dT,"credit-card":KE,hash:rT,globe:oT,link:uT,"circle-check":VE,"circle-x":qE,"triangle-alert":NT,info:cT,ban:BE,shield:LT,house:aT,"pen-line":wT,save:TT,share:kT,funnel:tT,settings:PT,"rotate-cw":ET,"shopping-cart":RT,"shopping-bag":IT,package:vT,truck:FT,tag:DT,gift:nT,receipt:MT,wallet:jT,store:OT,"dollar-sign":GE,percent:xT,play:AT,pause:CT,"volume-x":UT,camera:UE,image:lT,film:XE,headphones:sT,"message-circle":hT,bell:DE,heart:iT,"eye-off":YE,bookmark:_E,"calendar-days":$E,timer:_T,folder:ZE,"folder-open":eT,files:QE,"chart-column":jE,sparkles:WT,zap:VT,sun:BT,moon:bT,flag:JE,lightbulb:pT,monitor:yT,smartphone:HT};var St=(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:dO,load:qT}=vt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")});var nd=qT;import{Activity as zT,ArrowDown as KT,ArrowLeft as GT,ArrowRight as YT,ArrowUp as QT,ArrowUpRight as XT,AtSign as JT,Bot as ZT,Check as eP,ChevronDown as tP,ChevronLeft as nP,ChevronRight as oP,ChevronUp as rP,Clipboard as sP,ClipboardCopy as iP,CodeXml as aP,Copy as lP,Download as cP,Ellipsis as dP,EllipsisVertical as pP,ExternalLink as uP,Eye as gP,File as mP,FileCode as fP,FileSpreadsheet as hP,FileText as yP,History as bP,ImagePlus as vP,Loader as CP,LoaderCircle as wP,Maximize as xP,Menu as SP,MessageSquare as AP,Mic as MP,Minimize as EP,Minus as TP,PanelLeft as PP,Paperclip as kP,Pencil as LP,Plus as IP,Quote as RP,RefreshCw as HP,Search as WP,Send as OP,ShieldAlert as BP,ShieldCheck as DP,ShieldX as _P,Square as NP,Star as FP,ThumbsDown as $P,ThumbsUp as UP,Trash as jP,Trash2 as VP,Upload as qP,Volume2 as zP,X as KP}from"lucide";var GP={activity:zT,"arrow-down":KT,"arrow-up":QT,"arrow-up-right":XT,bot:ZT,"chevron-down":tP,"chevron-up":rP,"chevron-right":oP,"chevron-left":nP,check:eP,clipboard:sP,"clipboard-copy":iP,"code-xml":aP,copy:lP,file:mP,"file-code":fP,"file-spreadsheet":hP,"file-text":yP,"image-plus":vP,loader:CP,"loader-circle":wP,mic:MP,paperclip:kP,quote:RP,"refresh-cw":HP,search:WP,send:OP,"shield-alert":BP,"shield-check":DP,"shield-x":_P,square:NP,"thumbs-down":$P,"thumbs-up":UP,upload:qP,"volume-2":zP,x:KP,"at-sign":JT,"arrow-left":GT,"arrow-right":YT,"external-link":uP,ellipsis:dP,"ellipsis-vertical":pP,menu:SP,"panel-left":PP,plus:IP,minus:TP,pencil:LP,trash:jP,"trash-2":VP,download:cP,maximize:xP,minimize:EP,"message-square":AP,star:FP,eye:gP,history:bP},YP=["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"],Bs=new Map(Object.entries(GP)),Hi=new Set,Wi=!1,od=new Set,Og=e=>{let t=[...od];e&&od.clear();for(let n of t)try{n()}catch{}},tv=e=>Wi?()=>{}:(od.add(e),()=>{od.delete(e)}),Bg=()=>{let e=0;for(let t of[...Hi]){let n=Bs.get(t.name);if(!n)continue;Hi.delete(t),e++;let o=St(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},QP=e=>{for(let[t,n]of Object.entries(e))Bs.set(t,n);Bg()>0&&!Wi&&Og(!1)},nv=e=>{if(!Wi){for(let[t,n]of Object.entries(e))Bs.has(t)||Bs.set(t,n);Wi=!0,Bg(),Og(!0)}},Wg=!1,XP=()=>{nd().then(e=>{if(!Wi){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))Bs.has(t)||Bs.set(t,n);Wi=!0,Bg(),Og(!0)}}).catch(e=>{Wg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},JP=(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},ae=(e,t=24,n="currentColor",o=2)=>{let r=Bs.get(e);if(r)return St(r,t,n,o);if(YP.includes(e)){Wg&&(Wg=!1);let s=JP(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}),XP(),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};nv(ev);import{Circle as uk,Clock as gk}from"lucide";var ov=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ho(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];ov(s)&&ov(r)?n[o]=ho(s,r):n[o]=r}return n}var Dg=Symbol("persona.defaultsProvenance"),_g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function rd(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return _g(o)?rd(o,r):[r]})}function rv(e,t){for(let n of t.split(".")){if(!_g(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function sv(e,t){return e?.[Dg]??t.filter(n=>rv(e,n)==="explicit")}function Ng(e,t){return Object.defineProperty(e,Dg,{value:t,enumerable:!0,configurable:!0}),e}function Fg(e,t,n){return Ng(e,sv(t,rd(n)))}function iv(e,t,n){let o=t[Dg];if(o)return o;let r=new Set(sv(e,n));for(let s of n){let a=rv(t,s);a==="clear"&&r.delete(s),a==="explicit"&&r.add(s)}return[...r]}function av(e,t,n){let o={...e};for(let r of t){if(n.includes(r))continue;let s=r.split("."),a=o;for(let l of s.slice(0,-1)){let d=a[l];if(!_g(d)){a=void 0;break}a[l]={...d},a=a[l]}a&&delete a[s[s.length-1]]}return o}var lv="var(--persona-components-panel-width)",$g=Symbol("persona.panelAliasProvenance"),Ds=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),sd=(e,t)=>Ds(e,t)&&e[t]!==void 0,ZP=e=>({launcherWidth:sd(e?.launcher,"width"),legacyLauncherWidth:sd(e,"launcherWidth"),sidebarWidth:sd(e?.launcher,"sidebarWidth"),dockWidth:sd(e?.launcher?.dock,"width")}),cr=e=>{let t=e?.[$g];return t?{...t}:ZP(e)},Ug=(e,t)=>(Object.defineProperty(e,$g,{value:t,enumerable:!0,configurable:!0}),e),jg=(e,t)=>Ug(e,cr(t)),cv=(e,t)=>{let n=t[$g];if(n)return{...n};let o=cr(e);return Ds(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),Ds(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(Ds(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),Ds(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),Ds(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:Ds(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)};var Oi="min(440px, calc(100vw - 24px))",ek="440px",el="40px",Vg="How can I help...",dr={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},Ns={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},tk={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:Oi,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:el,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)"},nk={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:tk,copy:{inputPlaceholder:Vg,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:dr,reasoningDisplay:Ns,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},ok={},rk={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},_s={launcher:rk,features:{toolCallDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,grouped:!0,groupedMode:"collapsible",loadingAnimation:"shimmer"},reasoningDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,loadingAnimation:"shimmer"}},composer:{layout:"single-row",placement:"overlay"},sendButton:{iconName:"arrow-up"},statusIndicator:{mode:"transient"},layout:{contentMaxWidth:"768px",topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:"full"}}}};function Ur(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function pv(e){let t=Ur(e)==="v5"?_s:ok;return ho(nk,t)}var sk=pv();function dv(e,t){if(!(!e&&!t))return e?t?ho(e,t):e:t}function tl(e){let t=pv(e);return e?Fg(jg({...t,...e,theme:dv(t.theme,e.theme),darkTheme:dv(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let n=t.features?.artifacts,o=e.features?.artifacts,r=t.features?.scrollToBottom,s=e.features?.scrollToBottom,a=t.features?.scrollBehavior,l=e.features?.scrollBehavior,d=t.features?.streamAnimation,p=e.features?.streamAnimation,u=t.features?.askUserQuestion,m=e.features?.askUserQuestion,h=t.features?.history,y=e.features?.history,v=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},C=r===void 0&&s===void 0?void 0:{...r,...s},x=a===void 0&&l===void 0?void 0:{...a,...l},E=d===void 0&&p===void 0?void 0:{...d,...p},H=u===void 0&&m===void 0?void 0:{...u,...m,styles:{...u?.styles,...m?.styles}},B=h===void 0&&y===void 0?void 0:{...h,...y,copy:{...h?.copy,...y?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...C!==void 0?{scrollToBottom:C}:{},...x!==void 0?{scrollBehavior:x}:{},...v!==void 0?{artifacts:v}:{},...E!==void 0?{streamAnimation:E}:{},...H!==void 0?{askUserQuestion:H}:{},...B!==void 0?{history:B}:{}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,_s):Fg(jg(t),void 0,_s)}var S=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var G=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let l of Object.keys(a)){let d=a[l];d!=null&&(s[l]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},fn=(...e)=>e.filter(Boolean).join(" ");import{ChevronDown as ik,ChevronUp as ak}from"lucide";var lk=["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"],ck="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",dk="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",pk=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),id=(e,t)=>{let n=S("div",["persona-message-bubble",e,...lk].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},ad=e=>{let t=S("button",e.expandable?ck:dk);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},qg=(e,t,n)=>{e.innerHTML="";let o=St(t?ak:ik,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},Bi=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=S("div","persona-flex persona-items-center");qg(o,n.expanded,n.iconColor);let r=S("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},ld=e=>{let t=S("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?.();pk(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},cd=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&qg(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"},dd=(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&&qg(d,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};function pd(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?dr:Ns,...e?.future?.v5Defaults===!0?_s.features?.[n]:{},...e?.features?.[n]}}}}function jr(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function nl(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?"a moment":t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function pr(e,t,n,o){if(jr(n,o)!=="row")return e;e.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,e.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=e.querySelector(":scope > button");if(!r)return e;r.className="persona-activity-header";let s=o==="tool"?t.toolCall:t.reasoning,a=s?.status!=="complete",l=t.approval?.status??t.toolCall?.approvalStatus,d=l==="denied"?"denied":l==="pending"?"awaiting-approval":t.toolCall?.success===!1?"error":a?s?.status==="pending"?"pending":"running":"done";e.dataset.activityState=d;let p=S("span","persona-activity-icon");p.dataset.activityIcon=d;let u={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},m=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,h=m?ae(m,16,"currentColor",2):d==="pending"?St(uk,16,"currentColor",2):d==="awaiting-approval"?St(gk,16,"currentColor",2):ae(u[d],16,"currentColor",2);h&&p.appendChild(h),r.querySelector(".persona-reasoning-header-icon")?.remove();let y=o==="tool"?"toolCallDisplay":"reasoningDisplay",v=n.features?.[y]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((v==="always"||v==="active"&&d!=="done")&&r.prepend(p),o==="tool"&&s){let H=S("span","persona-activity-duration");a&&s.startedAt&&H.setAttribute("data-tool-elapsed",String(s.startedAt));let B=(o==="tool"?t.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);H.textContent=B===void 0?"":nl(B),r.appendChild(H)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let E=e.querySelector(":scope > .persona-border-t");return E?.classList.add("persona-activity-body"),E&&(E.id=`activity-details-${t.id}`,r.setAttribute("aria-controls",E.id)),e}function uv(e){let t=new Set,n=new Set,o=new Set,r=new Map,s=a=>{clearTimeout(r.get(a)),r.delete(a)};return{observe(a,l,d,p={}){let u=l==="tool"?a.toolCall:a.reasoning;if(!(!u||n.has(a.id))&&(!t.has(a.id)&&u.status!=="complete"&&u.chunks?.some(Boolean)&&(t.add(a.id),p.autoExpand!==!1&&d.add(a.id)),t.has(a.id)&&u.status==="complete"&&!o.has(a.id))){if(o.add(a.id),p.autoCollapseDelay===!1)return;r.set(a.id,setTimeout(()=>{r.delete(a.id),d.delete(a.id),e(a.id,l)},p.autoCollapseDelay??1e3))}},manual(a){n.add(a),s(a)},prune(a){for(let l of new Set([...t,...n,...o]))a.has(l)||(s(l),t.delete(l),n.delete(l),o.delete(l))},clear(){for(let a of r.keys())s(a);t.clear(),n.clear(),o.clear()}}}function gv(e,t,n,o){let r=S("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let s=S("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let a=S("div","");typeof o=="string"?a.textContent=o:a.appendChild(o),Bi(s,a,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=S("div","persona-border-t");return l.id=`activity-details-${e.id}`,l.style.display=n?"":"none",s.setAttribute("aria-controls",l.id),r.append(s,l),pr(r,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",t.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:l}}var mk=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),Fs=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=mk(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},zg=(e,t,n)=>{!t.parentElement||e.parentElement!==t.parentElement||(n.mode==="transient"?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))};function mv(e,t){let n=e.voiceRecognition,o=t.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||e.agentId!==t.agentId||e.clientToken!==t.clientToken||e.apiUrl!==t.apiUrl}function Ln(e){return e?.type==="runtype"||e?.type==="custom"}var fk=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function fv(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:fk()}catch{return!1}}var hk=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},ud=e=>{let t=null;return n=>{let o=Bo();if(!o)return Vr(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=hk(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},gd=e=>e?ud({markedOptions:e.options,renderer:e.renderer}):ud(),yk=ud(),yv=e=>yk(e),Vr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),bv=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),hv=e=>`%%FORM_PLACEHOLDER_${e}%%`,vv=(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=hv(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=hv(t.length);return t.push({token:s,type:r}),s}),n},bk=e=>{let t=gd(e);return n=>{let o=[],r=vv(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="${bv(l)}"></div>`;s=s.replace(d,u)}),s}},vk=e=>{let t=[],n=vv(e,t),o=yv(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="${bv(s)}"></div>`;o=o.replace(a,d)}),o};var Ck={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"]},wk=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Cv=()=>{let e=null;return t=>{let n=Bo();if(!n)return Vr(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:")&&!wk.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Ck)}},Kg=e=>e===!1?null:typeof e=="function"?e:Cv();var wv=/^\s*\|?[\s:|-]*-[\s:|-]*$/,xv=e=>e.includes("|"),Sv=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())},xk=e=>`| ${e.join(" | ")} |`,Sk=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Ak=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Av=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(!xv(r)||wv.test(r)||!wv.test(s))continue;let a=Sv(r).length;if(a<1)continue;let l=Sk(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()===""||!xv(p))break;let u=xk(Ak(Sv(p),a));t[d]!==u&&(t[d]=u,n=!0)}o=d-1}return n?t.join(`
|
|
3
|
+
`):e};var Mv="var(--persona-md-table-scroll-fade, 24px)",Ev=new WeakSet;function Pv(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 Tv(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":Mv),e.style.setProperty("--persona-fade-r",r<=1?"0px":Mv)}function Gg(e){Ev.has(e)||(Ev.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Tv(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Tv)}var md="webmcp:",Yg=new Map,fd=e=>{Yg.clear();for(let t of e){let n=t.title?.trim();n&&Yg.set(t.name,n)}},Di=e=>Yg.get(Rv(e)),kv=null;function Iv(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}:${Mk(t.join(""))}`}function Lv(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 Mk(e){let t=Lv(e,0).toString(36),n=Lv(e,2654435761).toString(36);return`${t}.${n}`}var Rv=e=>e.startsWith(md)?e.slice(md.length):e,$s=e=>e.startsWith(md),hd=()=>kv?kv():import("@mcp-b/webmcp-polyfill");var{setLoader:QO,load:Ek}=vt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var Hv=Ek;function $n(e){return e==="card"?"collapsed":e}function Us(e){return e.split(";",1)[0].trim().toLowerCase()}function Tk(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Us(r)===t)return{mode:$n(s),selector:Us(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Us(r)===o)return{mode:$n(s),selector:o}}function Wv(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:$n(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Us(t.file.mimeType):void 0,d=l?Tk(o.files.byMediaType,l):void 0;if(l&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:l,selector:d.selector}};if(o.files.default)return{mode:$n(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:$n(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:$n(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:$n(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:$n(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function ur(e,t){return Wv(e,t).mode}function ol(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 Pk="agent_",kk="flow_";function Ov(e){return e.startsWith(Pk)?{kind:"agentId",agentId:e}:e.startsWith(kk)?{kind:"flowId",flowId:e}:null}function Bv(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=Ov(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=Ov(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 Lk(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function rl(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function js(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Dv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}import{parse as Ik,ARR as Rk,OBJ as Hk,STR as Wk}from"partial-json";var yd="ask_user_question",sl=8,_i="data-persona-ask-sheet-for",Ok="Other",Bk="Other\u2026",Nv="Type your own answer here",Fv="Send",Dk="Next",_k="Back",Nk="Submit all",Fk="Skip",$k=3,Qg="data-ask-current-index",Xg="data-ask-question-count",$v="data-ask-answers",Jg="data-ask-grouped",Uv="data-ask-layout",Uk=e=>e.layout==="pills"?"pills":"rows",jk=e=>e.getAttribute(Uv)==="pills"?"pills":"rows",_v=!1,jv=e=>e.replace(/["\\]/g,"\\$&"),qr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===yd,bd=e=>e?.features?.askUserQuestion??{},zr=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=Ik(r,Wk|Hk|Rk);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},il=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>sl&&!_v&&(_v=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${sl}.`)),t.slice(0,sl)},Vk=e=>il(e)[0]??null,qk=(e,t)=>il(e)[t]??null,Vv=(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))},qv=(e,t,n)=>{if(e!=="rows")return null;let o=S("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=S("span","persona-ask-row-check");o.appendChild(r)}else{let r=S("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},zk=(e,t,n,o)=>{let s=S("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=S("span","persona-ask-row-content"),l=S("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let p=S("span","persona-ask-row-description");p.textContent=e.description,a.appendChild(p)}s.appendChild(a);let d=qv(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Kk=e=>{let n=S("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},Gk=(e,t,n,o)=>{let s=S("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<$k;u++)s.appendChild(Kk(o));return s}if(d.forEach((u,m)=>{s.appendChild(zk(u,m,o,a))}),e?.allowFreeText!==!1){let u=o==="rows"?Ok:Bk;if(o==="rows"){let m=S("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 h=S("span","persona-ask-row-content"),y=document.createElement("input");y.type="text",y.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",y.placeholder=t.freeTextPlaceholder??Nv,y.setAttribute("data-ask-free-text-input","true"),y.setAttribute("aria-label",t.freeTextLabel??u),h.appendChild(y),m.appendChild(h);let v=qv(o,a,d.length);v&&m.appendChild(v),s.appendChild(m)}else{let m=S("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},zv=(e,t)=>{let o=S("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??Nv,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=S("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Fv,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Yk=e=>{let t=S("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=S("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Fv,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Qk=(e,t,n)=>{let o=S("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=S("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??_k,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=S("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=S("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Fk,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=S("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=e===t-1;return l.textContent=d?n.submitAllLabel??Nk:n.nextLabel??Dk,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Vs=e=>{let t=e.getAttribute($v);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Kv=(e,t)=>{e.setAttribute($v,JSON.stringify(t))},so=e=>{let t=Number(e.getAttribute(Qg)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Xk=(e,t)=>{e.setAttribute(Qg,String(Math.max(0,Math.floor(t))))},Ni=e=>{let t=Number(e.getAttribute(Xg)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Kr=e=>e.getAttribute(Jg)==="true",Jk=(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},Zk=(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)))},vd=(e,t)=>{let{payload:n}=zr(t),o=il(n),r=Vs(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},Gv=e=>{let t=Vs(e),n=so(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="")},Yv=e=>{if(!Kr(e))return;let t=Vs(e),n=so(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}},Zg=(e,t,n)=>{let o=bd(n),r=jk(e),{payload:s,complete:a}=zr(t),l=Kr(e),d=so(e),p=Ni(e),u=l?qk(s,d):Vk(s),m=!!u?.multiSelect,h=e.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=l?`${d+1}/${p}`:"");let y=e.querySelector('[data-ask-stepper="true"]');y&&y.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let H=typeof u?.question=="string"?u.question:"";v.textContent=H,v.classList.toggle("persona-ask-question-skeleton",!H&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let H=Gk(u,o,a,r);C.replaceWith(H)}if(r!=="rows"){let H=e.querySelector('[data-ask-free-text-row="true"]');H&&H.replaceWith(zv(o,r))}let x=e.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!x?e.appendChild(Yk(o)):(!m||l)&&x&&x.remove(),e.setAttribute("data-multi-select",m?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(l){let H=Qk(d,p,o);E?E.replaceWith(H):e.appendChild(H)}else E&&E.remove();Gv(e),Yv(e)},e0=(e,t,n)=>{let o=bd(t),r=Uk(o),s=e.toolCall.id,a=il(n),l=Math.max(1,a.length),d=l>1,p=Jk(e,a),u=d?Zk(e,l):0,m=S("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(_i,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",e.id),m.setAttribute(Xg,String(l)),m.setAttribute(Qg,String(u)),m.setAttribute(Jg,d?"true":"false"),m.setAttribute(Uv,r),Kv(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`),Vv(m,o);let h=S("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),y=S("div","persona-ask-sheet-question persona-flex-1");y.setAttribute("data-ask-question","true"),y.textContent="",h.appendChild(y);let v=S("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",h.appendChild(v),m.appendChild(h);let x=S("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(zv(o,r)),Zg(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},t0=(e,t,n)=>{let{payload:o}=zr(t),r=Math.max(1,il(o).length);r>Ni(e)&&(e.setAttribute(Xg,String(r)),r>1&&!Kr(e)&&e.setAttribute(Jg,"true")),Zg(e,t,n)},n0=(e,t)=>{let n=S("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=bd(t);Vv(n,o);let r=S("span","persona-ask-stub-label"),{complete:s}=zr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},al=(e,t,n)=>{if(!n||!qr(e)||bd(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${_i}]`).forEach(p=>{p.getAttribute(_i)!==r&&p.remove()});let a=n.querySelector(`[${_i}="${jv(r)}"]`);if(a){t0(a,e,t);return}let{payload:l}=zr(e),d=e0(e,t,l);n.appendChild(d)},qs=(e,t)=>{if(!e)return;let n=t?`[${_i}="${jv(t)}"]`:`[${_i}]`;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)})},em=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),Gr=(e,t)=>{let n=Vs(e),o=so(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Kv(e,n),Gv(e),Yv(e)},Cd=(e,t,n,o)=>{let r=Ni(e),s=Math.max(0,Math.min(r-1,o));Xk(e,s),Zg(e,t,n)};var gr="suggest_replies";var Xv={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},tm={name:gr,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:Xv,origin:"sdk",annotations:{readOnlyHint:!0}},Jv=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Fi=e=>e.variant==="tool"&&e.toolCall?.name===gr,Zv=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},nm=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Fi(n))continue;let o=Zv(n.toolCall?.args);return o.length>0?o:null}return null},Qv=new Set,o0=(e,t,n)=>{let o=`${e}:${t}:${n}`;Qv.has(o)||(Qv.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Yr=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&&o0(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 eC={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:sl,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},tC={name:yd,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:eC,origin:"sdk",annotations:{readOnlyHint:!0}},ll=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(tC),Yr(e).expose&&t.push(tm),t};var r0=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),s0=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),i0=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=r0(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:s0(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},om=(e,t)=>{let n=[],o=[],r=[],s="",a,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let d of e){let p=i0(d);if(p){let m=d.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(m===void 0||m!==a)&&l(),o.length===0&&(s=d.createdAt,a=m),o.some(h=>h.toolCallId===p.call.toolCallId)||(o.push(p.call),r.push(p.result));continue}let u=t(d);u&&(l(),n.push(u))}return l(),n};import{parse as nC,STR as oC,OBJ as rC}from"partial-json";var wd=e=>e.replace(/\\n/g,`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),$i=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)}},a0=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`},sC=e=>e.status==="complete"?a0(e):e.status==="pending"?"Waiting":"",l0=15e3,c0=1200,iC=(e,t)=>{let n=t?.durationMs??l0,o=t?.chars??c0;return typeof e.durationMs=="number"?e.durationMs<n:(e.chunks??[]).join("").length<o},d0=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 aC=e=>e.status==="complete"?d0(e):"Using tool...",xd=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},dl=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 xd(t)},Sd=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return xd(t)},rm=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=dl(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Ad=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&cl(o,n.slice(s,a.index),[]),a[1]!==void 0?cl(o,a[1],["bold"]):a[2]!==void 0?cl(o,a[2],["italic"]):a[3]!==void 0&&cl(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&cl(o,n.slice(s),[]),o},cl=(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})},p0=()=>{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()=>{}}},qa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},hg=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},yg=()=>{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)}},bg=()=>{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=Yb(n,Qb|Xb);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Gc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Gc(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},GP=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=l=>typeof l=="string"?Gc(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Gc(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let l=Yb(s,Qb|Xb),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},vg=()=>{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 tv="4.23.2";var Ho=tv;var wi="[Image]";function QP(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Cg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function za(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function XP(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function fo(e){return{type:"text",text:e}}function wg(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function JP(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 ZP(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 nv=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ek=["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=[...nv,...ek];function tk(e){return nv.includes(e)||e.startsWith("image/")}function Zc(e){return tk(e.type)}function ov(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function rv(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Zc(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function sv(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 nk(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function iv(e,t){let n=nk(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 ok=["user","assistant","system"],rk=0;function av(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function ed(e){return typeof e=="string"?e:void 0}function sk(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"?wg(t.image,{mimeType:ed(t.mimeType),alt:ed(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?ov(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...ed(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...ed(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function ik(e,t){let n=av(t),o=e.map(a=>av(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:rk+y;s=l+1}return r.map(a=>new Date(a).toISOString())}function lv(e,t){let n=ik(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!ok.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(sk).filter(u=>u!==null),p=Cg(d);o.push({id:r.id,role:a,content:p||(za(d)?wi:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Va(e){let t=e.content;if(typeof t!="string"||t==="")return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof n=="string"&&n===t))return t}function Ka(e,t){let n=new Map;for(let o of e)n.set(o.id,o);for(let o of t)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),a=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(a)&&s!==a)return s-a;let l=o.sequence??0,d=r.sequence??0;return l!==d?l-d:o.id.localeCompare(r.id)})}var ak="https://api.runtype.com/v1/dispatch",cv="https://api.runtype.com",Ne=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},dv=32768,xg=49152,pv=e=>{let t=e??{},n=typeof t.targetId=="string"?t.targetId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:n,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},uv=e=>"reason"in e?e.reason:void 0,gv="The identity proof was not admitted; account history is unavailable",mv="The identity proof was rejected",fv="The request carried no visitor credential",hv="The stored visitor belongs to a different signed-in user",Sg=(e,t)=>e instanceof Ne&&e.code===t;function lk(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 Ag=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),yv=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),bv=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function ck(e){switch(e){case"json":return bg;case"regex-json":return yg;case"xml":return vg;default:return hg}}var vv=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function dk(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=vv(n);if(!vv(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=qa(e);return qa(t)!==null&&a===null?t:e}var xi=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??ak,this.headers={"Content-Type":"application/json","X-Persona-Version":Ho,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??ck(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 Eb().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Uc,getToolDisplayTitle:yi,loadPolyfill:jc});return this.pendingWebMcpConfirmHandler!==void 0&&o.setConfirmHandler(this.pendingWebMcpConfirmHandler),this.webMcpBridge=o,o}).catch(n=>(this.webMcpBridgePromise=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}getWebMcpBridge(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.webMcpBridgePromise||(this.webMcpBridgePromise=this.createWebMcpBridge(this.config.webmcp)),this.webMcpBridgePromise)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.pendingWebMcpConfirmHandler=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.getWebMcpBridge().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=kb(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$/,"")||cv}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new Ne("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:t.after}),d=await fetch(`${a}?${l}`,{method:"GET",headers:{"X-Persona-Version":Ho,"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&&uv(n)===uv(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}:{}};t.signal?.throwIfAborted();let p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ho},body:JSON.stringify(d),signal:t.signal});if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new Ne("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw p.status===403&&m.error==="durable_recovery_disabled"?new Ne("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&m.error==="visitor_required"?new Ne("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new Ne("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):p.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.createClientSession({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,t,!1)}catch(r){if(!Sg(r,"not_found")&&!Sg(r,"visitor_required")&&!Sg(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(t,n)):this.doOrdinaryInit(t,n)}async doOrdinaryInit(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,t,n)}async reinitWithProof(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:t}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),s}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&t.durableRecovery?.enabled!==!0)return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Ne("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new Ne("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:t,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ho},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}historyUrl(t,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new Ne("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Ne("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Ne("proof_not_admitted",gv);return r}async readErrorCode(t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Ne("invalid_identity_proof",mv);if(r.includes("visitor token required"))throw new Ne("visitor_token_missing",fv);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Ne("visitor_identity_mismatch",hv);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new Ne("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,n){let o=await this.readErrorCode(t);if(t.status===404)return new Ne("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new Ne("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Ne("proof_not_admitted",gv);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Ne("invalid_identity_proof",mv)):r.includes("visitor token required")?new Ne("visitor_token_missing",fv):r.includes("visitor_identity_mismatch")?new Ne("visitor_identity_mismatch",hv):new Ne("unauthorized",o||"History request was not authorized")}return new Ne("request_failed",o||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new Ne("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Ne("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new Ne("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let d=a?.revision()??0,p=await this.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new Ne("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Ho,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),y=await u.json().catch(()=>{});if(a&&a.revision()!==d)throw new Ne("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),y}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new Ne("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let n=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(pv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:pv(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(t,n){this.assertHistoryUsable();let o=0;for(let d of n){let p=d.displayContent.length;if(p>dv)throw new Ne("payload_too_large",`displayContent exceeds the ${dv} character limit`);o+=p}if(o>xg)throw new Ne("payload_too_large",`Display projection batch exceeds the ${xg} 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<=xg,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=Lb();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();a();let d=async()=>{a();let P=l,I=P.durableRecovery?.enabled===!0;if(I&&(!P.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");a();let O=await this.createClientSession({...I||this.isHistoryCapable()?{conversationId:P.conversationId,durableResume:I}:{storedSessionId:P.sessionId},signal:t.signal});if(a(),P.conversationId&&O.conversationId!==P.conversationId||I&&O.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.finishInit(O,P.conversationId??null,!1),this.clientSession=l,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await d();let p=await this.buildPayload(t.messages),u=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([P])=>P!=="sessionId"&&P!=="session_id")):void 0,m=this.isHistoryCapable(),y={sessionId:l.sessionId,messages:t.messages.filter(Ag).map(P=>{let I=m?Va(P):void 0;return{id:P.id,role:P.role,content:P.contentParts??P.llmContent??P.rawContent??P.content,...I!==void 0&&{displayContent:I}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},h=async()=>{a();let P=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return a(),this.sendWithClientToolsDiff(l.sessionId,p.clientTools,I=>{let O={...y,sessionId:l.sessionId,...I};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",O),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ho,...P?{"X-Visitor-Token":P}:{}},body:JSON.stringify(O),signal:t.signal})})},C=await h();if(a(),C.response.status===401){let P=await C.response.clone().json().catch(()=>null);a(),P?.error==="Session not found or expired"&&(await d(),C=await h(),a())}let{response:w,commit:S}=C;if(!w.ok){let P=await w.json().catch(()=>({error:"Chat request failed"}));if(w.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let O=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:O}),O}if(w.status===429){let O=new Error(P.hint||"Message limit reached for this session.");throw s({type:"error",error:O}),O}if(w.status===410&&P.error==="conversation_deleted"){let O=new Ne("conversation_deleted","This conversation was deleted");throw s({type:"error",error:O}),O}let I=new Error(P.error||"Failed to send message");throw s({type:"error",error:I}),I}if(!w.body){let P=new Error("No response body received");throw s({type:"error",error:P}),P}S(),s({type:"status",status:"connected"});try{await this.streamResponse(w.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof Ne)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let o=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?Ab(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(/\/+$/,"")||cv}/resume`,a,l=null;if(r){let u=await this.initSession();a=u.sessionId,u.durableRecovery?.enabled===!0&&(l=await this.readVisitorToken())}let d={"Content-Type":"application/json",...l?{"X-Visitor-Token":l}:{},...this.headers};this.getHeaders&&Object.assign(d,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(a&&(p.sessionId=a),r&&a){let u=[...$a(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:y}=await this.sendWithClientToolsDiff(a,u,h=>{let 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=mg(yv(t),p=>Ag(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?bv(p):null),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...$a(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(a.clientTools=l);let d=await this.buildContextAggregate(t);return d&&(a.context=d),a}async buildPayload(t,n){let o=mg(yv(t),p=>Ag(p)?bv(p):null),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,u]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=u);let a=[...$a(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(s.clientTools=a);let l=await this.buildContextAggregate(t);l&&(s.context=l);let d=this.normalizeComposerOptions(n);if(d&&(s.composerOptions=d),this.requestMiddleware)try{let p=await this.requestMiddleware({payload:{...s},config:this.config});if(p&&typeof p=="object"){let u=p;return s.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=s.clientTools),u}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=m,r(m),m},p=u=>o.current?o.current:d(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",d=Date.now(),p=0,u=()=>d+p++,m=q=>{let x=q.reasoning?{...q.reasoning,chunks:[...q.reasoning.chunks]}:void 0,N=q.toolCall?{...q.toolCall,chunks:q.toolCall.chunks?[...q.toolCall.chunks]:void 0}:void 0,z=q.tools?q.tools.map(Y=>({...Y,chunks:Y.chunks?[...Y.chunks]:void 0})):void 0;return{...q,reasoning:x,toolCall:N,tools:z}},y=q=>{if(q.role!=="assistant"||q.variant)return!0;let x=Array.isArray(q.contentParts)&&q.contentParts.length>0,N=typeof q.rawContent=="string"&&q.rawContent.trim()!=="";return typeof q.content=="string"&&q.content.trim()!==""||x||N||!!q.stopReason},h=q=>{y(q)&&n({type:"message",message:m(q)})},C=null,w=null,S={current:null},P={current:null},I=null,O="",T=new Map,R=new Map,A=new Map,D=new Map,K=new Map,ie=o,Z=!1,M=()=>{if(C)return C;let q,x="",N=I;return!Z&&ie?(q=ie,Z=!0,x=r??""):ie&&N?q=`${ie}_${N}`:q=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,C={id:q,role:"assistant",content:x,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},h(C),C},_=q=>{let x=D.get(q);if(x)return x;let N={id:`reason-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:q,status:"streaming",chunks:[]}};return D.set(q,N),h(N),N},W=new Set,H=new Map,J=new Set,V=new Map,pe=q=>{if(!q)return!1;let x=q.replace(/_+/g,"_").replace(/^_|_$/g,"");return x==="emit_artifact_markdown"||x==="emit_artifact_component"},se=q=>{let x=K.get(q);if(x)return x;let N={id:`tool-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:q,status:"pending"}};return K.set(q,N),h(N),N},ge=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){let x=Number(q);if(!Number.isNaN(x)&&Number.isFinite(x))return x;let N=Date.parse(q);if(!Number.isNaN(N))return N}return Date.now()},Ie=q=>{if(typeof q=="string")return q;if(q==null)return"";try{return JSON.stringify(q)}catch{return String(q)}},ye=new Map,ce=new Map,Je=(q,x)=>{let N=Ie(x),z=ce.get(q.id),Y=dk(z,N);q.rawContent=Y;let ee=ye.get(q.id),he=Ke=>{let je=q.content??"";Ke.trim()!==""&&(je.trim().length===0||Ke.startsWith(je)||Ke.trimStart().startsWith(je.trim()))&&(q.content=Ke)},Te=()=>{if(ee){let Ke=ee.close?.();Ke instanceof Promise&&Ke.catch(()=>{})}ye.delete(q.id),ce.delete(q.id),q.streaming=!1,h(q)};if(!ee){he(N),Te();return}let ke=qa(Y);if(ke!==null&&ke.trim()!==""){he(ke),Te();return}let He=Ke=>{let je=typeof Ke=="string"?Ke:Ke?.text??null;if(je!==null&&je.trim()!=="")return je;let ht=ee.getExtractedText();return ht!==null&&ht.trim()!==""?ht:N},rt;try{rt=ee.processChunk(Y)}catch{he(N),Te();return}if(rt instanceof Promise){rt.then(Ke=>{he(He(Ke)),Te()}).catch(()=>{he(N),Te()});return}he(He(rt)),Te()},fe=null,F=(q,x,N,z)=>{q.rawContent=x,ye.has(q.id)||ye.set(q.id,this.createStreamParser());let Y=ye.get(q.id),ee=x.trim().startsWith("{")||x.trim().startsWith("[");if(ee&&ce.set(q.id,x),Y.__isPlainTextParser===!0){q.content=z!==void 0?x:q.content+N,ce.delete(q.id),ye.delete(q.id),q.rawContent=void 0,h(q);return}let Te=Y.processChunk(x);if(Te instanceof Promise)Te.then(ke=>{let He=typeof ke=="string"?ke:ke?.text??null;He!==null&&He.trim()!==""?(q.content=He,h(q)):!ee&&!x.trim().startsWith("<")&&(q.content=z!==void 0?x:q.content+N,ce.delete(q.id),ye.delete(q.id),q.rawContent=void 0,h(q))}).catch(()=>{q.content=z!==void 0?x:q.content+N,ce.delete(q.id),ye.delete(q.id),q.rawContent=void 0,h(q)});else{let ke=typeof Te=="string"?Te:Te?.text??null;ke!==null&&ke.trim()!==""?(q.content=ke,h(q)):!ee&&!x.trim().startsWith("<")&&(q.content=z!==void 0?x:q.content+N,ce.delete(q.id),ye.delete(q.id),q.rawContent=void 0,h(q))}},Oe=(q,x)=>{let N=x??q.content;if(N==null||N===""){q.streaming=!1,h(q);return}let Y=ce.get(q.id)??Ie(N);q.rawContent=Y;let ee=ye.get(q.id),he=null,Te=!1;if(ee&&(he=ee.getExtractedText(),he===null&&(he=qa(Y)),he===null)){let ke=ee.processChunk(Y);ke instanceof Promise?(Te=!0,ke.then(He=>{let rt=typeof He=="string"?He:He?.text??null;rt!==null&&(q.content=rt,q.streaming=!1,ye.delete(q.id),ce.delete(q.id),h(q))}).catch(()=>{})):he=typeof ke=="string"?ke:ke?.text??null}if(!Te){he!==null&&he.trim()!==""?q.content=he:ce.has(q.id)||(q.content=Ie(N));let ke=ye.get(q.id);if(ke){let He=ke.close?.();He instanceof Promise&&He.catch(()=>{}),ye.delete(q.id)}ce.delete(q.id),q.streaming=!1,h(q)}},Ue=(q,x,N)=>{let z=R.get(q);if(z)return z;let Y={id:`nested-${x}-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...N?{variant:N}:{},...N==="reasoning"?{reasoning:{id:q,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:x}};return R.set(q,Y),h(Y),Y},Bt=[],be,Be=new Map,ve=0,xe="agent",bt=!1,Rt=null,ut=null,vn=this.config.iterationDisplay??"separate";for(be=()=>{for(let q=0;q<Bt.length;q++){let x=Bt[q];if(!bt&&xe!=="flow"&&typeof x.stepType=="string"&&(xe="flow"),x.type==="reasoning_start"){let N=typeof x.id=="string"?x.id:null,z=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(N&&z){T.set(N,z),Ue(N,z,"reasoning");continue}let Y=x.id,ee=_(Y);ee.reasoning=ee.reasoning??{id:Y,status:"streaming",chunks:[]},ee.reasoning.startedAt=ee.reasoning.startedAt??Date.now(),ee.reasoning.completedAt=void 0,ee.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(ee.reasoning.scope=x.scope),ee.streaming=!0,ee.reasoning.status="streaming",h(ee)}else if(x.type==="reasoning_delta"){let N=typeof x.id=="string"?x.id:null;if(N&&T.has(N)&&R.has(N)){let ee=R.get(N),he=x.delta;he&&ee.reasoning&&(ee.reasoning.chunks.push(String(he)),h(ee));continue}let z=x.id,Y=_(z);Y.reasoning=Y.reasoning??{id:z,status:"streaming",chunks:[]},Y.reasoning.startedAt=Y.reasoning.startedAt??Date.now(),x.delta&&Y.reasoning.chunks.push(x.delta),Y.reasoning.status="streaming",Y.streaming=!0,h(Y)}else if(x.type==="reasoning_complete"){let N=typeof x.id=="string"?x.id:null;if(N&&T.has(N)&&R.has(N)){let he=R.get(N);if(he.reasoning){let Te=typeof x.text=="string"?x.text:"";Te&&he.reasoning.chunks.length===0&&he.reasoning.chunks.push(Te),he.reasoning.status="complete",he.streaming=!1,h(he)}T.delete(N),R.delete(N);continue}let z=x.id,Y=typeof x.text=="string"?x.text:"";!D.get(z)&&(Y||x.scope==="loop")&&_(z);let ee=D.get(z);if(ee?.reasoning){(x.scope==="loop"||x.scope==="turn")&&(ee.reasoning.scope=x.scope),Y&&ee.reasoning.chunks.length===0&&ee.reasoning.chunks.push(Y),ee.reasoning.status="complete",ee.reasoning.completedAt=Date.now();let he=ee.reasoning.startedAt??Date.now();ee.reasoning.durationMs=Math.max(0,(ee.reasoning.completedAt??Date.now())-he),ee.streaming=!1,h(ee)}}else if(x.type==="tool_start"){C&&(C.streaming=!1,h(C),C=null),typeof x.iteration=="number"&&(ve=x.iteration);let N=x.toolCallId,z=x.toolName;if(pe(z)){W.add(N);continue}let Y=se(N),ee=Y.toolCall??{id:N,status:"pending"};ee.name=z??ee.name,ee.status="running",ee.success=void 0,ee.error=void 0,ee.duration=void 0,x.parameters!==void 0&&(ee.args=x.parameters),ee.startedAt=ee.startedAt??ge(x.startedAt),ee.completedAt=void 0,ee.durationMs=void 0,Y.toolCall=ee,Y.streaming=!0,x.executionId&&(Y.agentMetadata={executionId:x.executionId,iteration:x.iteration}),h(Y)}else if(x.type==="tool_output_delta"){let N=x.toolCallId;if(W.has(N))continue;let z=se(N),Y=z.toolCall??{id:N,status:"running"};Y.startedAt=Y.startedAt??Date.now();let ee=x.delta;ee&&(Y.chunks=Y.chunks??[],Y.chunks.push(String(ee))),Y.status="running",z.toolCall=Y,z.streaming=!0,x.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:x.executionId,iteration:ve}),h(z)}else if(x.type==="tool_complete"){let N=x.toolCallId;if(W.has(N)){W.delete(N);continue}let z=se(N),Y=z.toolCall??{id:N,status:"running"};Y.status="complete",x.result!==void 0&&(Y.result=x.result),Y.name=x.toolName??Y.name,Y.success=x.success,Y.error=x.error,Y.completedAt=Date.now();let ee=x.executionTime;if(typeof ee=="number")Y.durationMs=ee,Y.duration=ee;else{let he=Y.startedAt??Date.now();Y.durationMs=Math.max(0,(Y.completedAt??Date.now())-he)}z.toolCall=Y,z.streaming=!1,x.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:x.executionId,iteration:x.iteration??ve}),h(z)}else if(x.type==="await"&&x.toolName){let N=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,z=N??x.toolId??`local-${u()}`,Y=se(z),ee=x.toolName,he=x.origin==="webmcp"&&!xs(ee)?`webmcp:${ee}`:ee,Te=xs(he),ke=Y.toolCall??{id:z,status:"pending"};ke.name=he,ke.args=x.parameters,ke.status=Te?"running":"complete",ke.chunks=ke.chunks??[],ke.startedAt=ke.startedAt??ge(x.awaitedAt),Te?(ke.completedAt=void 0,ke.duration=void 0,ke.durationMs=void 0):ke.completedAt=ke.completedAt??ke.startedAt,Y.toolCall=ke,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:x.executionId??Y.agentMetadata?.executionId,awaitingLocalTool:!0,...N?{webMcpToolCallId:N}:{}},h(Y)}else if(x.type==="text_start"){let N=typeof x.id=="string"?x.id:null,z=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(N&&z){T.set(N,z);continue}let Y=C;Y&&(xe==="flow"?(Oe(Y),fe=Y):(Y.streaming=!1,h(Y)),C=null),I=typeof x.id=="string"?x.id:I,O=""}else if(x.type==="text_delta"){let N=typeof x.id=="string"?x.id:null,z=N?T.get(N):void 0;if(N&&z){let he=typeof x.delta=="string"?x.delta:"",Te=(A.get(N)??"")+he;if(A.set(N,Te),Te.trim()==="")continue;let ke=Ue(N,z);ke.agentMetadata={...ke.agentMetadata,executionId:x.executionId,parentToolId:z},F(ke,Te,he,void 0);continue}if(I=typeof x.id=="string"?x.id:I,xe==="flow"){let he=typeof x.delta=="string"?x.delta:"";if(O+=he,O.trim()==="")continue;let Te=M();Te.agentMetadata={executionId:x.executionId,iteration:ve},F(Te,O,he,void 0),w=Te;continue}let Y=typeof x.delta=="string"?x.delta:"";O+=Y;let ee=M();ee.agentMetadata={executionId:x.executionId,iteration:ve,turnId:Rt??void 0,agentName:ut?.agentName},F(ee,O,Y,void 0),w=ee}else if(x.type==="text_complete"){let N=typeof x.id=="string"?x.id:null;if(N&&T.has(N)){let Y=R.get(N);Y&&Oe(Y),T.delete(N),A.delete(N),R.delete(N);continue}let z=C;z&&(xe==="flow"?(Oe(z),fe=z):((z.content??"")===""&&typeof x.text=="string"&&(z.content=x.text),z.streaming=!1,h(z)),C=null),I=null,O=""}else if(x.type==="step_complete"){if(x.stepType==="tool")continue;if(x.success===!1){let N=x.error||"Step failed";n({type:"error",error:new Error(N)});let z=C;z&&z.streaming&&(z.streaming=!1,h(z)),n({type:"status",status:"idle"});continue}{let N=fe;fe=null;let z=x.stopReason,ee=(x.result&&typeof x.result=="object"?x.result:null)?.response;if(N)z&&(N.stopReason=z),ee!=null?Je(N,ee):N.streaming!==!1&&(ye.delete(N.id),ce.delete(N.id),N.streaming=!1,h(N));else{let he=ee!=null&&ee!=="";if(he||z){let Te=M();z&&(Te.stopReason=z),he?Oe(Te,ee):(Te.streaming=!1,h(Te))}}continue}}else if(x.type==="execution_start")xe=x.kind==="flow"?"flow":"agent",bt=!0,xe==="agent"&&(ut={executionId:x.executionId,agentId:x.agentId??"virtual",agentName:x.agentName??""});else if(x.type==="turn_start"){let N=typeof x.iteration=="number"?x.iteration:ve;if(N!==ve){if(vn==="separate"&&N>1){let z=C;z&&(z.streaming=!1,h(z),C=null)}ve=N}Rt=typeof x.id=="string"?x.id:null,w=null}else if(x.type==="tool_input_delta"){let N=x.toolCallId;if(N){let z=K.get(N);z?.toolCall&&(z.toolCall.chunks=z.toolCall.chunks??[],z.toolCall.chunks.push(x.delta??""),h(z))}}else if(x.type==="tool_input_complete"){if(W.has(x.toolCallId))continue;let N=se(x.toolCallId),z=N.toolCall;z.args=x.parameters,z.name=x.toolName??z.name,h(N)}else if(x.type==="turn_complete"){let N=x.stopReason,z=C??w;if(N&&z!==null){let Y=x.id;(!Y||z.agentMetadata?.turnId===Y)&&(z.stopReason=N,h(z))}Rt===x.id&&(Rt=null)}else if(x.type==="media_start"){let N=String(x.id);Be.set(N,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,toolCallId:x.toolCallId,parts:[]})}else if(x.type==="media_delta"){let N=Be.get(String(x.id));N&&typeof x.delta=="string"&&N.parts.push(x.delta)}else if(x.type==="media_complete"){let N=String(x.id),z=Be.get(N);Be.delete(N);let Y=(typeof x.mediaType=="string"?x.mediaType:void 0)??z?.mediaType??"application/octet-stream",ee=typeof x.data=="string"?x.data:void 0,he=typeof x.url=="string"?x.url:z&&z.parts.length>0?z.parts.join(""):void 0,Te=null;if(ee)Te={type:"media",data:ee,mediaType:Y};else if(he){let Ke=Y.toLowerCase();Te={type:Ke==="image"||Ke.startsWith("image/")?"image-url":"file-url",url:he,mediaType:Y}}let ke=x.toolCallId??z?.toolCallId,He=Te?[Te]:[],rt=[];for(let Ke of He){if(!Ke||typeof Ke!="object")continue;let je=Ke,ht=typeof je.type=="string"?je.type:void 0,Gt=typeof je.mediaType=="string"?je.mediaType.toLowerCase():"",Ht=null,sn="";if(ht==="media"){let Cn=typeof je.data=="string"?je.data:void 0;if(!Cn)continue;sn=Gt.length>0?Gt:"application/octet-stream",Ht=`data:${sn};base64,${Cn}`}else if(ht==="image-url"){let Cn=typeof je.url=="string"?je.url:void 0;if(!Cn)continue;sn=Gt,Ht=Cn}else if(ht==="file-url"){let Cn=typeof je.url=="string"?je.url:void 0;if(!Cn)continue;sn=Gt,Ht=Cn}else continue;if(Ht)if(ht==="image-url"||sn.startsWith("image/"))rt.push({type:"image",image:Ht,...sn.includes("/")?{mimeType:sn}:{}});else if(sn.startsWith("audio/"))rt.push({type:"audio",audio:Ht,mimeType:sn});else if(sn.startsWith("video/"))rt.push({type:"video",video:Ht,mimeType:sn});else{let Cn=sn||"application/octet-stream";rt.push({type:"file",data:Ht,mimeType:Cn,filename:lk(Cn)})}}if(rt.length>0){let Ke=u(),je=ke,Gt={id:`agent-media-${typeof je=="string"&&je.length>0?`${je}-${Ke}`:String(Ke)}`,role:"assistant",content:"",contentParts:rt,createdAt:new Date().toISOString(),streaming:!1,sequence:Ke,agentMetadata:{executionId:x.executionId,iteration:ve}};h(Gt);let Ht=C;Ht&&(Ht.streaming=!1,h(Ht)),C=null,S.current=null}}else if(x.type==="execution_complete"){let N=C;N&&(x.kind==="flow"&&N.streaming!==!1?Oe(N):(N.streaming=!1,h(N)),C=null),I=null,O="",fe=null,n({type:"status",status:"idle",terminal:!0})}else if(x.type==="execution_error"){let N=typeof x.error=="string"?x.error:x.error?.message??"Execution error";n({type:"error",error:new Error(N)})}else if(x.type!=="ping"){if(x.type==="approval_start"){let N=x.approvalId??`approval-${u()}`,z={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:"pending",agentId:ut?.agentId??"virtual",executionId:x.executionId??ut?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};h(z)}else if(x.type==="approval_complete"){let N=x.approvalId;if(N){let Y={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:x.decision??"approved",agentId:ut?.agentId??"virtual",executionId:x.executionId??ut?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(Y)}}else if(x.type==="artifact_start"||x.type==="artifact_delta"||x.type==="artifact_update"||x.type==="artifact_complete"){if(x.type==="artifact_start"){let N=x.artifactType,z=String(x.id),Y=typeof x.title=="string"?x.title:void 0,ee=x.file,he;if(ee&&typeof ee=="object"&&!Array.isArray(ee)&&typeof ee.path=="string"&&typeof ee.mimeType=="string"&&(he={path:ee.path,mimeType:ee.mimeType,...typeof ee.language=="string"?{language:ee.language}:{}}),n({type:"artifact_start",id:z,artifactType:N,title:Y,component:typeof x.component=="string"?x.component:void 0,...he?{file:he}:{}}),V.set(z,{markdown:"",title:Y,file:he}),!J.has(z)){J.add(z);let Te=sr(this.config.features?.artifacts,{artifactType:N,...he?{file:he}:{}}),ke=typeof x.component=="string"?x.component:void 0,He={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:Ba(Te,{artifactId:z,title:Y,artifactType:N,status:"streaming",...he?{file:he}:{},...ke?{component:ke}:{}})};H.set(z,He),h(He)}}else if(x.type==="artifact_delta"){let N=String(x.id),z=typeof x.delta=="string"?x.delta:String(x.delta??"");n({type:"artifact_delta",id:N,artDelta:z});let Y=V.get(N);Y&&(Y.markdown+=z)}else if(x.type==="artifact_update"){let N=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};n({type:"artifact_update",id:String(x.id),props:N,component:typeof x.component=="string"?x.component:void 0});let z=V.get(String(x.id));z&&(z.props={...z.props??{},...N})}else if(x.type==="artifact_complete"){let N=String(x.id);n({type:"artifact_complete",id:N});let z=H.get(N);if(z){z.streaming=!1;try{let Y=JSON.parse(z.rawContent??"{}");if(Y.props){Y.props.status="complete";let ee=V.get(N);ee?.markdown&&(Y.props.markdown=ee.markdown),ee?.file&&(Y.props.file=ee.file),Y.component==="PersonaArtifactInline"&&ee?.props&&Object.keys(ee.props).length>0&&(Y.props.componentProps=ee.props)}z.rawContent=JSON.stringify(Y)}catch{}V.delete(N),h(z),H.delete(N)}}}else if(x.type==="error"&&x.recoverable===!1&&x.error!=null&&x.error!==""){let N=typeof x.error=="string"?x.error:x.error?.message!=null?String(x.error.message):"Execution error";n({type:"error",error:new Error(N)});let z=C;z&&z.streaming&&(z.streaming=!1,h(z)),n({type:"status",status:"idle"})}}}Bt.length=0};;){let{done:q,value:x}=await s.read();if(q)break;l+=a.decode(x,{stream:!0});let N=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()=>{}}},pl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},sm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},im=()=>{let e=p0();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)}},am=()=>{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=nC(n,oC|rC);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?wd(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=wd(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},u0=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=l=>typeof l=="string"?wd(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?wd(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=nC(s,oC|rC),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},lm=()=>{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 lC="4.24.0";var Do=lC;var Ui="[Image]";function m0(e){return typeof e=="string"?[{type:"text",text:e}]:e}function cm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ul(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function f0(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function yo(e){return{type:"text",text:e}}function dm(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function h0(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 y0(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 cC=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],b0=["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"],mr=[...cC,...b0];function v0(e){return cC.includes(e)||e.startsWith("image/")}function Md(e){return v0(e.type)}function dC(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function pC(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Md(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 uC(e,t=mr,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 C0(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function gC(e,t){let n=C0(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 w0=["user","assistant","system"],x0=0;function mC(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Ed(e){return typeof e=="string"?e:void 0}function S0(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?yo(t.text):null;case"image":return typeof t.image=="string"?dm(t.image,{mimeType:Ed(t.mimeType),alt:Ed(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?dC(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...Ed(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...Ed(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function A0(e,t){let n=mC(t),o=e.map(a=>mC(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 h=0;h<d;h+=1)r[s+h]=m!==null?m-(d-h):p!==null?p+h+1:x0+h;s=l+1}return r.map(a=>new Date(a).toISOString())}function fC(e,t){let n=A0(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!w0.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(S0).filter(u=>u!==null),p=cm(d);o.push({id:r.id,role:a,content:p||(ul(d)?Ui:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function gl(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 ml(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 M0="https://api.runtype.com/v1/dispatch",hC="https://api.runtype.com",$e=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},yC=32768,pm=49152,bC=e=>{let t=e??{},n=typeof t.targetId=="string"?t.targetId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:n,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},vC=e=>"reason"in e?e.reason:void 0,CC="The identity proof was not admitted; account history is unavailable",um="The identity proof was rejected",wC="The request carried no visitor credential",xC="The stored visitor belongs to a different signed-in user",gm=(e,t)=>e instanceof $e&&e.code===t;function E0(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 mm=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),SC=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),AC=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function T0(e){switch(e){case"json":return am;case"regex-json":return im;case"xml":return lm;default:return sm}}var MC=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function P0(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=MC(n);if(!MC(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=pl(e);return pl(t)!==null&&a===null?t:e}var ji=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.sessionWarmLatch=!1;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??M0,this.headers={"Content-Type":"application/json","X-Persona-Version":Do,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??T0(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 Hv().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:fd,getToolDisplayTitle:Di,loadPolyfill:hd});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=Bv(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$/,"")||hC}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new $e("visitor_token_missing","Durable recovery is not enabled for this client session");let a=`${this.clientApiBase()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:t.after}),d=await fetch(`${a}?${l}`,{method:"GET",headers:{"X-Persona-Version":Do,"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 warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.sessionInitPromise||t&&new Date<t.expiresAt||this.sessionWarmLatch===t?null:(this.sessionWarmLatch=t,this.initSession().catch(()=>null))}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;let t=this.sessionInitPromise=this._doInitSession().then(n=>this.sessionInitPromise!==t?this.initSession():(this.clientSession=n,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.sessionInitPromise===t&&(this.sessionInitPromise=null)});return t}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&&vC(n)===vC(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}:{}};t.signal?.throwIfAborted();let p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Do},body:JSON.stringify(d),signal:t.signal});if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new $e("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw p.status===403&&m.error==="durable_recovery_disabled"?new $e("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&m.error==="visitor_required"?new $e("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new $e("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):p.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.createClientSession({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,t,!1)}catch(r){if(!gm(r,"not_found")&&!gm(r,"visitor_required")&&!gm(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.sessionWarmLatch=!1,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.sessionWarmLatch=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new $e("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new $e("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:t,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.sessionWarmLatch=!1,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":Do},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.sessionWarmLatch=!1,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()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession()??await this.initSession();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 resolveChatIdentityProof(t){t?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let r,s;try{let a=Promise.resolve().then(()=>o());r=t?await Promise.race([a,new Promise((l,d)=>{s=()=>d(t.reason),t.addEventListener("abort",s,{once:!0}),t.aborted&&s()})]):await a}catch{throw t?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{s&&t?.removeEventListener("abort",s)}if(typeof r!="string"||!r.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:r}}async resolveIdentityProof(t,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new $e("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new $e("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new $e("proof_not_admitted",CC);return r}async readErrorCode(t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new $e("invalid_identity_proof",um);if(r.includes("visitor token required"))throw new $e("visitor_token_missing",wC);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new $e("visitor_identity_mismatch",xC);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new $e("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,n){let o=await this.readErrorCode(t);if(t.status===404)return new $e("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new $e("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new $e("proof_not_admitted",CC);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new $e("invalid_identity_proof",um)):r.includes("visitor token required")?new $e("visitor_token_missing",wC):r.includes("visitor_identity_mismatch")?new $e("visitor_identity_mismatch",xC):new $e("unauthorized",o||"History request was not authorized")}return new $e("request_failed",o||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new $e("identity_contract_violation","Server reported an ignored identity proof on a success response"):new $e("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new $e("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let d=a?.revision()??0,p=await this.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new $e("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Do,...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"),h=await u.json().catch(()=>{});if(a&&a.revision()!==d)throw new $e("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),h}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new $e("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let n=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(bC),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:bC(o),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(t,n){this.assertHistoryUsable();let o=0;for(let d of n){let p=d.displayContent.length;if(p>yC)throw new $e("payload_too_large",`displayContent exceeds the ${yC} character limit`);o+=p}if(o>pm)throw new $e("payload_too_large",`Display projection batch exceeds the ${pm} 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<=pm,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=Dv();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();a();let d=async()=>{a();let E=l,H=E.durableRecovery?.enabled===!0;if(H&&(!E.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");a();let B=await this.createClientSession({...H||this.isHistoryCapable()?{conversationId:E.conversationId,durableResume:H}:{storedSessionId:E.sessionId},signal:t.signal});if(a(),E.conversationId&&B.conversationId!==E.conversationId||H&&B.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.finishInit(B,E.conversationId??null,!1),this.clientSession=l,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await d();let p=await this.buildPayload(t.messages),u=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,m=this.isHistoryCapable(),h={sessionId:l.sessionId,messages:t.messages.filter(mm).map(E=>{let H=m?gl(E):void 0;return{id:E.id,role:E.role,content:E.contentParts??E.llmContent??E.rawContent??E.content,...H!==void 0&&{displayContent:H}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},y=async()=>{a();let E=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return a(),this.sendWithClientToolsDiff(l.sessionId,p.clientTools,async H=>{a();let B=await this.resolveChatIdentityProof(t.signal);a();let A={...h,sessionId:l.sessionId,...H,...B&&{identityProof:B}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...A,...B&&{identityProof:{provider:B.provider,token:"[REDACTED]"}}}),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Do,...E?{"X-Visitor-Token":E}:{}},body:JSON.stringify(A),signal:t.signal})})},v=await y();if(a(),v.response.status===401){let E=await v.response.clone().json().catch(()=>null);a(),E?.error==="Session not found or expired"&&(await d(),v=await y(),a())}let{response:C,commit:x}=v;if(!C.ok){let E=await C.json().catch(()=>({error:"Chat request failed"}));if(C.status===401&&E.error==="invalid_identity_proof"){let B=new $e("invalid_identity_proof",um);throw s({type:"error",error:B}),B}if(C.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let B=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:B}),B}if(C.status===429){let B=new Error(E.hint||"Message limit reached for this session.");throw s({type:"error",error:B}),B}if(C.status===410&&E.error==="conversation_deleted"){let B=new $e("conversation_deleted","This conversation was deleted");throw s({type:"error",error:B}),B}let H=new Error(E.error||"Failed to send message");throw s({type:"error",error:H}),H}if(!C.body){let E=new Error("No response body received");throw s({type:"error",error:E}),E}x(),s({type:"status",status:"connected"});try{await this.streamResponse(C.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof $e)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let o=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?Iv(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 h=0;;h++){if(m=await o({...s&&(u||!d)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),m.status===409&&h===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(/\/+$/,"")||hC}/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=[...ll(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:h}=await this.sendWithClientToolsDiff(a,u,y=>{let v={...p,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",v),fetch(s,{method:"POST",headers:d,body:JSON.stringify(v),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&h(),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=om(SC(t),p=>mm(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?AC(p):null),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=[...ll(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=om(SC(t),p=>mm(p)?AC(p):null),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=[...ll(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=j=>{let M=j.reasoning?{...j.reasoning,chunks:[...j.reasoning.chunks]}:void 0,N=j.toolCall?{...j.toolCall,chunks:j.toolCall.chunks?[...j.toolCall.chunks]:void 0}:void 0,z=j.tools?j.tools.map(X=>({...X,chunks:X.chunks?[...X.chunks]:void 0})):void 0;return{...j,reasoning:M,toolCall:N,tools:z}},h=j=>{if(j.role!=="assistant"||j.variant)return!0;let M=Array.isArray(j.contentParts)&&j.contentParts.length>0,N=typeof j.rawContent=="string"&&j.rawContent.trim()!=="";return typeof j.content=="string"&&j.content.trim()!==""||M||N||!!j.stopReason},y=j=>{h(j)&&n({type:"message",message:m(j)})},v=null,C=null,x={current:null},E={current:null},H=null,B="",A=new Map,O=new Map,L=new Map,$=new Map,K=new Map,se=o,te=!1,P=()=>{if(v)return v;let j,M="",N=H;return!te&&se?(j=se,te=!0,M=r??""):se&&N?j=`${se}_${N}`:j=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:j,role:"assistant",content:M,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},y(v),v},k=j=>{let M=$.get(j);if(M)return M;let N={id:`reason-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:j,status:"streaming",chunks:[]}};return $.set(j,N),y(N),N},_=new Set,I=new Map,Z=new Set,U=new Map,ce=j=>{if(!j)return!1;let M=j.replace(/_+/g,"_").replace(/^_|_$/g,"");return M==="emit_artifact_markdown"||M==="emit_artifact_component"},de=j=>{let M=K.get(j);if(M)return M;let N={id:`tool-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:j,status:"pending"}};return K.set(j,N),y(N),N},pe=j=>{if(typeof j=="number"&&Number.isFinite(j))return j;if(typeof j=="string"){let M=Number(j);if(!Number.isNaN(M)&&Number.isFinite(M))return M;let N=Date.parse(j);if(!Number.isNaN(N))return N}return Date.now()},ke=j=>{if(typeof j=="string")return j;if(j==null)return"";try{return JSON.stringify(j)}catch{return String(j)}},we=new Map,fe=new Map,lt=(j,M)=>{let N=ke(M),z=fe.get(j.id),X=P0(z,N);j.rawContent=X;let Q=we.get(j.id),ge=Je=>{let Ve=j.content??"";Je.trim()!==""&&(Ve.trim().length===0||Je.startsWith(Ve)||Je.trimStart().startsWith(Ve.trim()))&&(j.content=Je)},xe=()=>{if(Q){let Je=Q.close?.();Je instanceof Promise&&Je.catch(()=>{})}we.delete(j.id),fe.delete(j.id),j.streaming=!1,y(j)};if(!Q){ge(N),xe();return}let Se=pl(X);if(Se!==null&&Se.trim()!==""){ge(Se),xe();return}let ut=Je=>{let Ve=typeof Je=="string"?Je:Je?.text??null;if(Ve!==null&&Ve.trim()!=="")return Ve;let gt=Q.getExtractedText();return gt!==null&>.trim()!==""?gt:N},Dt;try{Dt=Q.processChunk(X)}catch{ge(N),xe();return}if(Dt instanceof Promise){Dt.then(Je=>{ge(ut(Je)),xe()}).catch(()=>{ge(N),xe()});return}ge(ut(Dt)),xe()},rt=null,be=(j,M,N,z)=>{j.rawContent=M,we.has(j.id)||we.set(j.id,this.createStreamParser());let X=we.get(j.id),Q=M.trim().startsWith("{")||M.trim().startsWith("[");if(Q&&fe.set(j.id,M),X.__isPlainTextParser===!0){j.content=z!==void 0?M:j.content+N,fe.delete(j.id),we.delete(j.id),j.rawContent=void 0,y(j);return}let xe=X.processChunk(M);if(xe instanceof Promise)xe.then(Se=>{let ut=typeof Se=="string"?Se:Se?.text??null;ut!==null&&ut.trim()!==""?(j.content=ut,y(j)):!Q&&!M.trim().startsWith("<")&&(j.content=z!==void 0?M:j.content+N,fe.delete(j.id),we.delete(j.id),j.rawContent=void 0,y(j))}).catch(()=>{j.content=z!==void 0?M:j.content+N,fe.delete(j.id),we.delete(j.id),j.rawContent=void 0,y(j)});else{let Se=typeof xe=="string"?xe:xe?.text??null;Se!==null&&Se.trim()!==""?(j.content=Se,y(j)):!Q&&!M.trim().startsWith("<")&&(j.content=z!==void 0?M:j.content+N,fe.delete(j.id),we.delete(j.id),j.rawContent=void 0,y(j))}},D=(j,M)=>{let N=M??j.content;if(N==null||N===""){j.streaming=!1,y(j);return}let X=fe.get(j.id)??ke(N);j.rawContent=X;let Q=we.get(j.id),ge=null,xe=!1;if(Q&&(ge=Q.getExtractedText(),ge===null&&(ge=pl(X)),ge===null)){let Se=Q.processChunk(X);Se instanceof Promise?(xe=!0,Se.then(ut=>{let Dt=typeof ut=="string"?ut:ut?.text??null;Dt!==null&&(j.content=Dt,j.streaming=!1,we.delete(j.id),fe.delete(j.id),y(j))}).catch(()=>{})):ge=typeof Se=="string"?Se:Se?.text??null}if(!xe){ge!==null&&ge.trim()!==""?j.content=ge:fe.has(j.id)||(j.content=ke(N));let Se=we.get(j.id);if(Se){let ut=Se.close?.();ut instanceof Promise&&ut.catch(()=>{}),we.delete(j.id)}fe.delete(j.id),j.streaming=!1,y(j)}},De=(j,M,N)=>{let z=O.get(j);if(z)return z;let X={id:`nested-${M}-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...N?{variant:N}:{},...N==="reasoning"?{reasoning:{id:j,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:M}};return O.set(j,X),y(X),X},_e=[],At,zt=new Map,$t=0,Te="agent",ve=!1,We=null,Ae=null,Cn=this.config.iterationDisplay??"separate";for(At=()=>{for(let j=0;j<_e.length;j++){let M=_e[j];if(!ve&&Te!=="flow"&&typeof M.stepType=="string"&&(Te="flow"),M.type==="reasoning_start"){let N=typeof M.id=="string"?M.id:null,z=typeof M.parentToolCallId=="string"&&M.parentToolCallId?M.parentToolCallId:null;if(N&&z){A.set(N,z),De(N,z,"reasoning");continue}let X=M.id,Q=k(X);Q.reasoning=Q.reasoning??{id:X,status:"streaming",chunks:[]},Q.reasoning.startedAt=Q.reasoning.startedAt??Date.now(),Q.reasoning.completedAt=void 0,Q.reasoning.durationMs=void 0,(M.scope==="loop"||M.scope==="turn")&&(Q.reasoning.scope=M.scope),Q.streaming=!0,Q.reasoning.status="streaming",y(Q)}else if(M.type==="reasoning_delta"){let N=typeof M.id=="string"?M.id:null;if(N&&A.has(N)&&O.has(N)){let Q=O.get(N),ge=M.delta;ge&&Q.reasoning&&(Q.reasoning.chunks.push(String(ge)),y(Q));continue}let z=M.id,X=k(z);X.reasoning=X.reasoning??{id:z,status:"streaming",chunks:[]},X.reasoning.startedAt=X.reasoning.startedAt??Date.now(),M.delta&&X.reasoning.chunks.push(M.delta),X.reasoning.status="streaming",X.streaming=!0,y(X)}else if(M.type==="reasoning_complete"){let N=typeof M.id=="string"?M.id:null;if(N&&A.has(N)&&O.has(N)){let ge=O.get(N);if(ge.reasoning){let xe=typeof M.text=="string"?M.text:"";xe&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(xe),ge.reasoning.status="complete",ge.streaming=!1,y(ge)}A.delete(N),O.delete(N);continue}let z=M.id,X=typeof M.text=="string"?M.text:"";!$.get(z)&&(X||M.scope==="loop")&&k(z);let Q=$.get(z);if(Q?.reasoning){(M.scope==="loop"||M.scope==="turn")&&(Q.reasoning.scope=M.scope),X&&Q.reasoning.chunks.length===0&&Q.reasoning.chunks.push(X),Q.reasoning.status="complete",Q.reasoning.completedAt=Date.now();let ge=Q.reasoning.startedAt??Date.now();Q.reasoning.durationMs=Math.max(0,(Q.reasoning.completedAt??Date.now())-ge),Q.streaming=!1,y(Q)}}else if(M.type==="tool_start"){v&&(v.streaming=!1,y(v),v=null),typeof M.iteration=="number"&&($t=M.iteration);let N=M.toolCallId,z=M.toolName;if(ce(z)){_.add(N);continue}let X=de(N),Q=X.toolCall??{id:N,status:"pending"};Q.name=z??Q.name,Q.status="running",Q.success=void 0,Q.error=void 0,Q.duration=void 0,M.parameters!==void 0&&(Q.args=M.parameters),Q.startedAt=Q.startedAt??pe(M.startedAt),Q.completedAt=void 0,Q.durationMs=void 0,X.toolCall=Q,X.streaming=!0,M.executionId&&(X.agentMetadata={executionId:M.executionId,iteration:M.iteration}),y(X)}else if(M.type==="tool_output_delta"){let N=M.toolCallId;if(_.has(N))continue;let z=de(N),X=z.toolCall??{id:N,status:"running"};X.startedAt=X.startedAt??Date.now();let Q=M.delta;Q&&(X.chunks=X.chunks??[],X.chunks.push(String(Q))),X.status="running",z.toolCall=X,z.streaming=!0,M.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:M.executionId,iteration:$t}),y(z)}else if(M.type==="tool_complete"){let N=M.toolCallId;if(_.has(N)){_.delete(N);continue}let z=de(N),X=z.toolCall??{id:N,status:"running"};X.status="complete",M.result!==void 0&&(X.result=M.result),X.name=M.toolName??X.name,X.success=M.success,X.error=M.error,X.completedAt=Date.now();let Q=M.executionTime;if(typeof Q=="number")X.durationMs=Q,X.duration=Q;else{let ge=X.startedAt??Date.now();X.durationMs=Math.max(0,(X.completedAt??Date.now())-ge)}z.toolCall=X,z.streaming=!1,M.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:M.executionId,iteration:M.iteration??$t}),y(z)}else if(M.type==="await"&&M.toolName){let N=typeof M.toolCallId=="string"&&M.toolCallId.length>0?M.toolCallId:void 0,z=N??M.toolId??`local-${u()}`,X=de(z),Q=M.toolName,ge=M.origin==="webmcp"&&!$s(Q)?`webmcp:${Q}`:Q,xe=$s(ge),Se=X.toolCall??{id:z,status:"pending"};Se.name=ge,Se.args=M.parameters,Se.status=xe?"running":"complete",Se.chunks=Se.chunks??[],Se.startedAt=Se.startedAt??pe(M.awaitedAt),xe?(Se.completedAt=void 0,Se.duration=void 0,Se.durationMs=void 0):Se.completedAt=Se.completedAt??Se.startedAt,X.toolCall=Se,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:M.executionId??X.agentMetadata?.executionId,awaitingLocalTool:!0,...N?{webMcpToolCallId:N}:{}},y(X)}else if(M.type==="text_start"){let N=typeof M.id=="string"?M.id:null,z=typeof M.parentToolCallId=="string"&&M.parentToolCallId?M.parentToolCallId:null;if(N&&z){A.set(N,z);continue}let X=v;X&&(Te==="flow"?(D(X),rt=X):(X.streaming=!1,y(X)),v=null),H=typeof M.id=="string"?M.id:H,B=""}else if(M.type==="text_delta"){let N=typeof M.id=="string"?M.id:null,z=N?A.get(N):void 0;if(N&&z){let ge=typeof M.delta=="string"?M.delta:"",xe=(L.get(N)??"")+ge;if(L.set(N,xe),xe.trim()==="")continue;let Se=De(N,z);Se.agentMetadata={...Se.agentMetadata,executionId:M.executionId,parentToolId:z},be(Se,xe,ge,void 0);continue}if(H=typeof M.id=="string"?M.id:H,Te==="flow"){let ge=typeof M.delta=="string"?M.delta:"";if(B+=ge,B.trim()==="")continue;let xe=P();xe.agentMetadata={executionId:M.executionId,iteration:$t},be(xe,B,ge,void 0),C=xe;continue}let X=typeof M.delta=="string"?M.delta:"";B+=X;let Q=P();Q.agentMetadata={executionId:M.executionId,iteration:$t,turnId:We??void 0,agentName:Ae?.agentName},be(Q,B,X,void 0),C=Q}else if(M.type==="text_complete"){let N=typeof M.id=="string"?M.id:null;if(N&&A.has(N)){let X=O.get(N);X&&D(X),A.delete(N),L.delete(N),O.delete(N);continue}let z=v;z&&(Te==="flow"?(D(z),rt=z):((z.content??"")===""&&typeof M.text=="string"&&(z.content=M.text),z.streaming=!1,y(z)),v=null),H=null,B=""}else if(M.type==="step_complete"){if(M.stepType==="tool")continue;if(M.success===!1){let N=M.error||"Step failed";n({type:"error",error:new Error(N)});let z=v;z&&z.streaming&&(z.streaming=!1,y(z)),n({type:"status",status:"idle"});continue}{let N=rt;rt=null;let z=M.stopReason,Q=(M.result&&typeof M.result=="object"?M.result:null)?.response;if(N)z&&(N.stopReason=z),Q!=null?lt(N,Q):N.streaming!==!1&&(we.delete(N.id),fe.delete(N.id),N.streaming=!1,y(N));else{let ge=Q!=null&&Q!=="";if(ge||z){let xe=P();z&&(xe.stopReason=z),ge?D(xe,Q):(xe.streaming=!1,y(xe))}}continue}}else if(M.type==="execution_start")Te=M.kind==="flow"?"flow":"agent",ve=!0,Te==="agent"&&(Ae={executionId:M.executionId,agentId:M.agentId??"virtual",agentName:M.agentName??""});else if(M.type==="turn_start"){let N=typeof M.iteration=="number"?M.iteration:$t;if(N!==$t){if(Cn==="separate"&&N>1){let z=v;z&&(z.streaming=!1,y(z),v=null)}$t=N}We=typeof M.id=="string"?M.id:null,C=null}else if(M.type==="tool_input_delta"){let N=M.toolCallId;if(N){let z=K.get(N);z?.toolCall&&(z.toolCall.chunks=z.toolCall.chunks??[],z.toolCall.chunks.push(M.delta??""),y(z))}}else if(M.type==="tool_input_complete"){if(_.has(M.toolCallId))continue;let N=de(M.toolCallId),z=N.toolCall;z.args=M.parameters,z.name=M.toolName??z.name,y(N)}else if(M.type==="turn_complete"){let N=M.stopReason,z=v??C;if(N&&z!==null){let X=M.id;(!X||z.agentMetadata?.turnId===X)&&(z.stopReason=N,y(z))}We===M.id&&(We=null)}else if(M.type==="media_start"){let N=String(M.id);zt.set(N,{mediaType:typeof M.mediaType=="string"?M.mediaType:void 0,toolCallId:M.toolCallId,parts:[]})}else if(M.type==="media_delta"){let N=zt.get(String(M.id));N&&typeof M.delta=="string"&&N.parts.push(M.delta)}else if(M.type==="media_complete"){let N=String(M.id),z=zt.get(N);zt.delete(N);let X=(typeof M.mediaType=="string"?M.mediaType:void 0)??z?.mediaType??"application/octet-stream",Q=typeof M.data=="string"?M.data:void 0,ge=typeof M.url=="string"?M.url:z&&z.parts.length>0?z.parts.join(""):void 0,xe=null;if(Q)xe={type:"media",data:Q,mediaType:X};else if(ge){let Je=X.toLowerCase();xe={type:Je==="image"||Je.startsWith("image/")?"image-url":"file-url",url:ge,mediaType:X}}let Se=M.toolCallId??z?.toolCallId,ut=xe?[xe]:[],Dt=[];for(let Je of ut){if(!Je||typeof Je!="object")continue;let Ve=Je,gt=typeof Ve.type=="string"?Ve.type:void 0,Xt=typeof Ve.mediaType=="string"?Ve.mediaType.toLowerCase():"",kt=null,pn="";if(gt==="media"){let mt=typeof Ve.data=="string"?Ve.data:void 0;if(!mt)continue;pn=Xt.length>0?Xt:"application/octet-stream",kt=`data:${pn};base64,${mt}`}else if(gt==="image-url"){let mt=typeof Ve.url=="string"?Ve.url:void 0;if(!mt)continue;pn=Xt,kt=mt}else if(gt==="file-url"){let mt=typeof Ve.url=="string"?Ve.url:void 0;if(!mt)continue;pn=Xt,kt=mt}else continue;if(kt)if(gt==="image-url"||pn.startsWith("image/"))Dt.push({type:"image",image:kt,...pn.includes("/")?{mimeType:pn}:{}});else if(pn.startsWith("audio/"))Dt.push({type:"audio",audio:kt,mimeType:pn});else if(pn.startsWith("video/"))Dt.push({type:"video",video:kt,mimeType:pn});else{let mt=pn||"application/octet-stream";Dt.push({type:"file",data:kt,mimeType:mt,filename:E0(mt)})}}if(Dt.length>0){let Je=u(),Ve=Se,Xt={id:`agent-media-${typeof Ve=="string"&&Ve.length>0?`${Ve}-${Je}`:String(Je)}`,role:"assistant",content:"",contentParts:Dt,createdAt:new Date().toISOString(),streaming:!1,sequence:Je,agentMetadata:{executionId:M.executionId,iteration:$t}};y(Xt);let kt=v;kt&&(kt.streaming=!1,y(kt)),v=null,x.current=null}}else if(M.type==="execution_complete"){let N=v;N&&(M.kind==="flow"&&N.streaming!==!1?D(N):(N.streaming=!1,y(N)),v=null),H=null,B="",rt=null,n({type:"status",status:"idle",terminal:!0})}else if(M.type==="execution_error"){let N=typeof M.error=="string"?M.error:M.error?.message??"Execution error";n({type:"error",error:new Error(N)})}else if(M.type!=="ping"){if(M.type==="approval_start"){let N=M.approvalId??`approval-${u()}`,z={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:"pending",agentId:Ae?.agentId??"virtual",executionId:M.executionId??Ae?.executionId??"",toolName:M.toolName??"",toolType:M.toolType,description:M.description??`Execute ${M.toolName??"tool"}`,...typeof M.reason=="string"&&M.reason?{reason:M.reason}:{},parameters:M.parameters}};y(z)}else if(M.type==="approval_complete"){let N=M.approvalId;if(N){let X={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:M.decision??"approved",agentId:Ae?.agentId??"virtual",executionId:M.executionId??Ae?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};y(X)}}else if(M.type==="artifact_start"||M.type==="artifact_delta"||M.type==="artifact_update"||M.type==="artifact_complete"){if(M.type==="artifact_start"){let N=M.artifactType,z=String(M.id),X=typeof M.title=="string"?M.title:void 0,Q=M.file,ge;if(Q&&typeof Q=="object"&&!Array.isArray(Q)&&typeof Q.path=="string"&&typeof Q.mimeType=="string"&&(ge={path:Q.path,mimeType:Q.mimeType,...typeof Q.language=="string"?{language:Q.language}:{}}),n({type:"artifact_start",id:z,artifactType:N,title:X,component:typeof M.component=="string"?M.component:void 0,...ge?{file:ge}:{}}),U.set(z,{markdown:"",title:X,file:ge}),!Z.has(z)){Z.add(z);let xe=ur(this.config.features?.artifacts,{artifactType:N,...ge?{file:ge}:{}}),Se=typeof M.component=="string"?M.component:void 0,ut={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:ol(xe,{artifactId:z,title:X,artifactType:N,status:"streaming",...ge?{file:ge}:{},...Se?{component:Se}:{}})};I.set(z,ut),y(ut)}}else if(M.type==="artifact_delta"){let N=String(M.id),z=typeof M.delta=="string"?M.delta:String(M.delta??"");n({type:"artifact_delta",id:N,artDelta:z});let X=U.get(N);X&&(X.markdown+=z)}else if(M.type==="artifact_update"){let N=M.props&&typeof M.props=="object"&&!Array.isArray(M.props)?M.props:{};n({type:"artifact_update",id:String(M.id),props:N,component:typeof M.component=="string"?M.component:void 0});let z=U.get(String(M.id));z&&(z.props={...z.props??{},...N})}else if(M.type==="artifact_complete"){let N=String(M.id);n({type:"artifact_complete",id:N});let z=I.get(N);if(z){z.streaming=!1;try{let X=JSON.parse(z.rawContent??"{}");if(X.props){X.props.status="complete";let Q=U.get(N);Q?.markdown&&(X.props.markdown=Q.markdown),Q?.file&&(X.props.file=Q.file),X.component==="PersonaArtifactInline"&&Q?.props&&Object.keys(Q.props).length>0&&(X.props.componentProps=Q.props)}z.rawContent=JSON.stringify(X)}catch{}U.delete(N),y(z),I.delete(N)}}}else if(M.type==="error"&&M.recoverable===!1&&M.error!=null&&M.error!==""){let N=typeof M.error=="string"?M.error:M.error?.message!=null?String(M.error.message):"Execution error";n({type:"error",error:new Error(N)});let z=v;z&&z.streaming&&(z.streaming=!1,y(z)),n({type:"status",status:"idle"})}}}_e.length=0};;){let{done:j,value:M}=await s.read();if(j)break;l+=a.decode(M,{stream:!0});let N=l.split(`
|
|
7
7
|
|
|
8
|
-
`);l=N.pop()??"";for(let z of N){let
|
|
9
|
-
`),
|
|
10
|
-
`)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function
|
|
8
|
+
`);l=N.pop()??"";for(let z of N){let X=z.split(`
|
|
9
|
+
`),Q="message",ge="",xe=null;for(let Ve of X)Ve.startsWith("event:")?Q=Ve.replace("event:","").trim():Ve.startsWith("data:")?ge+=Ve.replace("data:","").trim():Ve.startsWith("id:")&&(xe=Ve.slice(3).trim());let Se=()=>{xe!==null&&xe!==""&&n({type:"cursor",id:xe})};if(!ge){Se();continue}let ut;try{ut=JSON.parse(ge)}catch(Ve){n({type:"error",error:Ve instanceof Error?Ve:new Error("Failed to parse chat stream payload")});continue}let Dt=ut!==null&&typeof ut=="object"&&!Array.isArray(ut)?ut:null,Je=Q!=="message"?Q:typeof Dt?.type=="string"?Dt.type:"message";if(this.onSSEEvent?.(Je,ut),this.parseSSEEvent){x.current=v;let Ve=await this.handleCustomSSEEvent(ut,n,x,y,u,E);if(x.current&&x.current!==v&&(v=x.current),Ve){Se();continue}}Dt&&(_e.push({...Dt,type:Je}),At()),Se()}}At()}};function k0(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 EC(e,t){let n="`".repeat(Math.max(3,k0(t)+1));return`${n}${e}
|
|
11
11
|
${t}
|
|
12
|
-
${n}`}var
|
|
12
|
+
${n}`}var L0=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function I0(e){let t=e?.text?.trim()??"";return t?EC(L0(e),t):""}function TC(e){let t=I0(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[yo(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
13
13
|
|
|
14
|
-
`)}:{}}function
|
|
14
|
+
`)}:{}}function Td(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function PC(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 fm(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 kC(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 fm(e,n.id)?n.id:null}return null}function hm(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 bo=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function R0(e){return e instanceof bo}function fl(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 zs=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):fl(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 Vi=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 hl=class{constructor(){this.cancelled=!1}start(t){this.turnId=t,this.cancelled=!1}cancel(){this.cancelled=!0}accepts(t){return!this.cancelled&&(!t||!this.turnId||t===this.turnId)}};var{setLoader:_B,load:H0}=vt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var ym=H0;function bm(e){if(!e)return"";let t=W0(e);return LC(t!==null?t:e)}function W0(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 LC(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /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
|
|
16
|
+
`),t.trim()}var OC=null;var Cm=()=>OC?OC():Promise.resolve().then(()=>(WC(),HC));var{setLoader:YB,load:D0}=vt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var BC=D0;var _0=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","identityProvider","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function N0(e,t){return _0.some(n=>e[n]!==t[n])}var _o=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function wm(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 Rg=e=>({isError:!0,content:[{type:"text",text:e}]}),xk=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Iv=e=>xs(e)||e===ir,Qa=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new Ya;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new Si(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(xs(n.name)||n.name===ir&&Br(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.isAwaitPending()||this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new xi(t,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts(),this.prefetchVoiceRuntime()}prefetchVoiceRuntime(){this.config.voiceRecognition?.provider&&Tg().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||Lg().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 lb(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=Ts.isSupported()?new Ts({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return Lg().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new d(p,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):p});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.voiceDisconnectPromise,r=++this.voiceSetupGeneration;this.voiceSetupPromise=Tg().then(async s=>{await o,r===this.voiceSetupGeneration&&this.wireVoiceProvider(s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(t){try{this.voiceProvider=t;let n=this.voiceSetupGeneration,o=()=>this.voiceProvider===t&&n===this.voiceSetupGeneration,s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{o()&&a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,l,d,p)=>{if(o())if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:l,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=u.id}if(d){this.voiceTurns.start(p?.turnId),this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(p?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:l,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=u.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(a=>{o()&&(this.voiceLevel=Number.isFinite(a)?Math.max(0,Math.min(1,a)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{o()&&this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{o()&&(console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(a=>{o()&&(this.voiceStatus=a,this.voiceActive=a==="listening",(a==="listening"||a==="idle"||a==="disconnected")&&this.settlePendingVoiceTurn(a!=="listening"),this.callbacks.onVoiceStatusChanged?.(a))}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){let t=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let n=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(n)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new Ya,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(t){let n=t?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),t&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new 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 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 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=Ka(this.messages,a.messages);this.messages=this.sortMessages(l.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=a.nextCursor;for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(t){let n=this.requireHistoryProvider(),o=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new 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.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(t){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(t,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let a=await t.getPage(n,{context:o}),l=new Set(a.messages.map(m=>m.id)),d=this.messages.some(m=>l.has(m.id)),p=a.messages[0]?.createdAt,u;if(!d)u=a.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,y=this.messages.filter(h=>l.has(h.id)||h.id===m?!0:p!==void 0&&h.createdAt<p);u=Ka(y,a.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of a.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let n of t){let o=Va(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Va(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(t,n))}enqueueProjectionFinalization(t,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,n,o){if(this.activeConversationId!==t)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===t&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(t,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(t,r,!0);return}if(s instanceof Ne&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(t,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof Ne?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,n){let o=this.readPendingProjections();if(!o||o.conversationId!==t)return;let r=new Set(n.map(a=>a.id)),s=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of t.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof Ne&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,n,o,r,s){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(a){if(!e.isConversationDeleted(a))throw a;let l=await this.recoverFromDeletedConversation(r);if(!l)throw a;this.recordDispatchedProjections([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=ab(this.config,o),s=wk(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&In(o.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),a&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new xi(this.config,this.historyInternals),a&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:d,streaming:p=!1,voiceProcessing:u,rawContent:m}=t,h={id:a??(n==="user"?_a():n==="assistant"?As():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:d,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:y,rawContent:h}=o,w={id:d??(r==="user"?_a():r==="assistant"?As():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...y!==void 0&&{voiceProcessing:y},...h!==void 0&&{rawContent:h}};n.push(w)}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 xm=e=>({isError:!0,content:[{type:"text",text:e}]}),F0=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,DC=e=>$s(e)||e===gr,yl=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.voiceTurns=new hl;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new Vi(()=>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&&($s(n.name)||n.name===gr&&Yr(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 ji(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&&ym().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||Cm().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 fv(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&(this.voiceTurns.cancel(),this.voiceProvider.stopPlayback())}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=zs.isSupported()?new zs({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 Cm().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new d(p,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):p});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.cleanupVoice();let o=this.voiceDisconnectPromise,r=++this.voiceSetupGeneration;this.voiceSetupPromise=ym().then(async s=>{await o,r===this.voiceSetupGeneration&&this.wireVoiceProvider(s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(t){try{this.voiceProvider=t;let n=this.voiceSetupGeneration,o=()=>this.voiceProvider===t&&n===this.voiceSetupGeneration,s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{o()&&a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,l,d,p)=>{if(o())if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:l,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let u=this.injectMessage({role:"user",content:l,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=u.id}if(d){this.voiceTurns.start(p?.turnId),this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(p?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let u=this.injectMessage({role:"assistant",content:l,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=u.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(a=>{o()&&(this.voiceLevel=Number.isFinite(a)?Math.max(0,Math.min(1,a)):0)}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{o()&&this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{o()&&(console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null))}),this.voiceProvider.onStatusChange(a=>{o()&&(this.voiceStatus=a,this.voiceActive=a==="listening",(a==="listening"||a==="idle"||a==="disconnected")&&this.settlePendingVoiceTurn(a!=="listening"),this.callbacks.onVoiceStatusChanged?.(a))}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){let t=this.voiceProvider!==null;if(this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider){let n=this.voiceProvider;this.voiceProvider=null,this.voiceDisconnectPromise=this.disconnectVoice(n)}this.voiceActive=!1,this.voiceStatus="disconnected",this.settlePendingVoiceTurn(!0),this.voiceTurns=new hl,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(t){let n=t?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),t&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}warmClientSession(){let t=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,t)})}setClientSession(t,n){this.clientSession=t,this.injectWelcomeMessage(t,n)}injectWelcomeMessage(t,n=!this.messages.length){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||!n)return;let o=this.messages[0],r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.nextSequence()};this.appendMessage(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new _o("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 bo("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 _o("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 _o("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new _o("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=ml(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 _o("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 _o("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 _o("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 _o("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,h=this.messages.filter(y=>l.has(y.id)||y.id===m?!0:p!==void 0&&y.createdAt<p);u=ml(h,a.messages).map(y=>this.ensureSequence(y))}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=gl(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=gl(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(t,n))}enqueueProjectionFinalization(t,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,n,o){if(this.activeConversationId!==t)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===t&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(t,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(t,r,!0);return}if(s instanceof $e&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(t,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof $e?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,n){let o=this.readPendingProjections();if(!o||o.conversationId!==t)return;let r=new Set(n.map(a=>a.id)),s=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of t.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof $e&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,n,o,r,s){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(a){if(!e.isConversationDeleted(a))throw a;let l=await this.recoverFromDeletedConversation(r);if(!l)throw a;this.recordDispatchedProjections([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=mv(this.config,o),s=N0(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Ln(o.voiceRecognition.provider)&&this.setupVoice());let a=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),a&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new ji(this.config,this.historyInternals),a&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:d,streaming:p=!1,voiceProcessing:u,rawContent:m}=t,y={id:a??(n==="user"?rl():n==="assistant"?js():`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(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:d,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:h,rawContent:y}=o,C={id:d??(r==="user"?rl():r==="assistant"?js():`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},...h!==void 0&&{voiceProcessing:h},...y!==void 0&&{rawContent:y}};n.push(C)}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(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=_a(),a=As();this.activeAssistantMessageId=null;let l=n?.contentParts&&za(n.contentParts)?wi:"",d={id:s,role:"user",content:o||l,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(d),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let m=this.messages.find(y=>y.id===s)??d;if(await this.applyMentionBundle(m,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(h=>h.id===s)??d,y=wv({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=Ig(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=xv(this.messages,t);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,a=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!a?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},u=s?this.toComposerOptionsPayload(s.options):r.composerOptions,m=s?s.contentSegments:r.contentSegments,y=s?s.options?.quote:void 0,h=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(a??"",{...l?.length?{contentParts:[...l]}:{},...m?.length?{contentSegments:[...m]}:{},...u?{composerOptions:u}:{},...y?{quote:y}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:h===!0}),!0}toComposerOptionsPayload(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=As();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=Ig(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],w=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:w||"*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:zb(),toolMessage:d,startedAt:y,completedAt:Date.now()};let C=this.client.executeWebMcpToolCall(p,d.toolCall?.args,r.signal),w;if(!C)w={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{w=await C}catch(S){let P=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));return P||this.callbacks.onError?.(S instanceof Error?S:new Error(String(S))),this.markWebMcpToolComplete(d,Rg(P?"Aborted by cancel()":xk(S)),y),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,Rg("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:h,output:w,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(m=>m!==null),l.length===0)return;let d={};for(let m of l)d[m.resumeKey]=m.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 m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}let u=l[0].dedupeKey;for(let m of l){this.webMcpResolvedKeys.add(m.dedupeKey);let y=m.toolMessage.toolCall?.name,h=m.toolMessage.agentMetadata?.webMcpToolCallId;this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt,{...y===ir?{suggestRepliesResolved:!0}:{},...y&&h?{clientToolAnswer:{toolCallId:h,toolName:y,args:m.toolMessage.toolCall?.args,result:m.output,batch:u}}:{}})}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,Rg("Aborted by cancel()"),u.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let a=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(a)}catch(l){this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{this.webMcpInflightKeys.delete(a)}return}let s=`${n}:${r}`;if(!(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t)))return this.resolveWebMcpToolCallBatch(n,[t])}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=sr(this.config.features?.artifacts,t),r=Ba(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=sr(this.config.features?.artifacts,n),s=Ba(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Lv().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=>Ig(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=As(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=Pg(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ga(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Pg(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};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});let l=r.agentMetadata?.clientToolAnswer;if(l&&a.agentMetadata&&!a.agentMetadata.clientToolAnswer&&(a.agentMetadata={...a.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let m=r.approval,y=n.approval;a.approval={...m,...y,executionId:y.executionId||m.executionId,toolName:y.toolName||m.toolName,description:y.description||m.description,toolType:y.toolType??m.toolType,reason:y.reason??m.reason,parameters:y.parameters??m.parameters}}let d=n.toolCall?.name,p=n.agentMetadata?.executionId,u=n.toolCall?.id;if(d&&Iv(d)&&p&&u&&n.agentMetadata?.awaitingLocalTool===!0){let m=`${p}:${u}`,y=this.webMcpInflightKeys.has(m),h=this.webMcpResolvedKeys.has(m),C=r.toolCall?.name,w=r.agentMetadata?.executionId===p&&r.toolCall?.id===u&&C!==void 0&&Iv(C)&&r.toolCall?.status==="complete";(y||h||w)&&(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 Sk,FileCode as Ak,FileSpreadsheet as Mk,FileText as Hg,X as Ek}from"lucide";var Tk={add:e=>rv(e)},Pk=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,rd={allowedTypes:ar,maxFileSize:10*1024*1024,maxFiles:4};function kk(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Lk(e){return e==="application/pdf"?Hg:e.startsWith("text/")?Hg:e.includes("word")?Hg:e.includes("excel")||e.includes("spreadsheet")?Mk:e==="application/json"?Ak:Sk}var Mi=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??rd.allowedTypes,maxFileSize:t.maxFileSize??rd.maxFileSize,maxFiles:t.maxFiles??rd.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}hasCustomAdapter(){return typeof this.config.adapter?.add=="function"}adapter(){return this.hasCustomAdapter()?this.config.adapter:Tk}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:rd.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange),t.adapter!==void 0&&(this.config.adapter=t.adapter)}isReady(){return this.attachments.every(t=>t.status==="ready")}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart).filter(t=>t!==null)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(!t.length||this.destroyed)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=sv(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:kk(),file:o,previewUrl:Zc(o)?URL.createObjectURL(o):null,contentPart:null,status:this.hasCustomAdapter()?"uploading":"processing",progress:this.hasCustomAdapter()?0:void 0};this.attachments.push(s),this.renderPreview(s),n.push(s)}this.updatePreviewsVisibility(),this.notify(),await Promise.all(n.map(o=>this.runAdd(o)))}async runAdd(t){let n=new AbortController;this.pendingAdds.set(t.id,n);let o=()=>this.destroyed||n.signal.aborted||this.pendingAdds.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.adapter().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=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=Zc(t.file),o=E("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let u=E("img");u.src=t.previewUrl,u.alt=t.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=E("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=Lk(t.file.type),y=It(m,20,"var(--persona-muted, #6b7280)",1.5);y&&u.appendChild(y);let h=E("span");h.textContent=iv(t.file.type,t.file.name),h.style.fontSize="8px",h.style.fontWeight="600",h.style.color="var(--persona-muted, #6b7280)",h.style.textTransform="uppercase",h.style.lineHeight="1",u.appendChild(h),o.appendChild(u)}let r=G("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=E("div","persona-attachment-progress");s.appendChild(E("div","persona-attachment-progress__bar"));let a=G("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=le("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?a.appendChild(l):a.textContent="\u21BB",a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,a),o.appendChild(r);let d=E("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let p=It(Ek,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 Rv=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),Ik=(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 Hv(){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=>{Ik(e.attachments,u)||(e.attachments=[...u],p())},setMentionRefs:u=>{Rv(e.mentionRefs,u)||(e.mentionRefs=[...u],p())},setSelectedModelId:u=>{e.selectedModelId!==u&&(e.selectedModelId=u,p())},setActiveModeIds:u=>{Rv(e.activeModeIds,u)||(e.activeModeIds=[...u],p())},setQuote:u=>{let m=e.quote;m?.text===u?.text&&m?.messageId===u?.messageId&&m?.sourceLabel===u?.sourceLabel||(e.quote=u?{...u}:void 0,p())},setPendingSubmission:u=>{e.pendingSubmission!==u&&(e.pendingSubmission=u,p())},setPreparing:u=>{e.preparing!==u&&(e.preparing=u,p())},setStreaming:u=>{e.streaming!==u&&(e.streaming=u,p())},setInputDisabled:u=>{e.inputDisabled!==u&&(e.inputDisabled=u,p())},setSendDisabled:u=>{e.sendDisabled!==u&&(e.sendDisabled=u,p())},flush:()=>{o&&d()},destroy:()=>{r=!0,o=!1,t.clear()}}}var Rn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},Wv=(e,t)=>{let n=E("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function Ov(e,t={}){let n=Rn(e,"[data-persona-composer-form]"),o=Rn(e,"[data-persona-composer-input]");if(!n||!o){let P=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||o))throw new Error(P);return typeof console<"u"&&console.warn(P),null}let r={header:Rn(e,"[data-persona-composer-header]"),body:Rn(e,"[data-persona-composer-body]"),actionsStart:Rn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Rn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Rn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Rn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Rn(e,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=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,P,I,O,T)=>{if(P)return P;s.add(S);let R=Wv(I,O);return T.appendChild(R),R},p=d("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=d("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),y=d("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[],C=(S,P)=>S.target===P.target&&S.type===P.type&&S.handler===P.handler,w=Rn(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:a,body:l,actionsStart:p,actionsEnd:u,suggestions:m,status:y,attachmentInput:w,attachmentPreviews:Rn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Rn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Rn(e,"[data-persona-composer-submit]")??void 0,micButton:Rn(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(S,P,I,O)=>{S.addEventListener(P,I,O),h.push({target:S,type:P,handler:I,options:O})},removeListener:(S,P,I,O)=>{S.removeEventListener(P,I,O),h=h.filter(T=>!C(T,{target:S,type:P,handler:I}))},destroy:()=>{for(let S of h)S.target.removeEventListener(S.type,S.handler,S.options);h=[]}}}var qt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},rn=1e5,Ei=rn+1;var Rk=8,Hk=8,Wg=10,Bv=200,_v=300,Dv=0,id=e=>Math.max(0,e);function Nv(e){e.delayMs!==void 0&&(Bv=id(e.delayMs)),e.skipDelayMs!==void 0&&(_v=id(e.skipDelayMs))}var Wk=()=>Date.now()<Dv,Ok=e=>{Dv=e>0?Date.now()+e:0},sd=new WeakMap,Bg="data-persona-tooltip-suppressed",Bk=e=>typeof e.closest=="function"&&e.closest(`[${Bg}]`)!==null;function Fv(e){sd.get(e)?.hide()}var $v=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,_k=e=>{let t=e.getRootNode?.();return $v(t)?t:e.ownerDocument.body},Og=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),Dk=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function Zt(e){sd.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:a=Rk,viewportPadding:l=Hk}=e,d=()=>t.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,y=null,h=null,C,w=!1,S=!1,P=!1,I=()=>(typeof o=="function"?o():o).trim(),O=()=>(typeof r=="function"?r():r??"").trim(),T=()=>id(e.delayMs??Bv),R=()=>id(e.skipDelayMs??_v),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&&Ok(R())},K=()=>{if(!u)return;let ge=d(),Ie=p(),ye=t.getBoundingClientRect(),ce=u.getBoundingClientRect(),Je=ge.documentElement.clientWidth||Ie.innerWidth,fe=ge.documentElement.clientHeight||Ie.innerHeight,F=Je-l-ce.width,Oe=ye.left+ye.width/2-ce.width/2,Ue=Og(Oe,l,F),Bt=ye.top-l,be=fe-l-ye.bottom,Be=ce.height+a,ve=Bt>=Be||Bt>=be?"top":"bottom",xe=ve==="top"?ye.top-a-ce.height:ye.bottom+a,bt=fe-l-ce.height,Rt=Og(xe,l,bt),ut=ye.left+ye.width/2,vn=Math.max(Wg,ce.width-Wg),q=Og(ut-Ue,Wg,vn);u.dataset.placement=ve,u.style.left=`${Ue}px`,u.style.top=`${Rt}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${q}px`)},ie=()=>{if(P||!s||u||!t.isConnected||Bk(t))return;let ge=I(),Ie=_k(t);if(!ge||!Ie)return;let ye=d(),ce=p();u=ye.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Ei);let Je=ce.getComputedStyle?.(t);if(Je){for(let Be of Dk){let ve=Je.getPropertyValue(Be).trim();ve&&u.style.setProperty(Be,ve)}Je.fontFamily&&(u.style.fontFamily=Je.fontFamily)}m=ye.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ge,u.appendChild(m);let fe=O();fe&&(y=ye.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=fe,u.appendChild(y));let F=ye.createElement("span");F.className="persona-control-tooltip__arrow",u.appendChild(F),Ie.appendChild(u),K(),u.dataset.state="open";let Oe=()=>{if(!t.isConnected){D();return}m&&(m.textContent=I()),y&&(y.textContent=O()),K()};ce.addEventListener("scroll",Oe,!0),ce.addEventListener("resize",Oe);let Ue=t.getRootNode(),Bt=$v(Ue)?Ue:ye.documentElement,be=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||D()});be?.observe(Bt,{childList:!0,subtree:!0}),h=()=>{ce.removeEventListener("scroll",Oe,!0),ce.removeEventListener("resize",Oe),be?.disconnect()}},Z=ge=>{if(!(P||u)){if(A(),ge||T()<=0||Wk()){ie();return}C=p().setTimeout(()=>{C=void 0,ie()},T())}},M=()=>{w||S?Z(S):D()},_=()=>{let ge=p();(!ge.matchMedia||!ge.matchMedia("(hover: none)").matches)&&(w=!0,M())},W=()=>{w=!1,M()},H=()=>{try{S=t.matches(":focus-visible")}catch{S=!0}M()},J=()=>{S=!1,M()},V=()=>{w=!1,S=!1,D()},pe=ge=>{ge.key==="Escape"&&V()};n.addEventListener("mouseenter",_),n.addEventListener("mouseleave",W),t.addEventListener("focus",H),t.addEventListener("blur",J),t.addEventListener("keydown",pe),t.addEventListener("click",V);let se={get isOpen(){return u!==null},show:ie,hide:D,reposition:K,destroy:()=>{P||(P=!0,D(),n.removeEventListener("mouseenter",_),n.removeEventListener("mouseleave",W),t.removeEventListener("focus",H),t.removeEventListener("blur",J),t.removeEventListener("keydown",pe),t.removeEventListener("click",V),sd.delete(t))}};return sd.set(t,se),se}var Uv=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];Uv(s)&&Uv(r)?n[o]=Ti(s,r):n[o]=r}return n}var oo="min(440px, calc(100vw - 24px))",_g="440px",Dg="How can I help...",Nk={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)"},lt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:Nk,copy:{inputPlaceholder:Dg,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 jv(e,t){if(!(!e&&!t))return e?t?Ti(e,t):e:t}function Za(e){return e?{...lt,...e,theme:jv(lt.theme,e.theme),darkTheme:jv(lt.darkTheme,e.darkTheme),launcher:{...lt.launcher,...e.launcher,dock:{...lt.launcher?.dock,...e.launcher?.dock},clearChat:{...lt.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...lt.tooltip,...e.tooltip},copy:{...lt.copy,...e.copy},sendButton:{...lt.sendButton,...e.sendButton},statusIndicator:{...lt.statusIndicator,...e.statusIndicator},voiceRecognition:{...lt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=lt.features?.artifacts,n=e.features?.artifacts,o=lt.features?.scrollToBottom,r=e.features?.scrollToBottom,s=lt.features?.scrollBehavior,a=e.features?.scrollBehavior,l=lt.features?.streamAnimation,d=e.features?.streamAnimation,p=lt.features?.askUserQuestion,u=e.features?.askUserQuestion,m=lt.features?.history,y=e.features?.history,h=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},C=o===void 0&&r===void 0?void 0:{...o,...r},w=s===void 0&&a===void 0?void 0:{...s,...a},S=l===void 0&&d===void 0?void 0:{...l,...d},P=p===void 0&&u===void 0?void 0:{...p,...u,styles:{...p?.styles,...u?.styles}},I=m===void 0&&y===void 0?void 0:{...m,...y,copy:{...m?.copy,...y?.copy}};return{...lt.features,...e.features,...C!==void 0?{scrollToBottom:C}:{},...w!==void 0?{scrollBehavior:w}:{},...h!==void 0?{artifacts:h}:{},...S!==void 0?{streamAnimation:S}:{},...P!==void 0?{askUserQuestion:P}:{},...I!==void 0?{history:I}:{}}})(),suggestionChips:e.suggestionChips??lt.suggestionChips,suggestionChipsConfig:{...lt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...lt.layout,...e.layout,header:{...lt.layout?.header,...e.layout?.header},messages:{...lt.layout?.messages,...e.layout?.messages,avatar:{...lt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...lt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...lt.layout?.slots,...e.layout?.slots}},markdown:{...lt.markdown,...e.markdown,options:{...lt.markdown?.options,...e.markdown?.options}},messageActions:{...lt.messageActions,...e.messageActions}}:lt}function Ng(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith("px"))return 20;let o=parseFloat(n);return Number.isFinite(o)&&o>0?o:20}function ad(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function qv(e,t){e.style.maxHeight=`${t*Ng(e)}px`,e.style.overflowY="auto"}function el(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function zv(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Vv(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||!zv(t)}function Fk(e){return(e.submitKey??"enter")!=="enter"||zv(e)?"enter":"send"}function ld(e,t){e.setAttribute("enterkeyhint",Fk(t))}function cd(e,t){let n=t?.autocomplete;e.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?e.removeAttribute(r):e.setAttribute(r,s)};o("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),o("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),o("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),o("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function Fg(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",Ug=40,mn=24,dd=(e,t,n)=>{let o=e.ownerDocument?.defaultView;if(!o)return;let r=o.getComputedStyle(e);for(let s of n){let a=r.getPropertyValue(s).trim();a?t.style.setProperty(s,a):t.style.removeProperty(s)}},pd=(e,t)=>{let n=E("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Dg,n.dir="auto",ld(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:el(n)}),cd(n,e?.composer?.inputAttributes),n.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=ad(e?.composer?.maxLines,t?.defaultMaxLines??3),r=`${o*20}px`;n.style.maxHeight=r,n.style.overflowY="auto";let s=()=>{let l=n.style.maxHeight;if(l!==r){let p=parseFloat(l);if(Number.isFinite(p)&&p>0)return p}let d=o*Ng(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}},Uk="[data-persona-glyph-stack]",jg=(e,t,n="send")=>{let o=G("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),o.append(e,t),o},ud=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",d=e?.copy?.sendButtonLabel??"Send",p=e?.copy?.stopButtonLabel??"Stop",u=t.showTooltip??!1,m=t.size,y=parseFloat(m??"")||Ug,h=t.backgroundColor,C=t.textColor,w=E("div","persona-send-button-wrapper"),S=G("button",{className:gn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${jn}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!C&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?C||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":C||void 0,backgroundColor:n&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),P=null,I=null,O=null;if(n){let A=parseFloat(t.iconSize??"")||Math.round(y*.5),D=t.iconStrokeWidth??2,K=C?.trim()||"currentColor";r&&(P=le(r,A,K,D)),I=le(s,A,K,D),P&&I?(O=jg(P,I),S.appendChild(O)):P?S.appendChild(P):(S.textContent=o,I=null)}else S.textContent=d;S.setAttribute("aria-label",a),w.appendChild(S),Zt({anchor:S,trigger:w,text:()=>S.getAttribute("aria-label")??"",enabled:u});let T="send";return{button:S,wrapper:w,setMode:A=>{if(A===T)return;T=A;let D=A==="stop"?l:a;S.setAttribute("aria-label",D),S.setAttribute("data-persona-send-mode",A),n?(S.querySelector(Uk)??O)?.setAttribute("data-mode",A):S.textContent=A==="stop"?p:d},glyphStack:O}},Pi=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",s=t.provider?.type==="custom";if(!(o||r||s))return null;let l=t.iconName??"mic",d=t.iconSize,p=parseFloat(d??"")||mn,u=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,y=E("div","persona-send-button-wrapper"),h=G("button",{className:gn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",jn,!d&&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}}),w=le(l,p,m||"currentColor",1.5);w?h.appendChild(w):h.textContent="\u{1F3A4}",y.appendChild(h);let S=t.tooltipText??"Start voice recognition",P=t.showTooltip??!1;return Zt({anchor:h,trigger:y,text:()=>h.getAttribute("aria-label")??S,enabled:P}),{button:h,wrapper:y}},gd=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=E("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=E("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??ar).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=E("div","persona-send-button-wrapper"),a=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${jn} ${yo}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=le(r,mn,"currentColor",1.5);l?a.appendChild(l):a.textContent="\u{1F4CE}",a.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(a);let d=t.buttonTooltipText??"Attach file";return Zt({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},md=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=E("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=E("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},fd=()=>G("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function jk(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??jk(t),y=!1,h=null,C=()=>{if(!y)return;let P=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${P.width}px`),a&&(n.style.maxWidth=`${P.width}px`);let I=n.getBoundingClientRect(),O=l?.()??null,T=O!=null?P.top+O:P.top,R=o==="top-start"||o==="top-end"?T-r-I.height:P.bottom+r,D=o==="bottom-end"||o==="top-end"?P.right-I.width:P.left,K=a?.()??null;if(K!=null){let ie=Math.max(P.left,P.right-I.width);D=Math.min(Math.max(P.left+K,P.left),ie)}n.style.top=`${R}px`,n.style.left=`${D}px`},w=()=>{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 P=(t.ownerDocument??document).defaultView??window,I=t.ownerDocument??document,O=()=>{if(!t.isConnected){w(),u?.("anchor-removed");return}C()},T=A=>{let D=typeof A.composedPath=="function"?A.composedPath():[];D.includes(n)||D.includes(t)||(w(),u?.("outside"))},R=P.setTimeout(()=>{I.addEventListener("pointerdown",T,!0)},0);P.addEventListener("scroll",O,!0),P.addEventListener("resize",O),h=()=>{P.clearTimeout(R),I.removeEventListener("pointerdown",T,!0),P.removeEventListener("scroll",O,!0),P.removeEventListener("resize",O)},p?.()};return{get isOpen(){return y},open:S,close:w,toggle:()=>y?w():S(),reposition:C,destroy:w}}var qk='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',zk=["--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"],qg="data-persona-menu-focus",Vk=new Set(["ArrowDown","ArrowUp","Home","End"]);function Kv(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(qk)??e}var Kk=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function Gv(e){let t=e.label,n=!1,o=E("div","persona-send-button-wrapper"),r=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${jn} ${yo}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=G("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let H=e.getButtonSize?.()??"";r.style.width=H,r.style.height=H,r.style.minWidth=H,r.style.minHeight=H,r.style.lineHeight="1",r.replaceChildren();let J=le("plus",mn,"currentColor",1.5);J?r.appendChild(J):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),a();let d=[],p=-1,u=!1,m=()=>{let J=s.getRootNode().activeElement;return J instanceof HTMLElement?J:null},y=()=>{let H=m();for(let J of d){let V=!!H&&Kv(J)===H;J.toggleAttribute(qg,V&&u)}},h=()=>d.filter(H=>H.isConnected||s.contains(H)).map(Kv).filter(H=>!Kk(H)),C=(H,J)=>{H.forEach((V,pe)=>{V.setAttribute("tabindex",pe===J?"0":"-1")})},w=H=>{let J=h();if(J.length===0)return;let V=(H%J.length+J.length)%J.length;p=V,C(J,V),J[V].focus(),y()},S=()=>o.ownerDocument??document,P=null,I=null,O=null,T=()=>{P&&(S().removeEventListener("focusin",P,!0),P=null)},R=()=>{I&&(s.removeEventListener("focusin",I),I=null),O&&(s.removeEventListener("pointerdown",O,!0),O=null)},A=null,D=()=>(A||(A=hd({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),T()}})),A),K=()=>A?.isOpen===!0,ie=(H=!1)=>{if(K()){A?.close(),r.setAttribute("aria-expanded","false"),T(),R(),p=-1,u=!1;for(let J of d)J.removeAttribute(qg);H&&r.focus()}},Z=(H=0,J=!1)=>{if(n||K())return;u=J,dd(r,s,zk),D().open(),r.setAttribute("aria-expanded","true");let V=h();C(V,-1),w(H<0?V.length-1:H),P=pe=>{let se=typeof pe.composedPath=="function"?pe.composedPath():[];se.includes(s)||se.includes(o)||ie()},S().addEventListener("focusin",P,!0),I=()=>y(),s.addEventListener("focusin",I),O=()=>{u=!1},s.addEventListener("pointerdown",O,!0)},M=H=>{H.preventDefault(),H.stopPropagation(),K()?ie(!0):Z(0)},_=H=>{if(H.key==="ArrowDown"||H.key==="Enter"||H.key===" "){H.preventDefault(),u=!0,K()?w(0):Z(0,!0);return}H.key==="ArrowUp"&&(H.preventDefault(),u=!0,K()?w(-1):Z(-1,!0))},W=H=>{switch(Vk.has(H.key)&&(u=!0),H.key){case"ArrowDown":H.preventDefault(),w(p+1);return;case"ArrowUp":H.preventDefault(),w(p-1);return;case"Home":H.preventDefault(),w(0);return;case"End":H.preventDefault(),w(h().length-1);return;case"Escape":H.preventDefault(),H.stopPropagation(),ie(!0);return;case"Tab":ie(!0);return;default:}};return r.addEventListener("click",M),r.addEventListener("keydown",_),s.addEventListener("keydown",W),{trigger:o,triggerButton:r,panel:s,setItems:H=>{for(let V of d)H.includes(V)||V.removeAttribute(qg);if(d=[...H],!K())return;let J=h();C(J,Math.min(p,J.length-1)),y()},isOpen:K,open:()=>Z(0),close:ie,setLabel:H=>{H!==t&&(t=H,l())},applyButtonSize:a,destroy:()=>{n=!0,T(),R(),r.removeEventListener("click",M),r.removeEventListener("keydown",_),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},Yv="data-persona-composer-action",zg="data-persona-composer-disable-when-streaming",Gk="core:overflow",Yk=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function Qk(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let o=E("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function Vg(e){let t=e.clientWidth;if(!t)return 0;let n=e.ownerDocument?.defaultView;if(!n?.getComputedStyle)return t;let o=n.getComputedStyle(e),r=(Number.parseFloat(o.paddingLeft)||0)+(Number.parseFloat(o.paddingRight)||0);return Math.max(0,t-r)}var Qv=(e,t)=>{!e||typeof console>"u"||console.warn(t)},Xk=(e,t)=>t.includes(":")?t:`${e}:${t}`;function Jk(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){Qv(t,`[Persona] composer action "${l.id}" is already contributed by ${Xv(d)}; the ${Xv(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?Xk(p,l.id):l.id,m=l.order??Oo.custom;l.placement==="end"&&m>=Oo.send&&(Qv(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 Xv=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",Jv=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,Zk=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function e0(e,t){if(!e||e==="always")return!0;let n=Zk(t);return e==="when-text"?n:!n}var _r=e=>e.kind==="custom",Kg=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,t0=e=>{let t=Kg(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},n0='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function o0(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(n0)||o.childNodes.forEach(n)};return n(e),t.trim()}var r0=e=>o0(e).length===0;function Zv(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(M,_)=>{let W=M.button;if(!W)return;W.setAttribute("role","menuitem"),W.setAttribute("tabindex","-1"),W.className="persona-composer-overflow-menu__item";for(let V of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])W.style[V]="";W.style.lineHeight="1",_.tooltipText?W.setAttribute("title",_.tooltipText):W.removeAttribute("title"),W.replaceChildren();let H=E("span","persona-composer-overflow-menu__icon");if(_.iconName){let V=le(_.iconName,16,"currentColor",1.5);V&&H.appendChild(V)}let J=E("span","persona-composer-overflow-menu__label");J.textContent=_.shortLabel??_.label,W.append(H,J)},a=(M,_)=>{let W=M.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(zg,_.disableWhenStreaming===!0),M.mode==="menu"){M.tooltip?.destroy(),M.tooltip=void 0,s(M,_);return}W.removeAttribute("role"),W.removeAttribute("tabindex"),W.removeAttribute("title");let H=r(),J=!!_.shortLabel;if(W.className=gn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",jn,yo,J&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),W.style.width=H&&!J?H:"",W.style.height=H??"",W.style.minWidth=H&&!J?H:"",W.style.minHeight=H??"",W.style.fontSize=J?"":"18px",W.style.lineHeight="1",W.style.color=_.iconColor??"",W.style.backgroundColor=_.backgroundColor??"",W.replaceChildren(),_.iconName){let V=le(_.iconName,mn,"currentColor",1.5);V&&W.appendChild(V)}if(J){let V=E("span","persona-composer-action-button__label");V.textContent=_.shortLabel,W.appendChild(V)}else W.firstChild||(W.textContent=_.label);M.tooltip?.destroy(),M.tooltip=Zt({anchor:W,trigger:M.element,text:()=>_.tooltipText??_.label,enabled:!!_.tooltipText})},l=(M,_)=>{let W=M.action,H=G("button",{attrs:{type:"button"}}),J=H;if(_==="bar"){let se=E("div","persona-send-button-wrapper");se.appendChild(H),J=se}J.setAttribute(Yv,M.id);let V={resolved:M,element:J,button:H,owned:!0,managed:!0,busy:!1,visible:!0,mode:_},pe=se=>{if(se.preventDefault(),se.stopPropagation(),V.busy||H.disabled)return;let ge=V.resolved.action;V.mode==="menu"&&h?.close(!0);let Ie;try{Ie=ge.onSelect(e.actionContext,se)}catch(ye){e.reportError(ye,{actionId:V.resolved.id});return}!Ie||typeof Ie.then!="function"||(V.busy=!0,H.setAttribute("aria-busy","true"),Ie.catch(ye=>{e.reportError(ye,{actionId:V.resolved.id})}).finally(()=>{V.busy=!1,H.removeAttribute("aria-busy")}))};return H.addEventListener("click",pe),V.detach=()=>H.removeEventListener("click",pe),a(V,W),V},d=M=>{let _=M.action,W;try{W=_.render({...e.actionContext,id:M.id,action:_})}catch(H){return e.reportError(H,{actionId:M.id}),null}return W?.element?(W.element.setAttribute(Yv,M.id),W.element.toggleAttribute(zg,_.disableWhenStreaming===!0),{resolved:M,element:W.element,owned:!0,managed:!0,destroy:W.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(M,_)=>{if(M.builtIn){let H=M.builtIn.element;return H?{resolved:M,element:H,owned:!1,managed:M.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let W=M.action;return W?_r(W)?d(M):l(M,_):null},u=M=>{if(M.detach?.(),M.tooltip?.destroy(),M.detachMenuSlot?.(),M.detachMenuSlot=void 0,M.menuLabel?.remove(),M.menuLabel=void 0,M.menuSlot?.remove(),M.menuSlot=void 0,M.owned){try{M.destroy?.()}catch(_){e.reportError(_,{actionId:M.resolved.id})}M.element.remove()}},m=(M,_)=>{for(let W=0;W<_.length;W++){let H=_[W];if(!H.managed)continue;let J=null;for(let V=W+1;V<_.length;V++){let pe=_[V];if(!pe.managed&&pe.element.parentElement===M){J=pe.element;break}}J?(H.element.parentElement!==M||H.element.nextSibling!==J)&&M.insertBefore(H.element,J):M.lastChild!==H.element&&M.appendChild(H.element)}},y=(M,_)=>{if(M.button){M.button.disabled=_;return}if(!M.owned)return;let W=M.element;W.toggleAttribute("data-disabled",_),W.setAttribute("aria-disabled",_?"true":"false");let H=W instanceof HTMLButtonElement||W instanceof HTMLSelectElement||W instanceof HTMLInputElement||W instanceof HTMLTextAreaElement?W:W.querySelector("button, select, input, textarea");H&&(H.disabled=_)},h=null,C=null,w=null,S=0,P=()=>{let M=e.getOverflow?.();return M?.enabled===!0?M:void 0},I=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=Gv({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),O=M=>{C!==M&&(w?.disconnect(),C=M,S=Vg(M),!(typeof ResizeObserver>"u")&&(w=new ResizeObserver(_=>{let H=_[_.length-1]?.contentRect?.width??Vg(M);H!==S&&(S=H,ie())}),w.observe(M)))},T=(M,_)=>{let W=Qk(M.collapseAutoActionsBelow,_);if(W===null)return!1;let H=S||Vg(_);return H>0&&H<W},R=(M,_,W)=>{if(!_)return"bar";if(M.resolved.builtIn){let J=Yk(M.resolved.id);return J&&_.includeBuiltIns?.includes(J)?"menu":"bar"}let H=M.resolved.presentation;return H==="overflow"||H==="auto"&&W?"menu":"bar"},A=M=>{let _=M.menuSlot;if(!_)return;if(!r0(M.element)){M.menuLabel?.remove(),M.menuLabel=void 0;return}let W=t0(M.element);if(!W){M.menuLabel?.remove(),M.menuLabel=void 0;return}M.menuLabel||(M.menuLabel=E("span","persona-composer-overflow-menu__label")),M.menuLabel.textContent!==W&&(M.menuLabel.textContent=W),M.menuLabel.parentElement!==_&&_.appendChild(M.menuLabel)},D=(M,_)=>{if(M.mode===_)return M;let W=M.resolved.action;if(W&&!_r(W)){u(M),t.delete(M.resolved.id);let H=l(M.resolved,_);return t.set(M.resolved.id,H),H}if(_==="menu"){let H=G("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Bg]:""}});H.appendChild(M.element),Fv(Kg(M.element)),M.menuSlot=H;let J=V=>{let pe=Kg(M.element);if(pe.disabled)return;let se=V.target===pe||pe.contains(V.target);h?.close(!0),se||pe.click()};H.addEventListener("click",J,!0),M.detachMenuSlot=()=>H.removeEventListener("click",J,!0),M.managed=!0,A(M)}else M.detachMenuSlot?.(),M.detachMenuSlot=void 0,M.menuLabel?.remove(),M.menuLabel=void 0,M.menuSlot?.remove(),M.menuSlot=void 0;return M.mode=_,M},K=(M,_)=>{let W=_.map(H=>H.menuSlot??H.element);for(W.forEach((H,J)=>{let V=M.children[J];V!==H&&(V?M.insertBefore(H,V):M.appendChild(H))});M.children.length>W.length;)M.lastElementChild?.remove()},ie=()=>{if(o)return;let M=e.getBindings();if(!M)return;let _=e.getState(),W=_.phase==="streaming",H=P();H&&O(M.footer);let J=H?T(H,M.footer):!1,V={start:[],end:[]},pe=[];for(let se of n){let ge=t.get(se.id);if(!ge)continue;let Ie=se.action,ye=Ie?Jv(Ie.visible,_,!0)&&e0(Ie.visibility,_):!0;if(ge.visible!==ye&&(ge.visible=ye,!ye&&ge.managed&&(ge.menuSlot??ge.element).remove()),!!ye){if(ge=D(ge,R(ge,H,J)),Ie){let ce=Jv(Ie.disabled,_,!1)||Ie.disableWhenStreaming===!0&&W;y(ge,ce),!_r(Ie)&&Ie.pressed!==void 0&&ge.button?.setAttribute("aria-pressed",Ie.pressed?"true":"false")}ge.mode==="menu"?(A(ge),pe.push(ge)):V[se.placement].push(ge)}}if(pe.length>0){let se=I();K(se.panel,pe),se.setItems(pe.map(ce=>ce.menuSlot??ce.element)),se.applyButtonSize();let ge=Number.isFinite(H?.order)?H?.order:Oo.overflow,Ie=V.start.findIndex(ce=>ce.resolved.order>ge),ye={resolved:{id:Gk,placement:"start",presentation:"bar",order:ge,sequence:-1,source:"core"},element:se.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};V.start.splice(Ie<0?V.start.length:Ie,0,ye)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));m(M.actionsStart,V.start),m(M.actionsEnd,V.end)};return{resolve:()=>{if(o)return;let M=Jk(e.collect()),_=new Set(M.map(W=>W.id));for(let[W,H]of t)_.has(W)||(u(H),t.delete(W));for(let W of M){let H=t.get(W.id);if(!H){let se=p(W,"bar");se&&t.set(W.id,se);continue}let J=H.resolved.action,V=W.action;if(!!J!=!!V||J&&V&&_r(J)!==_r(V)||J&&V&&_r(J)&&_r(V)&&J.render!==V.render){u(H),t.delete(W.id);let se=p(W,H.mode);se&&t.set(W.id,se);continue}H.resolved=W,W.builtIn?(H.managed=W.builtIn.managed===!0||H.mode==="menu",W.builtIn.element&&H.mode==="bar"&&(H.element=W.builtIn.element)):V&&!_r(V)?a(H,V):V&&H.element.toggleAttribute(zg,V.disableWhenStreaming===!0)}n=M,ie()},sync:ie,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,w?.disconnect(),w=null,C=null;for(let M of t.values())u(M);t.clear(),h?.destroy(),h=null,n=[]}}}}var s0="core:model",i0=700,eC=16,a0=["--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"],tC=()=>{let e=G("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=G("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function nC(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=d=>{let p=e.getSelectedModelId();return d.find(u=>u.id===p)??d[0]},s=()=>{let d=G("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),p="",u=()=>{let w=e.getModels(),S=w.map(P=>`${P.id}:${P.label}`).join("|");S!==p&&(p=S,d.replaceChildren(...w.map(P=>{let I=G("option",{attrs:{value:P.id}});return I.textContent=P.label,I}))),d.value=r(w)?.id??""};u(),o=u;let m=()=>{d.value&&e.onSelect(d.value)};d.addEventListener("change",m);let y=w=>w.stopPropagation();d.addEventListener("click",y);let{wrapper:h,chevron:C}=tC();return h.append(d,C),{element:h,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",y)}}},a=()=>{let d=G("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=E("span","persona-composer-model-picker-label"),u=E("span","persona-composer-model-picker-suffix");d.append(p,u);let m=G("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),y=new Map,h="",C=null,w=()=>C?.isOpen===!0,S=(_=!1)=>{w()&&(C?.close(),d.setAttribute("aria-expanded","false"),_&&d.focus())},P=_=>{let W=[...y.values()];if(W.length===0)return;let H=(_%W.length+W.length)%W.length;W[H].focus()},I=_=>{if(w())return;C||(C=hd({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),dd(d,m,a0),C.open(),d.setAttribute("aria-expanded","true");let H=[...y.keys()].indexOf(r(e.getModels())?.id??"");P(_??(H>=0?H:0))},O=_=>{S(!0),e.onSelect(_)},T=_=>{_.preventDefault(),_.stopPropagation();let W=_.currentTarget.getAttribute("data-persona-model-option");W&&O(W)},R=_=>{let W=G("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":_.id}});if(_.icon){let se=le(_.icon,eC,"currentColor",1.5);if(se){let ge=E("span","persona-composer-model-option-icon");ge.appendChild(se),W.appendChild(ge)}}let H=E("span","persona-composer-model-option-body"),J=E("span","persona-composer-model-option-label");if(J.textContent=_.label,H.appendChild(J),_.description){let se=E("span","persona-composer-model-option-description");se.textContent=_.description,H.appendChild(se)}W.appendChild(H);let V=E("span","persona-composer-model-option-check");V.setAttribute("aria-hidden","true");let pe=le("check",eC,"currentColor",2);return pe&&V.appendChild(pe),W.appendChild(V),W.addEventListener("click",T),W},A=()=>{let _=e.getModels(),W=_.map(V=>`${V.id}:${V.label}:${V.icon??""}:${V.description??""}`).join("|");if(W!==h){h=W;for(let V of y.values())V.removeEventListener("click",T);y.clear(),m.replaceChildren(..._.map(V=>{let pe=R(V);return y.set(V.id,pe),pe}))}let H=r(_);for(let[V,pe]of y)pe.setAttribute("aria-selected",String(V===H?.id));p.textContent=H?.label??"";let J=e.getSuffix?.()??"";u.textContent=J,d.setAttribute("aria-label",[t,[H?.label,J].filter(Boolean).join(" ")].filter(Boolean).join(": "))};A(),o=A;let D=_=>{_.preventDefault(),_.stopPropagation(),w()?S(!0):I()},K=_=>{if(_.key==="ArrowDown"){_.preventDefault(),w()?P(0):I(0);return}_.key==="ArrowUp"&&(_.preventDefault(),w()?P(-1):I(-1))},ie=_=>{let W=[...y.values()],H=W.indexOf(_.target?.closest?.(".persona-composer-model-option"));switch(_.key){case"ArrowDown":_.preventDefault(),P(H+1);return;case"ArrowUp":_.preventDefault(),P(H-1);return;case"Home":_.preventDefault(),P(0);return;case"End":_.preventDefault(),P(W.length-1);return;case"Escape":_.preventDefault(),_.stopPropagation(),S(!0);return;case"Tab":S(!0);return;default:}};d.addEventListener("click",D),d.addEventListener("keydown",K),m.addEventListener("keydown",ie);let{wrapper:Z,chevron:M}=tC();return Z.append(d,M),{element:Z,destroy:()=>{o===A&&(o=null),d.removeEventListener("click",D),d.removeEventListener("keydown",K),m.removeEventListener("keydown",ie);for(let _ of y.values())_.removeEventListener("click",T);y.clear(),C?.destroy(),C=null,m.remove()}}};return{action:{id:s0,kind:"custom",placement:"end",order:i0,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}var Gg="[data-persona-composer-chip-row]";function yd(e){e.style.display=e.childElementCount>0?"flex":"none"}function Yg(e){let t=e.querySelector(Gg);if(t)return t;let n=G("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(n,o):e.appendChild(n),n}var l0=":scope > [data-persona-composer-mode]";function oC(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let u=G("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let C=E("span","persona-mention-chip-icon"),w=le(p.iconName,12,"currentColor",1.5);w&&C.appendChild(w),u.appendChild(C)}let m=E("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let y=G("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=le("x",12,"currentColor",2);return h?y.appendChild(h):y.textContent="\xD7",y.addEventListener("click",C=>{C.preventDefault(),C.stopPropagation(),e.onRemove(p.id)}),u.appendChild(y),u},a=()=>Array.from(t.querySelectorAll(l0)),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(w=>p.includes(w.id)),y=m.map(w=>`${w.id}:${w.shortLabel??w.label}`).join("|");if(y===n)return;n=y;let h=new Map;for(let w of a()){let S=w.getAttribute("data-persona-composer-mode");S&&m.some(I=>I.id===S)&&!w.hasAttribute("data-persona-chip-exit")?h.set(S,w):w.hasAttribute("data-persona-chip-exit")||l(w)}let C=t.firstChild;for(let w of m){let S=h.get(w.id);S||(S=s(w),r.has(w.id)||(S.setAttribute("data-persona-chip-enter",""),S.addEventListener("animationend",()=>S?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(w.id),S!==C&&t.insertBefore(S,C),C=S.nextSibling}yd(t)},destroy:()=>{o=!0,d(),yd(t)}}}var rC=e=>`core:mode:${e}`;var Qg=e=>Math.min(300+e,499),sC=e=>`core:mode-group:${e}`;function bd(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function c0(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function iC(e,t){return e?.length?e.filter(n=>!bd(n.groupId,t)&&!c0(n.groupId,t)):[]}var d0=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function aC(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(d0(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 lC(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function cC(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var p0=16;function dC(e){let t=null;return{action:{id:sC(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=G("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",a=p=>{p.preventDefault(),p.stopPropagation();let m=p.currentTarget.getAttribute("data-persona-composer-mode");!m||e.getActiveIds().includes(m)&&e.getGroup()?.selection==="single"||e.onSelect(m)},l=p=>{let u=G("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let y=le(p.iconName,p0,"currentColor",1.5);y&&u.appendChild(y)}let m=E("span","persona-composer-segmented-label");return m.textContent=p.shortLabel??p.label,u.appendChild(m),u.addEventListener("click",a),u},d=()=>{let p=e.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=e.getModes(),m=u.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(m!==s){s=m;for(let C of r.values())C.removeEventListener("click",a);r.clear();let h=u.map(C=>{let w=l(C);return r.set(C.id,w),w});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 pC(e){let t=G("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let a=E("span","persona-composer-quote-bar"),l=E("div","persona-composer-quote-content");if(s.sourceLabel){let m=E("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let d=G("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=td(s.text),l.appendChild(d);let p=G("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=le("x",12,"currentColor",2);u?p.appendChild(u):p.textContent="\xD7",p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),e.onDismiss()}),t.replaceChildren(a,l,p)};return{element:t,render:s=>{if(o)return;let a=s?`${s.sourceLabel??""}\0${s.text}`:"";if(a!==n){if(n=a,!s){t.replaceChildren(),t.style.display="none";return}r(s),t.style.display="flex"}},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function uC(e){let t=G("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(a,l,d,p)=>{let u=G("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[d]:""}}),m=le(a,12,"currentColor",2);return m?u.appendChild(m):u.textContent=l,u.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),p()}),u},s=a=>{let l=td(a.text??"",90);if(l)return l;let d=a.contentParts?.length??0;return d>0?d===1?"1 attachment":`${d} attachments`:(a.mentionRefs?.length??0)>0?a.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:t,render:a=>{if(o||a===n)return;if(n=a,!a){t.replaceChildren(),t.style.display="none";return}let l=E("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let d=G("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});d.textContent=s(a),t.replaceChildren(l,d,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function gC(e){let t=G("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=G("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=e.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=E("div","persona-message-edit-actions"),s=(l,d,p,u)=>{let m=G("button",{className:`persona-message-edit-button ${d}`,attrs:{type:"button",[p]:""},text:l});return m.addEventListener("click",y=>{y.preventDefault(),y.stopPropagation(),u()}),m},a=()=>{let l=n.value.trim();l&&e.onSave(l)};return r.append(s(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),s(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",a)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),e.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),a())}),t.append(n,r),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function mC(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 fC(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 hC(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 yC(e){return e.wrapped||e.text.includes(`
|
|
23
|
-
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission
|
|
24
|
-
`:o===""||
|
|
25
|
-
`||a==="\uFFFC"||!r&&
|
|
26
|
-
`).some(
|
|
27
|
-
`)[0]).startsWith(R.trigger):!1),s=(T,R)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:R}))}catch{}},a=!e.chipRow,l=e.chipRow??G("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,p=null,u=e.textarea,m=null,y=null,h=null,C=null,w=()=>{if(d)return Promise.resolve(d);if(p)return p;let T=Jg().then(R=>(R.setMentionIconRenderer(le),d=R.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:l,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:O,emit:s}),d)).catch(R=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",R),p===T&&(p=null),null));return p=T,T},S=()=>{kC().then(T=>{let R=T.mountInlineComposer({textarea:e.textarea,renderToken:D=>tl(D,{render:t.renderMentionToken}),onMentionRemoved:D=>d?.untrackMention(D)});m=R.input,y=R.destroy;let A=u;A.replaceWith(R.element),u=R.element,C={next:R.element,prev:A},h?.(R.element,A),d?d.rebindComposer(R.input):p&&p.then(D=>D?.rebindComposer(R.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};t.display==="inline"&&S();let P=[],I=new Map;for(let T of n){if(!T.showButton)continue;let R=PC({config:{...t,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},onOpen:()=>{w().then(A=>A?.openMenu(T.trigger))}});P.push(R),I.set(T.trigger,R.button)}let O=(T,R,A)=>{let D=I.get(R);D&&(D.setAttribute("aria-expanded",T?"true":"false"),T?D.setAttribute("aria-controls",A):D.removeAttribute("aria-controls"))};return{affordanceButtons:P.map(T=>T.wrapper),contextRow:l,handleInput:T=>{if(d){d.handleInput();return}if(!EC(T))return;let R=u,A=R.selectionStart??0;MC(R.value,A,n)&&w().then(D=>D?.handleInput())},handleKeydown:T=>{if(d?.isMenuOpen())return d.handleKeydown(T);if(T.key==="Backspace"&&d?.hasMentions()&&!C){let R=u,A=R.selectionStart===0&&R.selectionEnd===0;if((R.value.length===0||A)&&d.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async T=>r(T)?(d??await w())?.dispatchInlineCommand(T)??null:null,clear:()=>d?.clear(),prefetch:()=>{Jg().catch(()=>{})},onComposerSwap:T=>{h=T,C&&T(C.next,C.prev)},destroy:()=>{d?.destroy(),y?.();for(let T of P)T.wrapper.remove();a&&l.remove()}}}var Cd="16px",wd="transparent",y0=(()=>{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})(),RC={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:y0,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"}},HC={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:_g,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Cd,canvasBackground:wd},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function fn(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?fn(e,o):o}function em(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let d=fn(e,a);d!==void 0&&(t[l]={path:l,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function OC(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 BC(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]=BC(s,r):n[o]=r}return n}function b0(e,t){return t?BC(e,t):e}function xd(e,t={}){let n={palette:RC,semantic:HC,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:b0(n.components,e?.components)};if(t.validate!==!1){let r=OC(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,IC="--persona-",v0=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},C0=.179,en=(e,t)=>{for(let[n,...o]of t){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):e[IC+s],r!==void 0)break;r!==void 0&&(e[IC+n]=r)}};function tm(e){let t=em(e),n={};for(let[F,Oe]of Object.entries(t)){let Ue=F.replace(/\./g,"-");n[`--persona-${Ue}`]=Oe.value}en(n,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],en(n,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),en(n,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,en(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Cd,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??wd,en(n,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),en(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],a=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],en(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??a??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??a??n["--persona-muted"],en(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=e.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[F,Oe]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ue=n[`--persona-components-history-overlay-${F}`];Ue&&(n[`--persona-history-overlay-${Oe}`]=Ue)}for(let[F,Oe]of[["background","bg"],["borderRadius","radius"]]){let Ue=n[`--persona-components-history-menu-${F}`];Ue&&(n[`--persona-history-menu-${Oe}`]=Ue)}let m=e.components?.history?.motion;if(m){let F=Bt=>{if(Bt===void 0)return;let be=String(Bt).trim();return/^\d+(\.\d+)?$/.test(be)?`${be}ms`:be},Oe=F(m.enterDurationMs);Oe!==void 0&&(n["--persona-history-enter-ms"]=Oe);let Ue=F(m.exitDurationMs);Ue!==void 0&&(n["--persona-history-exit-ms"]=Ue),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let y=n["--persona-components-history-dangerForeground"];y&&(n["--persona-history-danger-fg"]=y),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let F of["scrim","shadow"]){let Oe=n[`--persona-components-history-confirm-${F}`];Oe&&(n[`--persona-history-confirm-${F}`]=Oe)}for(let[F,Oe]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Ue=n[`--persona-components-tooltip-${F}`];Ue&&(n[`--persona-tooltip-${Oe}`]=Ue)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[F,Oe]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ue=n[`--persona-components-messageActions-${F}`];Ue&&(n[`--persona-message-action-${Oe}`]=Ue)}en(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],C=n["--persona-components-introCard-shadow"],w=(!h||h==="transparent"||h==="none")&&(!C||C==="none"),S=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=w&&S==="1.5rem"?"1.5rem 0":S,en(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),en(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let P=n["--persona-components-markdown-heading-h1-fontSize"];P&&(n["--persona-md-h1-size"]=P);let I=n["--persona-components-markdown-heading-h1-fontWeight"];I&&(n["--persona-md-h1-weight"]=I);let O=n["--persona-components-markdown-heading-h2-fontSize"];O&&(n["--persona-md-h2-size"]=O);let T=n["--persona-components-markdown-heading-h2-fontWeight"];T&&(n["--persona-md-h2-weight"]=T);let R=n["--persona-components-markdown-prose-fontFamily"];R&&R!=="inherit"&&(n["--persona-md-prose-font-family"]=R),en(n,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),en(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),en(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),en(n,[["md-hr-color","components-markdown-hr-color","divider"]]),en(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]),n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],en(n,[["message-border","components-message-border","border"]]),en(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let A=e.components,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 K=A?.labelButton;K&&(K.background&&(n["--persona-label-btn-bg"]=K.background),K.border&&(n["--persona-label-btn-border"]=K.border),K.color&&(n["--persona-label-btn-color"]=K.color),K.padding&&(n["--persona-label-btn-padding"]=K.padding),K.borderRadius&&(n["--persona-label-btn-radius"]=K.borderRadius),K.hoverBackground&&(n["--persona-label-btn-hover-bg"]=K.hoverBackground),K.fontSize&&(n["--persona-label-btn-font-size"]=K.fontSize),K.gap&&(n["--persona-label-btn-gap"]=K.gap));let ie=A?.toggleGroup;ie&&(ie.gap&&(n["--persona-toggle-group-gap"]=ie.gap),ie.borderRadius&&(n["--persona-toggle-group-radius"]=ie.borderRadius));let Z=A?.artifact;if(Z?.toolbar){let F=Z.toolbar;F.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=F.iconHoverColor),F.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=F.iconHoverBackground),F.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=F.iconPadding),F.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=F.iconBorderRadius),F.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=F.iconBorder),F.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Zg(F.toggleGroupGap)),F.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=F.toggleBorderRadius),F.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Zg(F.toggleGroupPadding)),F.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=F.toggleGroupBorder),F.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=F.toggleGroupBorderRadius),F.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=fn(e,F.toggleGroupBackground)??F.toggleGroupBackground),F.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=F.copyBackground),F.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=F.copyBorder),F.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=F.copyColor),F.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Zg(F.copyBorderRadius)),F.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=F.copyPadding),F.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=F.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??F.copyMenuBackground),F.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=F.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??F.copyMenuBorder),F.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=F.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??F.copyMenuShadow),F.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=F.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??F.copyMenuBorderRadius),F.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=F.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??F.copyMenuItemHoverBackground),F.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=F.iconBackground),F.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=F.toolbarBorder)}if(Z?.tab){let F=Z.tab;F.background&&(n["--persona-artifact-tab-bg"]=F.background),F.activeBackground&&(n["--persona-artifact-tab-active-bg"]=F.activeBackground),F.activeBorder&&(n["--persona-artifact-tab-active-border"]=F.activeBorder),F.borderRadius&&(n["--persona-artifact-tab-radius"]=F.borderRadius),F.textColor&&(n["--persona-artifact-tab-color"]=F.textColor),F.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=F.hoverBackground),F.listBackground&&(n["--persona-artifact-tab-list-bg"]=F.listBackground),F.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=F.listBorderColor),F.listPadding&&(n["--persona-artifact-tab-list-padding"]=F.listPadding)}if(Z?.pane){let F=Z.pane;if(F.toolbarBackground){let Oe=fn(e,F.toolbarBackground)??F.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Oe}}if(Z?.card){let F=Z.card;F.background&&(n["--persona-artifact-card-bg"]=F.background),F.border&&(n["--persona-artifact-card-border"]=F.border),F.borderRadius&&(n["--persona-artifact-card-radius"]=F.borderRadius),F.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=F.hoverBackground),F.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=F.hoverBorderColor)}if(Z?.inline){let F=Z.inline;F.background&&(n["--persona-artifact-inline-bg"]=fn(e,F.background)??F.background),F.border&&(n["--persona-artifact-inline-border"]=F.border),F.borderRadius&&(n["--persona-artifact-inline-radius"]=F.borderRadius),F.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=fn(e,F.chromeBackground)??F.chromeBackground),F.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=fn(e,F.chromeBorder)??F.chromeBorder),F.titleColor&&(n["--persona-artifact-inline-title-color"]=fn(e,F.titleColor)??F.titleColor),F.mutedColor&&(n["--persona-artifact-inline-muted-color"]=fn(e,F.mutedColor)??F.mutedColor),F.frameHeight&&(n["--persona-artifact-inline-frame-height"]=F.frameHeight)}let M=A?.code;M&&(M.keywordColor&&(n["--persona-code-keyword-color"]=M.keywordColor),M.stringColor&&(n["--persona-code-string-color"]=M.stringColor),M.commentColor&&(n["--persona-code-comment-color"]=M.commentColor),M.numberColor&&(n["--persona-code-number-color"]=M.numberColor),M.tagColor&&(n["--persona-code-tag-color"]=M.tagColor),M.attrColor&&(n["--persona-code-attr-color"]=M.attrColor),M.propertyColor&&(n["--persona-code-property-color"]=M.propertyColor),M.lineNumberColor&&(n["--persona-code-line-number-color"]=M.lineNumberColor),M.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=M.gutterBorderColor),M.background&&(n["--persona-code-bg"]=fn(e,M.background)??M.background));let _=n["--persona-surface"],W=n["--persona-container"],H=n["--persona-palette-colors-gray-100"]??"#f3f4f6",J=n["--persona-palette-colors-gray-200"]??"#e5e7eb",V=n["--persona-palette-colors-gray-300"]??"#d1d5db",pe=!W||W===_,se=v0(_??n["--persona-background"]),ge=pe&&se!==void 0&&se<C0,Ie=ge?"rgba(255, 255, 255, 0.08)":H,ye=ge?"rgba(255, 255, 255, 0.12)":J,ce=ge?"rgba(255, 255, 255, 0.16)":V,Je=pe?Ie:W,fe=pe?ye:W;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Je,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??fe,pe&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ce),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Je,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Je,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Je,n}var w0={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 x0={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"}}},S0={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},_C=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",A0=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Sd()},nm=e=>A0(e),M0=e=>xd(e),E0=e=>{let t=Ti(S0,e??{})??{};return xd({...t,palette:{...t.palette,colors:{...x0.colors,...t.palette?.colors}}},{validate:!1})},Ps=e=>{let t=nm(e),n=_C(e?.theme),o=_C(e?.darkTheme);return t==="dark"?E0(Ti(n??{},o??{})):M0(n)},T0=e=>tm(e),ki=(e,t)=>{let n=Ps(t),o=T0(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",nm(t))},nl=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Sd())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Sd());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};import{Activity as hx,Check as yx,Copy as bx}from"lucide";var Dr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Ad="24px",om=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",ol=e=>{if(typeof e!="string")return null;let t=/^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(e);if(!t)return null;let n=Number(t[1])/100;return n>0&&n<1?n:null},DC=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var NC=null;var rm=()=>{if(NC!==null)return NC;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},P0="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)},k0=e=>P0.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),FC=(e,t)=>{let n=Ed(e);if(!n)return"";let o=rm(),r=k0(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=>FC(e,!1),rl=e=>FC(e,!0),L0=(e,t)=>t.key?.toLowerCase()===e.key&&(rm()?t.metaKey:t.ctrlKey)===e.mod&&!(rm()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,I0=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},$C=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(L0(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&I0(a))){s.preventDefault();try{l.run(s)}catch(d){Md(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=Ed(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=t.get(l);return d?(Md(`${d.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",rl(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}};import{Idiomorph as R0}from"idiomorph";var Pd=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;R0.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 UC=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var sm={index:-1,draft:""};function jC(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 qC(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 zC(){return new Map}function VC(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function KC(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function GC(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function YC(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function QC(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Bo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ks(e,t){return Bo(e)-e.scrollTop<=t}function XC(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 JC(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 ZC(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function im(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 ew(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var sl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},H0=["pre","code","a","script","style"],kd=e=>({type:e?.type??sl.type,placeholder:e?.placeholder??sl.placeholder,speed:e?.speed??sl.speed,duration:e?.duration??sl.duration,buffer:e?.buffer??sl.buffer}),nw=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],il=new Map;for(let e of nw)il.set(e.name,e);var ow=["wipe","glyph-cycle"],Ld=e=>{il.set(e.name,e)},W0=e=>{nw.some(t=>t.name===e)||il.delete(e)},O0=()=>Array.from(il.keys()),al=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:il.get(e)??null,Id=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
28
|
-
`);return s<0?"":e.slice(0,s)}return e},B0=(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},_0=(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},am=/\s/,D0=(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},N0=(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(am.test(s[l])){let d=l;for(;d<s.length&&am.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&&!am.test(s[p]);)d.appendChild(B0(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,e)},F0=(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(_0(o,d,t,n.value)),n.value+=1));r.replaceChild(a,e)},ll=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??H0).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)D0(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=t==="char"?N0:F0;for(let m of l)u(m,n,p);return r.innerHTML},Rd=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},cl=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},tw=new WeakMap,$0=(e,t)=>{if(!e.styles)return;let n=tw.get(t);if(n||(n=new Set,tw.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)},lm=new WeakMap,U0=(e,t)=>{if(!e.onAttach)return;let n=lm.get(t);if(n||(n=new Map,lm.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},rw=e=>{let t=lm.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},dl=(e,t)=>{$0(e,t),U0(e,t)};var{setLoader:S_,load:j0}=ft({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var sw=j0;function cm(e,t=rn){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var pl=0,Nr=null;function dm(e=document){if(pl++,pl===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Nr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,pl=Math.max(0,pl-1),pl===0&&Nr)){let n=e.body,o=e.defaultView??window;n.style.overflow=Nr.originalOverflow,n.style.position=Nr.originalPosition,n.style.top=Nr.originalTop,n.style.width=Nr.originalWidth,o.scrollTo(0,Nr.scrollY),Nr=null}}}var ul={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},St=e=>(e?.launcher?.mountMode??"floating")==="docked",Fr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",qn=e=>{let t=e?.launcher?.dock;return{side:t?.side??ul.side,width:t?.width??ul.width,animate:t?.animate??ul.animate,reveal:t?.reveal??ul.reveal,maxHeight:t?.maxHeight??ul.maxHeight}};import{ArrowRight as q0}from"lucide";var pm=e=>e==="followUp"?"follow-up":e,um=(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"}},z0=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'}},iw=new WeakSet,V0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,K0=e=>{V0()||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"})})},gm=e=>{var O,T,R;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:d,chipsConfig:p,session:u,getTextarea:m,eventTarget:y,submitPrompt:h}=e,C=o==="followUp",w=t.behavior,S=()=>{if(u.isStreaming())return;let A={suggestion:{...t},surface:o,source:r,behavior:w},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 ie of d)if(ie.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let K=m();if(w==="fill"){K.value=t.prompt,K.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),K.focus();return}if(h){h(t.prompt);return}K.value="",u.sendMessage(t.prompt)},P=()=>{let A=E("button",`persona-suggestion persona-suggestion--${s}`);if(A.type="button",A.disabled=a,A.dataset.suggestionId=t.id,A.dataset.emphasis=t.emphasis,A.dataset.behavior=w,s==="chip"&&(p?.fontFamily&&(A.style.fontFamily=z0(p.fontFamily)),p?.fontWeight&&(A.style.fontWeight=p.fontWeight),p?.paddingX&&(A.style.paddingLeft=p.paddingX,A.style.paddingRight=p.paddingX),p?.paddingY&&(A.style.paddingTop=p.paddingY,A.style.paddingBottom=p.paddingY)),t.icon){let K=le(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);K&&(K.classList.add("persona-suggestion__icon"),t.iconColor&&(K.style.color=t.iconColor),A.appendChild(K))}let D=E("span","persona-suggestion__copy");if(D.appendChild(G("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&D.appendChild(G("span",{className:"persona-suggestion__description",text:t.description})),A.appendChild(D),s!=="chip"){let K=It(q0,16,"currentColor",1.8);K&&(K.classList.add("persona-suggestion__arrow"),A.appendChild(K))}return A.addEventListener("click",S),A},I=null;for(let A of d)if(A.renderSuggestion&&(I=A.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:P,select:S}),I))break;return I??(I=P()),(O=I.dataset).suggestionId||(O.suggestionId=t.id),(T=I.dataset).behavior||(T.behavior=w),(R=I.dataset).emphasis||(R.emphasis=t.emphasis),I instanceof HTMLButtonElement||I.setAttribute("aria-disabled",a?"true":"false"),I},gl=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,e.scrollWidth-e.clientWidth);if(u<=1){s();return}let m=getComputedStyle(e).direction==="rtl",y=Math.min(u,Math.max(0,Math.abs(e.scrollLeft))),h=4,C=y<=h,w=y>=u-h,S=m?!w:!C,P=m?!C:!w;e.toggleAttribute("data-scroll-left",S),e.toggleAttribute("data-scroll-right",P)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,m,y,h,C,w)=>{e.replaceChildren(),t.length=0,n.length=0;let S=w?.source??"config",P=w?.surface??(S==="config"?"starter":"followUp"),I=P==="followUp",O=w?.variant??"chip",T=w?.behavior??"send",R=w?.overflow??"wrap",A=w?.config??{},D=w?.plugins??[],K=typeof w?.maxItems=="number"?Math.max(0,Math.floor(w.maxItems)):void 0,ie=I?"followUps":"starters";!iw.has(A)&&A.debug===!0&&O!=="chip"&&A.suggestions?.[ie]?.overflow!==void 0&&(iw.add(A),console.info(`[persona] suggestions.${ie}.overflow applies to the "chip" variant only; the "${O}" variant manages its own stacking.`));let Z=V=>V.map(um).filter(pe=>pe!==null).map(pe=>({...pe,behavior:pe.behavior??T})),M=Z(u??[]);D.forEach(V=>{V.transformSuggestions&&(M=Z(V.transformSuggestions({suggestions:M.map(pe=>({...pe})),surface:P,source:S,config:A})))});let _=K===void 0?M:M.slice(0,K);if(!_.length){e.hidden=!0,o=null,s();return}if(!I&&(h??m.getMessages()).some(pe=>pe.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=pm(P),e.dataset.variant=O,e.dataset.overflow=R;let W=document.createDocumentFragment(),H=m.isStreaming();_.forEach((V,pe)=>{let se=gm({item:V,index:pe,surface:P,source:S,variant:O,streaming:H,config:A,plugins:D,chipsConfig:C,session:m,getTextarea:()=>y,eventTarget:e,submitPrompt:w?.submitPrompt});W.appendChild(se),n.push(se),[...se instanceof HTMLButtonElement?[se]:[],...Array.from(se.querySelectorAll("button"))].forEach(Ie=>{t.includes(Ie)||(Ie.disabled=H,t.push(Ie))})}),e.appendChild(W),a(),l();let J=JSON.stringify({normalized:_,surface:P,variant:O,source:S});J!==o&&(o=J,K0(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:_.map(V=>({...V})),surface:P,source:S,variant:O},bubbles:!0,composed:!0})),I&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:_.map(V=>V.prompt)},bubbles:!0,composed:!0})))}}};var zn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var G0="persona-header-control",Y0="persona-header-control--glyph",Q0="persona-header-control--sparse",X0=20,J0={x:[1.4,1.05]},aw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Z0="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Hd=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=J0[t]??[1,1.5],l=!o;e.classList.toggle(Y0,l),e.classList.toggle(Q0,l&&s!==1);let d=parseFloat(o??"")||X0,p=le(t,`${Math.round(d*s)}px`,"currentColor",a);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),e.replaceChildren(p)):r&&(e.textContent=r)},Ls=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=aw,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:y,borderRadius:h,paddingX:C,paddingY:w,hidden:S,extraClassName:P,attrs:I}=e,O=E("div",a),T=!!(m||y),R=G("button",{className:gn(G0,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!T&&"persona-border-none",!h&&"persona-rounded-full",P),attrs:{type:"button","aria-label":t,...I},style:{width:l,height:l,minWidth:l,minHeight:l,display:S?"none":void 0,color:p||hn.actionIconColor,backgroundColor:u,border:T?`${m||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:h,paddingLeft:C,paddingRight:C,paddingTop:w,paddingBottom:w}});return r?Hd(R,r,{iconSize:d,iconText:s}):s&&(R.textContent=s),O.appendChild(R),Zt({anchor:R,trigger:O,text:()=>R.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:R,wrapper:O}},Li=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=aw,buttonSize:r,iconSize:s}=t,a=e?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=Ls({ariaLabel:l,tooltip:d,iconName:a.closeButtonIconName??"x",iconText:a.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??a.closeButtonSize,iconSize:s,color:a.closeButtonColor,backgroundColor:a.closeButtonBackgroundColor,borderWidth:a.closeButtonBorderWidth,borderColor:a.closeButtonBorderColor,borderRadius:a.closeButtonBorderRadius,paddingX:a.closeButtonPaddingX,paddingY:a.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:u}},Ii=(e,t={})=>{let{wrapperClassName:n=Z0,buttonSize:o,iconSize:r}=t,a=(e?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=Ls({ariaLabel:l,tooltip:d,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:p,wrapper:u}};var hn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))",minHeight:"var(--persona-header-min-height, auto)"},mm={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)"},eL={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},$r=e=>{let{config:t,showClose:n=!0}=e,o=G("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{minHeight:hn.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,p=G("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(d){let R=parseFloat(s)||24,A=le(d,R*.6,"currentColor",1);A?p.replaceChildren(A):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let R=E("img");R.src=t.launcher.iconUrl,R.alt="",R.className="persona-rounded-xl persona-object-cover",R.style.height=s,R.style.width=s,p.replaceChildren(R)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let u=E("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=G("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:hn.titleColor,...mm}}),y=G("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:hn.subtitleColor,...eL}});u.append(m,y),l?o.append(u):o.append(p,u);let h=r.clearChat??{},C=h.enabled??!0,w=h.placement??"inline",S=null,P=null;if(C){let A=Ii(t,{wrapperClassName:w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=A.button,P=A.wrapper,w==="top-right"&&(P.style.right="48px"),w==="inline"&&o.appendChild(P)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&w==="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:O,wrapper:T}=Li(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(T),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:y,closeButton:O,closeButtonWrapper:T,clearChatButton:S,clearChatButtonWrapper:P}},Ri=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Hi(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=e,l=E("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(Ei)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let C of t){if(C.dividerBefore){let P=document.createElement("hr");l.appendChild(P)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",C.id),C.destructive&&w.setAttribute("data-destructive",""),C.icon){let P=le(C.icon,16,"currentColor",1.5);P&&w.appendChild(P)}let S=document.createElement("span");S.textContent=C.label,w.appendChild(S),w.addEventListener("click",P=>{P.stopPropagation(),m(),n(C.id)}),l.appendChild(w)}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 w=S=>{!l.contains(S.target)&&!o.contains(S.target)&&m()};document.addEventListener("click",w,!0),d=()=>document.removeEventListener("click",w,!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=E("button",gn(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=le(t,o??16,"currentColor",r??2);if(u&&p.appendChild(u),l&&p.addEventListener("click",l),d)for(let[m,y]of Object.entries(d))p.setAttribute(m,y);return p}function lw(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:d}=e,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let u=E("button",p);if(u.type="button",u.setAttribute("aria-label",n),t){let y=le(t,s??14,"currentColor",2);y&&u.appendChild(y)}let m=E("span");if(m.textContent=n,u.appendChild(m),l&&u.addEventListener("click",l),d)for(let[y,h]of Object.entries(d))u.setAttribute(y,h);return u}function Wd(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=E("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function d(){for(let u of l)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of t){let m;u.icon?m=Vn({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,d(),o(u.id)}}):(m=E("button","persona-icon-btn"+(u.className?" "+u.className:"")),m.type="button",m.setAttribute("aria-label",u.label),m.title=u.label,m.textContent=u.label,m.addEventListener("click",()=>{a=u.id,d(),o(u.id)})),m.setAttribute("aria-pressed",u.id===a?"true":"false"),l.push({id:u.id,btn:m}),s.appendChild(m)}function p(u){a=u,d()}return{element:s,setSelected:p}}function tL(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,w=E("div","persona-split-btn"+(y?" "+y:"")),S={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},P=r&&n?Vn({...S,icon:n,size:o??14}):lw({...S,icon:n,iconSize:o??14}),I=Vn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(C?" "+C:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});w.append(P,I);let O=null,T=()=>{if(O)return O;let R=(typeof p=="function"?p():p)??void 0;return O=Hi({items:s,onSelect:a,anchor:w,position:d,portal:R,onOpenChange:A=>{I.setAttribute("aria-expanded",A?"true":"false")}}),R||w.appendChild(O.element),O};return w.isConnected?T():requestAnimationFrame(()=>{O||T()}),I.addEventListener("click",R=>{R.stopPropagation(),T().toggle()}),{element:w,primaryButton:P,chevronButton:I,openMenu:()=>T().show(),closeMenu:()=>O?.hide(),toggleMenu:()=>T().toggle(),destroy:()=>{O?.destroy(),w.remove()}}}function fm(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:d}=e,p=E("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",t);let u=E("span","persona-combo-btn-label");u.textContent=t,p.appendChild(u);let m=le(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",p.appendChild(m)),d&&(p.style.borderRadius=d.borderRadius??"10px",p.style.padding=d.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=d.background??"",p.style.borderColor=d.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let y=Hi({items:o,onSelect: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 w=!y.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",w?"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 cw=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 nL(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=Ls({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Td(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let a=rl(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=Hi({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var dw=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=E("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=hn.minHeight,l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r?.titleMenu,p,u;if(d){let T=fm({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:R=>{let A=K=>{K===!1&&T.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:R}}))},D=d.onSelect(R);D instanceof Promise?D.then(A,()=>{}):A(D)},hover:d.hover,className:""});p=T.element,p.style.color=hn.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=E("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=E("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=hn.titleColor,Object.assign(u.style,mm),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let R=r.onTitleClick;p.addEventListener("click",A=>{A.target.closest("button")||R()}),p.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),R())})}let T=r?.titleRowHover;T&&(p.style.borderRadius=T.borderRadius??"10px",p.style.padding=T.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=T.background??"",p.style.borderColor=T.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:y,wrapper:h}=Li(t,{showClose:n,wrapperClassName:m});o&&y.addEventListener("click",o);let C=E("div","persona-flex persona-items-center persona-gap-1");d||nL(C,r?.trailingActions,r?.onAction??s);let w=a.clearChat??{},S=null,P=null;if(w.enabled??!0){let T=w.placement??"inline",R=Ii(t,{wrapperClassName:T==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});S=R.button,P=R.wrapper,T==="top-right"?P.style.right="48px":C.appendChild(P)}C.appendChild(h),l.appendChild(C);let I=E("div");I.style.display="none";let O=E("span");return O.style.display="none",{header:l,iconHolder:I,headerTitle:u,headerSubtitle:O,closeButton:y,closeButtonWrapper:h,clearChatButton:S,clearChatButtonWrapper:P}},hm={default:cw,minimal:dw},pw=e=>hm[e]??hm.default,ml=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=E("div");l.style.display="none";let d=E("span"),p=E("span"),u=E("button");u.style.display="none";let m=E("div");return m.style.display="none",{header:a,iconHolder:l,headerTitle:d,headerSubtitle:p,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=pw(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Wi=e=>{let{config:t}=e,n=G("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=fd(),r=G("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=pd(t);a();let l=ud(t),d=Pi(t),p=gd(t),u=md(t),m=G("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),p&&(p.previewsContainer.style.gap="8px",m.append(p.previewsContainer),r.append(p.input)),r.append(s);let y=G("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=G("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),C=G("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&h.append(p.wrapper),d&&C.append(d.wrapper),C.append(l.wrapper),y.append(h,C),r.append(y),r.addEventListener("click",w=>{w.target!==l.button&&w.target!==l.wrapper&&w.target!==d?.button&&w.target!==d?.wrapper&&w.target!==p?.button&&w.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 oL,MessageSquare as rL}from"lucide";var uw=()=>{let e=G("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=E("span","persona-pill-peek__icon"),n=It(rL,16,"currentColor",1.5);n&&t.appendChild(n);let o=E("span","persona-pill-peek__text"),r=E("span","persona-pill-peek__caret"),s=It(oL,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Od=e=>{let{config:t}=e,n=G("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=fd(),r=md(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=pd(t,{defaultMaxLines:5});a();let l=ud(t),d=Pi(t),p=gd(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=G("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=G("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let y=G("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&y.append(d.wrapper),y.append(l.wrapper),u.addEventListener("click",w=>{w.target!==l.button&&w.target!==l.wrapper&&w.target!==d?.button&&w.target!==d?.wrapper&&w.target!==p?.button&&w.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,y);let h=G("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),p&&h.append(p.previewsContainer),n.append(o,u,r);let 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 sL=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}},iL=(e,t)=>{if(!e)return null;let n=sL(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},aL=(e,t)=>{let n=E("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},lL=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},bm=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(":"))},vm=320,yw=320,cL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),dL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),pL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),uL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),gL=e=>{if(!e||e.length===0)return null;let t=G("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=G("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=E("span","persona-mention-chip-icon"),s=le(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(G("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},mL=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(tl(o.ref,{readonly:!0,render:t}))}return n},gw="\uE000",mw="\uE001",fL=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${gw}${r}:${y}${mw}`,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(mL(t,o));return}e.innerHTML=l;let p=new RegExp(`${gw}${r}:(\\d+)${mw}`),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 w=t[Number(C[1])],S=h.splitText(C.index);S.data=S.data.slice(C[0].length),w?.kind==="mention"&&S.parentNode?.insertBefore(tl(w.ref,{readonly:!0,render:o}),S),h=S}}},hL=(e,t,n)=>{if(e.length===0)return null;try{let o=E("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,d)=>{let p=E("img");p.alt=l.alt?.trim()||`Attached image ${d+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${vm}px`,p.style.maxHeight=`${yw}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}),lL(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}},yL=e=>{if(e.length===0)return null;try{let t=E("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!bm(o.audio))return;let r=E("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${vm}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},bL=e=>{if(e.length===0)return null;try{let t=E("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!bm(o.video))return;let r=E("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${vm}px`,r.style.maxHeight=`${yw}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}},vL=e=>{if(e.length===0)return null;try{let t=E("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!bm(o.data))return;let r=E("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Oi=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},bw=(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()},CL=(e,t)=>{let n=E("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=E("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},fw=(e,t,n="div")=>{let o=E(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},fl=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},hw={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"}},wL=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=hw[n??"bubble"]??hw.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:",xL=e=>`${Bd}${e}`,vw=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),Cw=(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=vw(t,e.role);if(!r&&!s&&!a&&!l&&!d&&!p&&!u&&m.length===0){let O=E("div");return O.style.display="none",O.id=`actions-${e.id}`,O.setAttribute("data-actions-for",e.id),O}let y=t.visibility??"hover",h=t.align??"right",C=t.layout??"pill-inside",w={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],P=E("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${w} ${S} ${y==="hover"?"persona-message-actions-hover":""}`);P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id);let I=(O,T,R)=>{let A=Vn({icon:O,label:T,size:14,className:"persona-message-action-btn",chromeless:!0});return A.setAttribute("data-action",R),A};r&&P.appendChild(I("copy","Copy message","copy")),l&&P.appendChild(I("volume-2","Read aloud","read-aloud")),s&&P.appendChild(I("thumbs-up","Upvote","upvote")),a&&P.appendChild(I("thumbs-down","Downvote","downvote")),d&&P.appendChild(I("refresh-cw","Regenerate response","regenerate")),p&&P.appendChild(I("pencil","Edit message","edit")),u&&P.appendChild(I("quote","Quote message","quote"));for(let O of m)P.appendChild(I(O.iconName??"ellipsis",O.label,xL(O.id)));return P},hl=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",d=a.avatar,p=a.timestamp,u=d?.show??!1,m=p?.show??!1,y=d?.position??"left",h=p?.position??"below",C=fl(e.role,l),w=E("div",C.join(" "));w.id=`bubble-${e.id}`,w.setAttribute("data-message-id",e.id),w.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let S=s?.widgetConfig?.theme?.components?.message;wL(w,e.role,l,e.role==="user"?S?.user:S?.assistant),l==="flat"?(w.style.backgroundColor="transparent",w.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(w.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",w.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(w.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",w.style.color="var(--persona-message-assistant-text, var(--persona-text))");let P=cL(e),I=e.content?.trim()??"",T=P.length>0&&I===wi,R=kd(s?.widgetConfig?.features?.streamAnimation),A=s?.widgetConfig?.features?.streamAnimation?.plugins,D=e.role==="assistant"&&R.type!=="none"?al(R.type,A):null,K=e.role==="assistant"&&D?.isAnimating?.(e)===!0,ie=e.role==="assistant"&&D!==null&&(!!e.streaming||K);ie&&D?.bubbleClass&&w.classList.add(D.bubbleClass);let Z=document.createElement("div");Z.classList.add("persona-message-content"),e.streaming&&Z.classList.add("persona-content-streaming"),ie&&D&&(D.containerClass&&Z.classList.add(D.containerClass),Z.style.setProperty("--persona-stream-step",`${R.speed}ms`),Z.style.setProperty("--persona-stream-duration",`${R.duration}ms`));let M=ie?Id(e.content??"",R.buffer,D,e,!!e.streaming):e.content??"",_=()=>{let fe=t({text:M,message:e,streaming:!!e.streaming,raw:e.rawContent});return ie&&D?.wrap==="char"?ll(fe,"char",e.id,{skipTags:D.skipTags}):ie&&D?.wrap==="word"?ll(fe,"word",e.id,{skipTags:D.skipTags}):fe},W=null;if(T?(W=document.createElement("div"),W.innerHTML=_(),W.style.display="none",Z.appendChild(W)):e.contentSegments?.length?fL(Z,e.contentSegments,fe=>t({text:fe,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):Z.innerHTML=_(),ie&&D?.useCaret&&!T&&I){let fe=Rd(),F=Z.querySelectorAll(".persona-stream-char, .persona-stream-word"),Oe=F[F.length-1];if(Oe?.parentNode)Oe.parentNode.insertBefore(fe,Oe.nextSibling);else{let Ue=Z.lastElementChild;Ue?Ue.appendChild(fe):Z.appendChild(fe)}}if(m&&h==="inline"&&e.createdAt){let fe=fw(e,p,"span");fe.classList.add("persona-timestamp-inline");let F=Z.lastElementChild;F?F.appendChild(fe):Z.appendChild(fe)}if(P.length>0){let fe=hL(P,!T&&!!I,()=>{T&&W&&(W.style.display="")});fe?w.appendChild(fe):T&&W&&(W.style.display="")}let H=dL(e);if(H.length>0){let fe=yL(H);fe&&w.appendChild(fe)}let J=pL(e);if(J.length>0){let fe=bL(J);fe&&w.appendChild(fe)}let V=uL(e);if(V.length>0){let fe=vL(V);fe&&w.appendChild(fe)}let pe=e.contentSegments?.length?null:gL(e.contextMentions);if(pe&&w.appendChild(pe),w.appendChild(Z),m&&h==="below"&&e.createdAt){let fe=fw(e,p);fe.classList.add("persona-mt-1"),w.appendChild(fe)}let se=e.role==="assistant"?iL(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let fe=!!(M&&M.trim()),F=R.placeholder==="skeleton",Oe=F&&R.buffer==="line"&&fe;if(fe)Oe&&w.appendChild(cl());else if(F)w.appendChild(cl());else{let Ue=bw("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);Ue&&w.appendChild(Ue)}}se&&e.stopReason&&!e.streaming&&(I||(Z.style.display="none"),w.appendChild(aL(e.stopReason,se)));let ge=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1,Ie=s?.actionEligibility,ye=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Ie?.canEdit===!0||o?.showQuote===!0&&Ie?.canQuote===!0||vw(o,"user").length>0);if((ge||ye)&&o){let fe=Cw(e,ye?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Ie);w.appendChild(fe)}if(!u||e.role==="system")return w;let ce=E("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Je=CL(d,e.role);return y==="right"||y==="left"&&e.role==="user"?ce.append(w,Je):ce.append(Je,w),ce},SL=(e,t,n,o,r,s)=>{let a=n??{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):hl(e,t,n,o,r,s)};var AL=40,ML=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=le(t.name,AL);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(G("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(G("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},ww=(e,t,n={})=>{let o=G("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=E("p","persona-welcome-kicker");r.hidden=!0;let s=E("h2","persona-welcome-title"),a=E("p","persona-welcome-subtitle"),l=G("div",{className:"persona-welcome-head-text"},r,s),d=G("div",{className:"persona-welcome-title-row"},o,l);return{host:G("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},d,a,t),iconHolder:o,kicker:r,title:s,subtitle:a,starterSuggestions:t}},Bi=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},Dd=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",ML(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")},EL="data-persona-welcome-plugin",xw="data-persona-welcome-overlay",_d="persona-welcome-overlay-active",Cm=new WeakMap,wm=(e,t,n)=>{n.setAttribute(EL,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(xw,""),e.classList.contains(_d)||(Cm.set(e,e.scrollTop),e.classList.add(_d),e.scrollTop=0)},xm=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(xw),e.classList.contains(_d)&&(e.classList.remove(_d),e.scrollTop=Cm.get(e)??e.scrollTop,Cm.delete(e))},Sw=()=>{let e=G("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Nd=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=G("div",{className:fl("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(G("div",{className:"persona-flex"},r)),e.hidden=!1},Aw=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Mw=(e,t)=>{if(Aw()||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 w=e.previousElementSibling,S=e.nextElementSibling,I=o.getBoundingClientRect().top+(parseFloat(C.borderTopWidth)||0)+(parseFloat(C.paddingTop)||0)-o.scrollTop;s=Math.max(0,w?n.top-w.getBoundingClientRect().bottom-r:n.top-I),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},Ew=(e,t,n)=>{if(t<=1||Aw()||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 TL="Hello \u{1F44B}",PL="I can answer questions and help you get things done here.",Tw=new WeakSet,yn=(e,t)=>!!e&&e[t]!==void 0,kL=(e,t)=>{!e||e.debug!==!0||!t.length||Tw.has(e)||(Tw.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},_o=e=>{let t=e?.welcome,n=e?.copy,o=yn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":yn(t,"dismiss")?t.dismiss:"never",s=[];yn(t,"title")&&yn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),yn(t,"subtitle")&&yn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),yn(t,"variant")&&yn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&yn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&yn(t,"dismiss")&&t.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let a=t?.anchor==="center"?"center":"bottom",l=ol(t?.anchorComposerTop)!==null;return yn(t,"anchorComposerTop")&&!l&&s.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),a!=="center"&&(yn(t,"anchorComposerTop")||yn(t,"composerGap"))&&s.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),kL(e,s),{title:yn(t,"title")?t.title:n?.welcomeTitle??TL,kicker:t?.kicker??"",subtitle:yn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??PL,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}},Pw=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Is=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var kw="16px",Am="10px",Mm="14px",Lw=e=>{let t=e?.launcher?.enabled??!0,n=St(e);if(Fr(e)){let u=e?.launcher?.composerBar??{},m=E("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=u.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??rn);let y=E("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",m.appendChild(y);let h=E("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=u.expandedSize??"anchored",h.style.zIndex=String(e?.launcher?.zIndex??rn),{wrapper:m,panel:y,pillRoot:h}}if(n){let u=E("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=E("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return u.appendChild(m),{wrapper:u,panel:m}}if(!t){let u=E("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=E("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=e?.launcher?.width??"100%";return u.style.width=y,m.style.width="100%",u.appendChild(m),{wrapper:u,panel:m}}let r=e?.launcher??{},s=r.position&&zn[r.position]?zn[r.position]:zn["bottom-right"],a=E("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??rn);let l=E("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=e?.launcher?.width??e?.launcherWidth??oo;return l.style.width=p,l.style.maxWidth=p,a.appendChild(l),{wrapper:a,panel:l}},Em=e=>{let t=G("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":pm(e)}});return t.hidden=!0,t},Iw=(e,t)=>{let n=Em("starter"),o=ww(e,n,{flatShadow:St(e)}),r=_o(e);Dd(o,r),Bi(t,o.host,Is(r,e?.initialMessages));let s=Sw();return Nd(s,r.message,e),{welcome:o,greetingHost:s}},LL=(e,t)=>{let n=E("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Li(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:kw,iconSize:Am});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=Ii(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:kw,iconSize:Mm});a=D.button,l=D.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=G("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=G("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=Iw(e,p),{host:y,title:h,subtitle:C}=u,w=u.starterSuggestions,S=E("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),P=Em("followUp"),I=Dr(e,!0);I&&(S.style.maxWidth=I,S.style.marginLeft="auto",S.style.marginRight="auto",S.style.width="100%"),p.append(y,m,S,P);let O=G("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),T=Od({config:e}),{root:R,textNode:A}=uw();return n.append(d,r,p,O),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:S,starterSuggestions:w,transcriptSuggestions:P,composerOverlay:O,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:E("span"),headerTitle:E("span"),headerSubtitle:E("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:R,peekTextNode:A}},Rw=(e,t=!0)=>{if(Fr(e))return LL(e,t);let n=G("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?ml(e,o,{showClose:t}):$r({config:e,showClose:t}),a=G("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=Iw(e,a),{host:p,title:u,subtitle:m}=l,y=l.starterSuggestions,h=E("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),C=Em("followUp"),w=Dr(e,!1);w&&(h.style.maxWidth=w,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),a.append(p,d,h,C);let S=Wi({config:e}),P=e?.layout?.showFooter!==!1;r?Ri(n,s,e):(s.header.style.display="none",Ri(n,s,e)),n.append(a);let I=G("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return P||(S.footer.style.display="none"),n.append(S.footer),n.append(I),{container:n,body:a,messagesWrapper:h,starterSuggestions:y,transcriptSuggestions:C,composerOverlay:I,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 Tm=(e,t)=>{let n=E("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(yo(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(d){let p=[];a&&p.push(yo(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=rl(),a=js();this.activeAssistantMessageId=null;let l=n?.contentParts&&ul(n.contentParts)?Ui:"",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(h=>h.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(y=>y.id===s)??d,h=TC({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});h.contentParts&&(m.contentParts=h.contentParts),h.llmContent!==void 0&&(m.llmContent=h.llmContent),(h.contentParts||h.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 h=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!h){let y=wm(m,this.config.errorMessage);if(y){let v={id:a,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(v)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(t,n){let o=PC(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,h=s?s.options?.quote:void 0,y=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}:{},...h?{quote:h}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:y===!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=js();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=wm(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 h=await u.json().catch(()=>null);throw new Error(h?.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 h=typeof m[0]?.question=="string"?m[0].question:"";h&&(a={[h]: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,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).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,h)=>{let y=typeof m?.question=="string"?m.question:"";if(!y)return;let v=u[y],C=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${h}`,role:"assistant",content:y,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${h}`,role:"user",content:C||"*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!==gr?!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 h=this.markWebMcpToolRunning(d),y=d.agentMetadata?.webMcpToolCallId??p;if(p===gr)return{dedupeKey:m,resumeKey:y,output:Jv(),toolMessage:d,startedAt:h,completedAt:Date.now()};let v=this.client.executeWebMcpToolCall(p,d.toolCall?.args,r.signal),C;if(!v)C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{C=await v}catch(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));return E||this.callbacks.onError?.(x instanceof Error?x:new Error(String(x))),this.markWebMcpToolComplete(d,xm(E?"Aborted by cancel()":F0(x)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,xm("Aborted by cancel()"),h),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:y,output:C,toolMessage:d,startedAt:h,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(m=>m!==null),l.length===0)return;let d={};for(let m of l)d[m.resumeKey]=m.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 m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}let u=l[0].dedupeKey;for(let m of l){this.webMcpResolvedKeys.add(m.dedupeKey);let h=m.toolMessage.toolCall?.name,y=m.toolMessage.agentMetadata?.webMcpToolCallId;this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt,{...h===gr?{suggestRepliesResolved:!0}:{},...h&&y?{clientToolAnswer:{toolCallId:y,toolName:h,args:m.toolMessage.toolCall?.args,result:m.output,batch:u}}:{}})}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,xm("Aborted by cancel()"),u.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let a=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(a)}catch(l){this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{this.webMcpInflightKeys.delete(a)}return}let s=`${n}:${r}`;if(!(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t)))return this.resolveWebMcpToolCallBatch(n,[t])}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=ur(this.config.features?.artifacts,t),r=ol(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=ur(this.config.features?.artifacts,n),s=ol(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=BC().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=>wm(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=js(),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=bm(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return fl(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=bm(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};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});let l=r.agentMetadata?.clientToolAnswer;if(l&&a.agentMetadata&&!a.agentMetadata.clientToolAnswer&&(a.agentMetadata={...a.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let m=r.approval,h=n.approval;a.approval={...m,...h,executionId:h.executionId||m.executionId,toolName:h.toolName||m.toolName,description:h.description||m.description,toolType:h.toolType??m.toolType,reason:h.reason??m.reason,parameters:h.parameters??m.parameters}}let d=n.toolCall?.name,p=n.agentMetadata?.executionId,u=n.toolCall?.id;if(d&&DC(d)&&p&&u&&n.agentMetadata?.awaitingLocalTool===!0){let m=`${p}:${u}`,h=this.webMcpInflightKeys.has(m),y=this.webMcpResolvedKeys.has(m),v=r.toolCall?.name,C=r.agentMetadata?.executionId===p&&r.toolCall?.id===u&&v!==void 0&&DC(v)&&r.toolCall?.status==="complete";(h||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 $0,FileCode as U0,FileSpreadsheet as j0,FileText as Sm,X as V0}from"lucide";var q0={add:e=>pC(e)},z0=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Ld={allowedTypes:mr,maxFileSize:10*1024*1024,maxFiles:4};function K0(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function G0(e){return e==="application/pdf"?Sm:e.startsWith("text/")?Sm:e.includes("word")?Sm:e.includes("excel")||e.includes("spreadsheet")?j0:e==="application/json"?U0:$0}var zi=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??Ld.allowedTypes,maxFileSize:t.maxFileSize??Ld.maxFileSize,maxFiles:t.maxFiles??Ld.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:q0}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:Ld.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=uC(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:K0(),file:o,previewUrl:Md(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=z0(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=Md(t.file),o=S("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=S("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=S("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=G0(t.file.type),h=St(m,20,"var(--persona-muted, #6b7280)",1.5);h&&u.appendChild(h);let y=S("span");y.textContent=gC(t.file.type,t.file.name),y.style.fontSize="8px",y.style.fontWeight="600",y.style.color="var(--persona-muted, #6b7280)",y.style.textTransform="uppercase",y.style.lineHeight="1",u.appendChild(y),o.appendChild(u)}let r=G("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=S("div","persona-attachment-progress");s.appendChild(S("div","persona-attachment-progress__bar"));let a=G("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ae("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=S("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=St(V0,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 _C=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),Y0=(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 NC(){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(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},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=>{Y0(e.attachments,u)||(e.attachments=[...u],p())},setMentionRefs:u=>{_C(e.mentionRefs,u)||(e.mentionRefs=[...u],p())},setSelectedModelId:u=>{e.selectedModelId!==u&&(e.selectedModelId=u,p())},setActiveModeIds:u=>{_C(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 In=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},FC=(e,t)=>{let n=S("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function $C(e,t={}){let n=In(e,"[data-persona-composer-form]"),o=In(e,"[data-persona-composer-input]");if(!n||!o){let E=`[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(E);return typeof console<"u"&&console.warn(E),null}let r={header:In(e,"[data-persona-composer-header]"),body:In(e,"[data-persona-composer-body]"),actionsStart:In(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:In(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:In(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:In(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:In(e,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=FC("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,E,H,B,A)=>{if(E)return E;s.add(x);let O=FC(H,B);return A.appendChild(O),O},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),h=d("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),y=[],v=(x,E)=>x.target===E.target&&x.type===E.type&&x.handler===E.handler,C=In(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:h,attachmentInput:C,attachmentPreviews:In(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:In(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:In(e,"[data-persona-composer-submit]")??void 0,micButton:In(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(x,E,H,B)=>{x.addEventListener(E,H,B),y.push({target:x,type:E,handler:H,options:B})},removeListener:(x,E,H,B)=>{x.removeEventListener(E,H,B),y=y.filter(A=>!v(A,{target:x,type:E,handler:H}))},destroy:()=>{for(let x of y)x.target.removeEventListener(x.type,x.handler,x.options);y=[]}}}var Bt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},cn=1e5,Ki=cn+1;var Q0=8,X0=8,Am=10,UC=200,jC=300,VC=0,Rd=e=>Math.max(0,e);function qC(e){e.delayMs!==void 0&&(UC=Rd(e.delayMs)),e.skipDelayMs!==void 0&&(jC=Rd(e.skipDelayMs))}var J0=()=>Date.now()<VC,Z0=e=>{VC=e>0?Date.now()+e:0},Id=new WeakMap,Em="data-persona-tooltip-suppressed",eL=e=>typeof e.closest=="function"&&e.closest(`[${Em}]`)!==null;function zC(e){Id.get(e)?.hide()}var KC=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,tL=e=>{let t=e.getRootNode?.();return KC(t)?t:e.ownerDocument.body},Mm=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),nL=[...["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 rn(e){Id.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:a=Q0,viewportPadding:l=X0}=e,d=()=>t.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,h=null,y=null,v,C=!1,x=!1,E=!1,H=()=>(typeof o=="function"?o():o).trim(),B=()=>(typeof r=="function"?r():r??"").trim(),A=()=>Rd(e.delayMs??UC),O=()=>Rd(e.skipDelayMs??jC),L=()=>{v!==void 0&&(p().clearTimeout(v),v=void 0)},$=()=>{L();let pe=u!==null;y?.(),y=null,u?.remove(),u=null,m=null,h=null,pe&&Z0(O())},K=()=>{if(!u)return;let pe=d(),ke=p(),we=t.getBoundingClientRect(),fe=u.getBoundingClientRect(),lt=pe.documentElement.clientWidth||ke.innerWidth,rt=pe.documentElement.clientHeight||ke.innerHeight,be=lt-l-fe.width,D=we.left+we.width/2-fe.width/2,De=Mm(D,l,be),_e=we.top-l,At=rt-l-we.bottom,zt=fe.height+a,$t=_e>=zt||_e>=At?"top":"bottom",Te=$t==="top"?we.top-a-fe.height:we.bottom+a,ve=rt-l-fe.height,We=Mm(Te,l,ve),Ae=we.left+we.width/2,Cn=Math.max(Am,fe.width-Am),j=Mm(Ae-De,Am,Cn);u.dataset.placement=$t,u.style.left=`${De}px`,u.style.top=`${We}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${j}px`)},se=()=>{if(E||!s||u||!t.isConnected||eL(t))return;let pe=H(),ke=tL(t);if(!pe||!ke)return;let we=d(),fe=p();u=we.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Ki);let lt=fe.getComputedStyle?.(t);if(lt){for(let zt of nL){let $t=lt.getPropertyValue(zt).trim();$t&&u.style.setProperty(zt,$t)}lt.fontFamily&&(u.style.fontFamily=lt.fontFamily)}m=we.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=pe,u.appendChild(m);let rt=B();rt&&(h=we.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=rt,u.appendChild(h));let be=we.createElement("span");be.className="persona-control-tooltip__arrow",u.appendChild(be),ke.appendChild(u),K(),u.dataset.state="open";let D=()=>{if(!t.isConnected){$();return}m&&(m.textContent=H()),h&&(h.textContent=B()),K()};fe.addEventListener("scroll",D,!0),fe.addEventListener("resize",D);let De=t.getRootNode(),_e=KC(De)?De:we.documentElement,At=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||$()});At?.observe(_e,{childList:!0,subtree:!0}),y=()=>{fe.removeEventListener("scroll",D,!0),fe.removeEventListener("resize",D),At?.disconnect()}},te=pe=>{if(!(E||u)){if(L(),pe||A()<=0||J0()){se();return}v=p().setTimeout(()=>{v=void 0,se()},A())}},P=()=>{C||x?te(x):$()},k=()=>{let pe=p();(!pe.matchMedia||!pe.matchMedia("(hover: none)").matches)&&(C=!0,P())},_=()=>{C=!1,P()},I=()=>{try{x=t.matches(":focus-visible")}catch{x=!0}P()},Z=()=>{x=!1,P()},U=()=>{C=!1,x=!1,$()},ce=pe=>{pe.key==="Escape"&&U()};n.addEventListener("mouseenter",k),n.addEventListener("mouseleave",_),t.addEventListener("focus",I),t.addEventListener("blur",Z),t.addEventListener("keydown",ce),t.addEventListener("click",U);let de={get isOpen(){return u!==null},show:se,hide:$,reposition:K,destroy:()=>{E||(E=!0,$(),n.removeEventListener("mouseenter",k),n.removeEventListener("mouseleave",_),t.removeEventListener("focus",I),t.removeEventListener("blur",Z),t.removeEventListener("keydown",ce),t.removeEventListener("click",U),Id.delete(t))}};return Id.set(t,de),de}function Tm(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 Hd(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function GC(e,t){e.style.maxHeight=`${t*Tm(e)}px`,e.style.overflowY="auto"}function bl(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 YC(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function QC(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||!YC(t)}function oL(e){return(e.submitKey??"enter")!=="enter"||YC(e)?"enter":"send"}function Wd(e,t){e.setAttribute("enterkeyhint",oL(t))}function Od(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 Pm(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 Un="persona-composer-control",vo="persona-composer-control--glyph",Lm=40,hn=24,Bd=(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)}},Dd=(e,t)=>{let n=S("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Vg,n.dir="auto",Wd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:bl(n)}),Od(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=Hd(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*Tm(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}},sL="[data-persona-glyph-stack]",Im=(e,t,n="send")=>{let o=G("span",{className:"persona-composer-glyph-stack",attrs:{"data-mode":n,"data-persona-glyph-stack":""}});return e.setAttribute("data-glyph","send"),t.setAttribute("data-glyph","stop"),o.append(e,t),o},_d=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,h=parseFloat(m??"")||Lm,y=t.backgroundColor,v=t.textColor,C=S("div","persona-send-button-wrapper"),x=G("button",{className:fn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Un}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!y&&"persona-bg-persona-primary",!n&&!v&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?v||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":v||void 0,backgroundColor:n&&y||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}}),E=null,H=null,B=null;if(n){let L=parseFloat(t.iconSize??"")||Math.round(h*.5),$=t.iconStrokeWidth??2,K=v?.trim()||"currentColor";if(r&&(E=ae(r,L,K,$)),H=ae(s,L,K,$),!t.iconSize)for(let se of[E,H])se&&(se.style.width=`var(--persona-components-composer-sendIconSize, ${L}px)`,se.style.height=`var(--persona-components-composer-sendIconSize, ${L}px)`);E&&H?(B=Im(E,H),x.appendChild(B)):E?x.appendChild(E):(x.textContent=o,H=null)}else x.textContent=d;x.setAttribute("aria-label",a),C.appendChild(x),rn({anchor:x,trigger:C,text:()=>x.getAttribute("aria-label")??"",enabled:u});let A="send";return{button:x,wrapper:C,setMode:L=>{if(L===A)return;A=L;let $=L==="stop"?l:a;x.setAttribute("aria-label",$),x.setAttribute("data-persona-send-mode",L),n?(x.querySelector(sL)??B)?.setAttribute("data-mode",L):x.textContent=L==="stop"?p:d},glyphStack:B}},Gi=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,h=S("div","persona-send-button-wrapper"),y=G("button",{className:fn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Un,!d&&vo),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}}),C=ae(l,p,m||"currentColor",1.5);C?y.appendChild(C):y.textContent="\u{1F3A4}",h.appendChild(y);let x=t.tooltipText??"Start voice recognition",E=t.showTooltip??!1;return rn({anchor:y,trigger:h,text:()=>y.getAttribute("aria-label")??x,enabled:E}),{button:y,wrapper:h}},Nd=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=S("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=S("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??mr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=S("div","persona-send-button-wrapper"),a=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Un} ${vo}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ae(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 rn({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=S("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),Fs(o,t,"idle");let r=t.idleText??"Online";if(t.idleLink){let s=S("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=r;return o},$d=()=>G("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function iL(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Ud(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??iL(t),h=!1,y=null,v=()=>{if(!h)return;let E=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${E.width}px`),a&&(n.style.maxWidth=`${E.width}px`);let H=n.getBoundingClientRect(),B=l?.()??null,A=B!=null?E.top+B:E.top,O=o==="top-start"||o==="top-end"?A-r-H.height:E.bottom+r,$=o==="bottom-end"||o==="top-end"?E.right-H.width:E.left,K=a?.()??null;if(K!=null){let se=Math.max(E.left,E.right-H.width);$=Math.min(Math.max(E.left+K,E.left),se)}n.style.top=`${O}px`,n.style.left=`${$}px`},C=()=>{h&&(h=!1,y&&(y(),y=null),n.remove())},x=()=>{if(h)return;h=!0,d!=null&&(n.style.zIndex=String(d)),m.appendChild(n),v();let E=(t.ownerDocument??document).defaultView??window,H=t.ownerDocument??document,B=()=>{if(!t.isConnected){C(),u?.("anchor-removed");return}v()},A=L=>{let $=typeof L.composedPath=="function"?L.composedPath():[];$.includes(n)||$.includes(t)||(C(),u?.("outside"))},O=E.setTimeout(()=>{H.addEventListener("pointerdown",A,!0)},0);E.addEventListener("scroll",B,!0),E.addEventListener("resize",B),y=()=>{E.clearTimeout(O),H.removeEventListener("pointerdown",A,!0),E.removeEventListener("scroll",B,!0),E.removeEventListener("resize",B)},p?.()};return{get isOpen(){return h},open:x,close:C,toggle:()=>h?C():x(),reposition:v,destroy:C}}var aL='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',lL=["--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"],Rm="data-persona-menu-focus",cL=new Set(["ArrowDown","ArrowUp","Home","End"]);function XC(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(aL)??e}var dL=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function JC(e){let t=e.label,n=!1,o=S("div","persona-send-button-wrapper"),r=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Un} ${vo}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=G("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let I=e.getButtonSize?.()??"";r.style.width=I,r.style.height=I,r.style.minWidth=I,r.style.minHeight=I,r.style.lineHeight="1",r.replaceChildren();let Z=ae("plus",hn,"currentColor",1.5);Z?r.appendChild(Z):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 Z=s.getRootNode().activeElement;return Z instanceof HTMLElement?Z:null},h=()=>{let I=m();for(let Z of d){let U=!!I&&XC(Z)===I;Z.toggleAttribute(Rm,U&&u)}},y=()=>d.filter(I=>I.isConnected||s.contains(I)).map(XC).filter(I=>!dL(I)),v=(I,Z)=>{I.forEach((U,ce)=>{U.setAttribute("tabindex",ce===Z?"0":"-1")})},C=I=>{let Z=y();if(Z.length===0)return;let U=(I%Z.length+Z.length)%Z.length;p=U,v(Z,U),Z[U].focus(),h()},x=()=>o.ownerDocument??document,E=null,H=null,B=null,A=()=>{E&&(x().removeEventListener("focusin",E,!0),E=null)},O=()=>{H&&(s.removeEventListener("focusin",H),H=null),B&&(s.removeEventListener("pointerdown",B,!0),B=null)},L=null,$=()=>(L||(L=Ud({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),A()}})),L),K=()=>L?.isOpen===!0,se=(I=!1)=>{if(K()){L?.close(),r.setAttribute("aria-expanded","false"),A(),O(),p=-1,u=!1;for(let Z of d)Z.removeAttribute(Rm);I&&r.focus()}},te=(I=0,Z=!1)=>{if(n||K())return;u=Z,Bd(r,s,lL),$().open(),r.setAttribute("aria-expanded","true");let U=y();v(U,-1),C(I<0?U.length-1:I),E=ce=>{let de=typeof ce.composedPath=="function"?ce.composedPath():[];de.includes(s)||de.includes(o)||se()},x().addEventListener("focusin",E,!0),H=()=>h(),s.addEventListener("focusin",H),B=()=>{u=!1},s.addEventListener("pointerdown",B,!0)},P=I=>{I.preventDefault(),I.stopPropagation(),K()?se(!0):te(0)},k=I=>{if(I.key==="ArrowDown"||I.key==="Enter"||I.key===" "){I.preventDefault(),u=!0,K()?C(0):te(0,!0);return}I.key==="ArrowUp"&&(I.preventDefault(),u=!0,K()?C(-1):te(-1,!0))},_=I=>{switch(cL.has(I.key)&&(u=!0),I.key){case"ArrowDown":I.preventDefault(),C(p+1);return;case"ArrowUp":I.preventDefault(),C(p-1);return;case"Home":I.preventDefault(),C(0);return;case"End":I.preventDefault(),C(y().length-1);return;case"Escape":I.preventDefault(),I.stopPropagation(),se(!0);return;case"Tab":se(!0);return;default:}};return r.addEventListener("click",P),r.addEventListener("keydown",k),s.addEventListener("keydown",_),{trigger:o,triggerButton:r,panel:s,setItems:I=>{for(let U of d)I.includes(U)||U.removeAttribute(Rm);if(d=[...I],!K())return;let Z=y();v(Z,Math.min(p,Z.length-1)),h()},isOpen:K,open:()=>te(0),close:se,setLabel:I=>{I!==t&&(t=I,l())},applyButtonSize:a,destroy:()=>{n=!0,A(),O(),r.removeEventListener("click",P),r.removeEventListener("keydown",k),s.removeEventListener("keydown",_),L?.destroy(),L=null,o.remove(),s.remove(),d=[]}}}var No={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},ZC="data-persona-composer-action",Hm="data-persona-composer-disable-when-streaming",pL="core:overflow",uL=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function gL(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=S("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 Wm(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 ew=(e,t)=>{!e||typeof console>"u"||console.warn(t)},mL=(e,t)=>t.includes(":")?t:`${e}:${t}`;function fL(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){ew(t,`[Persona] composer action "${l.id}" is already contributed by ${tw(d)}; the ${tw(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?mL(p,l.id):l.id,m=l.order??No.custom;l.placement==="end"&&m>=No.send&&(ew(t,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${No.send-1}.`),m=No.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 tw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",nw=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,hL=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function yL(e,t){if(!e||e==="always")return!0;let n=hL(t);return e==="when-text"?n:!n}var Qr=e=>e.kind==="custom",Om=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,bL=e=>{let t=Om(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},vL='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function CL(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(vL)||o.childNodes.forEach(n)};return n(e),t.trim()}var wL=e=>CL(e).length===0;function ow(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(P,k)=>{let _=P.button;if(!_)return;_.setAttribute("role","menuitem"),_.setAttribute("tabindex","-1"),_.className="persona-composer-overflow-menu__item";for(let U of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])_.style[U]="";_.style.lineHeight="1",k.tooltipText?_.setAttribute("title",k.tooltipText):_.removeAttribute("title"),_.replaceChildren();let I=S("span","persona-composer-overflow-menu__icon");if(k.iconName){let U=ae(k.iconName,16,"currentColor",1.5);U&&I.appendChild(U)}let Z=S("span","persona-composer-overflow-menu__label");Z.textContent=k.shortLabel??k.label,_.append(I,Z)},a=(P,k)=>{let _=P.button;if(!_)return;if(_.setAttribute("aria-label",k.label),k.pressed===void 0?_.removeAttribute("aria-pressed"):_.setAttribute("aria-pressed",k.pressed?"true":"false"),_.toggleAttribute(Hm,k.disableWhenStreaming===!0),P.mode==="menu"){P.tooltip?.destroy(),P.tooltip=void 0,s(P,k);return}_.removeAttribute("role"),_.removeAttribute("tabindex"),_.removeAttribute("title");let I=r(),Z=!!k.shortLabel;if(_.className=fn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Un,vo,Z&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),_.style.width=I&&!Z?I:"",_.style.height=I??"",_.style.minWidth=I&&!Z?I:"",_.style.minHeight=I??"",_.style.fontSize=Z?"":"18px",_.style.lineHeight="1",_.style.color=k.iconColor??"",_.style.backgroundColor=k.backgroundColor??"",_.replaceChildren(),k.iconName){let U=ae(k.iconName,hn,"currentColor",1.5);U&&_.appendChild(U)}if(Z){let U=S("span","persona-composer-action-button__label");U.textContent=k.shortLabel,_.appendChild(U)}else _.firstChild||(_.textContent=k.label);P.tooltip?.destroy(),P.tooltip=rn({anchor:_,trigger:P.element,text:()=>k.tooltipText??k.label,enabled:!!k.tooltipText})},l=(P,k)=>{let _=P.action,I=G("button",{attrs:{type:"button"}}),Z=I;if(k==="bar"){let de=S("div","persona-send-button-wrapper");de.appendChild(I),Z=de}Z.setAttribute(ZC,P.id);let U={resolved:P,element:Z,button:I,owned:!0,managed:!0,busy:!1,visible:!0,mode:k},ce=de=>{if(de.preventDefault(),de.stopPropagation(),U.busy||I.disabled)return;let pe=U.resolved.action;U.mode==="menu"&&y?.close(!0);let ke;try{ke=pe.onSelect(e.actionContext,de)}catch(we){e.reportError(we,{actionId:U.resolved.id});return}!ke||typeof ke.then!="function"||(U.busy=!0,I.setAttribute("aria-busy","true"),ke.catch(we=>{e.reportError(we,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,I.removeAttribute("aria-busy")}))};return I.addEventListener("click",ce),U.detach=()=>I.removeEventListener("click",ce),a(U,_),U},d=P=>{let k=P.action,_;try{_=k.render({...e.actionContext,id:P.id,action:k})}catch(I){return e.reportError(I,{actionId:P.id}),null}return _?.element?(_.element.setAttribute(ZC,P.id),_.element.toggleAttribute(Hm,k.disableWhenStreaming===!0),{resolved:P,element:_.element,owned:!0,managed:!0,destroy:_.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(P,k)=>{if(P.builtIn){let I=P.builtIn.element;return I?{resolved:P,element:I,owned:!1,managed:P.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let _=P.action;return _?Qr(_)?d(P):l(P,k):null},u=P=>{if(P.detach?.(),P.tooltip?.destroy(),P.detachMenuSlot?.(),P.detachMenuSlot=void 0,P.menuLabel?.remove(),P.menuLabel=void 0,P.menuSlot?.remove(),P.menuSlot=void 0,P.owned){try{P.destroy?.()}catch(k){e.reportError(k,{actionId:P.resolved.id})}P.element.remove()}},m=(P,k)=>{for(let _=0;_<k.length;_++){let I=k[_];if(!I.managed)continue;let Z=null;for(let U=_+1;U<k.length;U++){let ce=k[U];if(!ce.managed&&ce.element.parentElement===P){Z=ce.element;break}}Z?(I.element.parentElement!==P||I.element.nextSibling!==Z)&&P.insertBefore(I.element,Z):P.lastChild!==I.element&&P.appendChild(I.element)}},h=(P,k)=>{if(P.button){P.button.disabled=k;return}if(!P.owned)return;let _=P.element;_.toggleAttribute("data-disabled",k),_.setAttribute("aria-disabled",k?"true":"false");let I=_ instanceof HTMLButtonElement||_ instanceof HTMLSelectElement||_ instanceof HTMLInputElement||_ instanceof HTMLTextAreaElement?_:_.querySelector("button, select, input, textarea");I&&(I.disabled=k)},y=null,v=null,C=null,x=0,E=()=>{let P=e.getOverflow?.();return P?.enabled===!0?P:void 0},H=()=>(y?y.setLabel(e.getOverflowLabel?.()??"More actions"):y=JC({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),y),B=P=>{v!==P&&(C?.disconnect(),v=P,x=Wm(P),!(typeof ResizeObserver>"u")&&(C=new ResizeObserver(k=>{let I=k[k.length-1]?.contentRect?.width??Wm(P);I!==x&&(x=I,se())}),C.observe(P)))},A=(P,k)=>{let _=gL(P.collapseAutoActionsBelow,k);if(_===null)return!1;let I=x||Wm(k);return I>0&&I<_},O=(P,k,_)=>{if(!k)return"bar";if(P.resolved.builtIn){let Z=uL(P.resolved.id);return Z&&k.includeBuiltIns?.includes(Z)?"menu":"bar"}let I=P.resolved.presentation;return I==="overflow"||I==="auto"&&_?"menu":"bar"},L=P=>{let k=P.menuSlot;if(!k)return;if(!wL(P.element)){P.menuLabel?.remove(),P.menuLabel=void 0;return}let _=bL(P.element);if(!_){P.menuLabel?.remove(),P.menuLabel=void 0;return}P.menuLabel||(P.menuLabel=S("span","persona-composer-overflow-menu__label")),P.menuLabel.textContent!==_&&(P.menuLabel.textContent=_),P.menuLabel.parentElement!==k&&k.appendChild(P.menuLabel)},$=(P,k)=>{if(P.mode===k)return P;let _=P.resolved.action;if(_&&!Qr(_)){u(P),t.delete(P.resolved.id);let I=l(P.resolved,k);return t.set(P.resolved.id,I),I}if(k==="menu"){let I=G("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[Em]:""}});I.appendChild(P.element),zC(Om(P.element)),P.menuSlot=I;let Z=U=>{let ce=Om(P.element);if(ce.disabled)return;let de=U.target===ce||ce.contains(U.target);y?.close(!0),de||ce.click()};I.addEventListener("click",Z,!0),P.detachMenuSlot=()=>I.removeEventListener("click",Z,!0),P.managed=!0,L(P)}else P.detachMenuSlot?.(),P.detachMenuSlot=void 0,P.menuLabel?.remove(),P.menuLabel=void 0,P.menuSlot?.remove(),P.menuSlot=void 0;return P.mode=k,P},K=(P,k)=>{let _=k.map(I=>I.menuSlot??I.element);for(_.forEach((I,Z)=>{let U=P.children[Z];U!==I&&(U?P.insertBefore(I,U):P.appendChild(I))});P.children.length>_.length;)P.lastElementChild?.remove()},se=()=>{if(o)return;let P=e.getBindings();if(!P)return;let k=e.getState(),_=k.phase==="streaming",I=E();I&&B(P.footer);let Z=I?A(I,P.footer):!1,U={start:[],end:[]},ce=[];for(let de of n){let pe=t.get(de.id);if(!pe)continue;let ke=de.action,we=ke?nw(ke.visible,k,!0)&&yL(ke.visibility,k):!0;if(pe.visible!==we&&(pe.visible=we,!we&&pe.managed&&(pe.menuSlot??pe.element).remove()),!!we){if(pe=$(pe,O(pe,I,Z)),ke){let fe=nw(ke.disabled,k,!1)||ke.disableWhenStreaming===!0&&_;h(pe,fe),!Qr(ke)&&ke.pressed!==void 0&&pe.button?.setAttribute("aria-pressed",ke.pressed?"true":"false")}pe.mode==="menu"?(L(pe),ce.push(pe)):U[de.placement].push(pe)}}if(ce.length>0){let de=H();K(de.panel,ce),de.setItems(ce.map(fe=>fe.menuSlot??fe.element)),de.applyButtonSize();let pe=Number.isFinite(I?.order)?I?.order:No.overflow,ke=U.start.findIndex(fe=>fe.resolved.order>pe),we={resolved:{id:pL,placement:"start",presentation:"bar",order:pe,sequence:-1,source:"core"},element:de.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(ke<0?U.start.length:ke,0,we)}else y&&(y.close(),y.trigger.remove(),y.setItems([]));m(P.actionsStart,U.start),m(P.actionsEnd,U.end)};return{resolve:()=>{if(o)return;let P=fL(e.collect()),k=new Set(P.map(_=>_.id));for(let[_,I]of t)k.has(_)||(u(I),t.delete(_));for(let _ of P){let I=t.get(_.id);if(!I){let de=p(_,"bar");de&&t.set(_.id,de);continue}let Z=I.resolved.action,U=_.action;if(!!Z!=!!U||Z&&U&&Qr(Z)!==Qr(U)||Z&&U&&Qr(Z)&&Qr(U)&&Z.render!==U.render){u(I),t.delete(_.id);let de=p(_,I.mode);de&&t.set(_.id,de);continue}I.resolved=_,_.builtIn?(I.managed=_.builtIn.managed===!0||I.mode==="menu",_.builtIn.element&&I.mode==="bar"&&(I.element=_.builtIn.element)):U&&!Qr(U)?a(I,U):U&&I.element.toggleAttribute(Hm,U.disableWhenStreaming===!0)}n=P,se()},sync:se,getResolved:()=>n,getOverflowMenu:()=>y,destroy:()=>{if(!o){o=!0,C?.disconnect(),C=null,v=null;for(let P of t.values())u(P);t.clear(),y?.destroy(),y=null,n=[]}}}}var xL="core:model",SL=700,rw=16,AL=["--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"],sw=()=>{let e=G("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=G("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function iw(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=d=>{let p=e.getSelectedModelId();return d.find(u=>u.id===p)??d[0]},s=()=>{let d=G("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),p="",u=()=>{let C=e.getModels(),x=C.map(E=>`${E.id}:${E.label}`).join("|");x!==p&&(p=x,d.replaceChildren(...C.map(E=>{let H=G("option",{attrs:{value:E.id}});return H.textContent=E.label,H}))),d.value=r(C)?.id??""};u(),o=u;let m=()=>{d.value&&e.onSelect(d.value)};d.addEventListener("change",m);let h=C=>C.stopPropagation();d.addEventListener("click",h);let{wrapper:y,chevron:v}=sw();return y.append(d,v),{element:y,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",h)}}},a=()=>{let d=G("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=S("span","persona-composer-model-picker-label"),u=S("span","persona-composer-model-picker-suffix");d.append(p,u);let m=G("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),h=new Map,y="",v=null,C=()=>v?.isOpen===!0,x=(k=!1)=>{C()&&(v?.close(),d.setAttribute("aria-expanded","false"),k&&d.focus())},E=k=>{let _=[...h.values()];if(_.length===0)return;let I=(k%_.length+_.length)%_.length;_[I].focus()},H=k=>{if(C())return;v||(v=Ud({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),Bd(d,m,AL),v.open(),d.setAttribute("aria-expanded","true");let I=[...h.keys()].indexOf(r(e.getModels())?.id??"");E(k??(I>=0?I:0))},B=k=>{x(!0),e.onSelect(k)},A=k=>{k.preventDefault(),k.stopPropagation();let _=k.currentTarget.getAttribute("data-persona-model-option");_&&B(_)},O=k=>{let _=G("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":k.id}});if(k.icon){let de=ae(k.icon,rw,"currentColor",1.5);if(de){let pe=S("span","persona-composer-model-option-icon");pe.appendChild(de),_.appendChild(pe)}}let I=S("span","persona-composer-model-option-body"),Z=S("span","persona-composer-model-option-label");if(Z.textContent=k.label,I.appendChild(Z),k.description){let de=S("span","persona-composer-model-option-description");de.textContent=k.description,I.appendChild(de)}_.appendChild(I);let U=S("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let ce=ae("check",rw,"currentColor",2);return ce&&U.appendChild(ce),_.appendChild(U),_.addEventListener("click",A),_},L=()=>{let k=e.getModels(),_=k.map(U=>`${U.id}:${U.label}:${U.icon??""}:${U.description??""}`).join("|");if(_!==y){y=_;for(let U of h.values())U.removeEventListener("click",A);h.clear(),m.replaceChildren(...k.map(U=>{let ce=O(U);return h.set(U.id,ce),ce}))}let I=r(k);for(let[U,ce]of h)ce.setAttribute("aria-selected",String(U===I?.id));p.textContent=I?.label??"";let Z=e.getSuffix?.()??"";u.textContent=Z,d.setAttribute("aria-label",[t,[I?.label,Z].filter(Boolean).join(" ")].filter(Boolean).join(": "))};L(),o=L;let $=k=>{k.preventDefault(),k.stopPropagation(),C()?x(!0):H()},K=k=>{if(k.key==="ArrowDown"){k.preventDefault(),C()?E(0):H(0);return}k.key==="ArrowUp"&&(k.preventDefault(),C()?E(-1):H(-1))},se=k=>{let _=[...h.values()],I=_.indexOf(k.target?.closest?.(".persona-composer-model-option"));switch(k.key){case"ArrowDown":k.preventDefault(),E(I+1);return;case"ArrowUp":k.preventDefault(),E(I-1);return;case"Home":k.preventDefault(),E(0);return;case"End":k.preventDefault(),E(_.length-1);return;case"Escape":k.preventDefault(),k.stopPropagation(),x(!0);return;case"Tab":x(!0);return;default:}};d.addEventListener("click",$),d.addEventListener("keydown",K),m.addEventListener("keydown",se);let{wrapper:te,chevron:P}=sw();return te.append(d,P),{element:te,destroy:()=>{o===L&&(o=null),d.removeEventListener("click",$),d.removeEventListener("keydown",K),m.removeEventListener("keydown",se);for(let k of h.values())k.removeEventListener("click",A);h.clear(),v?.destroy(),v=null,m.remove()}}};return{action:{id:xL,kind:"custom",placement:"end",order:SL,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}var Bm="[data-persona-composer-chip-row]";function jd(e){e.style.display=e.childElementCount>0?"flex":"none"}function Dm(e){let t=e.querySelector(Bm);if(t)return t;let n=G("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(n,o):e.appendChild(n),n}var ML=":scope > [data-persona-composer-mode]";function aw(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let u=G("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let v=S("span","persona-mention-chip-icon"),C=ae(p.iconName,12,"currentColor",1.5);C&&v.appendChild(C),u.appendChild(v)}let m=S("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let h=G("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),y=ae("x",12,"currentColor",2);return y?h.appendChild(y):h.textContent="\xD7",h.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),e.onRemove(p.id)}),u.appendChild(h),u},a=()=>Array.from(t.querySelectorAll(ML)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),jd(t)},m=t.ownerDocument.defaultView,h=typeof m?.getComputedStyle=="function"?m.getComputedStyle(p).animationName:"";if(!h||h==="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(C=>p.includes(C.id)),h=m.map(C=>`${C.id}:${C.shortLabel??C.label}`).join("|");if(h===n)return;n=h;let y=new Map;for(let C of a()){let x=C.getAttribute("data-persona-composer-mode");x&&m.some(H=>H.id===x)&&!C.hasAttribute("data-persona-chip-exit")?y.set(x,C):C.hasAttribute("data-persona-chip-exit")||l(C)}let v=t.firstChild;for(let C of m){let x=y.get(C.id);x||(x=s(C),r.has(C.id)||(x.setAttribute("data-persona-chip-enter",""),x.addEventListener("animationend",()=>x?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(C.id),x!==v&&t.insertBefore(x,v),v=x.nextSibling}jd(t)},destroy:()=>{o=!0,d(),jd(t)}}}var lw=e=>`core:mode:${e}`;var _m=e=>Math.min(300+e,499),cw=e=>`core:mode-group:${e}`;function Vd(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function EL(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function dw(e,t){return e?.length?e.filter(n=>!Vd(n.groupId,t)&&!EL(n.groupId,t)):[]}var TL=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function pw(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(TL(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 qd(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function uw(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function gw(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var PL=16;function mw(e){let t=null;return{action:{id:cw(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=G("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",a=p=>{p.preventDefault(),p.stopPropagation();let m=p.currentTarget.getAttribute("data-persona-composer-mode");!m||e.getActiveIds().includes(m)&&e.getGroup()?.selection==="single"||e.onSelect(m)},l=p=>{let u=G("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let h=ae(p.iconName,PL,"currentColor",1.5);h&&u.appendChild(h)}let m=S("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(y=>`${y.id}:${y.shortLabel??y.label}:${y.iconName??""}`).join("|");if(m!==s){s=m;for(let v of r.values())v.removeEventListener("click",a);r.clear();let y=u.map(v=>{let C=l(v);return r.set(v.id,C),C});o.replaceChildren(...y)}let h=e.getActiveIds();for(let[y,v]of r)v.setAttribute("aria-pressed",String(h.includes(y)))};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 fw(e){let t=G("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let a=S("span","persona-composer-quote-bar"),l=S("div","persona-composer-quote-content");if(s.sourceLabel){let m=S("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let d=G("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=Td(s.text),l.appendChild(d);let p=G("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=ae("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 hw(e){let t=G("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(a,l,d,p)=>{let u=G("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[d]:""}}),m=ae(a,12,"currentColor",2);return m?u.appendChild(m):u.textContent=l,u.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),u},s=a=>{let l=Td(a.text??"",90);if(l)return l;let d=a.contentParts?.length??0;return d>0?d===1?"1 attachment":`${d} attachments`:(a.mentionRefs?.length??0)>0?a.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:t,render:a=>{if(o||a===n)return;if(n=a,!a){t.replaceChildren(),t.style.display="none";return}let l=S("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let d=G("div",{className:"persona-composer-pending-text",attrs:{"data-persona-composer-pending-text":""}});d.textContent=s(a),t.replaceChildren(l,d,r("pencil",e.editLabel??"Edit queued message","data-persona-composer-pending-edit",e.onEdit),r("x",e.removeLabel??"Remove queued message","data-persona-composer-pending-remove",e.onRemove)),t.style.display="flex"},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function yw(e){let t=G("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=G("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=e.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=S("div","persona-message-edit-actions"),s=(l,d,p,u)=>{let m=G("button",{className:`persona-message-edit-button ${d}`,attrs:{type:"button",[p]:""},text:l});return m.addEventListener("click",h=>{h.preventDefault(),h.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 bw(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 vw(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 Cw(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 ww(e){return e.wrapped||e.text.includes(`
|
|
23
|
+
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function xw(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function Sw(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 Aw(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Nm(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 Ew(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var kL=e=>typeof e?.then=="function";function Mw(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 Tw(e,t,n){let o;try{o=e(Nm(t),{signal:n})}catch(r){return{status:"error",error:r}}return kL(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:Mw(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):Mw(t,o)}var Pw=/\s/;function LL(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===""||Pw.test(o)}function IL(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 LL(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
|
|
25
|
+
`||a==="\uFFFC"||!r&&Pw.test(a))return null;s--}return null}function kw(e,t,n){for(let o of n){let r=IL(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Lw(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Iw(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 Rw(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=S("div","persona-send-button-wrapper"),a=G("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Un} ${vo}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=ae(o,hn,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),s.appendChild(a),rn({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}var{setLoader:W_,load:RL}=vt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var Fm=RL;var{setLoader:D_,load:HL}=vt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var Hw=HL;function vl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=G("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=ae(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=S("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(G("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Ww(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Iw(t).filter(A=>A.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(A=>A.sources.some(O=>typeof O.matchCommand=="function")),r=A=>o.some(O=>O.trigger?O.position==="line-start"?A.split(`
|
|
26
|
+
`).some($=>$.startsWith(O.trigger)):(O.position==="anywhere"?A:A.split(`
|
|
27
|
+
`)[0]).startsWith(O.trigger):!1),s=(A,O)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:O}))}catch{}},a=!e.chipRow,l=e.chipRow??G("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,p=null,u=e.textarea,m=null,h=null,y=null,v=null,C=()=>{if(d)return Promise.resolve(d);if(p)return p;let A=Fm().then(O=>(O.setMentionIconRenderer(ae),d=O.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:B,emit:s}),d)).catch(O=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",O),p===A&&(p=null),null));return p=A,A},x=()=>{Hw().then(A=>{let O=A.mountInlineComposer({textarea:e.textarea,renderToken:$=>vl($,{render:t.renderMentionToken}),onMentionRemoved:$=>d?.untrackMention($)});m=O.input,h=O.destroy;let L=u;L.replaceWith(O.element),u=O.element,v={next:O.element,prev:L},y?.(O.element,L),d?d.rebindComposer(O.input):p&&p.then($=>$?.rebindComposer(O.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};t.display==="inline"&&x();let E=[],H=new Map;for(let A of n){if(!A.showButton)continue;let O=Rw({config:{...t,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},onOpen:()=>{C().then(L=>L?.openMenu(A.trigger))}});E.push(O),H.set(A.trigger,O.button)}let B=(A,O,L)=>{let $=H.get(O);$&&($.setAttribute("aria-expanded",A?"true":"false"),A?$.setAttribute("aria-controls",L):$.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(A=>A.wrapper),contextRow:l,handleInput:A=>{if(d){d.handleInput();return}if(!Lw(A))return;let O=u,L=O.selectionStart??0;kw(O.value,L,n)&&C().then($=>$?.handleInput())},handleKeydown:A=>{if(d?.isMenuOpen())return d.handleKeydown(A);if(A.key==="Backspace"&&d?.hasMentions()&&!v){let O=u,L=O.selectionStart===0&&O.selectionEnd===0;if((O.value.length===0||L)&&d.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(d??await C())?.dispatchInlineCommand(A)??null:null,clear:()=>d?.clear(),prefetch:()=>{Fm().catch(()=>{})},onComposerSwap:A=>{y=A,v&&A(v.next,v.prev)},destroy:()=>{d?.destroy(),h?.();for(let A of E)A.wrapper.remove();a&&l.remove()}}}var zd=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),Kd={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"};var Yd="16px",Qd="transparent",WL=(()=>{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})(),Cl={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:WL,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"}},Gd={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"}},jn={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:Oi,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Yd,canvasBackground:Qd,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}},OL=Cl.colors.gray,BL={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},Bw={...Cl,colors:{...Cl.colors,gray:OL}},DL={...Cl,colors:{...Cl.colors,gray:BL},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},_L=Bw,Dw=Gd,NL={...Gd,colors:{...Gd.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Gd.typography,fontSize:"14px",lineHeight:"1.5"}},FL=Dw,Xd=jn,$L={...jn,launcher:Kd,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...jn.input,borderRadius:"palette.radius.full"},introCard:{...jn.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...jn.suggestion.chip,fontWeight:"400"},card:{...jn.suggestion.card,fontWeight:"400"},list:{...jn.suggestion.list,fontWeight:"400"}},panel:{...jn.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...jn.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...jn.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...jn.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...jn.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...jn.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}},UL=Xd,jL=e=>Ur({future:e}),Um=e=>jL(e)==="v5"?{palette:DL,semantic:NL,components:$L}:{palette:Bw,semantic:Dw,components:Xd};function an(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."))?an(e,o):o}function jm(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=an(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 _w(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 Nw(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]=Nw(s,r):n[o]=r}return n}function VL(e,t){return t?Nw(e,t):e}function Jd(e,t={}){let n=Um(t.future),o={palette:n.palette,semantic:n.semantic,components:n.components},r={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:VL(o.components,e?.components)},s=e?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let u of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[u]!==void 0&&(r.components[p][u]=s[u]);let a=e?.components?.collapsibleWidget?.surface;a!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:a});let l=e?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let d=e?.components?.message;if(d?.gap!==void 0&&d.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),t.validate!==!1){let p=_w(r);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(u=>u.message).join(", ")}`)}if(t.plugins)for(let p of t.plugins)r=p.transform(r);return r}var $m=e=>e.trim()==="0"?"0px":e,Ow="--persona-",qL=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},zL=.179,sn=(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[Ow+s],r!==void 0)break;r!==void 0&&(e[Ow+n]=r)}};function Vm(e){let t=jm(e),n={};for(let[D,De]of Object.entries(t)){let _e=D.replace(/\./g,"-");n[`--persona-${_e}`]=De.value}sn(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"],sn(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"]]),sn(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"]}`,sn(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"]??Yd,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Qd,sn(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"]]),sn(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"],sn(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"],sn(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[D,De]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let _e=n[`--persona-components-history-overlay-${D}`];_e&&(n[`--persona-history-overlay-${De}`]=_e)}for(let[D,De]of[["background","bg"],["borderRadius","radius"]]){let _e=n[`--persona-components-history-menu-${D}`];_e&&(n[`--persona-history-menu-${De}`]=_e)}let m=e.components?.history?.motion;if(m){let D=At=>{if(At===void 0)return;let zt=String(At).trim();return/^\d+(\.\d+)?$/.test(zt)?`${zt}ms`:zt},De=D(m.enterDurationMs);De!==void 0&&(n["--persona-history-enter-ms"]=De);let _e=D(m.exitDurationMs);_e!==void 0&&(n["--persona-history-exit-ms"]=_e),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let h=n["--persona-components-history-dangerForeground"];h&&(n["--persona-history-danger-fg"]=h),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 D of["scrim","shadow"]){let De=n[`--persona-components-history-confirm-${D}`];De&&(n[`--persona-history-confirm-${D}`]=De)}for(let[D,De]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let _e=n[`--persona-components-tooltip-${D}`];_e&&(n[`--persona-tooltip-${De}`]=_e)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[D,De]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let _e=n[`--persona-components-messageActions-${D}`];_e&&(n[`--persona-message-action-${De}`]=_e)}sn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let y=n["--persona-components-introCard-background"],v=n["--persona-components-introCard-shadow"],C=(!y||y==="transparent"||y==="none")&&(!v||v==="none"),x=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=C&&x==="1.5rem"?"1.5rem 0":x,sn(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),sn(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 E=n["--persona-components-markdown-heading-h1-fontSize"];E&&(n["--persona-md-h1-size"]=E);let H=n["--persona-components-markdown-heading-h1-fontWeight"];H&&(n["--persona-md-h1-weight"]=H);let B=n["--persona-components-markdown-heading-h2-fontSize"];B&&(n["--persona-md-h2-size"]=B);let A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let O=n["--persona-components-markdown-prose-fontFamily"];O&&O!=="inherit"&&(n["--persona-md-prose-font-family"]=O),sn(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"]]),sn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),sn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),sn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),sn(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"]]);let L=[["container","surface"],["surface","surface"],["border","border"]];for(let[D,De]of L){let _e=n[`--persona-components-collapsibleWidget-${D}`]??n[`--persona-${De}`];_e!==void 0&&(n[`--persona-cw-${D}`]=_e,n[`--cw-${D}`]=_e)}sn(n,[["message-border","components-message-border","border"]]),sn(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-border-width","components-message-assistant-borderWidth"],["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 $=e.components,K=$?.iconButton;K&&(K.background&&(n["--persona-icon-btn-bg"]=K.background),K.border&&(n["--persona-icon-btn-border"]=K.border),K.color&&(n["--persona-icon-btn-color"]=K.color),K.padding&&(n["--persona-icon-btn-padding"]=K.padding),K.borderRadius&&(n["--persona-icon-btn-radius"]=K.borderRadius),K.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=K.hoverBackground),K.hoverColor&&(n["--persona-icon-btn-hover-color"]=K.hoverColor),K.activeBackground&&(n["--persona-icon-btn-active-bg"]=K.activeBackground),K.activeBorder&&(n["--persona-icon-btn-active-border"]=K.activeBorder));let se=$?.labelButton;se&&(se.background&&(n["--persona-label-btn-bg"]=se.background),se.border&&(n["--persona-label-btn-border"]=se.border),se.color&&(n["--persona-label-btn-color"]=se.color),se.padding&&(n["--persona-label-btn-padding"]=se.padding),se.borderRadius&&(n["--persona-label-btn-radius"]=se.borderRadius),se.hoverBackground&&(n["--persona-label-btn-hover-bg"]=se.hoverBackground),se.fontSize&&(n["--persona-label-btn-font-size"]=se.fontSize),se.gap&&(n["--persona-label-btn-gap"]=se.gap));let te=$?.toggleGroup;te&&(te.gap&&(n["--persona-toggle-group-gap"]=te.gap),te.borderRadius&&(n["--persona-toggle-group-radius"]=te.borderRadius));let P=$?.artifact;if(P?.toolbar){let D=P.toolbar;D.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=D.iconHoverColor),D.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=D.iconHoverBackground),D.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=D.iconPadding),D.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=D.iconBorderRadius),D.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=D.iconBorder),D.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=$m(D.toggleGroupGap)),D.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=D.toggleBorderRadius),D.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=$m(D.toggleGroupPadding)),D.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=D.toggleGroupBorder),D.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=D.toggleGroupBorderRadius),D.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=an(e,D.toggleGroupBackground)??D.toggleGroupBackground),D.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=D.copyBackground),D.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=D.copyBorder),D.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=D.copyColor),D.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=$m(D.copyBorderRadius)),D.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=D.copyPadding),D.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=D.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??D.copyMenuBackground),D.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=D.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??D.copyMenuBorder),D.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=D.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??D.copyMenuShadow),D.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=D.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??D.copyMenuBorderRadius),D.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=D.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??D.copyMenuItemHoverBackground),D.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=D.iconBackground),D.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=D.toolbarBorder)}if(P?.tab){let D=P.tab;D.background&&(n["--persona-artifact-tab-bg"]=D.background),D.activeBackground&&(n["--persona-artifact-tab-active-bg"]=D.activeBackground),D.activeBorder&&(n["--persona-artifact-tab-active-border"]=D.activeBorder),D.borderRadius&&(n["--persona-artifact-tab-radius"]=D.borderRadius),D.textColor&&(n["--persona-artifact-tab-color"]=D.textColor),D.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=D.hoverBackground),D.listBackground&&(n["--persona-artifact-tab-list-bg"]=D.listBackground),D.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=D.listBorderColor),D.listPadding&&(n["--persona-artifact-tab-list-padding"]=D.listPadding)}if(P?.pane){let D=P.pane;if(D.toolbarBackground){let De=an(e,D.toolbarBackground)??D.toolbarBackground;n["--persona-artifact-toolbar-bg"]=De}}if(P?.card){let D=P.card;D.background&&(n["--persona-artifact-card-bg"]=D.background),D.border&&(n["--persona-artifact-card-border"]=D.border),D.borderRadius&&(n["--persona-artifact-card-radius"]=D.borderRadius),D.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=D.hoverBackground),D.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=D.hoverBorderColor)}if(P?.inline){let D=P.inline;D.background&&(n["--persona-artifact-inline-bg"]=an(e,D.background)??D.background),D.border&&(n["--persona-artifact-inline-border"]=D.border),D.borderRadius&&(n["--persona-artifact-inline-radius"]=D.borderRadius),D.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=an(e,D.chromeBackground)??D.chromeBackground),D.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=an(e,D.chromeBorder)??D.chromeBorder),D.titleColor&&(n["--persona-artifact-inline-title-color"]=an(e,D.titleColor)??D.titleColor),D.mutedColor&&(n["--persona-artifact-inline-muted-color"]=an(e,D.mutedColor)??D.mutedColor),D.frameHeight&&(n["--persona-artifact-inline-frame-height"]=D.frameHeight)}let k=$?.code;k&&(k.keywordColor&&(n["--persona-code-keyword-color"]=k.keywordColor),k.stringColor&&(n["--persona-code-string-color"]=k.stringColor),k.commentColor&&(n["--persona-code-comment-color"]=k.commentColor),k.numberColor&&(n["--persona-code-number-color"]=k.numberColor),k.tagColor&&(n["--persona-code-tag-color"]=k.tagColor),k.attrColor&&(n["--persona-code-attr-color"]=k.attrColor),k.propertyColor&&(n["--persona-code-property-color"]=k.propertyColor),k.lineNumberColor&&(n["--persona-code-line-number-color"]=k.lineNumberColor),k.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=k.gutterBorderColor),k.background&&(n["--persona-code-bg"]=an(e,k.background)??k.background));let _=n["--persona-surface"],I=n["--persona-container"],Z=n["--persona-palette-colors-gray-100"]??"#f3f4f6",U=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ce=n["--persona-palette-colors-gray-300"]??"#d1d5db",de=!I||I===_,pe=qL(_??n["--persona-background"]),ke=de&&pe!==void 0&&pe<zL,we=ke?"rgba(255, 255, 255, 0.08)":Z,fe=ke?"rgba(255, 255, 255, 0.12)":U,lt=ke?"rgba(255, 255, 255, 0.16)":ce,rt=de?we:I,be=de?fe:I;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??rt,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??be,de&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??lt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??rt,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??rt,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??rt,n}var KL={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 GL=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),Fw=(e,t)=>{if(!t||!GL(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(Yi(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:Ur(t)==="v5"?"400px":"420px"}}}},YL={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"}}},wl={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},markdown:{link:{foreground:"palette.colors.primary.300"}},eventStream:{badge:{flow:{background:"palette.colors.success.900",foreground:"palette.colors.success.300"},step:{background:"palette.colors.primary.800",foreground:"palette.colors.primary.200"},reasoning:{background:"palette.colors.warning.900",foreground:"palette.colors.warning.300"},tool:{background:"palette.colors.purple.900",foreground:"palette.colors.purple.300"},agent:{background:"palette.colors.teal.900",foreground:"palette.colors.teal.300"},error:{background:"palette.colors.error.900",foreground:"palette.colors.error.300"},default:{background:"palette.colors.gray.800",foreground:"palette.colors.gray.300"}}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},qm=YL,QL={...qm,colors:{...qm.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},XL=wl,JL={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",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"}}},components:{...wl.components,button:{...wl.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...wl.components?.eventStream,badge:{...wl.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},ZL=e=>Ur({future:e})==="v5"?{palette:QL,components:JL}:{palette:qm,components:XL},$w=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Zd=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",eI=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Zd()},Yi=e=>eI(e),tI=(e,t={})=>Jd(e,t),nI=(e,t={})=>{let n=ZL(t.future),o=ho(n.components,e??{})??{};return Jd({...o,palette:{...o.palette,colors:Ur(t)==="v5"?ho(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},Fo=e=>{let t=Yi(e),n=$w(e?.theme),o=zd(e)==="circle"?Kd:{...Xd.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=ho({components:{launcher:o}},n),s=$w(e?.darkTheme);return Fw(t==="dark"?nI(ho(r??{},s??{}),{future:e?.future}):tI(r,{future:e?.future}),e)},oI=e=>Vm(e),Qi=(e,t)=>{let n=Fo(t),o=oI(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Yi(t)),e.setAttribute("data-persona-defaults",Ur(t))},xl=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Zd())});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(Zd());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 xS,Check as SS,Copy as AS}from"lucide";var Xr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var ep="24px",zm=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Sl=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},Uw=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var jw=null;var Km=()=>{if(jw!==null)return jw;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},rI="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",tp=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},np=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 tp("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(tp("unsupported",e),null):(n==="space"&&(o.key=" "),o)},sI=e=>rI.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),Vw=(e,t)=>{let n=np(e);if(!n)return"";let o=Km(),r=sI(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("+")},op=e=>Vw(e,!1),Al=e=>Vw(e,!0),iI=(e,t)=>t.key?.toLowerCase()===e.key&&(Km()?t.metaKey:t.ctrlKey)===e.mod&&!(Km()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,aI=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},qw=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(iI(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&aI(a))){s.preventDefault();try{l.run(s)}catch(d){tp(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=np(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=t.get(l);return d?(tp(`${d.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",Al(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}};import{Idiomorph as lI}from"idiomorph";var rp=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;lI.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 zw=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Gm={index:-1,draft:""};function Kw(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 Gw(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 Yw(){return new Map}function Qw(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Xw(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Jw(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Zw(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 ex(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 Ks(e,t){return $o(e)-e.scrollTop<=t}function tx(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 nx(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 ox(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Ym(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 rx(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Ml={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},cI=["pre","code","a","script","style"],sp=e=>({type:e?.type??Ml.type,placeholder:e?.placeholder??Ml.placeholder,speed:e?.speed??Ml.speed,duration:e?.duration??Ml.duration,buffer:e?.buffer??Ml.buffer}),ix=[{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"}],El=new Map;for(let e of ix)El.set(e.name,e);var ax=["wipe","glyph-cycle"],ip=e=>{El.set(e.name,e)},dI=e=>{ix.some(t=>t.name===e)||El.delete(e)},pI=()=>Array.from(El.keys()),Tl=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:El.get(e)??null,ap=(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},uI=(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},gI=(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},Qm=/\s/,mI=(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},fI=(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(Qm.test(s[l])){let d=l;for(;d<s.length&&Qm.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&&!Qm.test(s[p]);)d.appendChild(uI(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,e)},hI=(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(gI(o,d,t,n.value)),n.value+=1));r.replaceChild(a,e)},Pl=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??cI).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)mI(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=t==="char"?fI:hI;for(let m of l)u(m,n,p);return r.innerHTML},lp=(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},kl=(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},sx=new WeakMap,yI=(e,t)=>{if(!e.styles)return;let n=sx.get(t);if(n||(n=new Set,sx.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)},Xm=new WeakMap,bI=(e,t)=>{if(!e.onAttach)return;let n=Xm.get(t);if(n||(n=new Map,Xm.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},lx=e=>{let t=Xm.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ll=(e,t)=>{yI(e,t),bI(e,t)};var{setLoader:yN,load:vI}=vt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var cx=vI;function Jm(e,t=cn){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 Il=0,Jr=null;function Zm(e=document){if(Il++,Il===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Jr={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,Il=Math.max(0,Il-1),Il===0&&Jr)){let n=e.body,o=e.defaultView??window;n.style.overflow=Jr.originalOverflow,n.style.position=Jr.originalPosition,n.style.top=Jr.originalTop,n.style.width=Jr.originalWidth,o.scrollTo(0,Jr.scrollY),Jr=null}}}var Rl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ct=e=>(e?.launcher?.mountMode??"floating")==="docked",Zr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Vn=e=>{let t=e?.launcher?.dock,n=cr(e).dockWidth?t?.width:an(Fo(e),"components.panel.width");return{side:t?.side??Rl.side,width:n??Rl.width,animate:t?.animate??Rl.animate,reveal:t?.reveal??Rl.reveal,maxHeight:t?.maxHeight??Rl.maxHeight}};import{ArrowRight as CI}from"lucide";var ef=e=>e==="followUp"?"follow-up":e,tf=(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"}},dx=new WeakSet,wI=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,xI=e=>{wI()||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"})})},nf=e=>{var B,A,O;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:d,chipsConfig:p,session:u,getTextarea:m,eventTarget:h,submitPrompt:y}=e,v=o==="followUp",C=t.behavior,x=()=>{if(u.isStreaming())return;let L={suggestion:{...t},surface:o,source:r,behavior:C},$=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:L,bubbles:!0,composed:!0,cancelable:!0}));if(v&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!$)return;for(let se of d)if(se.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let K=m();if(C==="fill"){K.value=t.prompt,K.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),K.focus();return}if(y){y(t.prompt);return}K.value="",u.sendMessage(t.prompt)},E=()=>{let L=S("button",`persona-suggestion persona-suggestion--${s}`);if(L.type="button",L.disabled=a,L.dataset.suggestionId=t.id,L.dataset.emphasis=t.emphasis,L.dataset.behavior=C,s==="chip"&&(p?.fontWeight&&(L.style.fontWeight=p.fontWeight),p?.paddingX&&(L.style.paddingLeft=p.paddingX,L.style.paddingRight=p.paddingX),p?.paddingY&&(L.style.paddingTop=p.paddingY,L.style.paddingBottom=p.paddingY)),t.icon){let K=ae(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);K&&(K.classList.add("persona-suggestion__icon"),t.iconColor&&(K.style.color=t.iconColor),L.appendChild(K))}let $=S("span","persona-suggestion__copy");if($.appendChild(G("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&$.appendChild(G("span",{className:"persona-suggestion__description",text:t.description})),L.appendChild($),s!=="chip"){let K=St(CI,16,"currentColor",1.8);K&&(K.classList.add("persona-suggestion__arrow"),L.appendChild(K))}return L.addEventListener("click",x),L},H=null;for(let L of d)if(L.renderSuggestion&&(H=L.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:E,select:x}),H))break;return H??(H=E()),(B=H.dataset).suggestionId||(B.suggestionId=t.id),(A=H.dataset).behavior||(A.behavior=C),(O=H.dataset).emphasis||(O.emphasis=t.emphasis),H instanceof HTMLButtonElement||H.setAttribute("aria-disabled",a?"true":"false"),H},Hl=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,e.scrollWidth-e.clientWidth);if(u<=1){s();return}let m=getComputedStyle(e).direction==="rtl",h=Math.min(u,Math.max(0,Math.abs(e.scrollLeft))),y=4,v=h<=y,C=h>=u-y,x=m?!C:!v,E=m?!v:!C;e.toggleAttribute("data-scroll-left",x),e.toggleAttribute("data-scroll-right",E)},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,h,y,v,C)=>{e.replaceChildren(),t.length=0,n.length=0;let x=C?.source??"config",E=C?.surface??(x==="config"?"starter":"followUp"),H=E==="followUp",B=C?.variant??"chip",A=C?.behavior??"send",O=C?.overflow??"wrap",L=C?.config??{},$=C?.plugins??[],K=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,se=H?"followUps":"starters";!dx.has(L)&&L.debug===!0&&B!=="chip"&&L.suggestions?.[se]?.overflow!==void 0&&(dx.add(L),console.info(`[persona] suggestions.${se}.overflow applies to the "chip" variant only; the "${B}" variant manages its own stacking.`));let te=U=>U.map(tf).filter(ce=>ce!==null).map(ce=>({...ce,behavior:ce.behavior??A})),P=te(u??[]);$.forEach(U=>{U.transformSuggestions&&(P=te(U.transformSuggestions({suggestions:P.map(ce=>({...ce})),surface:E,source:x,config:L})))});let k=K===void 0?P:P.slice(0,K);if(!k.length){e.hidden=!0,o=null,s();return}if(!H&&(y??m.getMessages()).some(ce=>ce.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=ef(E),e.dataset.variant=B,e.dataset.overflow=O;let _=document.createDocumentFragment(),I=m.isStreaming();k.forEach((U,ce)=>{let de=nf({item:U,index:ce,surface:E,source:x,variant:B,streaming:I,config:L,plugins:$,chipsConfig:v,session:m,getTextarea:()=>h,eventTarget:e,submitPrompt:C?.submitPrompt});_.appendChild(de),n.push(de),[...de instanceof HTMLButtonElement?[de]:[],...Array.from(de.querySelectorAll("button"))].forEach(ke=>{t.includes(ke)||(ke.disabled=I,t.push(ke))})}),e.appendChild(_),a(),l();let Z=JSON.stringify({normalized:k,surface:E,variant:B,source:x});Z!==o&&(o=Z,xI(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:k.map(U=>({...U})),surface:E,source:x,variant:B},bubbles:!0,composed:!0})),H&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:k.map(U=>U.prompt)},bubbles:!0,composed:!0})))}}};var qn={"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 SI="persona-header-control",AI="persona-header-control--glyph",MI="persona-header-control--sparse",EI=20,TI={x:[1.4,1.05]},px="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",PI="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",cp=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=TI[t]??[1,1.5],l=!o;e.classList.toggle(AI,l),e.classList.toggle(MI,l&&s!==1);let d=parseFloat(o??"")||EI,p=ae(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)},Gs=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=px,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:h,borderRadius:y,paddingX:v,paddingY:C,hidden:x,extraClassName:E,attrs:H}=e,B=S("div",a),A=!!(m||h),O=G("button",{className:fn(SI,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"persona-border-none",!y&&"persona-rounded-full",E),attrs:{type:"button","aria-label":t,...H},style:{width:l,height:l,minWidth:l,minHeight:l,display:x?"none":void 0,color:p||yn.actionIconColor,backgroundColor:u,border:A?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:y,paddingLeft:v,paddingRight:v,paddingTop:C,paddingBottom:C}});return r?cp(O,r,{iconSize:d,iconText:s}):s&&(O.textContent=s),B.appendChild(O),rn({anchor:O,trigger:B,text:()=>O.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:O,wrapper:B}},Xi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=px,buttonSize:r,iconSize:s}=t,a=e?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=Gs({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}},Ji=(e,t={})=>{let{wrapperClassName:n=PI,buttonSize:o,iconSize:r}=t,a=(e?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=Gs({ariaLabel:l,tooltip:d,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:p,wrapper:u}};var yn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},of={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)"},kI={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)"},es=e=>{let{config:t,showClose:n=!0}=e,o=G("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:yn.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??el,a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,p=G("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(d){let O=parseFloat(s)||24,L=ae(d,O*.6,"currentColor",1);L?(L.style.width=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,L.style.height=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(L)):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let O=S("img");O.src=t.launcher.iconUrl,O.alt="",O.className="persona-rounded-xl persona-object-cover",O.style.height=s,O.style.width=s,p.replaceChildren(O)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let u=S("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=G("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:yn.titleColor,...of}}),h=G("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:yn.subtitleColor,...kI}});u.append(m,h),l?o.append(u):o.append(p,u);let y=r.clearChat??{},v=y.enabled??!0,C=y.placement??"inline",x=null,E=null;if(v){let L=Ji(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});x=L.button,E=L.wrapper,C==="top-right"&&(E.style.right="48px"),C==="inline"&&o.appendChild(E)}let H=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:B,wrapper:A}=Xi(t,{showClose:n,wrapperClassName:H});return a!=="top-right"&&o.appendChild(A),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:h,closeButton:B,closeButtonWrapper:A,clearChatButton:x,clearChatButtonWrapper:E}},Zi=(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 ea(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=e,l=S("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(Ki)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let v of t){if(v.dividerBefore){let E=document.createElement("hr");l.appendChild(E)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",v.id),v.destructive&&C.setAttribute("data-destructive",""),v.icon){let E=ae(v.icon,16,"currentColor",1.5);E&&C.appendChild(E)}let x=document.createElement("span");x.textContent=v.label,C.appendChild(x),C.addEventListener("click",E=>{E.stopPropagation(),m(),n(v.id)}),l.appendChild(C)}let d=null;function p(){if(!s)return;let v=o.getBoundingClientRect();l.style.top=`${v.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-v.right}px`,l.style.left="auto"):(l.style.left=`${v.left}px`,l.style.right="auto")}function u(){let v=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),v&&a?.(!0),requestAnimationFrame(()=>{let C=x=>{!l.contains(x.target)&&!o.contains(x.target)&&m()};document.addEventListener("click",C,!0),d=()=>document.removeEventListener("click",C,!0)})}function m(){let v=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,v&&a?.(!1)}function h(){l.classList.contains("persona-hidden")?u():m()}function y(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:m,toggle:h,destroy:y}}function zn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=e,p=S("button",fn(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=ae(t,o??16,"currentColor",r??2);if(u&&p.appendChild(u),l&&p.addEventListener("click",l),d)for(let[m,h]of Object.entries(d))p.setAttribute(m,h);return p}function ux(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=S("button",p);if(u.type="button",u.setAttribute("aria-label",n),t){let h=ae(t,s??14,"currentColor",2);h&&u.appendChild(h)}let m=S("span");if(m.textContent=n,u.appendChild(m),l&&u.addEventListener("click",l),d)for(let[h,y]of Object.entries(d))u.setAttribute(h,y);return u}function dp(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=S("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=zn({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,d(),o(u.id)}}):(m=S("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 LI(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:h,primaryClassName:y,chevronClassName:v}=e,C=S("div","persona-split-btn"+(h?" "+h:"")),x={label:t,className:"persona-split-btn-primary"+(y?" "+y:""),onClick:l},E=r&&n?zn({...x,icon:n,size:o??14}):ux({...x,icon:n,iconSize:o??14}),H=zn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(v?" "+v:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});C.append(E,H);let B=null,A=()=>{if(B)return B;let O=(typeof p=="function"?p():p)??void 0;return B=ea({items:s,onSelect:a,anchor:C,position:d,portal:O,onOpenChange:L=>{H.setAttribute("aria-expanded",L?"true":"false")}}),O||C.appendChild(B.element),B};return C.isConnected?A():requestAnimationFrame(()=>{B||A()}),H.addEventListener("click",O=>{O.stopPropagation(),A().toggle()}),{element:C,primaryButton:E,chevronButton:H,openMenu:()=>A().show(),closeMenu:()=>B?.hide(),toggleMenu:()=>A().toggle(),destroy:()=>{B?.destroy(),C.remove()}}}function rf(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:d}=e,p=S("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=S("span","persona-combo-btn-label");u.textContent=t,p.appendChild(u);let m=ae(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 h=ea({items:o,onSelect:v=>{p.setAttribute("aria-expanded","false"),r(v)},anchor:p,position:s,portal:a});a||p.appendChild(h.element);let y=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",v=>{if(v.stopPropagation(),y())return;let C=!h.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",C?"false":"true"),h.toggle()}),p.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),p.click())}),{element:p,setLabel:v=>{u.textContent=v,p.setAttribute("aria-label",v)},open:()=>{p.setAttribute("aria-expanded","true"),h.show()},close:()=>{p.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let v=!h.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",v?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),p.remove()}}}var gx=e=>{let t=es({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 II(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=Gs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?op(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let a=Al(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=ea({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 mx=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=S("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=yn.minHeight,l.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",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 A=rf({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:O=>{let L=K=>{K===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:O}}))},$=d.onSelect(O);$ instanceof Promise?$.then(L,()=>{}):L($)},hover:d.hover,className:""});p=A.element,p.style.color=yn.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=S("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=S("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=yn.titleColor,Object.assign(u.style,of),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let O=r.onTitleClick;p.addEventListener("click",L=>{L.target.closest("button")||O()}),p.addEventListener("keydown",L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),O())})}let A=r?.titleRowHover;A&&(p.style.borderRadius=A.borderRadius??"10px",p.style.padding=A.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=A.background??"",p.style.borderColor=A.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:h,wrapper:y}=Xi(t,{showClose:n,wrapperClassName:m});o&&h.addEventListener("click",o);let v=S("div","persona-flex persona-items-center persona-gap-1");d||II(v,r?.trailingActions,r?.onAction??s);let C=a.clearChat??{},x=null,E=null;if(C.enabled??!0){let A=C.placement??"inline",O=Ji(t,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});x=O.button,E=O.wrapper,A==="top-right"?E.style.right="48px":v.appendChild(E)}v.appendChild(y),l.appendChild(v);let H=S("div");H.style.display="none";let B=S("span");return B.style.display="none",{header:l,iconHolder:H,headerTitle:u,headerSubtitle:B,closeButton:h,closeButtonWrapper:y,clearChatButton:x,clearChatButtonWrapper:E}},sf={default:gx,minimal:mx},fx=e=>sf[e]??sf.default,Wl=(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=S("div");l.style.display="none";let d=S("span"),p=S("span"),u=S("button");u.style.display="none";let m=S("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=fx(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 ta=e=>{let{config:t}=e,n=G("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=$d(),r=G("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""}}),{textarea:s,attachAutoResize:a}=Dd(t);a();let l=_d(t),d=Gi(t),p=Nd(t),u=Fd(t),m=G("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),p&&(p.previewsContainer.style.gap="8px",m.append(p.previewsContainer),r.append(p.input)),r.append(s);let h=G("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=G("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),v=G("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&y.append(p.wrapper),d&&v.append(d.wrapper),v.append(l.wrapper),h.append(y,v),r.append(h),r.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==d?.button&&C.target!==d?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),t?.statusIndicator?.mode==="transient"?n.append(o,u,r):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:h,leftActions:y,rightActions:v,setSendButtonMode:l.setMode}};import{ChevronUp as RI,MessageSquare as HI}from"lucide";var hx=()=>{let e=G("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=S("span","persona-pill-peek__icon"),n=St(HI,16,"currentColor",1.5);n&&t.appendChild(n);let o=S("span","persona-pill-peek__text"),r=S("span","persona-pill-peek__caret"),s=St(RI,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},pp=e=>{let{config:t}=e,n=G("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=$d(),r=Fd(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Dd(t,{defaultMaxLines:5});a();let l=_d(t),d=Gi(t),p=Nd(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=G("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),m=G("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let h=G("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&h.append(d.wrapper),h.append(l.wrapper),u.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==d?.button&&C.target!==d?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,h);let y=G("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(y),p&&y.append(p.previewsContainer),n.append(o,u,r);let v=u;return{footer:n,suggestions:o,composerForm:u,header:y,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:v,leftActions:m,rightActions:h,setSendButtonMode:l.setMode}};var WI=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}},OI=(e,t)=>{if(!e)return null;let n=WI(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},BI=(e,t)=>{let n=S("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},DI=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},lf=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(":"))},cf=320,wx=320,_I=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),NI=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),FI=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),$I=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),UI=e=>{if(!e||e.length===0)return null;let t=G("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=G("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=S("span","persona-mention-chip-icon"),s=ae(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(G("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},jI=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(vl(o.ref,{readonly:!0,render:t}))}return n},yx="\uE000",bx="\uE001",VI=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=h=>`${yx}${r}:${h}${bx}`,a=t.map((h,y)=>h.kind==="text"?h.text:s(y)).join(""),l=n(a);if(!t.every((h,y)=>h.kind==="text"||l.includes(s(y)))){e.replaceChildren(jI(t,o));return}e.innerHTML=l;let p=new RegExp(`${yx}${r}:(\\d+)${bx}`),u=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let h=u.nextNode();h;h=u.nextNode())m.push(h);for(let h of m){let y=h;for(let v=p.exec(y.data);v;v=p.exec(y.data)){let C=t[Number(v[1])],x=y.splitText(v.index);x.data=x.data.slice(v[0].length),C?.kind==="mention"&&x.parentNode?.insertBefore(vl(C.ref,{readonly:!0,render:o}),x),y=x}}},qI=(e,t,n)=>{if(e.length===0)return null;try{let o=S("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=S("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=`${cf}px`,p.style.maxHeight=`${wx}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}),DI(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}},zI=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!lf(o.audio))return;let r=S("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${cf}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},KI=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!lf(o.video))return;let r=S("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${cf}px`,r.style.maxHeight=`${wx}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}},GI=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!lf(o.data))return;let r=S("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}},na=()=>{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},xx=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:na};if(t){let r=t(o);if(r!==null)return r}return na()},YI=(e,t)=>{let n=S("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=S("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},vx=(e,t,n="div")=>{let o=S(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},Ol=(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},Cx={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"}},QI=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=Cx[n??"bubble"]??Cx.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)`)},up="custom:",XI=e=>`${up}${e}`,Sx=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),Ax=(e,t,n,o)=>{let r=t.showCopy??!0,s=t.showUpvote??!1,a=t.showDownvote??!1,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=Sx(t,e.role);if(!r&&!s&&!a&&!l&&!d&&!p&&!u&&m.length===0){let B=S("div");return B.style.display="none",B.id=`actions-${e.id}`,B.setAttribute("data-actions-for",e.id),B}let h=t.visibility??"hover",y=t.align??"right",v=t.layout??"pill-inside",C={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[y],x={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[v],E=S("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${C} ${x} ${h==="hover"?"persona-message-actions-hover":""}`);E.id=`actions-${e.id}`,E.setAttribute("data-actions-for",e.id);let H=(B,A,O)=>{let L=zn({icon:B,label:A,size:14,className:"persona-message-action-btn",chromeless:!0});return L.setAttribute("data-action",O),L};r&&E.appendChild(H("copy","Copy message","copy")),l&&E.appendChild(H("volume-2","Read aloud","read-aloud")),s&&E.appendChild(H("thumbs-up","Upvote","upvote")),a&&E.appendChild(H("thumbs-down","Downvote","downvote")),d&&E.appendChild(H("refresh-cw","Regenerate response","regenerate")),p&&E.appendChild(H("pencil","Edit message","edit")),u&&E.appendChild(H("quote","Quote message","quote"));for(let B of m)E.appendChild(H(B.iconName??"ellipsis",B.label,XI(B.id)));return E},Bl=(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,h=d?.position??"left",y=p?.position??"below",v=Ol(e.role,l),C=S("div",v.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let x=Um(s?.widgetConfig?.future).components.message,E=s?.widgetConfig?.theme?.components?.message;QI(C,e.role,l,e.role==="user"?{...x.user,...E?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...x.assistant,...E?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let H=_I(e),B=e.content?.trim()??"",O=H.length>0&&B===Ui,L=sp(s?.widgetConfig?.features?.streamAnimation),$=s?.widgetConfig?.features?.streamAnimation?.plugins,K=e.role==="assistant"&&L.type!=="none"?Tl(L.type,$):null,se=e.role==="assistant"&&K?.isAnimating?.(e)===!0,te=e.role==="assistant"&&K!==null&&(!!e.streaming||se);te&&K?.bubbleClass&&C.classList.add(K.bubbleClass);let P=document.createElement("div");P.classList.add("persona-message-content"),e.streaming&&P.classList.add("persona-content-streaming"),te&&K&&(K.containerClass&&P.classList.add(K.containerClass),P.style.setProperty("--persona-stream-step",`${L.speed}ms`),P.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let k=te?ap(e.content??"",L.buffer,K,e,!!e.streaming):e.content??"",_=()=>{let be=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent});return te&&K?.wrap==="char"?Pl(be,"char",e.id,{skipTags:K.skipTags}):te&&K?.wrap==="word"?Pl(be,"word",e.id,{skipTags:K.skipTags}):be},I=null;if(O?(I=document.createElement("div"),I.innerHTML=_(),I.style.display="none",P.appendChild(I)):e.contentSegments?.length?VI(P,e.contentSegments,be=>t({text:be,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):P.innerHTML=_(),te&&K?.useCaret&&!O&&B){let be=lp(),D=P.querySelectorAll(".persona-stream-char, .persona-stream-word"),De=D[D.length-1];if(De?.parentNode)De.parentNode.insertBefore(be,De.nextSibling);else{let _e=P.lastElementChild;_e?_e.appendChild(be):P.appendChild(be)}}if(m&&y==="inline"&&e.createdAt){let be=vx(e,p,"span");be.classList.add("persona-timestamp-inline");let D=P.lastElementChild;D?D.appendChild(be):P.appendChild(be)}if(H.length>0){let be=qI(H,!O&&!!B,()=>{O&&I&&(I.style.display="")});be?C.appendChild(be):O&&I&&(I.style.display="")}let Z=NI(e);if(Z.length>0){let be=zI(Z);be&&C.appendChild(be)}let U=FI(e);if(U.length>0){let be=KI(U);be&&C.appendChild(be)}let ce=$I(e);if(ce.length>0){let be=GI(ce);be&&C.appendChild(be)}let de=e.contentSegments?.length?null:UI(e.contextMentions);if(de&&C.appendChild(de),C.appendChild(P),m&&y==="below"&&e.createdAt){let be=vx(e,p);be.classList.add("persona-mt-1"),C.appendChild(be)}let pe=e.role==="assistant"?OI(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let be=!!(k&&k.trim()),D=L.placeholder==="skeleton",De=D&&L.buffer==="line"&&be;if(be)De&&C.appendChild(kl());else if(D)C.appendChild(kl());else{let _e=xx("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);_e&&C.appendChild(_e)}}pe&&e.stopReason&&!e.streaming&&(B||(P.style.display="none"),C.appendChild(BI(e.stopReason,pe)));let ke=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1,we=s?.actionEligibility,fe=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&we?.canEdit===!0||o?.showQuote===!0&&we?.canQuote===!0||Sx(o,"user").length>0);if((ke||fe)&&o){let be=Ax(e,fe?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,we);C.appendChild(be)}if(!u||e.role==="system")return C;let lt=S("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),rt=YI(d,e.role);return h==="right"||h==="left"&&e.role==="user"?lt.append(C,rt):lt.append(rt,C),lt},JI=(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}):Bl(e,t,n,o,r,s)};var ZI=40,eR=(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=ae(t.name,ZI);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(G("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(G("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},Mx=(e,t,n={})=>{let o=G("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=S("p","persona-welcome-kicker");r.hidden=!0;let s=S("h2","persona-welcome-title"),a=S("p","persona-welcome-subtitle"),l=G("div",{className:"persona-welcome-head-text"},r,s),d=G("div",{className:"persona-welcome-title-row"},o,l);return{host:G("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},d,a,t),iconHolder:o,kicker:r,title:s,subtitle:a,starterSuggestions:t}},oa=(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)},mp=(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==="",eR(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-layout",t.layout??"top"),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")},tR="data-persona-welcome-plugin",Ex="data-persona-welcome-overlay",gp="persona-welcome-overlay-active",df=new WeakMap,pf=(e,t,n)=>{n.setAttribute(tR,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(Ex,""),e.classList.contains(gp)||(df.set(e,e.scrollTop),e.classList.add(gp),e.scrollTop=0)},uf=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(Ex),e.classList.contains(gp)&&(e.classList.remove(gp),e.scrollTop=df.get(e)??e.scrollTop,df.delete(e))},Tx=()=>{let e=G("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},fp=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=G("div",{className:Ol("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(G("div",{className:"persona-flex"},r)),e.hidden=!1},Px=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,kx=(e,t)=>{if(Px()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,a=0;if(o){let v=getComputedStyle(o);r=parseFloat(v.rowGap)||0;let C=e.previousElementSibling,x=e.nextElementSibling,H=o.getBoundingClientRect().top+(parseFloat(v.borderTopWidth)||0)+(parseFloat(v.paddingTop)||0)-o.scrollTop;s=Math.max(0,C?n.top-C.getBoundingClientRect().bottom-r:n.top-H),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"}),h=!1,y=()=>{h||(h=!0,e.style.overflow=l,t(m))};return m.finished.then(y).catch(y),m},Lx=(e,t,n,o=260)=>{if(t<=1||Px()||typeof e.animate!="function"||!e.isConnected)return null;let r=n==="drop"?-t:t;return e.animate([{transform:`translateY(${r}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var nR="Hello \u{1F44B}",oR="I can answer questions and help you get things done here.",Ix=new WeakSet,bn=(e,t)=>!!e&&e[t]!==void 0,rR=(e,t)=>{!e||e.debug!==!0||!t.length||Ix.has(e)||(Ix.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Dl=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!=="docked")=>{let n=e?.welcome,o=e?.copy,r=e?.future?.v5Defaults===!0,s=n?.layout??(r?"centered":"top"),a=bn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=a==="hero"&&!r&&n?.layout===void 0?"on-first-message":bn(n,"dismiss")?n.dismiss:r||a==="hero"?"on-first-message":"never",d=[];bn(n,"title")&&bn(o,"welcomeTitle")&&d.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),bn(n,"subtitle")&&bn(o,"welcomeSubtitle")&&d.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),bn(n,"variant")&&bn(o,"showWelcomeCard")&&d.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),a==="hero"&&bn(n,"message")&&d.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&a==="hero"&&bn(n,"dismiss")&&n.dismiss!=="on-first-message"&&d.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let p=n?.anchor??(s==="centered"&&t?"center":"bottom"),u=Sl(n?.anchorComposerTop)!==null;return bn(n,"anchorComposerTop")&&!u&&d.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(bn(n,"anchorComposerTop")||bn(n,"composerGap"))&&d.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),rR(e,d),{title:bn(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":nR),kicker:n?.kicker??"",subtitle:bn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":oR),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:s==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:a,dismiss:l,message:a==="hero"?void 0:n?.message,layout:s,anchor:p,anchorComposerTop:u?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||ep}},Rx=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Ys=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var sR="var(--persona-components-panel-maxWidth)",Hx="var(--persona-components-panel-height)",iR="var(--persona-components-panel-maxHeight)",Qs=e=>{let t=cr(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${Hx})`:`max(200px, calc(${Hx} - ${o}px))`;return{width:n??lv,maxWidth:n??sR,height:r,maxHeight:iR}},Wx="16px",mf="10px",ff="14px",Ox=e=>{let t=e?.launcher?.enabled??!0,n=Ct(e);if(Zr(e)){let p=e?.launcher?.composerBar??{},u=S("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=p.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??cn);let m=S("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");m.style.width="100%",u.appendChild(m);let h=S("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=p.expandedSize??"anchored",h.style.zIndex=String(e?.launcher?.zIndex??cn),{wrapper:u,panel:m,pillRoot:h}}if(n){let p=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(u),{wrapper:p,panel:u}}if(!t){let p=S("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=S("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),m=cr(e),y=m.launcherWidth||m.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?Qs(e).width:"100%";return p.style.width=y,u.style.width="100%",p.appendChild(u),{wrapper:p,panel:u}}let r=e?.launcher??{},s=r.position&&qn[r.position]?qn[r.position]:qn["bottom-right"],a=S("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??cn);let l=S("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=Qs(e);return l.style.width=d.width,l.style.maxWidth=d.maxWidth,a.appendChild(l),{wrapper:a,panel:l}},hf=e=>{let t=G("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":ef(e)}});return t.hidden=!0,t},Bx=(e,t)=>{let n=hf("starter"),o=Mx(e,n,{flatShadow:Ct(e)}),r=Dl(e);mp(o,r),oa(t,o.host,Ys(r,e?.initialMessages));let s=Tx();return fp(s,r.message,e),{welcome:o,greetingHost:s}},aR=(e,t)=>{let n=S("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}=Xi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:Wx,iconSize:mf});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 $=Ji(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:Wx,iconSize:ff});a=$.button,l=$.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=G("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=G("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:m}=Bx(e,p),{host:h,title:y,subtitle:v}=u,C=u.starterSuggestions,x=S("div","persona-widget-messages persona-flex persona-flex-col");x.style.gap="var(--persona-components-message-gap, 12px)";let E=hf("followUp"),H=Xr(e,!0);H&&(x.style.maxWidth=H,x.style.marginLeft="auto",x.style.marginRight="auto",x.style.width="100%"),p.append(h,m,x,E);let B=G("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),A=pp({config:e}),{root:O,textNode:L}=hx();return n.append(d,r,p,B),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:x,starterSuggestions:C,transcriptSuggestions:E,composerOverlay:B,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:h,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:y,introSubtitle:v,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:S("span"),headerTitle:S("span"),headerSubtitle:S("span"),header:d,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:O,peekTextNode:L}},Dx=(e,t=!0)=>{if(Zr(e))return aR(e,t);let n=G("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?Wl(e,o,{showClose:t}):es({config:e,showClose:t}),a=G("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=Bx(e,a),{host:p,title:u,subtitle:m}=l,h=l.starterSuggestions,y=S("div","persona-widget-messages persona-flex persona-flex-col");y.style.gap="var(--persona-components-message-gap, 12px)";let v=hf("followUp"),C=Xr(e,!1);C&&(y.style.maxWidth=C,y.style.marginLeft="auto",y.style.marginRight="auto",y.style.width="100%"),a.append(p,d,y,v);let x=ta({config:e}),E=e?.layout?.showFooter!==!1;r?Zi(n,s,e):(s.header.style.display="none",Zi(n,s,e)),n.append(a);let H=G("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return E||(x.footer.style.display="none"),n.append(x.footer),n.append(H),{container:n,body:a,messagesWrapper:y,starterSuggestions:h,transcriptSuggestions:v,composerOverlay:H,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 yf=(e,t)=>{let n=S("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,15 @@ _Details: ${n.message}_`:o}var Rg=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=St(s),d=n.querySelector("[data-role='launcher-title']");if(d){let O=a.title??"Chat Assistant";d.textContent=O,d.setAttribute("title",O)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let O=a.subtitle??"Here to help you get answers fast";p.textContent=O,p.setAttribute("title",O)}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 O=a.agentIconSize??"40px";if(m.style.height=O,m.style.width=O,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(O)||24,R=le(a.agentIconName,T*.6,"var(--persona-text-inverse, #ffffff)",1.5);R?(m.appendChild(R),m.style.display=""):(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let O=a.agentIconSize??"40px";y.style.height=O,y.style.width=O,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 O=a.callToActionIconSize??"32px";h.style.height=O,h.style.width=O,a.callToActionIconBackgroundColor?(h.style.backgroundColor=a.callToActionIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(h.style.color=a.callToActionIconColor,h.classList.remove("persona-text-persona-call-to-action")):(h.style.color="",h.classList.add("persona-text-persona-call-to-action"));let T=0;if(a.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=a.callToActionIconPadding,T=(parseFloat(a.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),a.callToActionIconHidden)h.style.display="none";else if(h.style.display=l?"none":"",h.innerHTML="",a.callToActionIconName){let R=parseFloat(O)||24,A=Math.max(R-T,8),D=le(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"],w="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:`${w} ${C}`,l||(n.style.zIndex=String(a.zIndex??rn));let P="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??P,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:I,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}},IL="teaser-dismissed",Ww=new Set,Hw=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${IL}`},RL=(e,t)=>{if(Ww.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},HL=(e,t)=>{if(Ww.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},WL=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,OL=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||St(e??{})?null:t},Ow=(e,t)=>{let n=E("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,a=null,l=null,d=null,p=!1,u=!1,m=!1,y=!1,h=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,C=()=>{d!==null&&(clearTimeout(d),d=null)},w=()=>{!s||!p||(p=!1,s.hidden=!0)},S=J=>{C(),m=!0,w(),HL(Hw(o),J&&h())},P=J=>{!r||m||S(J==="user"&&p)},I=()=>{d=null,!(!s||m||y)&&(u=!0,p=!0,s.hidden=!1,!(WL()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},O=()=>{!r||!s||m||u||y||RL(Hw(o),h())||(C(),d=setTimeout(I,Math.max(0,r.delayMs??0)))},T=()=>{S(h()),t()},R=J=>{J.stopPropagation(),S(h())},D=Tm(e,()=>{P("user"),t()}),K=()=>{C(),l?.removeEventListener("click",T),a?.removeEventListener("click",R),s?.remove(),s=null,l=null,a=null,p=!1},ie=()=>{l=G("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",T),a=G("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",R),s=G("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,D.element)},Z=()=>{let J=o.launcher?.position??"bottom-right",V=zn[J]??zn["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",D.element.style.position="";return}n.className=gn("persona-launcher-surface",V),n.setAttribute("data-teaser",J),n.style.zIndex=String(o.launcher?.zIndex??rn),D.element.style.position="static"},M=J=>{let V=OL(J);if(r=V,!V){K();return}s||ie(),l.textContent=V.text,a.hidden=V.dismissible===!1,a.setAttribute("aria-label",V.dismissLabel??"Dismiss message"),O()},_=J=>{o=J,D.update(J),M(J),Z()},W=(J,V="user")=>{y=J,J&&P(V)},H=()=>{K(),D.destroy(),n.remove()};return n.appendChild(D.element),e&&(M(e),Z()),{element:n,launcher:D,get teaser(){return s?{element:s,show:I,dismiss:S}:null},setPanelOpen:W,update:_,destroy:H}};var Bw=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Lw(e),s=Rw(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}}},Pm=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>Tm(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Ow(e,n);return{instance:r,element:r.element}};var BL=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},_L=(e,t,n)=>`${BL(e)}plugin:${t}:${n}`,_w=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=>_L(e(),r,a);return{get:a=>{let l=s(a),d=o();if(d)try{return d.getItem(l)}catch{n=!0}return t.get(l)??null},set:(a,l)=>{let d=s(a),p=o();if(p)try{p.setItem(d,l);return}catch{n=!0}t.set(d,l)},remove:a=>{let l=s(a);t.delete(l);let d=o();if(d)try{d.removeItem(l)}catch{n=!0}}}}};var _i=(e,t,n)=>{let o=n;for(let r of t){let s=E("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};import{ChevronDown as DL,ChevronUp as NL}from"lucide";var FL=["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"],$L="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",UL="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",jL=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Fd=(e,t)=>{let n=E("div",["persona-message-bubble",e,...FL].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},$d=e=>{let t=E("button",e.expandable?$L:UL);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},km=(e,t,n)=>{e.innerHTML="";let o=It(t?NL:DL,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},Ud=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=E("div","persona-flex persona-items-center");km(o,n.expanded,n.iconColor);let r=E("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),e.append(t,r),o},jd=e=>{let t=E("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();jL(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&&km(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},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&&km(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,qL=(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
|
-
`):""},
|
|
38
|
-
`)
|
|
39
|
-
`):""},Im=(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)"},VL=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=n?.success===!1?n.error||"Tool failed":zL(e,o?.previewMaxLines??3),a=n?ev(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=fg(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=fg(n,d.completeTextTemplate,p)),n.success===!1&&(p+=" \xB7 Failed"),{summary:p,previewText:s,isActive:l}},Fw=(e,t,n)=>{zd(e,t,{stateSet:Ni,previewKind:"tool",iconColor:Nw(n?.toolCall??{})})},Rm=(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}=VL(e,t),m=$d({expandable:a,expanded:l,bubbleType:"tool"});o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let y=E("div","persona-flex persona-flex-col persona-text-left"),h=E("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(h.style.color=o.headerTextColor);let C=String(n.startedAt??Date.now()),w=()=>{let M=E("span","");return M.setAttribute("data-tool-elapsed",C),M.textContent=ja(n),M},S=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:t??{},elapsed:ja(n),createElapsedElement:w});typeof S=="string"&&S.trim()?(h.textContent=S,y.appendChild(h)):S instanceof HTMLElement?y.appendChild(S):(h.textContent=d,y.appendChild(h));let P=s.loadingAnimation??"none",I=o.activeTextTemplate,O=o.completeTextTemplate,T=u?I:O,R=S instanceof HTMLElement,A=(M,_)=>{h.textContent="";let W=n.name?.trim()||"tool",H=Jc(M,W),J=0;for(let V of H){let pe=V.styles.length>0?(()=>{let se=E("span",V.styles.map(ge=>`persona-tool-text-${ge}`).join(" "));return h.appendChild(se),se})():h;if(V.isDuration&&u)pe.appendChild(w());else{let se=V.isDuration?ja(n):V.text;_?J=_i(pe,se,J):pe.appendChild(document.createTextNode(se))}}};if(!R)if(u&&P!=="none"){let M=o.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),P==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${M}ms`),T&&A(T,!1);else if(h.classList.add(`persona-tool-loading-${P}`),h.style.setProperty("--persona-tool-anim-duration",`${M}ms`),P==="shimmer-color"&&(o.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),T)A(T,!0);else{let _=h.textContent||d;h.textContent="",_i(h,_,0)}}else T&&A(T,!1);let D=Nw(o),K=Ud(m,y,{expandable:a,expanded:l,iconColor:D,metaGap:!0}),ie=jd({bubble:r,previewKind:"tool",expanded:l,isActive:u,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:p,isActive:u,config:t??{}})});if(!a)return r.append(m,ie),r;let Z=E("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(Z.style.display=l?"":"none",o.contentBackgroundColor&&(Z.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(Z.style.color=o.contentTextColor),o.contentPaddingX&&(Z.style.paddingLeft=o.contentPaddingX,Z.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(Z.style.paddingTop=o.contentPaddingY,Z.style.paddingBottom=o.contentPaddingY),n.name){let M=E("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?M.style.color=o.contentTextColor:o.headerTextColor&&(M.style.color=o.headerTextColor),M.textContent=n.name,Z.appendChild(M)}if(n.args!==void 0){let M=E("div","persona-space-y-1"),_=E("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Arguments";let W=E("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",Im(W,o),W.textContent=Yc(n.args),M.append(_,W),Z.appendChild(M)}if(n.chunks&&n.chunks.length){let M=E("div","persona-space-y-1"),_=E("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Activity";let W=E("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",Im(W,o),W.textContent=n.chunks.join(""),M.append(_,W),Z.appendChild(M)}if(n.success===!1&&Z.appendChild(G("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),n.status==="complete"&&n.result!==void 0){let M=E("div","persona-space-y-1"),_=E("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Result";let W=E("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",Im(W,o),W.textContent=Yc(n.result),M.append(_,W),Z.appendChild(M)}if(n.status==="complete"&&typeof n.duration=="number"){let M=E("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(M.style.color=o.contentTextColor),M.textContent=`Duration: ${n.duration}ms`,Z.appendChild(M)}return qd({expanded:l,header:m,toggleIcon:K,content:Z,collapsedPreview:ie,iconColor:D}),r.append(m,ie,Z),r};var{setLoader:SN,load:KL,provide:AN,getSync:GL}=ft({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var $w=KL;var Uw=GL;var{setLoader:TN,load:YL}=ft({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var Hm=YL;var Wm=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 Wm;var Om=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:WN,load:QL,provide:ON,getSync:XL}=ft({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),Fi=null,Vd=new Set,jw=e=>{if(Fi)return Fi;Fi=e,e.initArtifactsUi({componentRegistry:Do});for(let o of Om)Do.has(o)||Do.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Ro();t?e.__provideMarkdownParsers(t):Oa(()=>{let o=Ro();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>_c());let n=[...Vd];Vd.clear();for(let o of n)try{o()}catch{}return e};var Kd=()=>QL().then(jw);var lr=()=>{if(Fi)return Fi;let e=XL();return e?jw(e):null},Bm=e=>Fi?()=>{}:(Vd.add(e),()=>{Vd.delete(e)});function bn(e){return e?.features?.artifacts?.enabled===!0}function qw(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!bn(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function JL(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 zw=["panel","seamless","detached"];function _m(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&zw.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Dm(e){return!e||!bn(e)?!1:_m(e)==="detached"}function yl(e,t){if(!bn(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),JL(e),qw(e,t);return}let n=t.features?.artifacts?.layout,o=_m(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)}qw(e,t)}function bl(e,t){for(let l of zw)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!bn(t))return;let n=t.features?.artifacts?.layout,o=_m(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 Vw(e,t){return!t||!bn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var ZL=new Set(["__proto__","prototype","constructor"]),eI=new Set(["collapsed","card","panel","inline"]),Kw=new Set(["markdown","component"]),tI=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Rs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yd=e=>!ZL.has(e),Nm=e=>typeof e=="string"&&eI.has(e),Hs=e=>Object.keys(e).length>0;function No(e,t,n,o){e.push({path:t,code:n,message:o})}var nI="Ignored because this key is not part of the persisted preference schema.",Gd="Ignored an unsupported value.",oI="Expected collapsed, panel, or inline.",rI='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Gw={kind:"mode",message:Gd},$i={kind:"string",message:"Expected a CSS length string."},cr={kind:"boolean"},sI={paneWidth:$i,paneMaxWidth:$i,paneMinWidth:$i,expandedPanelWidth:$i,resizableMinWidth:$i,resizableMaxWidth:$i,expandLauncherPanelWhenOpen:cr,resizable:cr},iI={kind:"object",message:"Expected a preference object.",children:{showToolCalls:cr,showReasoning:cr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Gd},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Gd},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Gd},expandable:cr,grouped:cr}},reasoningDisplay:{kind:"object",children:{expandable:cr,activePreview:cr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Gw,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Gw,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Kw,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Kw}}},filePreview:{kind:"object",children:{enabled:cr}},layout:{kind:"object",children:sI}}}}};function Yw(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 Nm(e)?Un(e):No(o,n,"invalid_value",t.message);case"modeMap":{if(!Rs(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:Ss(a);Yd(a)&&(r?r.has(a):tI.test(d))?Nm(l)?s[d]=Un(l):No(o,`${n}.${a}`,"invalid_value",oI):No(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":rI)}return Hs(s)?s:void 0}case"object":{if(t.bareMode&&Nm(e))return Un(e);if(!Rs(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))(!Yd(l)||!r.includes(l))&&No(o,s(l),"unknown_key",nI);let a={};for(let l of r){let d=t.children[l],p=Yw(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]=Rs(m)&&Rs(p)?{...m,...p}:p}return Hs(a)?a:void 0}}}function Qw(e){let t=[];return{preferences:(e===null?void 0:Yw(e,iI,"",t))??{},issues:t}}function Ui(e){if(Array.isArray(e))return e.map(Ui);if(!Rs(e))return e;let t={};for(let[n,o]of Object.entries(e))Yd(n)&&o!==void 0&&(t[n]=Ui(o));return t}function Xw(e,t){let n=Ui(e);for(let[o,r]of Object.entries(t)){if(!Yd(o)||r===void 0)continue;let s=n[o];n[o]=Rs(s)&&Rs(r)?Xw(s,r):Ui(r)}return n}function aI(e){let t={},n;for(let r of e){let s=Qw(r).preferences;n=Jw(n,s.artifacts?.display),t=Xw(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function lI(e,t){if(t===void 0)return e===void 0?void 0:Ui(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...Hs(r)?{byMediaType:r}:{}};return Hs(s)?s:void 0}function Jw(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=lI(n.files,t.files),a={...o?{default:o}:{},...Hs(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Hs(a)?a:void 0}function Zw(e={},t){let n=aI(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=Jw(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Qd(e){let t=e.preferences;return!t||!Hs(t)?e:{...e,features:Zw(e.features??{},[t])}}function cI(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 dI(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 pI(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function uI(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Fm(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 ex(e,t,n,o,r,s,a=200){let l=cI(r,200),d=uI(t,n,o,a);d=Math.max(l,d);let p=dI(s);return p!==null&&(d=Math.min(d,p)),pI(e,l,d)}var{setLoader:UN,load:gI,provide:jN,getSync:mI}=ft({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var tx=gI;var nx=mI;var $m=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 $m;var ox=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fI=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),rx=(e,t,n)=>{if(!ox(e)||!ox(t)||fI.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]=rx(e[r],t[r],s)}return o};function Jd(e,t){let n=rx(e,t,"");return Za(n)}var sx=()=>{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 hI=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},yI=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=hI(e),n=yI(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}},Um=e=>typeof e=="string"?e:e==null?"":String(e),ji={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Um(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Um(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:Um(n.text)}}},ix=e=>Array.isArray(e)?e.map(t=>String(t)):[],ep=e=>{let t=new Set(ix(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(ix(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 bI=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}},vI=e=>e.map(t=>({...t,streaming:!1})),CI=e=>e.map(t=>({...t,status:"complete"})),jm=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?bI(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?vI(n.messages):void 0,artifacts:n.artifacts?CI(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 wI=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")},ax=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 wI(e)},xI=async(e,t)=>{let n=await ax(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await ax(`${e}\0${t}`)}`}};var lx=(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 K=p;p=A,d+=1;let ie={previousToken:K,token:A,source:D,revision:d};for(let Z of m)Z(ie)},w=A=>{l||A.key!==null&&A.key!==o||C(A.key===null?null:A.newValue??null,"external")},S=(async()=>{let A=await xI(e,t);o=A.storageKey,r=A.leaseKey,s=A.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",w)})(),P=A=>new Promise(D=>setTimeout(D,A)),I=()=>{let A=y();if(!A)return null;try{let D=A.getItem(r);if(!D)return null;let K=JSON.parse(D);return typeof K?.expiresAt=="number"&&typeof K?.ownerNonce=="string"?K:null}catch{return null}},O=A=>{let D=y();if(D)try{I()?.ownerNonce===A&&D.removeItem(r)}catch{}},T=A=>new Promise(D=>{let K=setTimeout(ie,A);function ie(){clearTimeout(K),window.removeEventListener("storage",Z),D()}function Z(M){(M.key===null||M.key===r)&&ie()}window.addEventListener("storage",Z)}),R=async A=>{let D=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,K=Date.now()+15e3;for(;Date.now()<K;){let ie=y();if(!ie)break;let Z=Date.now(),M=I();if(M&&M.expiresAt>Z&&M.ownerNonce!==D){await T(Math.min(M.expiresAt-Z,500));continue}try{ie.setItem(r,JSON.stringify({ownerNonce:D,expiresAt:Z+1e4}))}catch{a=!0;break}if(await P(20+Math.random()*40),I()?.ownerNonce!==D){await T(500);continue}u=D;try{return await A()}finally{u=null,O(D)}}return A()};return{ready:S,async get(){return await S,C(h(),"external"),p},async set(A){await S;let D=y();if(D)try{D.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 D=globalThis.navigator?.locks;return D?.request?D.request(s,()=>A()):y()?R(A):A()},matches(A,D,K){return A===e&&D===t&&K===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",w),u&&O(u)}}};var{setLoader:ZN,load:SI}=ft({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var qm=SI;var zm=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},dr=e=>Object.freeze({...e}),cx=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),dx=e=>e?dr(e):null;function px(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,a=!1,l=null,d=[],p=()=>{for(let T of d.splice(0))try{T()}catch(R){zm("renderHistoryView cleanup",R)}},u=(T,R)=>{for(let A of t){let D=A[T];if(D)try{let K=D(R);if(K)return K}catch(K){zm(T,K)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),y={header:T=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:dr(T.identityStatus),pendingAction:dx(T.pendingAction),copy:dr(T.copy),actions:Object.freeze({close:w.close,startNewConversation:w.startNewConversation}),defaultRenderer:T.defaultRenderer})):null,conversation:T=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:cx(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(R=>({...R,placement:R.placement??"above-conversations",items:[],render:A=>R.render(Object.freeze({collapsed:A,presentation:e.getPresentation(),actions:w}))}))),C=e.createView({slots:y,renderDom:!1,onModelChange:()=>O(),railSections:h}),w=Object.freeze({...C.operations,close:e.close}),S=()=>(a=!0,C.setDomRenderEnabled(!0),C.element),P=T=>Object.freeze({conversations:Object.freeze(T.conversations.map(cx)),activeConversationId:T.activeConversationId,state:dr(T.state),pendingAction:dx(T.pendingAction),identityStatus:dr(T.identityStatus),nextCursor:T.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:dr(C.copy),actions:w,defaultRenderer:S,requestRender:()=>O(),onCleanup:R=>{d.push(R)}}),I=()=>{a=!1;let T=null;for(let A of t)if(A.renderHistoryView){try{T=A.renderHistoryView(P(C.getModel()))}catch(D){zm("renderHistoryView",D),T=null}if(T)break}let R=!T||T.contains(C.element);return a=R,C.setDomRenderEnabled(R),T??C.element};function O(){if(!(!s||o||r)){r=!0;try{p();let T=I();if(T===l)return;let R=l;l=T,e.onElementChanged(T,R)}finally{r=!1}}}return s=!0,O(),{view:C,get element(){return l??C.element},requestRender:O,dispose:()=>{o=!0,p()}}}var AI=null;function ux(){return AI}var MI=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"]]),EI=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."]]),Vm=e=>EI.get(e)??"Conversation history is unavailable right now.";function TI(e){if(e instanceof ho)return e;if(e instanceof Ne){let t=MI.get(e.code)??"unavailable";return new ho(t,Vm(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new ho("unavailable",Vm("unavailable"))}function gx(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",Vm("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw TI(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=lv(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:Ka([],u),conversationRevision:p.conversationRevision??"",nextCursor:p.nextMessageCursor}})},async prepareOpen(l,d){return s(d.context.scope,async()=>a(await t().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>a(await t().prepareNewConversationSession()))},async delete(l,d){await s(d.context.scope,()=>t().deleteConversation(l,{scope:d.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>t().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var 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"],mx={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 Km(e){if(!e)return mx;let t={...mx};for(let n of PI){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var kI="button:not([disabled])";function tp(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=G("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),a=G("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=G("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},G("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),G("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),G("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,a));for(let p of[s,a])p.style.minHeight="44px",p.style.minWidth="88px",p.style.padding="0 16px",p.style.borderRadius="var(--persona-radius-md, 0.5rem)",p.style.cursor="pointer",p.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",a.style.border="none",a.style.background="var(--persona-danger, #b42318)",a.style.color="var(--persona-danger-fg, #ffffff)";let d=G("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(p=>{let u=!1,m=h=>{u||(u=!0,d.removeEventListener("keydown",y,!0),d.remove(),t?.focus(),p(h))};function y(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),m(!1);return}if(h.key!=="Tab")return;let C=Array.from(l.querySelectorAll(kI));if(C.length===0)return;let w=C[0],S=C[C.length-1],P=document.activeElement;h.shiftKey&&(P===w||!l.contains(P))?(h.preventDefault(),S.focus()):!h.shiftKey&&P===S&&(h.preventDefault(),w.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 LI,STR as II,OBJ as RI}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 WI(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 Gm(){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=LI(n,II|RI),s=WI(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function OI(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ym(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Do.get(e.component);if(!s){if(Om.includes(e.component)){Kd().catch(()=>{});let l=E("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function BI(){let e=Gm();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function fx(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=fx(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 Qm(e){let t=fx(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 _I=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Xm(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=_I}=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 w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=r,h.appendChild(w),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 P=[];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=`
|
|
36
|
+
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=Ct(s),d=zd(s)==="circle";d?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",a.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let p=n.querySelector("[data-role='launcher-title']");if(p){let A=a.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let A=a.subtitle??"Here to help you get answers fast";u.textContent=A,u.setAttribute("title",A)}let m=n.querySelector(".persona-flex-col");m&&(a.textHidden||l||d?m.style.display="none":m.style.display="");let h=n.querySelector("[data-role='launcher-icon']");if(h)if(a.agentIconHidden)h.style.display="none";else{let A=a.agentIconSize??"40px";if(h.style.height=A,h.style.width=A,a.agentIconBackgroundColor?(h.style.backgroundColor=a.agentIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),h.innerHTML="",a.agentIconName){let O=parseFloat(A)||24,L=ae(a.agentIconName,O*.6,"var(--persona-text-inverse, #ffffff)",1.5);L?(h.appendChild(L),h.style.display=""):(h.textContent=a.agentIconText??"\u{1F4AC}",h.style.display="")}else a.iconUrl?h.style.display="none":(h.textContent=a.agentIconText??"\u{1F4AC}",h.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let A=a.agentIconSize??"40px";y.style.height=A,y.style.width=A,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let v=n.querySelector("[data-role='launcher-call-to-action-icon']");if(v){let A=a.callToActionIconSize??"32px";v.style.height=A,v.style.width=A,a.callToActionIconBackgroundColor?(v.style.backgroundColor=a.callToActionIconBackgroundColor,v.classList.remove("persona-bg-persona-primary")):(v.style.backgroundColor="",v.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(v.style.color=a.callToActionIconColor,v.classList.remove("persona-text-persona-call-to-action")):(v.style.color="",v.classList.add("persona-text-persona-call-to-action"));let O=0;if(a.callToActionIconPadding?(v.style.boxSizing="border-box",v.style.padding=a.callToActionIconPadding,O=(parseFloat(a.callToActionIconPadding)||0)*2):(v.style.boxSizing="",v.style.padding=""),a.callToActionIconHidden||d)v.style.display="none";else if(v.style.display=l?"none":"",v.innerHTML="",a.callToActionIconName){let L=parseFloat(A)||24,$=Math.max(L-O,8),K=ae(a.callToActionIconName,$,"currentColor",1.5);K?v.appendChild(K):v.textContent=a.callToActionIconText??"\u2197"}else v.textContent=a.callToActionIconText??"\u2197"}let C=a.position&&qn[a.position]?qn[a.position]:qn["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",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?E:`${x} ${C}`,l||(n.style.zIndex=String(a.zIndex??cn));let H="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??H,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}},lR="teaser-dismissed",Nx=new Set,_x=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${lR}`},cR=(e,t)=>{if(Nx.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},dR=(e,t)=>{if(Nx.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},pR=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,uR=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Ct(e??{})?null:t},Fx=(e,t)=>{let n=S("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,h=!1,y=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,v=()=>{d!==null&&(clearTimeout(d),d=null)},C=()=>{!s||!p||(p=!1,s.hidden=!0)},x=Z=>{v(),m=!0,C(),dR(_x(o),Z&&y())},E=Z=>{!r||m||x(Z==="user"&&p)},H=()=>{d=null,!(!s||m||h)&&(u=!0,p=!0,s.hidden=!1,!(pR()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},B=()=>{!r||!s||m||u||h||cR(_x(o),y())||(v(),d=setTimeout(H,Math.max(0,r.delayMs??0)))},A=()=>{x(y()),t()},O=Z=>{Z.stopPropagation(),x(y())},$=yf(e,()=>{E("user"),t()}),K=()=>{v(),l?.removeEventListener("click",A),a?.removeEventListener("click",O),s?.remove(),s=null,l=null,a=null,p=!1},se=()=>{l=G("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",A),a=G("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",O),s=G("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,$.element)},te=()=>{let Z=o.launcher?.position??"bottom-right",U=qn[Z]??qn["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",U),n.setAttribute("data-teaser",Z),n.style.zIndex=String(o.launcher?.zIndex??cn),$.element.style.position="static"},P=Z=>{let U=uR(Z);if(r=U,!U){K();return}s||se(),l.textContent=U.text,a.hidden=U.dismissible===!1,a.setAttribute("aria-label",U.dismissLabel??"Dismiss message"),B()},k=Z=>{o=Z,$.update(Z),P(Z),te()},_=(Z,U="user")=>{h=Z,Z&&E(U)},I=()=>{K(),$.destroy(),n.remove()};return n.appendChild($.element),e&&(P(e),te()),{element:n,launcher:$,get teaser(){return s?{element:s,show:H,dismiss:x}:null},setPanelOpen:_,update:k,destroy:I}};var $x=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Ox(e),s=Dx(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:h=>(d.element.replaceWith(h.header),d.element=h.header,d.iconHolder=h.iconHolder,d.headerTitle=h.headerTitle,d.headerSubtitle=h.headerSubtitle,d.closeButton=h.closeButton,d.closeButtonWrapper=h.closeButtonWrapper,d.clearChatButton=h.clearChatButton,d.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{p.footer.replaceWith(h),p.footer=h}}},bf=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>yf(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Fx(e,n);return{instance:r,element:r.element}};var gR=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},mR=(e,t,n)=>`${gR(e)}plugin:${t}:${n}`,Ux=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=>mR(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 ra=(e,t,n)=>{let o=n;for(let r of t){let s=S("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};var fR=(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
|
+
`):""},vf=(e,t,n)=>{dd(e,t,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},Cf=(e,t,n=new Set)=>{t=pd(t,"reasoning");let o=e.reasoning,r=id("persona-reasoning-bubble",e.id);if(!o)return pr(r,e,t,"reasoning");let s=t?.features?.reasoningDisplay??{},a=s.expandable??Ns.expandable,l=a&&n.has(e.id),d=o.status!=="complete",p=fR(e,s.previewMaxLines??Ns.previewMaxLines),u=ad({expandable:a,expanded:l,bubbleType:"reasoning"}),m=S("div","persona-flex persona-flex-col persona-text-left"),h=S("span","persona-text-xs persona-text-persona-primary"),y=jr(t,"reasoning")==="row",v=y&&!d?`Thought for ${nl(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",C=t?.reasoning??{},x=String(o.startedAt??Date.now()),E=()=>{let U=S("span","");return U.setAttribute("data-tool-elapsed",x),U.textContent=Sd(o),U},H=C.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:v,previewText:p,isActive:d,config:t??{},elapsed:Sd(o),createElapsedElement:E});typeof H=="string"&&H.trim()?(h.textContent=H,m.appendChild(h)):H instanceof HTMLElement?m.appendChild(H):(h.textContent=v,m.appendChild(h));let B=S("span","persona-text-xs persona-text-persona-primary");B.textContent=sC(o),y||m.appendChild(B);let A=s.loadingAnimation??Ns.loadingAnimation,O=C.activeTextTemplate,L=C.completeTextTemplate,$=d?O:L,K=H instanceof HTMLElement,se=(U,ce)=>{h.textContent="";let de=Ad(U,""),pe=0;for(let ke of de){let we=ke.styles.length>0?(()=>{let fe=S("span",ke.styles.map(lt=>`persona-tool-text-${lt}`).join(" "));return h.appendChild(fe),fe})():h;if(ke.isDuration&&d)we.appendChild(E());else{let fe=ke.isDuration?Sd(o):ke.text;ce?pe=ra(we,fe,pe):we.appendChild(document.createTextNode(fe))}}};if(!K&&$)if(B.style.display="none",h.style.display="",d&&A!=="none"){let U=C.loadingAnimationDuration??2e3;h.setAttribute("data-preserve-animation","true"),A==="pulse"?(h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${U}ms`),se($,!1)):(h.classList.add(`persona-tool-loading-${A}`),h.style.setProperty("--persona-tool-anim-duration",`${U}ms`),A==="shimmer-color"&&(C.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",C.loadingAnimationColor),C.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",C.loadingAnimationSecondaryColor)),se($,!0))}else se($,!1);else if(!K&&d&&A!=="none"){h.style.display="";let U=C.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),A==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${U}ms`);else{h.classList.add(`persona-tool-loading-${A}`),h.style.setProperty("--persona-tool-anim-duration",`${U}ms`),A==="shimmer-color"&&(C.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",C.loadingAnimationColor),C.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",C.loadingAnimationSecondaryColor));let ce=h.textContent||v;h.textContent="",ra(h,ce,0)}o.status==="complete"&&!y&&(h.style.display="none")}else K||(o.status==="complete"&&!y?h.style.display="none":h.style.display="");if(s.iconName&&!K){let U=S("span","persona-reasoning-header-icon"),ce=ae(s.iconName,16,"currentColor",2);ce&&(U.appendChild(ce),u.appendChild(U))}let te="currentColor",P=Bi(u,m,{expandable:a,expanded:l,iconColor:te,metaGap:!1}),k=ld({bubble:r,previewKind:"reasoning",expanded:l,isActive:d,previewText:p,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:p,isActive:d,config:t??{}})});if(!a)return r.append(u,k),pr(r,e,t,"reasoning");let _=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=l?"":"none";let I=o.chunks.join(""),Z=S("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=I||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(Z),cd({expanded:l,header:u,toggleIcon:P,content:_,collapsedPreview:k,iconColor:te}),r.append(u,k,_),pr(r,e,t,"reasoning")};var jx=e=>{if(e==null)return!0;if(typeof e=="string"){if(!e.trim())return!0;try{return jx(JSON.parse(e))}catch{return!1}}return typeof e=="object"&&Object.keys(e).length===0},hR=e=>{if(e!==null&&typeof e=="object")return!0;if(typeof e!="string")return!1;try{let t=JSON.parse(e);return t!==null&&typeof t=="object"}catch{return!1}};function Vx(e,t,n){let o=t.toolCall;if(!o)return;let r=n.toolCall??{},s=(l,d)=>{let p=G("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":l.toLowerCase()},style:{backgroundColor:r.codeBlockBackgroundColor,borderColor:r.codeBlockBorderColor,borderWidth:r.codeBlockBorderColor?"1px":void 0}}),u=G("div",{className:"persona-tool-detail-label",text:l,style:{color:r.labelTextColor}}),m=$i(d),h=G("pre",{className:`persona-tool-detail-value${hR(d)?" persona-tool-detail-code":""}`,text:m,attrs:m.length>420||m.split(`
|
|
38
|
+
`).length>7?{tabindex:"0","aria-label":`${l} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),y=G("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),v=ae("copy",14,"currentColor",1.7);v&&y.appendChild(v),p.append(u,h,y),e.appendChild(p)};jx(o.args)||s("Request",o.args);let a=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");a!==void 0&&(typeof a!="string"||a.trim())&&s("Response",a),o.success===!1&&e.appendChild(G("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var wf=new WeakMap;async function qx(e){let t=e.closest("[data-persona-tool-detail]"),n=t?.querySelector("pre");if(!n)return;let o=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(wf.get(e));try{await navigator.clipboard.writeText(n.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let r=ae("check",14,"currentColor",2);r&&e.replaceChildren(r)}catch{e.setAttribute("aria-label","Copy failed \u2014 try again"),e.title="Copy failed \u2014 try again"}wf.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o;let r=ae("copy",14,"currentColor",1.7);r&&e.replaceChildren(r),wf.delete(e)},1800))}var zx=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),yR=(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(`
|
|
39
|
+
`);let r=$i(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
40
|
+
`):""},xf=(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)"},bR=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??dr.collapsedMode,s=n?.success===!1?n.error||"Tool failed":yR(e,o?.previewMaxLines??dr.previewMaxLines),a=n?jr(t,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:aC(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=rm(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=rm(n,d.completeTextTemplate,p)),n.success===!1&&(p+=" \xB7 Failed"),{summary:p,previewText:s,isActive:l}},Sf=(e,t,n,o)=>{dd(e,t,{stateSet:n,previewKind:"tool",iconColor:zx(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},Af=(e,t,n=new Set)=>{t=pd(t,"tool");let o=e.toolCall,r=t?.toolCall??{},s=id("persona-tool-bubble",e.id);if(r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow)",!o)return pr(s,e,t,"tool");let a=t?.features?.toolCallDisplay??{},l=a.expandable??dr.expandable,d=l&&n.has(e.id),{summary:p,previewText:u,isActive:m}=bR(e,t),h=ad({expandable:l,expanded:d,bubbleType:"tool"});r.headerBackgroundColor&&(h.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(h.style.paddingLeft=r.headerPaddingX,h.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(h.style.paddingTop=r.headerPaddingY,h.style.paddingBottom=r.headerPaddingY);let y=S("div","persona-flex persona-flex-col persona-text-left"),v=S("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(v.style.color=r.headerTextColor);let C=String(o.startedAt??Date.now()),x=()=>{let k=S("span","");return k.setAttribute("data-tool-elapsed",C),k.textContent=dl(o),k},E=r.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:p,previewText:u,collapsedMode:a.collapsedMode??dr.collapsedMode,isActive:m,config:t??{},elapsed:dl(o),createElapsedElement:x});typeof E=="string"&&E.trim()?(v.textContent=E,y.appendChild(v)):E instanceof HTMLElement?y.appendChild(E):(v.textContent=p,y.appendChild(v));let H=a.loadingAnimation??dr.loadingAnimation,B=r.activeTextTemplate,A=r.completeTextTemplate,O=m?B:A,L=E instanceof HTMLElement,$=(k,_)=>{v.textContent="";let I=o.name?.trim()||"tool",Z=Ad(k,I),U=0;for(let ce of Z){let de=ce.styles.length>0?(()=>{let pe=S("span",ce.styles.map(ke=>`persona-tool-text-${ke}`).join(" "));return v.appendChild(pe),pe})():v;if(ce.isDuration&&m)de.appendChild(x());else{let pe=ce.isDuration?dl(o):ce.text;_?U=ra(de,pe,U):de.appendChild(document.createTextNode(pe))}}};if(!L)if(m&&H!=="none"){let k=r.loadingAnimationDuration??2e3;if(v.setAttribute("data-preserve-animation","true"),H==="pulse")v.classList.add("persona-tool-loading-pulse"),v.style.setProperty("--persona-tool-anim-duration",`${k}ms`),O&&$(O,!1);else if(v.classList.add(`persona-tool-loading-${H}`),v.style.setProperty("--persona-tool-anim-duration",`${k}ms`),H==="shimmer-color"&&(r.loadingAnimationColor&&v.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&v.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),O)$(O,!0);else{let _=v.textContent||p;v.textContent="",ra(v,_,0)}}else O&&$(O,!1);let K=zx(r,jr(t,"tool")==="row"),se=Bi(h,y,{expandable:l,expanded:d,iconColor:K,metaGap:!0}),te=ld({bubble:s,previewKind:"tool",expanded:d,isActive:m,previewText:u,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:u,isActive:m,config:t??{}})});if(!l)return s.append(h,te),pr(s,e,t,"tool");let P=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(P.style.display=d?"":"none",r.contentBackgroundColor&&(P.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(P.style.color=r.contentTextColor),r.contentPaddingX&&(P.style.paddingLeft=r.contentPaddingX,P.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(P.style.paddingTop=r.contentPaddingY,P.style.paddingBottom=r.contentPaddingY),t.future?.v5Defaults===!0)Vx(P,e,t);else{if(o.name){let k=S("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?k.style.color=r.contentTextColor:r.headerTextColor&&(k.style.color=r.headerTextColor),k.textContent=o.name,P.appendChild(k)}if(o.args!==void 0){let k=S("div","persona-space-y-1"),_=S("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Arguments";let I=S("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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",xf(I,r),I.textContent=$i(o.args),k.append(_,I),P.appendChild(k)}if(o.chunks&&o.chunks.length){let k=S("div","persona-space-y-1"),_=S("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Activity";let I=S("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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",xf(I,r),I.textContent=o.chunks.join(""),k.append(_,I),P.appendChild(k)}if(o.success===!1&&P.appendChild(G("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let k=S("div","persona-space-y-1"),_=S("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Result";let I=S("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");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",xf(I,r),I.textContent=$i(o.result),k.append(_,I),P.appendChild(k)}if(o.status==="complete"&&typeof o.duration=="number"){let k=S("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(k.style.color=r.contentTextColor),k.textContent=`Duration: ${o.duration}ms`,P.appendChild(k)}}return cd({expanded:d,header:h,toggleIcon:se,content:P,collapsedPreview:te,iconColor:K}),s.append(h,te,P),pr(s,e,t,"tool")};var{setLoader:PF,load:vR,provide:kF,getSync:CR}=vt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var Kx=vR;var Gx=CR;var{setLoader:RF,load:wR}=vt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var Mf=wR;var Ef=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)})}},Uo=new Ef;var Tf=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:NF,load:xR,provide:FF,getSync:SR}=vt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),sa=null,hp=new Set,Yx=e=>{if(sa)return sa;sa=e,e.initArtifactsUi({componentRegistry:Uo});for(let o of Tf)Uo.has(o)||Uo.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Bo();t?e.__provideMarkdownParsers(t):Xa(()=>{let o=Bo();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>nd());let n=[...hp];hp.clear();for(let o of n)try{o()}catch{}return e};var yp=()=>xR().then(Yx);var fr=()=>{if(sa)return sa;let e=SR();return e?Yx(e):null},Pf=e=>sa?()=>{}:(hp.add(e),()=>{hp.delete(e)});function vn(e){return e?.features?.artifacts?.enabled===!0}function Qx(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!vn(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function AR(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 Xx=["panel","seamless","detached"];function kf(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Xx.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Lf(e){return!e||!vn(e)?!1:kf(e)==="detached"}function _l(e,t){if(!vn(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),AR(e),Qx(e,t);return}let n=t.features?.artifacts?.layout,o=kf(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)}Qx(e,t)}function Nl(e,t){for(let l of Xx)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!vn(t))return;let n=t.features?.artifacts?.layout,o=kf(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 Jx(e,t){return!t||!vn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var MR=new Set(["__proto__","prototype","constructor"]),ER=new Set(["collapsed","card","panel","inline"]),Zx=new Set(["markdown","component"]),TR=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Xs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vp=e=>!MR.has(e),If=e=>typeof e=="string"&&ER.has(e),Js=e=>Object.keys(e).length>0;function jo(e,t,n,o){e.push({path:t,code:n,message:o})}var PR="Ignored because this key is not part of the persisted preference schema.",bp="Ignored an unsupported value.",kR="Expected collapsed, panel, or inline.",LR='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',eS={kind:"mode",message:bp},ia={kind:"string",message:"Expected a CSS length string."},hr={kind:"boolean"},IR={paneWidth:ia,paneMaxWidth:ia,paneMinWidth:ia,expandedPanelWidth:ia,resizableMinWidth:ia,resizableMaxWidth:ia,expandLauncherPanelWhenOpen:hr,resizable:hr},RR={kind:"object",message:"Expected a preference object.",children:{showToolCalls:hr,showReasoning:hr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:bp},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:bp},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:bp},expandable:hr,grouped:hr}},reasoningDisplay:{kind:"object",children:{expandable:hr,activePreview:hr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:eS,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:eS,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Zx,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Zx}}},filePreview:{kind:"object",children:{enabled:hr}},layout:{kind:"object",children:IR}}}}};function tS(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:jo(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:jo(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:jo(o,n,"invalid_value",t.message);case"mode":return If(e)?$n(e):jo(o,n,"invalid_value",t.message);case"modeMap":{if(!Xs(e))return jo(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:Us(a);vp(a)&&(r?r.has(a):TR.test(d))?If(l)?s[d]=$n(l):jo(o,`${n}.${a}`,"invalid_value",kR):jo(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":LR)}return Js(s)?s:void 0}case"object":{if(t.bareMode&&If(e))return $n(e);if(!Xs(e))return jo(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))(!vp(l)||!r.includes(l))&&jo(o,s(l),"unknown_key",PR);let a={};for(let l of r){let d=t.children[l],p=tS(e[l],d,s(l),o);if(d.deprecated&&e[l]!==void 0&&jo(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=Xs(m)&&Xs(p)?{...m,...p}:p}return Js(a)?a:void 0}}}function nS(e){let t=[];return{preferences:(e===null?void 0:tS(e,RR,"",t))??{},issues:t}}function aa(e){if(Array.isArray(e))return e.map(aa);if(!Xs(e))return e;let t={};for(let[n,o]of Object.entries(e))vp(n)&&o!==void 0&&(t[n]=aa(o));return t}function oS(e,t){let n=aa(e);for(let[o,r]of Object.entries(t)){if(!vp(o)||r===void 0)continue;let s=n[o];n[o]=Xs(s)&&Xs(r)?oS(s,r):aa(r)}return n}function HR(e){let t={},n;for(let r of e){let s=nS(r).preferences;n=rS(n,s.artifacts?.display),t=oS(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function WR(e,t){if(t===void 0)return e===void 0?void 0:aa(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}:{},...Js(r)?{byMediaType:r}:{}};return Js(s)?s:void 0}function rS(e,t){if(t===void 0)return e===void 0?void 0:aa(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=WR(n.files,t.files),a={...o?{default:o}:{},...Js(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Js(a)?a:void 0}function sS(e={},t){let n=HR(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=rS(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 Cp(e){let t=e.preferences;return!t||!Js(t)?e:{...e,features:sS(e.features??{},[t])}}function OR(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 BR(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 DR(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function _R(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Rf(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 iS(e,t,n,o,r,s,a=200){let l=OR(r,200),d=_R(t,n,o,a);d=Math.max(l,d);let p=BR(s);return p!==null&&(d=Math.min(d,p)),DR(e,l,d)}var{setLoader:KF,load:NR,provide:GF,getSync:FR}=vt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var aS=NR;var lS=FR;var Hf=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()}},wp=new Hf;var cS=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$R=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),dS=(e,t,n)=>{if(!cS(e)||!cS(t)||$R.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]=dS(e[r],t[r],s)}return o};function xp(e,t){let n=rd(_s),o=iv(e,t,n),r=Ng(av(dS(e,t,""),n,o),o);return Ug(tl(r),cv(e,t))}var pS=()=>{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 UR=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},jR=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},Sp=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=UR(e),n=jR(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}},Wf=e=>typeof e=="string"?e:e==null?"":String(e),la={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Wf(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Wf(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:Wf(n.text)}}},uS=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ap=e=>{let t=new Set(uS(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(uS(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 h=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:h,resubmit:m.resubmit}}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var VR=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}},qR=e=>e.map(t=>({...t,streaming:!1})),zR=e=>e.map(t=>({...t,status:"complete"})),Of=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?VR(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?qR(n.messages):void 0,artifacts:n.artifacts?zR(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 KR=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")},gS=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 KR(e)},GR=async(e,t)=>{let n=await gS(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await gS(`${e}\0${t}`)}`}};var mS=(e,t,n)=>{let o="",r="",s="",a=!1,l=!1,d=0,p=null,u=null,m=new Set,h=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},y=()=>{let L=h();if(!L)return p;try{return L.getItem(o)}catch{return a=!0,p}},v=(L,$)=>{if(l||L===p)return;let K=p;p=L,d+=1;let se={previousToken:K,token:L,source:$,revision:d};for(let te of m)te(se)},C=L=>{l||L.key!==null&&L.key!==o||v(L.key===null?null:L.newValue??null,"external")},x=(async()=>{let L=await GR(e,t);o=L.storageKey,r=L.leaseKey,s=L.lockName,p=y(),!n&&typeof window<"u"&&window.addEventListener("storage",C)})(),E=L=>new Promise($=>setTimeout($,L)),H=()=>{let L=h();if(!L)return null;try{let $=L.getItem(r);if(!$)return null;let K=JSON.parse($);return typeof K?.expiresAt=="number"&&typeof K?.ownerNonce=="string"?K:null}catch{return null}},B=L=>{let $=h();if($)try{H()?.ownerNonce===L&&$.removeItem(r)}catch{}},A=L=>new Promise($=>{let K=setTimeout(se,L);function se(){clearTimeout(K),window.removeEventListener("storage",te),$()}function te(P){(P.key===null||P.key===r)&&se()}window.addEventListener("storage",te)}),O=async L=>{let $=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,K=Date.now()+15e3;for(;Date.now()<K;){let se=h();if(!se)break;let te=Date.now(),P=H();if(P&&P.expiresAt>te&&P.ownerNonce!==$){await A(Math.min(P.expiresAt-te,500));continue}try{se.setItem(r,JSON.stringify({ownerNonce:$,expiresAt:te+1e4}))}catch{a=!0;break}if(await E(20+Math.random()*40),H()?.ownerNonce!==$){await A(500);continue}u=$;try{return await L()}finally{u=null,B($)}}return L()};return{ready:x,async get(){return await x,v(y(),"external"),p},async set(L){await x;let $=h();if($)try{$.setItem(o,L)}catch{a=!0}v(L,"local")},async clear(){await x;let L=h();if(L)try{L.removeItem(o)}catch{a=!0}v(null,"local")},revision(){return d},subscribe(L){return m.add(L),()=>{m.delete(L)}},async withFirstInitLock(L){await x;let $=globalThis.navigator?.locks;return $?.request?$.request(s,()=>L()):h()?O(L):L()},matches(L,$,K){return L===e&&$===t&&K===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",C),u&&B(u)}}};var{setLoader:i$,load:YR}=vt({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var Bf=YR;var Df=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},yr=e=>Object.freeze({...e}),fS=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),hS=e=>e?yr(e):null;function yS(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,a=!1,l=null,d=[],p=()=>{for(let A of d.splice(0))try{A()}catch(O){Df("renderHistoryView cleanup",O)}},u=(A,O)=>{for(let L of t){let $=L[A];if($)try{let K=$(O);if(K)return K}catch(K){Df(A,K)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),h={header:A=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:yr(A.identityStatus),pendingAction:hS(A.pendingAction),copy:yr(A.copy),actions:Object.freeze({close:C.close,startNewConversation:C.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:fS(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>a?u("renderHistoryState",Object.freeze({...m(),state:yr(A.state),identityStatus:yr(A.identityStatus),copy:yr(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},y=t.flatMap(A=>(A.railSections??[]).map(O=>({...O,placement:O.placement??"above-conversations",items:[],render:L=>O.render(Object.freeze({collapsed:L,presentation:e.getPresentation(),actions:C}))}))),v=e.createView({slots:h,renderDom:!1,onModelChange:()=>B(),railSections:y}),C=Object.freeze({...v.operations,close:e.close}),x=()=>(a=!0,v.setDomRenderEnabled(!0),v.element),E=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(fS)),activeConversationId:A.activeConversationId,state:yr(A.state),pendingAction:hS(A.pendingAction),identityStatus:yr(A.identityStatus),nextCursor:A.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:yr(v.copy),actions:C,defaultRenderer:x,requestRender:()=>B(),onCleanup:O=>{d.push(O)}}),H=()=>{a=!1;let A=null;for(let L of t)if(L.renderHistoryView){try{A=L.renderHistoryView(E(v.getModel()))}catch($){Df("renderHistoryView",$),A=null}if(A)break}let O=!A||A.contains(v.element);return a=O,v.setDomRenderEnabled(O),A??v.element};function B(){if(!(!s||o||r)){r=!0;try{p();let A=H();if(A===l)return;let O=l;l=A,e.onElementChanged(A,O)}finally{r=!1}}}return s=!0,B(),{view:v,get element(){return l??v.element},requestRender:B,dispose:()=>{o=!0,p()}}}var QR=null;function bS(){return QR}var XR=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"]]),JR=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."]]),_f=e=>JR.get(e)??"Conversation history is unavailable right now.";function ZR(e){if(e instanceof bo)return e;if(e instanceof $e){let t=XR.get(e.code)??"unavailable";return new bo(t,_f(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new bo("unavailable",_f("unavailable"))}function vS(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 bo("unsupported_scope",_f("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw ZR(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=fC(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:ml([],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 eH=["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"],CS={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 Nf(e){if(!e)return CS;let t={...CS};for(let n of eH){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var tH="button:not([disabled])";function Mp(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=G("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),a=G("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=G("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},G("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),G("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),G("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,a));for(let p of[s,a])p.style.minHeight="44px",p.style.minWidth="88px",p.style.padding="0 16px",p.style.borderRadius="var(--persona-radius-md, 0.5rem)",p.style.cursor="pointer",p.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",a.style.border="none",a.style.background="var(--persona-danger, #b42318)",a.style.color="var(--persona-danger-fg, #ffffff)";let d=G("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(p=>{let u=!1,m=y=>{u||(u=!0,d.removeEventListener("keydown",h,!0),d.remove(),t?.focus(),p(y))};function h(y){if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),m(!1);return}if(y.key!=="Tab")return;let v=Array.from(l.querySelectorAll(tH));if(v.length===0)return;let C=v[0],x=v[v.length-1],E=document.activeElement;y.shiftKey&&(E===C||!l.contains(E))?(y.preventDefault(),x.focus()):!y.shiftKey&&E===x&&(y.preventDefault(),C.focus())}d.addEventListener("keydown",h,!0),d.addEventListener("pointerdown",y=>{y.target===d&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),e.host.appendChild(d),s.focus()})}import{parse as nH,STR as oH,OBJ as rH}from"partial-json";function sH(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function iH(e,t){if(!sH(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 Ff(){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=nH(n,oH|rH),s=iH(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function aH(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function $f(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Uo.get(e.component);if(!s){if(Tf.includes(e.component)){yp().catch(()=>{});let l=S("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 lH(){let e=Ff();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function wS(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 Ep(e){let t=wS(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 Uf(e){let t=wS(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 cH=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function jf(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=cH}=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,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,y.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,y.appendChild(C),h.appendChild(y);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 E=[];for(let L=1;L<=5;L++){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",`${L} star${L>1?"s":""}: ${p[L-1]}`),$.title=p[L-1],$.dataset.rating=String(L),$.innerHTML=`
|
|
40
41
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
41
42
|
<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
43
|
</svg>
|
|
43
|
-
`,D.addEventListener("click",()=>{m=A,P.forEach((K,ie)=>{let Z=ie<A;K.classList.toggle("selected",Z),K.setAttribute("aria-checked",ie===A-1?"true":"false")})}),P.push(D),S.appendChild(D)}y.appendChild(S);let I=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),A.appendChild(I),y.appendChild(A)}let O=document.createElement("div");O.className="persona-feedback-actions";let T=document.createElement("button");T.type="button",T.className="persona-feedback-btn persona-feedback-btn-skip",T.textContent=l,T.addEventListener("click",()=>{n?.(),u.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(m===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let A=I?.value.trim()||void 0;await t(m,A),u.remove()}catch(A){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),O.appendChild(T),O.appendChild(R),y.appendChild(O),u.appendChild(y),u}function Jm(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 w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,C.appendChild(w);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,C.appendChild(S),h.appendChild(C);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-nps",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let O=document.createElement("span");O.className="persona-feedback-label-low",O.textContent=p;let T=document.createElement("span");T.className="persona-feedback-label-high",T.textContent=u,I.appendChild(O),I.appendChild(T);let R=document.createElement("div");R.className="persona-feedback-numbers";let A=[];for(let M=0;M<=10;M++){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 ${M} out of 10`),_.textContent=String(M),_.dataset.rating=String(M),M<=6?_.classList.add("persona-feedback-detractor"):M<=8?_.classList.add("persona-feedback-passive"):_.classList.add("persona-feedback-promoter"),_.addEventListener("click",()=>{y=M,A.forEach((W,H)=>{W.classList.toggle("selected",H===M),W.setAttribute("aria-checked",H===M?"true":"false")})}),A.push(_),R.appendChild(_)}P.appendChild(I),P.appendChild(R),h.appendChild(P);let D=null;if(d){let M=document.createElement("div");M.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"),M.appendChild(D),h.appendChild(M)}let K=document.createElement("div");K.className="persona-feedback-actions";let ie=document.createElement("button");ie.type="button",ie.className="persona-feedback-btn persona-feedback-btn-skip",ie.textContent=l,ie.addEventListener("click",()=>{n?.(),m.remove()});let Z=document.createElement("button");return Z.type="button",Z.className="persona-feedback-btn persona-feedback-btn-submit",Z.textContent=a,Z.addEventListener("click",async()=>{if(y===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}Z.disabled=!0,Z.textContent="Submitting...";try{let M=D?.value.trim()||void 0;await t(y,M),m.remove()}catch(M){Z.disabled=!1,Z.textContent=a,console.error("[NPS Feedback] Failed to submit:",M)}}),K.appendChild(ie),K.appendChild(Z),h.appendChild(K),m.appendChild(h),m}var qi="persona-chat-history",FI=30*1e3,$I=641,zi="data-persona-composer-reason",UI={"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 jI(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=UI[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 qI(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 zI(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},vx=e=>e.map(t=>({...t,streaming:!1})),Cx=(e,t,n)=>{let o=e?.markdown?Fc(e.markdown):null,r=rg(e?.sanitize);e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let s=!1,a=l=>{let d=l.text??"",p=l.message.rawContent??null;if(t){let y=t.process({text:d,raw:p??d,message:l.message,streaming:l.streaming});y!==null&&(d=y.text,y.persist||(l.message.__skipPersist=!0),y.resubmit&&!l.streaming&&n&&n())}let u=Ro()!==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?yb(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 wx(e){let t=E("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=le(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=E("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var VI=(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},KI=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:VI(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),ef=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Za(t),r=()=>{Nv({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=Qd(o);let a=Xd.getForInstance(o.plugins),l=$C(e),d=[],p=!1,u=_w(()=>o),m=null,y=null,h=null,C=!1,w=null,S=i=>{m=i,i.initApprovalUi({webMcpToolTitle:yi});let c=i.createBuiltInApprovalPlugin();y=c.plugin,h=c.teardown},P=()=>{if(m)return m;let i=Uw();return i?(S(i),i):($w().then(c=>{C||m||(S(c),w?.())}).catch(()=>{}),null)},I=!1,O=!1,T=null,R=(i,c,g,f)=>{if(!i.querySelector("[data-tv-form]"))return;let b=nx();if(b){b.enhanceWithForms(i,c,g,f);return}tx().then(()=>{I||O||!T||(O=!0,T())}).catch(()=>{})};o.components&&Do.registerAll(o.components);let A=sx(),K=o.persistState===!1?null:o.storageAdapter??jm(),ie=!!o.clientToken&&typeof o.reconnectStream!="function",Z={},M=null,_,W=new Promise(i=>{_=i}),H,J=!1,V=i=>{if(o.onStateLoaded)try{let c=o.onStateLoaded(i);if(c&&typeof c=="object"&&"state"in c){let{state:g,open:f}=c;return f&&(J=!0),g}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(K?.load)try{let i=K.load();if(i&&typeof i.then=="function")M=i.then(c=>V(c??{messages:[],metadata:{}}));else{let g=V(i??{messages:[],metadata:{}});g.metadata&&(Z=Zm(g.metadata)),g.messages?.length&&(o={...o,initialMessages:g.messages}),g.artifacts?.length&&(o={...o,initialArtifacts:g.artifacts,initialSelectedArtifactId:g.selectedArtifactId??null}),H=g.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=V({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}M||_();let pe=()=>Z,se=i=>{Z=i({...Z})??{},Ys()},ge=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zd],Ie=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ji.message,ji.messageAndClick],ye=ep({parsers:ge,handlers:Ie,getSessionMetadata:pe,updateSessionMetadata:se,emit:A.emit,documentRef:typeof document<"u"?document:null});ye.syncFromMetadata();let ce=o.launcher?.enabled??!0,Je=o.launcher?.autoExpand??!1,fe=o.autoFocusInput??!1,F=Je,Oe=ce,Ue=o.layout?.header?.layout,Bt=!1,be=()=>Fr(o),Be=()=>ce||be(),ve=be()?!1:ce?Je:!0,xe=!1,bt=null,Rt=()=>{xe=!0,bt&&clearTimeout(bt),bt=setTimeout(()=>{xe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),xe=!1)},1e4)},ut=Cx(o,ye,Rt),vn=o.features?.showReasoning??!0,q=o.features?.showToolCalls??!0,x=o.features?.showEventStreamToggle??!1,N=o.features?.scrollToBottom??{},z=o.features?.scrollBehavior??{},Y=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",he=`${Y()}event-stream`,Te=null,ke=o.features?.eventStream?.maxEvents??2e3,He=null,rt=null,Ke=null,je=!1,ht=null,Gt=!1,Ht=null,sn=0,Cn=(i,c)=>{He?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},yp=(i,c)=>{rt?.processEvent(i,c),He?Cn(i,c):Ke&&(Ke.length>=ke&&Ke.shift(),Ke.push({type:i,payload:c}))},xl=()=>{He||!x||(Ke??(Ke=[]),Hm().then(i=>{if(je||He||!x)return;Te=new i.EventStreamStore(he),He=new i.EventStreamBuffer(ke,Te),rt=rt??new i.ThroughputTracker,Te.open().then(()=>He?.restore()).catch(g=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",g)});let c=Ke??[];Ke=null;for(let g of c)rt?.processEvent(g.type,g.payload),Cn(g.type,g.payload)}).catch(()=>{}))};x&&xl();let At=!1,_t=null,bp=()=>{},$o=()=>{},ff=()=>{},hf=()=>{},vp=()=>{},iS=()=>Gt||At&&_t==="panel",Os={onCopy:i=>{A.emit("message:copy",i),k?.isClientTokenMode()&&k.submitMessageFeedback(i.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{A.emit("message:feedback",i),k?.isClientTokenMode()&&k.submitMessageFeedback(i.messageId,i.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(i)}},Bs=o.statusIndicator??{},yf=i=>i==="idle"?Bs.idleText??qt.idle:i==="connecting"?Bs.connectingText??qt.connecting:i==="connected"?Bs.connectedText??qt.connected:i==="error"?Bs.errorText??qt.error:i==="paused"?Bs.pausedText??qt.paused:i==="resuming"?Bs.resumingText??qt.resuming:qt[i];function Sl(i,c,g,f){if(!i.hasAttribute(zi))if(f==="idle"&&g.idleLink){i.textContent="";let b=document.createElement("a");b.href=g.idleLink,b.target="_blank",b.rel="noopener noreferrer",b.textContent=c,b.style.color="inherit",b.style.textDecoration="none",i.appendChild(b)}else i.textContent=c}let Hn=Bw({config:o,showClose:Be()}),{wrapper:Ge,panel:Se,pillRoot:Yt}=Hn.shell,_e=Hn.panelElements,{container:de,body:te,messagesWrapper:Pe,starterSuggestions:Cp,transcriptSuggestions:Vi,suggestions:ur,textarea:ae,sendButton:Me,composerForm:ro,statusText:st,welcomeHost:wn,welcomeIconHolder:aS,greetingHost:Wn,introKicker:lS,introTitle:cS,introSubtitle:dS,closeButton:Fe,iconHolder:Mt,headerTitle:gr,headerSubtitle:jr,header:Ee,footer:Le,actionsRow:pS}=_e,wp=_e.leftActions,Al=_e.rightActions,vo=_e.sendButtonWrapper,bf=_e.setSendButtonMode,ne=_e.micButton,On=_e.micButtonWrapper,xt=_e.attachmentButton,xn=_e.attachmentButtonWrapper,yt=_e.attachmentInput,Sn=_e.attachmentPreviewsContainer;de.classList.add("persona-relative"),te.classList.add("persona-relative");let uS=12,Ki=()=>N.label??"",gS=()=>N.iconName??"arrow-down",mS=()=>N.enabled!==!1,Bn=()=>z.mode??"anchor-top",mr=()=>Bn()==="follow"||Bn()==="anchor-top"&&oa,Gi=()=>z.anchorTopOffset??16,fS=()=>z.restorePosition??"bottom",vf=()=>z.pauseOnInteraction===!0,Cf=()=>z.showActivityWhilePinned!==!1,wf=()=>z.announce===!0,xp=()=>z.scrollbar??"on-scroll",Dt=E("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Dt.type="button",Dt.style.display="none",Dt.setAttribute("data-persona-scroll-to-bottom","true");let Yi=E("span","persona-flex persona-items-center"),Sp=E("span",""),qr=E("span","");qr.setAttribute("data-persona-scroll-to-bottom-count",""),qr.style.display="none",Dt.append(Yi,Sp,qr),de.appendChild(Dt);let Kn=E("div","persona-stream-anchor-spacer");Kn.setAttribute("aria-hidden","true"),Kn.setAttribute("data-persona-anchor-spacer",""),Kn.style.flexShrink="0",Kn.style.pointerEvents="none",Kn.style.height="0px",Kn.style.display="none",te.appendChild(Kn);let Uo=E("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"}),de.appendChild(Uo);let Qi=null,Ml=null,El=i=>{!wf()||!i||(Ml=i,Qi===null&&(Qi=setTimeout(()=>{Qi=null,Ml&&wf()&&(Uo.textContent=Ml),Ml=null},400)))},Tl="empty",Pl=0,Ap=()=>Pl||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,zr=()=>{let c=Le.style.display==="none"?0:Le.offsetHeight;Dt.style.bottom=`${c+Ap()+uS}px`};zr();let Mp=()=>{$s||(Le.style.marginBottom=Pl>0?`${Pl}px`:"")},kl=()=>{let i=om(o,be()),c=_o(o),f=Le.style.display==="none"?0:Le.offsetHeight,b=c.anchor==="center"&&Tl==="empty"?ol(c.anchorComposerTop)??ol("44%"):null,v=b===null||be()?0:DC({columnHeight:de.clientHeight,footerHeight:f,fraction:b});e.style.setProperty("--persona-composer-overlay-height",`${f}px`),e.style.setProperty("--persona-composer-lift",`${i==="overlay"?v:0}px`),Pl=i==="block"?v:0,Mp(),zr()},xf=()=>{let i=!!Ki();Dt.setAttribute("aria-label",Ki()||"Jump to latest"),Dt.title=Ki(),Dt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Yi.innerHTML="";let c=le(gS(),"14px","currentColor",2);c?(Yi.appendChild(c),Yi.style.display=""):Yi.style.display="none",Sp.textContent=Ki(),Sp.style.display=i?"":"none"};xf();let Ze=null,Wt=null,Ce=Hv(),hS=i=>{try{de.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};Ce.subscribe(hS);let Co=()=>{Ce.setText(ae?.value??"")},Vr=()=>{Ce.setMentionRefs(Wt?.getMentionRefs()??[])},yS=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}),Sf=i=>{let c=Object.freeze(i.map(yS));Ce.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(g){console.error("[AgentWidget] attachments.onChange failed:",g)}Jp()};Ce.setSelectedModelId(o.composer?.selectedModelId);let Xi=()=>o.composer?.modes??[],_s=()=>iC(Xi(),o.composer?.modeGroups);{let i=vd(o.composer?.defaultActiveModeIds??[],Xi());i.length&&Ce.setActiveModeIds(i)}function Af(i){if(Ce.getState().selectedModelId!==i){Ce.setSelectedModelId(i),fr?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function Ll(i){Ce.setActiveModeIds(i),jo?.render(i,_s()),Ds.forEach(c=>c.repaint()),xo?.resolve(),tc(),so()}function Ep(i){Ll(aC(Ce.getState().activeModeIds,i,Xi(),o.composer?.modeGroups))}let fr=null,Tp=null,jo=null,Ds=new Map,hr=null;function wo(i){Ce.setQuote(i),hr?.render(Ce.getState().quote),so(),hh()}let Mf=!1;function Pp(){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 yr=null;function Ns(i){Ce.setPendingSubmission(i),yr?.render(Ce.getState().pendingSubmission),so()}let bS=i=>{let c=Ds.get(i);if(c)return c;let g=dC({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===i),getModes:()=>Xi().filter(f=>f.groupId===i),getActiveIds:()=>Ce.getState().activeModeIds,onSelect:f=>Ep(f)});return Ds.set(i,g),g},vS=()=>{let i=[],c=Ce.getState().activeModeIds,g=new Set;if(Xi().forEach((f,b)=>{if(bd(f.groupId,o.composer?.modeGroups)){let v=f.groupId;if(g.has(v))return;g.add(v);let B=bS(v);B.action.order=Qg(b),B.action.label=o.composer?.modeGroups?.find(U=>U.id===v)?.label??v,i.push(B.action);return}i.push({id:rC(f.id),kind:"button",placement:"start",order:Qg(b),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:c.includes(f.id),onSelect:()=>Ep(f.id)})}),o.composer?.models?.length&&!a.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!fr||Tp!==f)&&(Tp=f,fr=nC({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Ce.getState().selectedModelId,onSelect:b=>Af(b),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(fr.action)}return i},kp=null,Ef=a.find(i=>i.renderHeader);if(Ef?.renderHeader){let i=Ef.renderHeader({config:o,defaultRenderer:()=>{let c=$r({config:o,showClose:Be()});return Ri(de,c,o),c.header},onClose:()=>gt(!1,"user")});if(i){let c=Ee;c&&(c.replaceWith(i),Ee=i,Hn.header.element=i)}}let Tf=()=>{ht&&(te.style.display="none",Le.parentNode?.insertBefore(ht.element,Le),ht.update())},Lp=()=>{if(!He){xl();return}if(Gt=!0,ht?Tf():Hm().then(c=>{ht||!Gt||!He||(ht=c.createEventStreamView({buffer:He,getFullHistory:()=>He.getAllFromStore(),onClose:()=>Fs(),config:o,plugins:a,getThroughput:()=>rt?.getMetric()??{status:"idle"},renderIconByName:le}),Tf())}).catch(()=>{Fs()}),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${hn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(g=>g&&tt.classList.add(g))}let i=()=>{if(!Gt)return;let c=Date.now();c-sn>=200&&(ht?.update(),sn=c),Ht=requestAnimationFrame(i)};sn=0,Ht=requestAnimationFrame(i),Vt(),A.emit("eventStream:opened",{timestamp:Date.now()})},Fs=()=>{if(Gt){if(Gt=!1,ht&&ht.element.remove(),te.style.display="",tt){tt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&tt.classList.remove(c))}Ht!==null&&(cancelAnimationFrame(Ht),Ht=null),Vt(),A.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(x){let i=o.features?.eventStream?.classNames,c="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");tt=E("button",c),tt.style.width="28px",tt.style.height="28px",tt.style.color=hn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let g=It(hx,"18px","currentColor",1.5);g&&tt.appendChild(g);let f=_e.clearChatButtonWrapper,b=_e.closeButtonWrapper,v=f||b;v&&v.parentNode===Ee?Ee.insertBefore(tt,v):Ee.appendChild(tt),tt.addEventListener("click",()=>{Gt?Fs():Lp()})}let Pf=i=>{let c=o.attachments;if(!c?.enabled)return;let g=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!g){g=E("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),g.setAttribute("data-persona-composer-attachment-previews",""),g.style.display="none";let b=i.querySelector("[data-persona-composer-form]");b?.parentNode?b.parentNode.insertBefore(g,b):i.insertBefore(g,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let b=E("input");b.type="file",b.setAttribute("data-persona-composer-attachment-input",""),b.accept=(c.allowedTypes??ar).join(","),b.multiple=(c.maxFiles??4)>1,b.style.display="none",b.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(b)}},$s=!1,kf=i=>{let c=a.find(b=>b.renderComposer);if(!c?.renderComposer)return null;let g=o.composer,f=p?k.isStreaming():!1;return c.renderComposer({config:o,defaultRenderer:i,requestRender:()=>Uy(),storage:u(c.id),onSubmit:b=>{!k||k.isStreaming()||Pc(b.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{Eo()||yt?.click()},models:g?.models,selectedModelId:Ce.getState().selectedModelId??g?.selectedModelId,onModelChange:b=>Af(b),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{kp?.()}:void 0})},Lf=kf(()=>Wi({config:o}).footer);Lf&&(Hn.replaceComposer(Lf),Le=Hn.composer.footer,$s=!0);let nt=null,CS=i=>{ro=i.form,ae=i.input,vo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Me=i.sendButton),i.micButton&&(ne=i.micButton,On=i.micButton.parentElement),i.found.status&&(st=i.found.status),i.found.suggestions&&(ur=i.found.suggestions),i.attachmentButton&&(xt=i.attachmentButton,xn=i.attachmentButton.parentElement),yt=i.attachmentInput??null,Sn=i.attachmentPreviews??null,i.found.actionsRow&&(pS=i.found.actionsRow),wp=i.found.actionsStart,Al=i.found.actionsEnd};function Ip(){let i=ae;if(!i)return;let c=o.composer?.inputAttributes,g=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;cd(i,c),g&&i.setAttribute("aria-label",g),ld(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:el(i)}),qv(i,ad(o.composer?.maxLines,be()?5:3))}let If=i=>{nt=Ov(i,{debug:o.debug===!0}),nt&&CS(nt),Ip()};Pf(Le),If(Le),Co();let Ji=Dr(o,be());Ji&&(Pe.style.maxWidth=Ji,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%",Wn.style.maxWidth=Ji,Wn.style.marginLeft="auto",Wn.style.marginRight="auto",Wn.style.width="100%",Cp.style.maxWidth=Ji,Vi.style.maxWidth=Ji,Vi.style.marginLeft="auto",Vi.style.marginRight="auto",Vi.style.width="100%");let Rf=()=>{let i=Dr(o,be());if(!(!i||be()))for(let c of[ro,ur,Sn,st])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};Rf();let Hf=()=>{!o.attachments?.enabled||!yt||!Sn||(Ze?Ze.remountPreviews(Sn):(Ze=Mi.fromConfig(o.attachments,Sf),Ze.setPreviewsContainer(Sn)),nt?.addListener(yt,"change",i=>{let c=i.target;Ze?.handleFileSelect(c.files),c.value=""}),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(wx(o.attachments.dropOverlay)))};Hf();let wS=()=>Wt?.prefetch(),Wf=()=>{if(!o.contextMentions?.enabled||!ae)return;let i=nt?.header??null,c=i?Yg(i):void 0;if(Wt=LC({config:o,textarea:ae,anchor:ro??ae,getMessages:()=>k.getMessages(),liveRegionHost:de,chipRow:c}),Wt&&!c){let g=ae;g.parentElement?.insertBefore(Wt.contextRow,g)}};Wf();let xo=null,xS={getState:()=>Ce.getState(),getValue:()=>ae?.value??"",setValue:i=>{ae&&(ae.value=i,ae.dispatchEvent(new Event("input",{bubbles:!0})),Co())},submit:()=>{CC(nt?.form??null)},openAttachmentPicker:()=>{Eo()||yt?.click()},toggleVoice:()=>{kp?.()},requestRender:()=>xo?.resolve()},SS=()=>{let i=[];return(Wt?.affordanceButtons??[]).forEach((g,f)=>{i.push({id:`core:mention-${f}`,placement:"start",order:Oo.mention+f,element:g,managed:!0})}),xn&&i.push({id:"core:attachment",placement:"start",order:Oo.attachment,element:xn}),On&&i.push({id:"core:mic",placement:"end",order:Oo.mic,element:On}),vo&&i.push({id:"core:send",placement:"end",order:Oo.send,element:vo}),i},Of=()=>{xo?.destroy(),xo=Zv({getBindings:()=>nt,collect:()=>({builtIns:SS(),configActions:[...vS(),...o.composer?.actions??[]],plugins:a,contributionContext:{config:o,getState:()=>Ce.getState(),requestRender:()=>xo?.resolve()},debug:o.debug===!0}),actionContext:xS,getState:()=>Ce.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),xo.resolve()};Of();let Rp=()=>{if(jo?.destroy(),jo=null,!_s().length)return;let i=nt?.header;i&&(jo=oC({row:Yg(i),onRemove:c=>Ep(c),initialIds:Ce.getState().activeModeIds}),jo.render(Ce.getState().activeModeIds,_s()))};Rp();let Bf=()=>{hr?.destroy(),hr=null,yr?.destroy(),yr=null;let i=nt?.header;i&&(hr=pC({onDismiss:()=>wo(void 0)}),i.appendChild(hr.element),hr.render(Ce.getState().quote),Pp()==="defer-one"&&(yr=uC({onEdit:()=>XA(),onRemove:()=>Ns(void 0)}),i.appendChild(yr.element),yr.render(Ce.getState().pendingSubmission)))};Bf();let Hp=bC(),AS=()=>{let i=nt?.header?.querySelector(Gg);if(i)return i.childElementCount>0;let c=Ce.getState();return c.mentionRefs.length>0||vd(c.activeModeIds,_s()).length>0},_f=()=>!1;function so(){let i=Ce.getState(),c=Hp.observe(vC(ae),i.text);Le.toggleAttribute("data-persona-composer-compact",yC({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:AS(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0,dictationActive:_f()}))}function Df(){o.composer?.layout==="single-row"&&!be()?Le.setAttribute("data-persona-composer-layout","single-row"):Le.removeAttribute("data-persona-composer-layout")}Df(),Ce.subscribe(()=>{xo?.sync(),Jp(),Zl(),so(),hh()}),Zl();let Nf=!1,MS=i=>{if(Nf||o.debug!==!0)return;let c=["messages","composer"].filter(g=>i[g]);c.length&&(Nf=!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 te.querySelector("[data-persona-intro-card]");case"messages":return Pe;case"footer-top":return ur;case"composer":return ro;case"footer-bottom":return st;default:return null}},g=(f,b)=>{switch(f){case"header-left":case"header-center":case"header-right":if(f==="header-left")Ee.insertBefore(b,Ee.firstChild);else if(f==="header-right")Ee.appendChild(b);else{let v=Ee.querySelector(".persona-flex-col");v?v.parentNode?.insertBefore(b,v.nextSibling):Ee.appendChild(b)}break;case"body-top":{let v=te.querySelector("[data-persona-intro-card]");v?v.replaceWith(b):te.insertBefore(b,te.firstChild);break}case"body-bottom":te.appendChild(b);break;case"footer-top":ur.replaceWith(b);break;case"footer-bottom":st.replaceWith(b);break;default:break}};for(let[f,b]of Object.entries(i))if(b)try{let v=b({config:o,defaultContent:()=>c(f)});v&&g(f,v)}catch(v){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${f}":`,v)}})();let Ff=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 v=g.getAttribute("data-bubble-type");if(v==="reasoning")Di.has(b)?Di.delete(b):Di.add(b),Dw(b,f);else if(v==="tool")Ni.has(b)?Ni.delete(b):Ni.add(b),Fw(b,f,o);else if(v==="approval"&&m){let U=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",$=m.approvalDetailsExpansionState.get(b)??U;m.approvalDetailsExpansionState.set(b,!$),m.updateApprovalDetailsUI(b,f,o)}Nt.delete(b)};Pe.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Ff(i))}),Pe.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Ff(i))}),Pe.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let g=Pe.getRootNode(),f=typeof g.getSelection=="function"?g.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let b=f.toString(),v=UC(b);!v||v===b||(c.setData("text/plain",v),i.preventDefault())});let Wp=new Map,$f=null,Uf="idle",ES={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},TS=(i,c)=>{let{icon:g,label:f}=ES[c];i.setAttribute("aria-label",f),i.title=f,i.setAttribute("aria-pressed",c==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",c!=="idle"),i.classList.toggle("persona-message-action-loading",c==="loading");let b=le(g,14,"currentColor",2);b&&(i.innerHTML="",i.appendChild(b))},jf=()=>{Pe.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let f=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;TS(c,f&&f===$f?Uf:"idle")})};Pe.addEventListener("click",i=>{let g=i.target.closest(".persona-message-action-btn[data-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest("[data-actions-for]");if(!f)return;let b=f.getAttribute("data-actions-for");if(!b)return;let v=g.getAttribute("data-action");if(v==="copy"){let U=k.getMessages().find($=>$.id===b);if(U&&Os.onCopy){let $=U.content||"";navigator.clipboard.writeText($).then(()=>{g.classList.add("persona-message-action-success");let j=It(yx,14,"currentColor",2);j&&(g.innerHTML="",g.appendChild(j)),setTimeout(()=>{g.classList.remove("persona-message-action-success");let Q=It(bx,14,"currentColor",2);Q&&(g.innerHTML="",g.appendChild(Q))},2e3)}).catch(j=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",j)}),Os.onCopy(U)}}else if(v==="read-aloud")k.toggleReadAloud(b);else if(v==="upvote"||v==="downvote"){let U=(Wp.get(b)??null)===v,$=v==="upvote"?"thumbs-up":"thumbs-down";if(U){Wp.delete(b),g.classList.remove("persona-message-action-active");let j=le($,14,"currentColor",2);j&&(g.innerHTML="",g.appendChild(j))}else{let j=v==="upvote"?"downvote":"upvote",Q=f.querySelector(`[data-action="${j}"]`);if(Q){Q.classList.remove("persona-message-action-active");let mt=le(j==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);mt&&(Q.innerHTML="",Q.appendChild(mt))}Wp.set(b,v),g.classList.add("persona-message-action-active");let oe=le($,14,"currentColor",2);oe&&(oe.setAttribute("fill","currentColor"),g.innerHTML="",g.appendChild(oe)),g.classList.remove("persona-message-action-pop"),g.offsetWidth,g.classList.add("persona-message-action-pop");let Xe=k.getMessages().find(dt=>dt.id===b);Xe&&Os.onFeedback&&Os.onFeedback({type:v,messageId:Xe.id,message:Xe})}}else if(v==="regenerate")Il?.regenerate(b);else if(v==="edit")Il?.edit(b);else if(v==="quote")Il?.quote(b);else if(v?.startsWith(Bd)){let B=v.slice(Bd.length),U=o.messageActions?.custom?.find(j=>j.id===B),$=k.getMessages().find(j=>j.id===b);if(!U||!$)return;try{U.onSelect($)}catch(j){console.error(`[AgentWidget] messageActions.custom "${B}" onSelect failed:`,j)}}});let Il=null;Pe.addEventListener("click",i=>{let g=i.target.closest("button[data-approval-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest(".persona-approval-bubble");if(!f)return;let b=f.getAttribute("data-message-id");if(!b)return;let v=g.getAttribute("data-approval-action");if(!v)return;let B=v==="approve"?"approved":"denied",$=k.getMessages().find(Q=>Q.id===b);if(!$?.approval)return;let j=f.querySelector("[data-approval-buttons]");j&&j.querySelectorAll("button").forEach(oe=>{oe.disabled=!0,oe.style.opacity="0.5",oe.style.cursor="not-allowed"}),$.approval.toolType==="webmcp"?k.resolveWebMcpApproval(b,B):k.resolveApproval($.approval,B)});let qe=null,qf=!1,Zi=null,Kr=()=>{},ea="none",Rl=null,Gn={artifacts:[],selectedId:null},qo=!1,io=!1,ta=!1,Us=!1,zf=()=>Us||Gn.artifacts.some(i=>sr(o.features?.artifacts,i)==="panel"),Hl=()=>Gn.artifacts.length>0&&!qo&&zf(),ct={current:null},Op=(i,c)=>{let g=k.getArtifactById(c),f=g?.markdown,b=g?.title||"artifact",v=g?.file,B=g?.artifactType??"markdown";if(!f){let j=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(j){let oe=k.getMessages().find(ue=>ue.id===j);if(oe?.rawContent)try{let ue=JSON.parse(oe.rawContent);f=ue?.props?.markdown,b=ue?.props?.title||b,ue?.props?.file&&typeof ue.props.file=="object"&&(v=ue.props.file),!g&&typeof ue?.props?.artifactType=="string"&&(B=ue.props.artifactType)}catch{}}}return{markdown:f,title:b,file:v,artifactType:B}};Pe.addEventListener("click",i=>{let g=i.target.closest("[data-download-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-download-artifact");if(!f||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:f})===!0)return;let{markdown:v,title:B,file:U}=Op(g,f);if(!v)return;let $=lr();$&&$.triggerArtifactDownload($.downloadInfoFor({title:B,markdown:v,file:U}))}),Pe.addEventListener("click",i=>{let g=i.target.closest("[data-artifact-custom-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-artifact-custom-action");if(!f)return;let b=g.closest("[data-artifact-inline]"),v=b?null:g.closest("[data-open-artifact]"),B=b?b.getAttribute("data-artifact-inline"):v?.getAttribute("data-open-artifact")??null,$=(b?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(dt=>dt.id===f);if(!$)return;let{markdown:j,title:Q,file:oe,artifactType:ue}=Op(g,B??""),Xe={artifactId:B,title:Q,artifactType:ue,markdown:j,file:oe};try{Promise.resolve($.onClick(Xe)).catch(()=>{})}catch{}}),Pe.addEventListener("click",i=>{let g=i.target.closest("[data-copy-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-copy-artifact");if(!f)return;let b=k.getArtifactById(f),v=lr();if(!v)return;let B="";if(b)B=v.artifactCopyText(b);else{let{markdown:U,file:$,artifactType:j}=Op(g,f);j==="markdown"&&(B=v.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:U??"",...$?{file:$}:{}}))}B&&navigator.clipboard.writeText(B).then(()=>{let U=It(yx,16,"currentColor",2);U&&(g.replaceChildren(U),setTimeout(()=>{let $=It(bx,16,"currentColor",2);$&&g.replaceChildren($)},1500))}).catch(()=>{})}),Pe.addEventListener("click",i=>{let g=i.target.closest("[data-expand-artifact-inline]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-expand-artifact-inline");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(qo=!1,Us=!0,io=!0,ta=!0,k.selectArtifact(f),ao())}),Pe.addEventListener("click",i=>{let c=i.target;if(c.closest("[data-download-artifact]")||c.closest("[data-artifact-custom-action]"))return;let g=c.closest("[data-open-artifact]");if(!g)return;let f=g.getAttribute("data-open-artifact");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(i.preventDefault(),i.stopPropagation(),qo=!1,Us=!0,k.selectArtifact(f),ao())}),Pe.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let c=i.target;!c.hasAttribute("data-open-artifact")&&!c.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),c.click())});let js=_e.composerOverlay,qs=(i,c,g)=>{let f=c.trim();if(!f||!ct.current)return;let b=i.getAttribute("data-tool-call-id")??"",v=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:v,source:g.source},bubbles:!0,composed:!0})),Es(js,b);let B=ct.current.getMessages().find(U=>U.toolCall?.id===b);B?.agentMetadata?.awaitingLocalTool?ct.current.resolveAskUserQuestion(B,g.structured??f):ct.current.sendMessage(f)},Gr=i=>{let c=ct.current;if(!c)return;let g=i.getAttribute("data-tool-call-id")??"",f=c.getMessages().find(b=>b.toolCall?.id===g);f&&c.persistAskUserQuestionProgress(f,{answers:Vc(i,f),currentIndex:no(i)})},Vf=i=>Object.entries(i).map(([c,g])=>`${c}: ${Array.isArray(g)?g.join(", "):g}`).join(" | "),Bp=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=no(i),g=vi(i);if(c>=g-1)return;let f=ct.current?.getMessages().find(b=>b.toolCall?.id===i.getAttribute("data-tool-call-id"));f&&(Kc(i,f,o,c+1),Gr(i))};js.addEventListener("click",i=>{let g=i.target.closest("[data-ask-user-action]");if(!g)return;let f=g.closest("[data-persona-ask-sheet-for]");if(!f)return;let b=g.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),b==="dismiss"){let v=f.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),Es(js,v);let B=ct.current?.getMessages().find(U=>U.toolCall?.id===v);B?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(B),ct.current?.resolveAskUserQuestion(B,"(dismissed)"));return}if(b==="pick"){let v=g.getAttribute("data-option-label");if(!v)return;let B=f.getAttribute("data-multi-select")==="true",U=Wr(f);if(U&&B){let $=Ms(f)[no(f)],j=new Set(Array.isArray($)?$:[]);j.has(v)?j.delete(v):j.add(v),Or(f,Array.from(j)),Gr(f);return}if(U){Or(f,v),Gr(f),Bp(f);return}if(B){let $=g.getAttribute("aria-pressed")==="true";g.setAttribute("aria-pressed",$?"false":"true"),g.classList.toggle("persona-ask-pill-selected",!$);let j=f.querySelector('[data-ask-user-action="submit-multi"]');j&&(j.disabled=pg(f).length===0);return}qs(f,v,{source:"pick",values:[v]});return}if(b==="submit-multi"){let v=pg(f);if(v.length===0)return;qs(f,v.join(", "),{source:"multi",values:v});return}if(b==="open-free-text"){let v=f.querySelector('[data-ask-free-text-row="true"]');v&&(v.classList.remove("persona-hidden"),v.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 B=f.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!B.trim())return;if(Wr(f)){Or(f,B.trim()),Gr(f),Bp(f);return}qs(f,B,{source:"free-text"});return}if(b==="next"||b==="back"){if(!ct.current)return;let v=f.getAttribute("data-tool-call-id")??"",B=ct.current.getMessages().find(oe=>oe.toolCall?.id===v);if(!B)return;let $=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if($){let oe=Ms(f)[no(f)];(typeof oe!="string"||oe!==$)&&Or(f,$)}let j=b==="next"?1:-1,Q=no(f)+j;Kc(f,B,o,Q),Gr(f);return}if(b==="submit-all"){if(!ct.current)return;let v=f.getAttribute("data-tool-call-id")??"",B=ct.current.getMessages().find(oe=>oe.toolCall?.id===v);if(!B)return;let $=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";$&&Or(f,$);let j=Vc(f,B);ct.current.persistAskUserQuestionProgress(B,{answers:j,currentIndex:no(f)});let Q=Vf(j);qs(f,Q||"(submitted)",{source:"submit-all",structured:j});return}if(b==="skip"){if(!ct.current)return;let v=f.getAttribute("data-tool-call-id")??"",B=ct.current.getMessages().find(ue=>ue.toolCall?.id===v);if(!B)return;let U=Wr(f),$=no(f),j=vi(f),Q=$>=j-1;if(!U){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:v},bubbles:!0,composed:!0})),Es(js,v),B.agentMetadata?.awaitingLocalTool&&(ct.current.markAskUserQuestionResolved(B),ct.current.resolveAskUserQuestion(B,"(dismissed)"));return}Or(f,"");let oe=f.querySelector('[data-ask-free-text-input="true"]');if(oe&&(oe.value=""),Q){let ue=Vc(f,B),Xe=Vf(ue);qs(f,Xe||"(skipped)",{source:"submit-all",structured:ue});return}Kc(f,B,o,$+1),Gr(f);return}}),js.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let g=i.target;if(!g.matches?.('[data-ask-free-text-input="true"]'))return;let f=g.closest("[data-persona-ask-sheet-for]");if(!f)return;i.preventDefault();let b=g.value;if(b.trim()){if(Wr(f)){Or(f,b.trim()),Gr(f),Bp(f);return}qs(f,b,{source:"free-text"})}});let Kf=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let c=i.target;if(c?.tagName==="INPUT"||c?.tagName==="TEXTAREA"||c?.isContentEditable)return;let g=js.querySelector("[data-persona-ask-sheet-for]");if(!g||g.getAttribute("data-ask-layout")!=="rows"||g.getAttribute("data-multi-select")==="true")return;let f=Number(i.key),v=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];v&&(i.preventDefault(),v.click())};document.addEventListener("keydown",Kf);let So=null,vt=null,na=null,Wl=null,Ol=()=>{},Gf=!1,Bl="",_l="";function _p(){Wl?.(),Wl=null}let PS=()=>{let i=oi&&ms?.isConnected?ms:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},Yf=()=>{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 v=Fm(So,c),B=f.offsetWidth+v/2-b/2;vt.style.left=`${Math.max(0,B)}px`},Dl=()=>{},kS=()=>{let i=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,g=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>g?!1:ce||St(o)},Nl=()=>!bn(o)||!Hl()||e.classList.contains("persona-artifact-narrow-host")||kS()||(e.ownerDocument.defaultView??window).innerWidth<$I?"none":Dm(o)?"detached":"welded",ao=()=>{if(!qe||!bn(o))return;yl(e,o),bl(e,o),Dl();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=Se.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let g=Hl();qe.setVisible(g),qe.update(Gn),qo?(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),io=!1,ta=!1):Gn.artifacts.length>0&&zf()?(qe.element.classList.remove("persona-hidden"),qe.setMobileOpen(!0)):(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),io=!1,ta=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(qe.setExpandToggleVisible(f),qe.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),qe.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),qe.setCustomActions(o.features?.artifacts?.toolbarActions??[]),qe.setTabFade(o.features?.artifacts?.layout?.tabFade),qe.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!ta&&(io=!1),io!==Gf){let v=qe.element;io?(Bl=v.style.width,_l=v.style.maxWidth,v.style.removeProperty("width"),v.style.removeProperty("max-width")):(Bl&&(v.style.width=Bl),_l&&(v.style.maxWidth=_l),Bl="",_l=""),Gf=io}e.classList.toggle("persona-artifact-expanded",io),qe.setExpanded(io);let b=Nl();b!==ea&&(ea=b,Kr()),Ol()};if(bn(o)){Se.style.position="relative";let i=E("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=E("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(de),So=c,c.appendChild(i),Se.appendChild(c);let g=b=>{qf||qe||(qe=b.createArtifactPane(o,{onSelect:v=>ct.current?.selectArtifact(v),onDismiss:()=>{qo=!0,ao()},onToggleExpand:()=>{let v=!io,B=Gn.selectedId??Gn.artifacts[Gn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:B,expanded:v})!==!0&&(io=v,v||(ta=!1),ao())}}),qe.element.classList.add("persona-hidden"),c.appendChild(qe.element),qe.backdrop&&Se.appendChild(qe.backdrop),Ol(),ao())},f=lr();f?g(f):(Bm(()=>{let b=lr();b&&g(b)}),Kd().catch(()=>{})),Ol=()=>{if(!So||!qe)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){na?.(),na=null,_p(),vt&&(vt.remove(),vt=null),qe.element.style.removeProperty("width"),qe.element.style.removeProperty("maxWidth");return}if(!vt){let v=E("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let B=e.ownerDocument,U=B.defaultView??window,$=j=>{if(!qe||j.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||U.innerWidth<=640)return;j.preventDefault(),_p();let Q=j.clientX,oe=qe.element.getBoundingClientRect().width,ue=o.features?.artifacts?.layout,Xe=mt=>{let Qt=So.getBoundingClientRect().width,$t=e.classList.contains("persona-artifact-welded-split"),Pt=Fm(So,U),an=$t?0:v.getBoundingClientRect().width||6,et=oe-(mt.clientX-Q),ln=ex(et,Qt,Pt,an,ue?.resizableMinWidth,ue?.resizableMaxWidth,PS());qe.element.style.width=`${ln}px`,qe.element.style.maxWidth="none",Yf()},dt=()=>{B.removeEventListener("pointermove",Xe),B.removeEventListener("pointerup",dt),B.removeEventListener("pointercancel",dt),Wl=null;try{v.releasePointerCapture(j.pointerId)}catch{}};Wl=dt,B.addEventListener("pointermove",Xe),B.addEventListener("pointerup",dt),B.addEventListener("pointercancel",dt);try{v.setPointerCapture(j.pointerId)}catch{}};v.addEventListener("pointerdown",$),vt=v,So.insertBefore(v,qe.element),na=()=>{v.removeEventListener("pointerdown",$)}}if(vt){let v=Hl();vt.classList.toggle("persona-hidden",!v),Yf()}},Dl=()=>{if(!ce||!qe||(o.launcher?.sidebarMode??!1)||St(o)&&qn(o).reveal==="emerge")return;let v=e.ownerDocument.defaultView??window,B=o.launcher?.mobileFullscreen??!0,U=o.launcher?.mobileBreakpoint??640;if(B&&v.innerWidth<=U||!Vw(o,ce))return;let $=o.launcher?.width??o.launcherWidth??oo,j=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Hl()?(Se.style.width=j,Se.style.maxWidth=j):(Se.style.width=$,Se.style.maxWidth=$)},typeof ResizeObserver<"u"&&(Zi=new ResizeObserver(()=>{ao()}),Zi.observe(Se))}else Se.appendChild(de);be()&&Yt&&(_e.peekBanner&&Yt.appendChild(_e.peekBanner),Yt.appendChild(Le)),e.appendChild(Ge),Yt&&e.appendChild(Yt);let Dp=()=>{if(be()){Se.style.width="100%",Se.style.maxWidth="100%";let De=o.launcher?.composerBar??{},we=Ge.dataset.state==="expanded",dn=De.expandedSize??"anchored";if(!(we&&dn!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let Pn=o.theme?.components?.panel,kn=Ps(o),at=(Ot,Ln)=>Ot==null||Ot===""?Ln:fn(kn,Ot)??Ot,pt="1px solid var(--persona-border)",We="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",rr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=at(Pn?.border,pt),de.style.borderRadius=at(Pn?.borderRadius,rr),de.style.boxShadow=at(Pn?.shadow,We),de.style.overflow="hidden";return}let i=St(o),c=o.launcher?.sidebarMode??!1,g=i||c||(o.launcher?.fullHeight??!1),f=o.launcher?.enabled===!1,b=o.launcher?.detachedPanel===!0,v=o.theme?.components?.panel,B=Ps(o),U=(De,we)=>De==null||De===""?we:fn(B,De)??De,$=e.ownerDocument.defaultView??window,j=o.launcher?.mobileFullscreen??!0,Q=o.launcher?.mobileBreakpoint??640,oe=$.innerWidth<=Q,ue=j&&oe&&ce,Xe=i&&j&&oe,dt=o.launcher?.position??"bottom-left",mt=dt==="bottom-left"||dt==="top-left",Qt=o.launcher?.zIndex??rn,$t="var(--persona-panel-border, 1px solid var(--persona-border))",Pt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",an="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",et=b&&!ue&&!Xe;et?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let ln=et?$t:c||ue?"none":$t,Lo=et?Pt:ue?"none":c?mt?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":f?"none":Pt;i&&!ue&&!et&&(Lo="none",ln="none");let or=et?an:c||ue?"0":an,po=U(v?.border,ln),La=U(v?.shadow,Lo),Cs=U(v?.borderRadius,or),uo=Nl(),tn=uo==="detached",go=uo==="welded";e.classList.toggle("persona-artifact-detached-split",tn),e.classList.toggle("persona-artifact-welded-split",go);let mi="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",Ae=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&bn(o)&&Dm(o)&&f&&!i;e.classList.toggle("persona-artifact-chat-flush",Ae);let re=tn||Ae?"none":La,kt=tn?$t:go?"none":po,Ut=tn?an:Cs;Ae&&(kt="none",Ut="0");let nn=v?.borderRadius!=null&&v.borderRadius!=="",jt=Ae&&!nn?"0":Cs,Kt=te.scrollTop;e.style.cssText="",Ge.style.cssText="",Se.style.cssText="",de.style.cssText="",te.style.cssText="",$s||(Le.style.cssText=""),Gt&&(te.style.display="none"),(g||f)&&(e.style.minWidth="0");let Lt=()=>{if(Kt<=0)return;(te.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(te.scrollTop===Kt)return;let we=te.scrollHeight-te.clientHeight;we<=0||(te.scrollTop=Math.min(Kt,we))})};if(ue){Ge.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Ge.style.cssText=`
|
|
44
|
+
`,$.addEventListener("click",()=>{m=L,E.forEach((K,se)=>{let te=se<L;K.classList.toggle("selected",te),K.setAttribute("aria-checked",se===L-1?"true":"false")})}),E.push($),x.appendChild($)}h.appendChild(x);let H=null;if(d){let L=document.createElement("div");L.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=s,H.rows=3,H.setAttribute("aria-label","Additional comments"),L.appendChild(H),h.appendChild(L)}let B=document.createElement("div");B.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=l,A.addEventListener("click",()=>{n?.(),u.remove()});let O=document.createElement("button");return O.type="button",O.className="persona-feedback-btn persona-feedback-btn-submit",O.textContent=a,O.addEventListener("click",async()=>{if(m===null){x.classList.add("persona-feedback-shake"),setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let L=H?.value.trim()||void 0;await t(m,L),u.remove()}catch(L){O.disabled=!1,O.textContent=a,console.error("[CSAT Feedback] Failed to submit:",L)}}),B.appendChild(A),B.appendChild(O),h.appendChild(B),u.appendChild(h),u}function Vf(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 h=null,y=document.createElement("div");y.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,v.appendChild(C);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,v.appendChild(x),y.appendChild(v);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let H=document.createElement("div");H.className="persona-feedback-labels";let B=document.createElement("span");B.className="persona-feedback-label-low",B.textContent=p;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=u,H.appendChild(B),H.appendChild(A);let O=document.createElement("div");O.className="persona-feedback-numbers";let L=[];for(let P=0;P<=10;P++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-number-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`Rating ${P} out of 10`),k.textContent=String(P),k.dataset.rating=String(P),P<=6?k.classList.add("persona-feedback-detractor"):P<=8?k.classList.add("persona-feedback-passive"):k.classList.add("persona-feedback-promoter"),k.addEventListener("click",()=>{h=P,L.forEach((_,I)=>{_.classList.toggle("selected",I===P),_.setAttribute("aria-checked",I===P?"true":"false")})}),L.push(k),O.appendChild(k)}E.appendChild(H),E.appendChild(O),y.appendChild(E);let $=null;if(d){let P=document.createElement("div");P.className="persona-feedback-comment-container",$=document.createElement("textarea"),$.className="persona-feedback-comment",$.placeholder=s,$.rows=3,$.setAttribute("aria-label","Additional comments"),P.appendChild($),y.appendChild(P)}let K=document.createElement("div");K.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 te=document.createElement("button");return te.type="button",te.className="persona-feedback-btn persona-feedback-btn-submit",te.textContent=a,te.addEventListener("click",async()=>{if(h===null){O.classList.add("persona-feedback-shake"),setTimeout(()=>O.classList.remove("persona-feedback-shake"),500);return}te.disabled=!0,te.textContent="Submitting...";try{let P=$?.value.trim()||void 0;await t(h,P),m.remove()}catch(P){te.disabled=!1,te.textContent=a,console.error("[NPS Feedback] Failed to submit:",P)}}),K.appendChild(se),K.appendChild(te),y.appendChild(K),m.appendChild(y),m}var ca="persona-chat-history",uH=30*1e3,gH=641,da="data-persona-composer-reason",mH={"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 fH(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=mH[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 Tp(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 hH(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 yH(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var qf=e=>!e||typeof e!="object"?{}:{...e},MS=e=>e.map(t=>({...t,streaming:!1})),ES=(e,t,n)=>{let o=e?.markdown?gd(e.markdown):null,r=Kg(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 h=t.process({text:d,raw:p??d,message:l.message,streaming:l.streaming});h!==null&&(d=h.text,h.persist||(l.message.__skipPersist=!0),h.resubmit&&!l.streaming&&n&&n())}let u=Bo()!==null,m;if(e?.postprocessMessage){let h=e.postprocessMessage({...l,text:d,raw:p??l.text??""});m=r?r(h):h}else if(o){let h=l.streaming?Av(d):d,y=o(h);m=r&&u?r(y):y}else m=Vr(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)),Vr(l.text??"")}}};function TS(e){let t=S("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=ae(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=S("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var bH=(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},vH=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:bH(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),zf=(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=tl(t),r=new Set,s=new Set,a=uv((i,c)=>{Nt.delete(i);let g=Array.from(he.querySelectorAll("[data-message-id]")).find(f=>f.dataset.messageId===i);g&&(c==="tool"?Sf(i,g,r,o):vf(i,g,s))}),l=new Map,d=()=>{qC({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};d();let p=o.features;o=Cp(o);let u=wp.getForInstance(o.plugins),m=qw(e),h=[],y=!1,v=Ux(()=>o),C=null,x=null,E=null,H=!1,B=null,A=i=>{C=i,i.initApprovalUi({webMcpToolTitle:Di});let c=i.createBuiltInApprovalPlugin(l);x=c.plugin,E=c.teardown},O=()=>{if(C)return C;let i=Gx();return i?(A(i),i):(Kx().then(c=>{H||C||(A(c),B?.())}).catch(()=>{}),null)},L=!1,$=!1,K=null,se=(i,c,g,f)=>{if(!i.querySelector("[data-tv-form]"))return;let b=lS();if(b){b.enhanceWithForms(i,c,g,f);return}aS().then(()=>{L||$||!K||($=!0,K())}).catch(()=>{})};o.components&&Uo.registerAll(o.components);let te=pS(),k=o.persistState===!1?null:o.storageAdapter??Of(),_=!!o.clientToken&&typeof o.reconnectStream!="function",I={},Z=null,U,ce=new Promise(i=>{U=i}),de,pe=!1,ke=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&&(pe=!0),g}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(k?.load)try{let i=k.load();if(i&&typeof i.then=="function")Z=i.then(c=>ke(c??{messages:[],metadata:{}}));else{let g=ke(i??{messages:[],metadata:{}});g.metadata&&(I=qf(g.metadata)),g.messages?.length&&(o={...o,initialMessages:g.messages}),g.artifacts?.length&&(o={...o,initialArtifacts:g.artifacts,initialSelectedArtifactId:g.selectedArtifactId??null}),de=g.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=ke({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}Z||U();let we=()=>I,fe=i=>{I=i({...I})??{},ui()},lt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Sp],rt=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[la.message,la.messageAndClick],be=Ap({parsers:lt,handlers:rt,getSessionMetadata:we,updateSessionMetadata:fe,emit:te.emit,documentRef:typeof document<"u"?document:null});be.syncFromMetadata();let D=o.launcher?.enabled??!0,De=o.launcher?.autoExpand??!1,_e=o.autoFocusInput??!1,At=De,zt=D,$t=o.layout?.header?.layout,Te=!1,ve=()=>Zr(o),We=()=>D||ve(),Ae=ve()?!1:D?De:!0,Cn=!1,j=null,M=()=>{Cn=!0,j&&clearTimeout(j),j=setTimeout(()=>{Cn&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Cn=!1)},1e4)},N=ES(o,be,M),z=o.features?.showReasoning??!0,X=o.features?.showToolCalls??!0,Q=o.features?.showEventStreamToggle??!1,ge=o.features?.scrollToBottom??{},xe=o.features?.scrollBehavior??{},Se=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Dt=`${Se()}event-stream`,Je=null,Ve=o.features?.eventStream?.maxEvents??2e3,gt=null,Xt=null,kt=null,pn=!1,mt=null,io=!1,vr=null,Up=0,ih=(i,c)=>{gt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},jp=(i,c)=>{Xt?.processEvent(i,c),gt?ih(i,c):kt&&(kt.length>=Ve&&kt.shift(),kt.push({type:i,payload:c}))},jl=()=>{gt||!Q||(kt??(kt=[]),Mf().then(i=>{if(pn||gt||!Q)return;Je=new i.EventStreamStore(Dt),gt=new i.EventStreamBuffer(Ve,Je),Xt=Xt??new i.ThroughputTracker,Je.open().then(()=>gt?.restore()).catch(g=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",g)});let c=kt??[];kt=null;for(let g of c)Xt?.processEvent(g.type,g.payload),ih(g.type,g.payload)}).catch(()=>{}))};Q&&jl();let Lt=!1,Ut=null,Vp=()=>{},qo=()=>{},ah=()=>{},lh=()=>{},qp=()=>{},uA=()=>io||Lt&&Ut==="panel",ei={onCopy:i=>{te.emit("message:copy",i),T?.isClientTokenMode()&&T.submitMessageFeedback(i.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{te.emit("message:feedback",i),T?.isClientTokenMode()&&T.submitMessageFeedback(i.messageId,i.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(i)}},VW=o.statusIndicator??{},zp=(i,c=o.statusIndicator??{})=>i==="idle"?c.idleText??Bt.idle:i==="connecting"?c.connectingText??Bt.connecting:i==="connected"?c.connectedText??Bt.connected:i==="error"?c.errorText??Bt.error:i==="paused"?c.pausedText??Bt.paused:i==="resuming"?c.resumingText??Bt.resuming:Bt[i];function pa(i,c,g,f){if(!ve()&&(g.mode==="transient"||i.classList.contains("persona-mb-2"))&&(zg(i,wn,g),Fs(i,g,f)),!i.hasAttribute(da))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=$x({config:o,showClose:We()}),{wrapper:Ge,panel:Ce,pillRoot:Jt}=Rn.shell,Ne=Rn.panelElements,{container:le,body:ee,messagesWrapper:he,starterSuggestions:Kp,transcriptSuggestions:ua,suggestions:Cr,textarea:ie,sendButton:Me,composerForm:wn,statusText:Qe,welcomeHost:Zt,welcomeIconHolder:gA,greetingHost:Hn,introKicker:mA,introTitle:fA,introSubtitle:hA,closeButton:je,iconHolder:It,headerTitle:wr,headerSubtitle:ns,header:Ee,footer:Ie,actionsRow:yA}=Ne,Gp=Ne.leftActions,Vl=Ne.rightActions,wo=Ne.sendButtonWrapper,ch=Ne.setSendButtonMode,re=Ne.micButton,Wn=Ne.micButtonWrapper,Tt=Ne.attachmentButton,xn=Ne.attachmentButtonWrapper,wt=Ne.attachmentInput,Sn=Ne.attachmentPreviewsContainer;le.classList.add("persona-relative"),ee.classList.add("persona-relative");let bA=12,ga=()=>ge.label??"",vA=()=>ge.iconName??"arrow-down",CA=()=>ge.enabled!==!1,On=()=>xe.mode??"anchor-top",xr=()=>On()==="follow"||On()==="anchor-top"&&Aa,ma=()=>xe.anchorTopOffset??16,wA=()=>xe.restorePosition??"bottom",dh=()=>xe.pauseOnInteraction===!0,ph=()=>xe.showActivityWhilePinned!==!1,uh=()=>xe.announce===!0,Yp=()=>xe.scrollbar??"on-scroll",jt=S("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");jt.type="button",jt.style.display="none",jt.setAttribute("data-persona-scroll-to-bottom","true");let fa=S("span","persona-flex persona-items-center"),Qp=S("span",""),os=S("span","");os.setAttribute("data-persona-scroll-to-bottom-count",""),os.style.display="none",jt.append(fa,Qp,os),le.appendChild(jt);let Kn=S("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",ee.appendChild(Kn);let zo=S("div","persona-sr-only");zo.setAttribute("aria-live","polite"),zo.setAttribute("aria-atomic","true"),zo.setAttribute("role","status"),zo.setAttribute("data-persona-live-region",""),Object.assign(zo.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),le.appendChild(zo);let ha=null,ql=null,zl=i=>{!uh()||!i||(ql=i,ha===null&&(ha=setTimeout(()=>{ha=null,ql&&uh()&&(zo.textContent=ql),ql=null},400)))},ya=()=>{let i=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&i.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(D||Ct(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!Ct(o)},rs=()=>Dl(o,ya()),Kl="empty",Gl=0,Xp=()=>Gl||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,ss=()=>{let c=Ie.style.display==="none"?0:Ie.offsetHeight;jt.style.bottom=`${c+Xp()+bA}px`};ss();let Jp=()=>{si||(Ie.style.marginBottom=Gl>0?`${Gl}px`:"")},Yl=()=>{let i=zm(o,ve()),c=rs();e.setAttribute("data-persona-welcome-fullscreen",String(ya())),e.setAttribute("data-persona-welcome-layout",c.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom");let f=Ie.style.display==="none"?0:Ie.offsetHeight,b=c.anchor==="center"&&Kl==="empty"?Sl(c.anchorComposerTop)??Sl("44%"):null,w=b!==null&&c.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,W=w?getComputedStyle(ee):null,V=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,F=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,q=Math.max(0,(parseFloat(W?.paddingBottom??"")||0)-(i==="overlay"?V+F:0)),Y=w?ee.getBoundingClientRect().top-le.getBoundingClientRect().top:0,oe=!w||Zt.hidden?0:(Zt.querySelector("[data-persona-welcome-plugin]")??Zt).offsetHeight,ue=b===null||ve()?0:w?Math.max(0,Math.round((le.clientHeight-Y-oe-q-f)/2)):Uw({columnHeight:le.clientHeight,footerHeight:f,fraction:b});e.style.setProperty("--persona-composer-overlay-height",`${f}px`),e.style.setProperty("--persona-composer-lift",`${i==="overlay"?ue:0}px`),Gl=i==="block"?ue:0,Jp(),ss()},gh=()=>{let i=!!ga();jt.setAttribute("aria-label",ga()||"Jump to latest"),jt.title=ga(),jt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),fa.innerHTML="";let c=ae(vA(),"14px","currentColor",2);c?(fa.appendChild(c),fa.style.display=""):fa.style.display="none",Qp.textContent=ga(),Qp.style.display=i?"":"none"};gh();let nt=null,_t=null,ye=NC(),xA=i=>{try{le.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};ye.subscribe(xA);let xo=()=>{ye.setText(ie?.value??"")},is=()=>{ye.setMentionRefs(_t?.getMentionRefs()??[])},SA=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}),mh=i=>{let c=Object.freeze(i.map(SA));ye.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(g){console.error("[AgentWidget] attachments.onChange failed:",g)}Tu()};ye.setSelectedModelId(o.composer?.selectedModelId);let ba=()=>o.composer?.modes??[],ti=()=>dw(ba(),o.composer?.modeGroups);{let i=qd(o.composer?.defaultActiveModeIds??[],ba());i.length&&ye.setActiveModeIds(i)}function fh(i){if(ye.getState().selectedModelId!==i){ye.setSelectedModelId(i),Sr?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function Ql(i){ye.setActiveModeIds(i),Ko?.render(i,ti()),ni.forEach(c=>c.repaint()),Ao?.resolve(),wc(),ao()}function Zp(i){Ql(pw(ye.getState().activeModeIds,i,ba(),o.composer?.modeGroups))}let Sr=null,eu=null,Ko=null,ni=new Map,Ar=null;function So(i){ye.setQuote(i),Ar?.render(ye.getState().quote),ao(),iy()}let hh=!1;function tu(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!hh&&o.debug===!0&&(hh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Mr=null;function oi(i){ye.setPendingSubmission(i),Mr?.render(ye.getState().pendingSubmission),ao()}let AA=i=>{let c=ni.get(i);if(c)return c;let g=mw({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===i),getModes:()=>ba().filter(f=>f.groupId===i),getActiveIds:()=>ye.getState().activeModeIds,onSelect:f=>Zp(f)});return ni.set(i,g),g},MA=()=>{let i=[],c=ye.getState().activeModeIds,g=new Set;if(ba().forEach((f,b)=>{if(Vd(f.groupId,o.composer?.modeGroups)){let w=f.groupId;if(g.has(w))return;g.add(w);let W=AA(w);W.action.order=_m(b),W.action.label=o.composer?.modeGroups?.find(V=>V.id===w)?.label??w,i.push(W.action);return}i.push({id:lw(f.id),kind:"button",placement:"start",order:_m(b),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:c.includes(f.id),onSelect:()=>Zp(f.id)})}),o.composer?.models?.length&&!u.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!Sr||eu!==f)&&(eu=f,Sr=iw({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>ye.getState().selectedModelId,onSelect:b=>fh(b),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Sr.action)}return i},nu=null,yh=u.find(i=>i.renderHeader);if(yh?.renderHeader){let i=yh.renderHeader({config:o,defaultRenderer:()=>{let c=es({config:o,showClose:We()});return Zi(le,c,o),c.header},onClose:()=>ft(!1,"user")});if(i){let c=Ee;c&&(c.replaceWith(i),Ee=i,Rn.header.element=i)}}let bh=()=>{mt&&(ee.style.display="none",Ie.parentNode?.insertBefore(mt.element,Ie),mt.update())},ou=()=>{if(!gt){jl();return}if(io=!0,mt?bh():Mf().then(c=>{mt||!io||!gt||(mt=c.createEventStreamView({buffer:gt,getFullHistory:()=>gt.getAllFromStore(),onClose:()=>ri(),config:o,plugins:u,getThroughput:()=>Xt?.getMetric()??{status:"idle"},renderIconByName:ae}),bh())}).catch(()=>{ri()}),st){st.style.boxShadow=`inset 0 0 0 1.5px ${yn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(g=>g&&st.classList.add(g))}let i=()=>{if(!io)return;let c=Date.now();c-Up>=200&&(mt?.update(),Up=c),vr=requestAnimationFrame(i)};Up=0,vr=requestAnimationFrame(i),Gt(),te.emit("eventStream:opened",{timestamp:Date.now()})},ri=()=>{if(io){if(io=!1,mt&&mt.element.remove(),ee.style.display="",st){st.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&st.classList.remove(c))}vr!==null&&(cancelAnimationFrame(vr),vr=null),Gt(),te.emit("eventStream:closed",{timestamp:Date.now()})}},st=null;if(Q){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:"");st=S("button",c),st.style.width="28px",st.style.height="28px",st.style.color=yn.actionIconColor,st.type="button",st.setAttribute("aria-label","Event Stream"),st.title="Event Stream";let g=St(xS,"18px","currentColor",1.5);g&&st.appendChild(g);let f=Ne.clearChatButtonWrapper,b=Ne.closeButtonWrapper,w=f||b;w&&w.parentNode===Ee?Ee.insertBefore(st,w):Ee.appendChild(st),st.addEventListener("click",()=>{io?ri():ou()})}let vh=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=S("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=S("input");b.type="file",b.setAttribute("data-persona-composer-attachment-input",""),b.accept=(c.allowedTypes??mr).join(","),b.multiple=(c.maxFiles??4)>1,b.style.display="none",b.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(b)}},si=!1,Ch=i=>{let c=u.find(b=>b.renderComposer);if(!c?.renderComposer)return null;let g=o.composer,f=y?T.isStreaming():!1;return c.renderComposer({config:o,defaultRenderer:i,requestRender:()=>_b(),storage:v(c.id),onSubmit:b=>{!T||T.isStreaming()||Gc(b.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{Po()||wt?.click()},models:g?.models,selectedModelId:ye.getState().selectedModelId??g?.selectedModelId,onModelChange:b=>fh(b),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{nu?.()}:void 0})},wh=Ch(()=>ta({config:o}).footer);wh&&(Rn.replaceComposer(wh),Ie=Rn.composer.footer,si=!0);let Ze=null,EA=i=>{wn=i.form,ie=i.input,wo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Me=i.sendButton),i.micButton&&(re=i.micButton,Wn=i.micButton.parentElement),i.found.status&&(Qe=i.found.status),i.found.suggestions&&(Cr=i.found.suggestions),i.attachmentButton&&(Tt=i.attachmentButton,xn=i.attachmentButton.parentElement),wt=i.attachmentInput??null,Sn=i.attachmentPreviews??null,i.found.actionsRow&&(yA=i.found.actionsRow),Gp=i.found.actionsStart,Vl=i.found.actionsEnd};function ru(){let i=ie;if(!i)return;let c=o.composer?.inputAttributes,g=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;Od(i,c),g&&i.setAttribute("aria-label",g),Wd(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:bl(i)}),GC(i,Hd(o.composer?.maxLines,ve()?5:3))}let xh=i=>{Ze=$C(i,{debug:o.debug===!0}),Ze&&EA(Ze),ru()};vh(Ie),xh(Ie),xo();let va=Xr(o,ve());va&&(he.style.maxWidth=va,he.style.marginLeft="auto",he.style.marginRight="auto",he.style.width="100%",Hn.style.maxWidth=va,Hn.style.marginLeft="auto",Hn.style.marginRight="auto",Hn.style.width="100%",Kp.style.maxWidth=va,ua.style.maxWidth=va,ua.style.marginLeft="auto",ua.style.marginRight="auto",ua.style.width="100%");let Sh=()=>{let i=Xr(o,ve());if(!(!i||ve()))for(let c of[wn,Cr,Sn,Qe])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};Sh();let Ah=()=>{!o.attachments?.enabled||!wt||!Sn||(nt?nt.remountPreviews(Sn):(nt=zi.fromConfig(o.attachments,mh),nt.setPreviewsContainer(Sn)),Ze?.addListener(wt,"change",i=>{let c=i.target;nt?.handleFileSelect(c.files),c.value=""}),le.querySelector(".persona-attachment-drop-overlay")||le.appendChild(TS(o.attachments.dropOverlay)))};Ah();let TA=()=>_t?.prefetch(),Mh=()=>{if(!o.contextMentions?.enabled||!ie)return;let i=Ze?.header??null,c=i?Dm(i):void 0;if(_t=Ww({config:o,textarea:ie,anchor:wn??ie,getMessages:()=>T.getMessages(),liveRegionHost:le,chipRow:c}),_t&&!c){let g=ie;g.parentElement?.insertBefore(_t.contextRow,g)}};Mh();let Ao=null,PA={getState:()=>ye.getState(),getValue:()=>ie?.value??"",setValue:i=>{ie&&(ie.value=i,ie.dispatchEvent(new Event("input",{bubbles:!0})),xo())},submit:()=>{Aw(Ze?.form??null)},openAttachmentPicker:()=>{Po()||wt?.click()},toggleVoice:()=>{nu?.()},requestRender:()=>Ao?.resolve()},kA=()=>{let i=[];return(_t?.affordanceButtons??[]).forEach((g,f)=>{i.push({id:`core:mention-${f}`,placement:"start",order:No.mention+f,element:g,managed:!0})}),xn&&i.push({id:"core:attachment",placement:"start",order:No.attachment,element:xn}),Wn&&i.push({id:"core:mic",placement:"end",order:No.mic,element:Wn}),wo&&i.push({id:"core:send",placement:"end",order:No.send,element:wo}),i},Eh=()=>{Ao?.destroy(),Ao=ow({getBindings:()=>Ze,collect:()=>({builtIns:kA(),configActions:[...MA(),...o.composer?.actions??[]],plugins:u,contributionContext:{config:o,getState:()=>ye.getState(),requestRender:()=>Ao?.resolve()},debug:o.debug===!0}),actionContext:PA,getState:()=>ye.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),Ao.resolve()};Eh();let su=()=>{if(Ko?.destroy(),Ko=null,!ti().length)return;let i=Ze?.header;i&&(Ko=aw({row:Dm(i),onRemove:c=>Zp(c),initialIds:ye.getState().activeModeIds}),Ko.render(ye.getState().activeModeIds,ti()))};su();let Th=()=>{Ar?.destroy(),Ar=null,Mr?.destroy(),Mr=null;let i=Ze?.header;i&&(Ar=fw({onDismiss:()=>So(void 0)}),i.appendChild(Ar.element),Ar.render(ye.getState().quote),tu()==="defer-one"&&(Mr=hw({onEdit:()=>nE(),onRemove:()=>oi(void 0)}),i.appendChild(Mr.element),Mr.render(ye.getState().pendingSubmission)))};Th();let iu=xw(),LA=()=>{let i=Ze?.header?.querySelector(Bm);if(i)return i.childElementCount>0;let c=ye.getState();return c.mentionRefs.length>0||qd(c.activeModeIds,ti()).length>0};function ao(){let i=ye.getState(),c=iu.observe(Sw(ie),i.text);Ie.toggleAttribute("data-persona-composer-compact",ww({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:LA(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0}))}function Ph(){o.composer?.layout==="single-row"&&!ve()?Ie.setAttribute("data-persona-composer-layout","single-row"):Ie.removeAttribute("data-persona-composer-layout")}Ph(),ye.subscribe(()=>{Ao?.sync(),Tu(),vc(),ao(),iy()}),vc();let kh=!1,IA=i=>{if(kh||o.debug!==!0)return;let c=["messages","composer"].filter(g=>i[g]);c.length&&(kh=!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??{};IA(i);let c=f=>{switch(f){case"body-top":return ee.querySelector("[data-persona-intro-card]");case"messages":return he;case"footer-top":return Cr;case"composer":return wn;case"footer-bottom":return Qe;default:return null}},g=(f,b)=>{switch(f){case"header-left":case"header-center":case"header-right":if(f==="header-left")Ee.insertBefore(b,Ee.firstChild);else if(f==="header-right")Ee.appendChild(b);else{let w=Ee.querySelector(".persona-flex-col");w?w.parentNode?.insertBefore(b,w.nextSibling):Ee.appendChild(b)}break;case"body-top":{let w=ee.querySelector("[data-persona-intro-card]");w?w.replaceWith(b):ee.insertBefore(b,ee.firstChild);break}case"body-bottom":ee.appendChild(b);break;case"footer-top":Cr.replaceWith(b);break;case"footer-bottom":Qe.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)}})(),he.addEventListener("click",i=>{let c=i.target;if(!(c instanceof Element))return;let g=c.closest("button[data-persona-copy-tool-detail]");g&&(i.preventDefault(),i.stopPropagation(),qx(g))});let au=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;Lr(),fi();let w=g.getAttribute("data-bubble-type");if(f.classList.contains("persona-activity-row")){a.manual(b);let W=f.parentElement?.closest("[data-persona-tool-group]");W?.dataset.messageId&&a.manual(W.dataset.messageId)}if(w==="reasoning")s.has(b)?s.delete(b):s.add(b),vf(b,f,s);else if(w==="tool")r.has(b)?r.delete(b):r.add(b),Sf(b,f,r,o);else if(w==="approval"&&C){let V=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",F=l.get(b)??V;l.set(b,!F),C.updateApprovalDetailsUI(b,f,o,l)}Nt.delete(b)};he.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),au(i))}),he.addEventListener("click",i=>{i.detail===0&&i.target.closest(".persona-activity-row")&&au(i)}),he.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),au(i))}),he.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let g=he.getRootNode(),f=typeof g.getSelection=="function"?g.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let b=f.toString(),w=zw(b);!w||w===b||(c.setData("text/plain",w),i.preventDefault())});let lu=new Map,Lh=null,Ih="idle",RA={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},HA=(i,c)=>{let{icon:g,label:f}=RA[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=ae(g,14,"currentColor",2);b&&(i.innerHTML="",i.appendChild(b))},Rh=()=>{he.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let f=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;HA(c,f&&f===Lh?Ih:"idle")})};he.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 V=T.getMessages().find(F=>F.id===b);if(V&&ei.onCopy){let F=V.content||"";navigator.clipboard.writeText(F).then(()=>{g.classList.add("persona-message-action-success");let q=St(SS,14,"currentColor",2);q&&(g.innerHTML="",g.appendChild(q)),setTimeout(()=>{g.classList.remove("persona-message-action-success");let Y=St(AS,14,"currentColor",2);Y&&(g.innerHTML="",g.appendChild(Y))},2e3)}).catch(q=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",q)}),ei.onCopy(V)}}else if(w==="read-aloud")T.toggleReadAloud(b);else if(w==="upvote"||w==="downvote"){let V=(lu.get(b)??null)===w,F=w==="upvote"?"thumbs-up":"thumbs-down";if(V){lu.delete(b),g.classList.remove("persona-message-action-active");let q=ae(F,14,"currentColor",2);q&&(g.innerHTML="",g.appendChild(q))}else{let q=w==="upvote"?"downvote":"upvote",Y=f.querySelector(`[data-action="${q}"]`);if(Y){Y.classList.remove("persona-message-action-active");let et=ae(q==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);et&&(Y.innerHTML="",Y.appendChild(et))}lu.set(b,w),g.classList.add("persona-message-action-active");let oe=ae(F,14,"currentColor",2);oe&&(oe.setAttribute("fill","currentColor"),g.innerHTML="",g.appendChild(oe)),g.classList.remove("persona-message-action-pop"),g.offsetWidth,g.classList.add("persona-message-action-pop");let Ue=T.getMessages().find(ot=>ot.id===b);Ue&&ei.onFeedback&&ei.onFeedback({type:w,messageId:Ue.id,message:Ue})}}else if(w==="regenerate")Xl?.regenerate(b);else if(w==="edit")Xl?.edit(b);else if(w==="quote")Xl?.quote(b);else if(w?.startsWith(up)){let W=w.slice(up.length),V=o.messageActions?.custom?.find(q=>q.id===W),F=T.getMessages().find(q=>q.id===b);if(!V||!F)return;try{V.onSelect(F)}catch(q){console.error(`[AgentWidget] messageActions.custom "${W}" onSelect failed:`,q)}}});let Xl=null;he.addEventListener("click",i=>{let g=i.target.closest("button[data-approval-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest(".persona-approval-bubble");if(!f)return;let b=f.getAttribute("data-message-id");if(!b)return;let w=g.getAttribute("data-approval-action");if(!w)return;let W=w==="approve"?"approved":"denied",F=T.getMessages().find(Y=>Y.id===b);if(!F?.approval)return;let q=f.querySelector("[data-approval-buttons]");q&&q.querySelectorAll("button").forEach(oe=>{oe.disabled=!0,oe.style.opacity="0.5",oe.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?T.resolveWebMcpApproval(b,W):T.resolveApproval(F.approval,W)});let qe=null,Hh=!1,Ca=null,as=()=>{},wa="none",Jl=null,Gn={artifacts:[],selectedId:null},Go=!1,lo=!1,xa=!1,ii=!1,Wh=()=>ii||Gn.artifacts.some(i=>ur(o.features?.artifacts,i)==="panel"),Zl=()=>Gn.artifacts.length>0&&!Go&&Wh(),at={current:null},cu=(i,c)=>{let g=T.getArtifactById(c),f=g?.markdown,b=g?.title||"artifact",w=g?.file,W=g?.artifactType??"markdown";if(!f){let q=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(q){let oe=T.getMessages().find(ue=>ue.id===q);if(oe?.rawContent)try{let ue=JSON.parse(oe.rawContent);f=ue?.props?.markdown,b=ue?.props?.title||b,ue?.props?.file&&typeof ue.props.file=="object"&&(w=ue.props.file),!g&&typeof ue?.props?.artifactType=="string"&&(W=ue.props.artifactType)}catch{}}}return{markdown:f,title:b,file:w,artifactType:W}};he.addEventListener("click",i=>{let g=i.target.closest("[data-download-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-download-artifact");if(!f||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:f})===!0)return;let{markdown:w,title:W,file:V}=cu(g,f);if(!w)return;let F=fr();F&&F.triggerArtifactDownload(F.downloadInfoFor({title:W,markdown:w,file:V}))}),he.addEventListener("click",i=>{let g=i.target.closest("[data-artifact-custom-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-artifact-custom-action");if(!f)return;let b=g.closest("[data-artifact-inline]"),w=b?null:g.closest("[data-open-artifact]"),W=b?b.getAttribute("data-artifact-inline"):w?.getAttribute("data-open-artifact")??null,F=(b?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ot=>ot.id===f);if(!F)return;let{markdown:q,title:Y,file:oe,artifactType:ue}=cu(g,W??""),Ue={artifactId:W,title:Y,artifactType:ue,markdown:q,file:oe};try{Promise.resolve(F.onClick(Ue)).catch(()=>{})}catch{}}),he.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=T.getArtifactById(f),w=fr();if(!w)return;let W="";if(b)W=w.artifactCopyText(b);else{let{markdown:V,file:F,artifactType:q}=cu(g,f);q==="markdown"&&(W=w.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:V??"",...F?{file:F}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let V=St(SS,16,"currentColor",2);V&&(g.replaceChildren(V),setTimeout(()=>{let F=St(AS,16,"currentColor",2);F&&g.replaceChildren(F)},1500))}).catch(()=>{})}),he.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||(Go=!1,ii=!0,lo=!0,xa=!0,T.selectArtifact(f),co())}),he.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(),Go=!1,ii=!0,T.selectArtifact(f),co())}),he.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 ai=Ne.composerOverlay,li=(i,c,g)=>{let f=c.trim();if(!f||!at.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})),qs(ai,b);let W=at.current.getMessages().find(V=>V.toolCall?.id===b);W?.agentMetadata?.awaitingLocalTool?at.current.resolveAskUserQuestion(W,g.structured??f):at.current.sendMessage(f)},ls=i=>{let c=at.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:vd(i,f),currentIndex:so(i)})},Oh=i=>Object.entries(i).map(([c,g])=>`${c}: ${Array.isArray(g)?g.join(", "):g}`).join(" | "),du=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=so(i),g=Ni(i);if(c>=g-1)return;let f=at.current?.getMessages().find(b=>b.toolCall?.id===i.getAttribute("data-tool-call-id"));f&&(Cd(i,f,o,c+1),ls(i))};ai.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})),qs(ai,w);let W=at.current?.getMessages().find(V=>V.toolCall?.id===w);W?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(W),at.current?.resolveAskUserQuestion(W,"(dismissed)"));return}if(b==="pick"){let w=g.getAttribute("data-option-label");if(!w)return;let W=f.getAttribute("data-multi-select")==="true",V=Kr(f);if(V&&W){let F=Vs(f)[so(f)],q=new Set(Array.isArray(F)?F:[]);q.has(w)?q.delete(w):q.add(w),Gr(f,Array.from(q)),ls(f);return}if(V){Gr(f,w),ls(f),du(f);return}if(W){let F=g.getAttribute("aria-pressed")==="true";g.setAttribute("aria-pressed",F?"false":"true"),g.classList.toggle("persona-ask-pill-selected",!F);let q=f.querySelector('[data-ask-user-action="submit-multi"]');q&&(q.disabled=em(f).length===0);return}li(f,w,{source:"pick",values:[w]});return}if(b==="submit-multi"){let w=em(f);if(w.length===0)return;li(f,w.join(", "),{source:"multi",values:w});return}if(b==="open-free-text"){let w=f.querySelector('[data-ask-free-text-row="true"]');w&&(w.classList.remove("persona-hidden"),w.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(b==="focus-free-text"){f.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(b==="submit-free-text"){let W=f.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!W.trim())return;if(Kr(f)){Gr(f,W.trim()),ls(f),du(f);return}li(f,W,{source:"free-text"});return}if(b==="next"||b==="back"){if(!at.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=at.current.getMessages().find(oe=>oe.toolCall?.id===w);if(!W)return;let F=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(F){let oe=Vs(f)[so(f)];(typeof oe!="string"||oe!==F)&&Gr(f,F)}let q=b==="next"?1:-1,Y=so(f)+q;Cd(f,W,o,Y),ls(f);return}if(b==="submit-all"){if(!at.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=at.current.getMessages().find(oe=>oe.toolCall?.id===w);if(!W)return;let F=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";F&&Gr(f,F);let q=vd(f,W);at.current.persistAskUserQuestionProgress(W,{answers:q,currentIndex:so(f)});let Y=Oh(q);li(f,Y||"(submitted)",{source:"submit-all",structured:q});return}if(b==="skip"){if(!at.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=at.current.getMessages().find(ue=>ue.toolCall?.id===w);if(!W)return;let V=Kr(f),F=so(f),q=Ni(f),Y=F>=q-1;if(!V){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:w},bubbles:!0,composed:!0})),qs(ai,w),W.agentMetadata?.awaitingLocalTool&&(at.current.markAskUserQuestionResolved(W),at.current.resolveAskUserQuestion(W,"(dismissed)"));return}Gr(f,"");let oe=f.querySelector('[data-ask-free-text-input="true"]');if(oe&&(oe.value=""),Y){let ue=vd(f,W),Ue=Oh(ue);li(f,Ue||"(skipped)",{source:"submit-all",structured:ue});return}Cd(f,W,o,F+1),ls(f);return}}),ai.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(Kr(f)){Gr(f,b.trim()),ls(f),du(f);return}li(f,b,{source:"free-text"})}});let Bh=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=ai.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",Bh);let Mo=null,Mt=null,Sa=null,ec=null,tc=()=>{},Dh=!1,nc="",oc="";function pu(){ec?.(),ec=null}let WA=()=>{let i=xi&&Ps?.isConnected?Ps:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},_h=()=>{if(!Mo||!Mt)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){Mt.style.removeProperty("position"),Mt.style.removeProperty("left"),Mt.style.removeProperty("top"),Mt.style.removeProperty("bottom"),Mt.style.removeProperty("width"),Mt.style.removeProperty("z-index");return}let f=Mo.firstElementChild;if(!f||f===Mt)return;let b=10;Mt.style.position="absolute",Mt.style.top="0",Mt.style.bottom="0",Mt.style.width=`${b}px`,Mt.style.zIndex="5";let w=Rf(Mo,c),W=f.offsetWidth+w/2-b/2;Mt.style.left=`${Math.max(0,W)}px`},rc=()=>{},Nh=()=>{let i=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,g=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>g?!1:D||Ct(o)},sc=()=>!vn(o)||!Zl()||e.classList.contains("persona-artifact-narrow-host")||Nh()||(e.ownerDocument.defaultView??window).innerWidth<gH?"none":Lf(o)?"detached":"welded",co=()=>{if(!qe||!vn(o))return;_l(e,o),Nl(e,o),rc();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=Ce.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let g=Zl();qe.setVisible(g),qe.update(Gn),Go?(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),lo=!1,xa=!1):Gn.artifacts.length>0&&Wh()?(qe.element.classList.remove("persona-hidden"),qe.setMobileOpen(!0)):(qe.setMobileOpen(!1),qe.element.classList.add("persona-hidden"),qe.backdrop?.classList.add("persona-hidden"),lo=!1,xa=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(qe.setExpandToggleVisible(f),qe.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),qe.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),qe.setCustomActions(o.features?.artifacts?.toolbarActions??[]),qe.setTabFade(o.features?.artifacts?.layout?.tabFade),qe.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!xa&&(lo=!1),lo!==Dh){let w=qe.element;lo?(nc=w.style.width,oc=w.style.maxWidth,w.style.removeProperty("width"),w.style.removeProperty("max-width")):(nc&&(w.style.width=nc),oc&&(w.style.maxWidth=oc),nc="",oc=""),Dh=lo}e.classList.toggle("persona-artifact-expanded",lo),qe.setExpanded(lo);let b=sc();b!==wa&&(wa=b,as()),tc()};if(vn(o)){Ce.style.position="relative";let i=S("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=S("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(le),Mo=c,c.appendChild(i),Ce.appendChild(c);let g=b=>{Hh||qe||(qe=b.createArtifactPane(o,{onSelect:w=>at.current?.selectArtifact(w),onDismiss:()=>{Go=!0,co()},onToggleExpand:()=>{let w=!lo,W=Gn.selectedId??Gn.artifacts[Gn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:W,expanded:w})!==!0&&(lo=w,w||(xa=!1),co())}}),qe.element.classList.add("persona-hidden"),c.appendChild(qe.element),qe.backdrop&&Ce.appendChild(qe.backdrop),tc(),co())},f=fr();f?g(f):(Pf(()=>{let b=fr();b&&g(b)}),yp().catch(()=>{})),tc=()=>{if(!Mo||!qe)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Sa?.(),Sa=null,pu(),Mt&&(Mt.remove(),Mt=null),qe.element.style.removeProperty("width"),qe.element.style.removeProperty("maxWidth");return}if(!Mt){let w=S("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");w.setAttribute("role","separator"),w.setAttribute("aria-orientation","vertical"),w.setAttribute("aria-label","Resize artifacts panel"),w.tabIndex=0;let W=e.ownerDocument,V=W.defaultView??window,F=q=>{if(!qe||q.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||V.innerWidth<=640)return;q.preventDefault(),pu();let Y=q.clientX,oe=qe.element.getBoundingClientRect().width,ue=o.features?.artifacts?.layout,Ue=et=>{let Pn=Mo.getBoundingClientRect().width,xt=e.classList.contains("persona-artifact-welded-split"),Pt=Rf(Mo,V),mn=xt?0:w.getBoundingClientRect().width||6,Wt=oe-(et.clientX-Y),ct=iS(Wt,Pn,Pt,mn,ue?.resizableMinWidth,ue?.resizableMaxWidth,WA());qe.element.style.width=`${ct}px`,qe.element.style.maxWidth="none",_h()},ot=()=>{W.removeEventListener("pointermove",Ue),W.removeEventListener("pointerup",ot),W.removeEventListener("pointercancel",ot),ec=null;try{w.releasePointerCapture(q.pointerId)}catch{}};ec=ot,W.addEventListener("pointermove",Ue),W.addEventListener("pointerup",ot),W.addEventListener("pointercancel",ot);try{w.setPointerCapture(q.pointerId)}catch{}};w.addEventListener("pointerdown",F),Mt=w,Mo.insertBefore(w,qe.element),Sa=()=>{w.removeEventListener("pointerdown",F)}}if(Mt){let w=Zl();Mt.classList.toggle("persona-hidden",!w),_h()}},rc=()=>{if(!D||!qe||(o.launcher?.sidebarMode??!1)||Ct(o)&&Vn(o).reveal==="emerge")return;let w=e.ownerDocument.defaultView??window,W=o.launcher?.mobileFullscreen??!0,V=o.launcher?.mobileBreakpoint??640;if(W&&w.innerWidth<=V||!Jx(o,D))return;let F=Qs(o).width,q=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Zl()?(Ce.style.width=q,Ce.style.maxWidth=q):(Ce.style.width=F,Ce.style.maxWidth=F)},typeof ResizeObserver<"u"&&(Ca=new ResizeObserver(()=>{co()}),Ca.observe(Ce))}else Ce.appendChild(le);ve()&&Jt&&(Ne.peekBanner&&Jt.appendChild(Ne.peekBanner),Jt.appendChild(Ie)),e.appendChild(Ge),Jt&&e.appendChild(Jt);let uu=()=>{let i=Nh()||ve()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!Ct(o);if(he.style.gap=i?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",he.style.setProperty("--persona-transcript-gap",he.style.gap),ve()){Ce.style.width="100%",Ce.style.maxWidth="100%";let Le=o.launcher?.composerBar??{},Fe=Ge.dataset.state==="expanded",Be=Le.expandedSize??"anchored";if(!(Fe&&Be!=="fullscreen")){le.style.background="",le.style.border="",le.style.borderRadius="",le.style.overflow="",le.style.boxShadow="";return}let qt=o.theme?.components?.panel,kn=Fo(o),ar=(lr,Os)=>lr==null||lr===""?Os:an(kn,lr)??lr,Lg="1px solid var(--persona-border)",Ws="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ig="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";le.style.background="var(--persona-surface, #ffffff)",le.style.border=ar(qt?.border,Lg),le.style.borderRadius=ar(qt?.borderRadius,Ig),le.style.boxShadow=ar(qt?.shadow,Ws),le.style.overflow="hidden";return}let c=Ct(o),g=o.launcher?.sidebarMode??!1,f=c||g||(o.launcher?.fullHeight??!1),b=o.launcher?.enabled===!1,w=o.launcher?.detachedPanel===!0,W=o.theme?.components?.panel,V=o.darkTheme?.components?.panel,F=Yi(o)==="dark"?ho(W??{},V??{}):W,q=Fo(o),Y=(Le,Fe)=>Le==null||Le===""?Fe:an(q,Le)??Le,oe=e.ownerDocument.defaultView??window,ue=o.launcher?.mobileFullscreen??!0,Ue=o.launcher?.mobileBreakpoint??640,ot=oe.innerWidth<=Ue,et=ue&&ot&&D,Pn=c&&ue&&ot,xt=o.launcher?.position??"bottom-left",Pt=xt==="bottom-left"||xt==="top-left",mn=o.launcher?.zIndex??cn,Wt=(Le,Fe,Be)=>`var(--persona-components-panel-modes-${Le}-${Fe}, ${Be})`,ct=F?.modes?.floating,Ro=Y(ct?.border??F?.border,Wt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),Ho=Y(ct?.shadow??F?.shadow,Wt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),no=Y(ct?.borderRadius??F?.borderRadius,Wt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),oo=w&&!et&&!Pn,Nr=et||Pn?"mobile":oo?"floating":c?"docked":g?"sidebar":b?"inline":"floating",Wo=F?.modes?.[Nr];oo?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let go=oo?Ro:g||et?"none":Ro,Fr=oo?Ho:et?"none":g?Pt?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":b?"none":Ho;c&&!et&&!oo&&(Fr="none",go="none");let Ya=oo?no:g||et?"0":no,Hs=Y(Wo?.border??F?.border,Wt(Nr,"border",go)),R=Y(Wo?.shadow??F?.shadow,Wt(Nr,"shadow",Fr)),Re=Y(Wo?.borderRadius??F?.borderRadius,Wt(Nr,"borderRadius",Ya)),He=sc(),ne=He==="detached",dt=He==="welded";e.classList.toggle("persona-artifact-detached-split",ne),e.classList.toggle("persona-artifact-welded-split",dt);let Ft="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)))))",ht=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&vn(o)&&Lf(o)&&b&&!c;e.classList.toggle("persona-artifact-chat-flush",ht);let Ot=ne||ht?"none":R,Yt=ne?Ro:dt?"none":Hs,Pe=ne?no:Re;ht&&(Yt="none",Pe="0");let yt=Wo?.borderRadius!=null&&Wo.borderRadius!==""||F?.borderRadius!=null&&F.borderRadius!=="",Oe=ht&&!yt?"0":Re,Qt=ee.scrollTop;e.style.cssText="",Ge.style.cssText="",Ce.style.cssText="",le.style.cssText="",ee.style.cssText="",si||(Ie.style.cssText=""),io&&(ee.style.display="none"),(f||b)&&(e.style.minWidth="0");let ro=()=>{if(Qt<=0)return;(ee.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ee.scrollTop===Qt)return;let Fe=ee.scrollHeight-ee.clientHeight;Fe<=0||(ee.scrollTop=Math.min(Qt,Fe))})};if(et){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
45
|
position: fixed !important;
|
|
45
46
|
inset: 0 !important;
|
|
46
47
|
width: 100% !important;
|
|
@@ -50,9 +51,9 @@ _Details: ${n.message}_`:o}var Rg=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
50
51
|
padding: 0 !important;
|
|
51
52
|
display: flex !important;
|
|
52
53
|
flex-direction: column !important;
|
|
53
|
-
z-index: ${
|
|
54
|
+
z-index: ${mn} !important;
|
|
54
55
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
55
|
-
`,
|
|
56
|
+
`,Ce.style.cssText=`
|
|
56
57
|
position: relative !important;
|
|
57
58
|
display: flex !important;
|
|
58
59
|
flex-direction: column !important;
|
|
@@ -65,7 +66,7 @@ _Details: ${n.message}_`:o}var Rg=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
65
66
|
padding: 0 !important;
|
|
66
67
|
box-shadow: none !important;
|
|
67
68
|
border-radius: 0 !important;
|
|
68
|
-
`,
|
|
69
|
+
`,le.style.cssText=`
|
|
69
70
|
display: flex !important;
|
|
70
71
|
flex-direction: column !important;
|
|
71
72
|
flex: 1 1 0% !important;
|
|
@@ -76,33 +77,33 @@ _Details: ${n.message}_`:o}var Rg=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
76
77
|
overflow: hidden !important;
|
|
77
78
|
border-radius: 0 !important;
|
|
78
79
|
border: none !important;
|
|
79
|
-
`,
|
|
80
|
+
`,ee.style.flex="1 1 0%",ee.style.minHeight="0",ee.style.overflowY="auto",Ie.style.flexShrink="0",Jp(),Te=!0,ro();return}let tn=Qs(o);if(!g&&!c)b&&f?(Ce.style.width="100%",Ce.style.maxWidth="100%"):(Ce.style.width=tn.width,Ce.style.maxWidth=tn.maxWidth);else if(c)if(Vn(o).reveal==="emerge"&&!w){let Fe=Vn(o).width;Ce.style.width=Fe,Ce.style.maxWidth=Fe}else Ce.style.width="100%",Ce.style.maxWidth="100%";if(rc(),Ce.style.boxShadow=Ot,Ce.style.borderRadius=Oe,ne?Ce.style.border="none":dt&&(Ce.style.border=Hs),le.style.border=Yt,le.style.borderRadius=Pe,le.style.boxShadow=ne&&!ht?Ft:"",ht&&(le.style.background="transparent",ee.style.background="transparent",Ie.style.background="transparent",Ie.style.borderTop="none"),dt){let Le=o.features?.artifacts?.layout;Jl=Le?.unifiedSplitOuterRadius?.trim()||Le?.paneBorderRadius?.trim()||Re}else Jl=null;let pt=Wo?.border!=null||F?.border!=null;if(c&&!et&&!oo&&!ne&&!dt&&!pt&&(le.style.border="none",Vn(o).side==="right"?le.style.borderLeft="1px solid var(--persona-border)":le.style.borderRight="1px solid var(--persona-border)"),c&&!et&&dt&&!pt&&(Vn(o).side==="right"?Ce.style.borderLeft="1px solid var(--persona-border)":Ce.style.borderRight="1px solid var(--persona-border)"),f&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(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%",b&&(Ge.style.overflow="hidden"),Ce.style.display="flex",Ce.style.flexDirection="column",Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.maxHeight="100%",Ce.style.height="100%",ne||(Ce.style.overflow="hidden"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.overflow="hidden",ee.style.flex="1 1 0%",ee.style.minHeight="0",ee.style.overflowY="auto",Ie.style.flexShrink="0"),b&&(oo||ne||ht)&&!c&&(ht||(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"),!g&&!b&&!c&&(qn[xt]??qn["bottom-right"]).split(" ").forEach(Fe=>Ge.classList.add(Fe)),g){let Le=cr(o).sidebarWidth?o.launcher?.sidebarWidth??"420px":an(Fo(o),"components.panel.width")??"420px";w?Ge.style.cssText=`
|
|
80
81
|
position: fixed !important;
|
|
81
82
|
top: var(--persona-panel-inset) !important;
|
|
82
83
|
bottom: var(--persona-panel-inset) !important;
|
|
83
|
-
width: ${
|
|
84
|
+
width: ${Le} !important;
|
|
84
85
|
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
85
86
|
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
86
87
|
margin: 0 !important;
|
|
87
88
|
padding: 0 !important;
|
|
88
89
|
display: flex !important;
|
|
89
90
|
flex-direction: column !important;
|
|
90
|
-
z-index: ${
|
|
91
|
-
${
|
|
91
|
+
z-index: ${mn} !important;
|
|
92
|
+
${Pt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
92
93
|
`:Ge.style.cssText=`
|
|
93
94
|
position: fixed !important;
|
|
94
95
|
top: 0 !important;
|
|
95
96
|
bottom: 0 !important;
|
|
96
|
-
width: ${
|
|
97
|
+
width: ${Le} !important;
|
|
97
98
|
height: 100vh !important;
|
|
98
99
|
max-height: 100vh !important;
|
|
99
100
|
margin: 0 !important;
|
|
100
101
|
padding: 0 !important;
|
|
101
102
|
display: flex !important;
|
|
102
103
|
flex-direction: column !important;
|
|
103
|
-
z-index: ${
|
|
104
|
-
${
|
|
105
|
-
`,
|
|
104
|
+
z-index: ${mn} !important;
|
|
105
|
+
${Pt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
106
|
+
`,Ce.style.cssText=`
|
|
106
107
|
position: relative !important;
|
|
107
108
|
display: flex !important;
|
|
108
109
|
flex-direction: column !important;
|
|
@@ -113,10 +114,10 @@ _Details: ${n.message}_`:o}var Rg=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
113
114
|
min-height: 0 !important;
|
|
114
115
|
margin: 0 !important;
|
|
115
116
|
padding: 0 !important;
|
|
116
|
-
box-shadow: ${
|
|
117
|
-
border-radius: ${
|
|
118
|
-
${
|
|
119
|
-
`,
|
|
117
|
+
box-shadow: ${Ot} !important;
|
|
118
|
+
border-radius: ${Oe} !important;
|
|
119
|
+
${ne?"border: none !important;":dt?`border: ${Hs} !important;`:""}
|
|
120
|
+
`,Ce.style.setProperty("width","100%","important"),Ce.style.setProperty("max-width","100%","important"),le.style.cssText=`
|
|
120
121
|
display: flex !important;
|
|
121
122
|
flex-direction: column !important;
|
|
122
123
|
flex: 1 1 0% !important;
|
|
@@ -125,32 +126,32 @@ _Details: ${n.message}_`:o}var Rg=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
125
126
|
min-height: 0 !important;
|
|
126
127
|
max-height: 100% !important;
|
|
127
128
|
overflow: hidden !important;
|
|
128
|
-
border-radius: ${
|
|
129
|
-
border: ${
|
|
130
|
-
${
|
|
131
|
-
${
|
|
132
|
-
|
|
129
|
+
border-radius: ${Pe} !important;
|
|
130
|
+
border: ${Yt} !important;
|
|
131
|
+
${ne&&!ht?`box-shadow: ${Ft} !important;`:""}
|
|
132
|
+
${ht?"background: transparent !important;":""}
|
|
133
|
+
`,si||(Ie.style.cssText=`
|
|
133
134
|
flex-shrink: 0 !important;
|
|
134
135
|
border-top: none !important;
|
|
135
136
|
padding: 8px 16px 12px 16px !important;
|
|
136
|
-
${
|
|
137
|
-
`)}if(!f&&!i){let De="max-height: -moz-available !important; max-height: stretch !important;",we=c?"":"padding-top: 1.25em !important;",dn=c?"":`z-index: ${o.launcher?.zIndex??rn} !important;`;Ge.style.cssText+=De+we+dn}Mp(),Lt()},Np=()=>{e.style.setProperty("--persona-content-max-width",Dr(o,be()))},Qf=!1,Xf=()=>{let i=om(o,be());be()&&o.composer?.placement&&o.debug===!0&&!Qf&&(Qf=!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()},Jf=()=>{if(be())return;let i=St(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!ce)return;let f=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,v=o.launcher?.mobileBreakpoint??640;if(b&&f.innerWidth<=v)return;let B=f.innerHeight,U=64,$=o.launcher?.heightOffset??0,j=Math.max(200,B-U),Q=Math.min(640,j);Se.style.height=`${Math.max(200,Q-$)}px`};Dp(),ki(e,o),yl(e,o),bl(e,o),Np(),Xf(),Kr=()=>{Dp(),Jf(),ki(e,o),yl(e,o),bl(e,o),Np(),Xf(),Rl?e.style.setProperty("--persona-artifact-welded-outer-radius",Rl):e.style.removeProperty("--persona-artifact-welded-outer-radius"),$o(),bp()};let me=[];me.push(()=>{qf=!0}),me.push(()=>{d.forEach(i=>i()),l.destroy()}),me.push(()=>{document.removeEventListener("keydown",Kf)}),me.push(()=>{Qi!==null&&clearTimeout(Qi)});let Ao=null,Mo=null;me.push(()=>{Ao?.(),Ao=null,Mo?.(),Mo=null}),Zi&&me.push(()=>{Zi?.disconnect(),Zi=null}),me.push(()=>{na?.(),na=null,_p(),vt&&(vt.remove(),vt=null),qe?.element.style.removeProperty("width"),qe?.element.style.removeProperty("maxWidth"),qe?.destroy()}),x&&me.push(()=>{je=!0,Ke=null,Ht!==null&&(cancelAnimationFrame(Ht),Ht=null),ht?.destroy(),ht=null,He?.destroy(),He=null,Te=null});let Yr=null,Zf=()=>{Yr&&(Yr(),Yr=null),o.colorScheme==="auto"&&(Yr=nl(()=>{ki(e,o)}))};Zf(),me.push(()=>{Yr&&(Yr(),Yr=null)}),me.push(()=>{C=!0,h?.()}),me.push(()=>{I=!0});let eh=!1;me.push(()=>{eh=!0});let Fp=(i,c)=>{let g=al(i,c);return g||!ow.includes(i)?g:(sw().then(f=>{if(eh)return;Ld(f.wipe),Ld(f.glyphCycle);let b=al(i,c);b&&dl(b,e)}).catch(()=>{}),null)},Fl=o.features?.streamAnimation;if(Fl?.type&&Fl.type!=="none"){let i=Fp(Fl.type,Fl.plugins);i&&dl(i,e),me.push(()=>rw(e))}let zo=gl(ur),th=gl(Cp),nh=gl(Vi),Qr=[zo,th,nh];me.push(()=>{Qr.forEach(i=>i.destroy())});let Xr=null,k,Jr=null,oh=!1,rh=0,sh=null,ih=i=>i.reduce((c,g)=>g.role==="user"?c+1:c,0),ah=i=>{for(let c=i.length-1;c>=0;c--)if(Ci(i[c]))return i[c].id??null;return null},lh=!1,LS=()=>{lh||o.debug!==!0||(lh=!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".'))},ch=!1,dh=!1,ph=(i,c)=>{ch||o.debug!==!0||!c.enabled||c.expose||oh||dh&&(k.isStreaming()||i.some(Ci)||(ch=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},zs=i=>{if(!k)return;let c=i??k.getMessages(),g=j=>{j.render([],k,ae,c)},f=j=>{Qr.forEach(Q=>{Q!==j&&g(Q)})};Jr&&(ih(c)>rh||ah(c)!==sh)&&(Jr=null);let b=Br(o);ph(c,b);let v=b.enabled?gg(c):null,B=Jr??v,U=Jr?"host":"agent";if(B){let j=o.suggestions?.followUps,Q=j?.placement??(j?"auto":"composer"),ue=(Q==="auto"?be()?"composer":"after-message":Q)==="after-message"?nh:zo;f(ue),ue.render(B,k,ae,c,o.suggestionChipsConfig,{source:U,surface:"followUp",variant:j?.variant??"chip",behavior:j?.behavior??"send",overflow:j?.overflow??"wrap",maxItems:j?.maxItems??4,config:o,plugins:a,submitPrompt:Tc});return}if(c.some(j=>j.role==="user")){Qr.forEach(g);return}let $=o.suggestions?.starters;if($){let j=Is(_o(o),c),Q=$.placement??"auto",oe=Q==="auto"?j?"welcome":"composer":Q;if(oe==="welcome"&&!j){LS(),Qr.forEach(g);return}let ue=oe==="welcome"?th:zo;f(ue),ue.render($.items??o.suggestionChips,k,ae,c,o.suggestionChipsConfig,{surface:"starter",variant:$.variant??"card",behavior:$.behavior??"send",overflow:$.overflow??"wrap",maxItems:$.maxItems??4,config:o,plugins:a,submitPrompt:Tc});return}f(zo),zo.render(o.suggestionChips,k,ae,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a,submitPrompt:Tc})},uh=()=>{Jr&&(Jr=null,zs())},IS=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){uh();return}let g=k?k.getMessages():[];Jr=c,oh=!0,rh=ih(g),sh=ah(g),zs(g)},_n=!1,Nt=zC(),Vs=new Map,Zr=new Map,br=new Map,es=null,vr=null;function ts(){if(!es)return;let i=es;es=null,vr?.destroy(),vr=null,Nt.delete(i),de.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),k&&Yn(Pe,k.getMessages(),ut)}let ns=0,RS=Ro()!==null,Dn=QC(),Nn=0,Cr=null,An=!1,$l=!1,wr=0,zt=null,os=null,$p=!1,Ks=!1,rs=null,oa=!0,Ul=!1,Gs=null,jl=!1,ss=()=>{jl=!0,BS()},Up=null,HS=4,Vo=24,WS=80,OS=1e3,Ko=null,gh=()=>{e.setAttribute("data-persona-scrollbar",xp()),xp()!=="on-scroll"&&(Ko!==null&&clearTimeout(Ko),Ko=null,te.removeAttribute("data-persona-scrollbar-visible"))},BS=()=>{xp()==="on-scroll"&&(te.setAttribute("data-persona-scrollbar-visible",""),Ko!==null&&clearTimeout(Ko),Ko=setTimeout(()=>{Ko=null,ks(te,Vo)&&te.removeAttribute("data-persona-scrollbar-visible")},OS))};gh(),me.push(()=>{Ko!==null&&clearTimeout(Ko)});let jp=new Map,ze={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};_f=()=>ze.active,so();let mh=o.voiceRecognition?.autoResume??!1,Go=i=>{A.emit("voice:state",{active:ze.active,source:i,timestamp:Date.now()})},lo=()=>{se(i=>({...i,voiceState:{active:ze.active,timestamp:Date.now(),manuallyDeactivated:ze.manuallyDeactivated}}))},_S=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Zm(Z.voiceState),c=!!i.active,g=Number(i.timestamp??0);ze.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-g<FI&&setTimeout(()=>{ze.active||(ze.manuallyDeactivated=!1,In(o.voiceRecognition?.provider)?k.toggleVoice().then(()=>{ze.active=k.isVoiceActive(),Go("restore"),k.isVoiceActive()&&ui()}):Lc("restore"))},1e3)},DS=()=>k?vx(k.getMessages()).filter(i=>!i.__skipPersist):[],ql=null,fh=(i,c)=>{typeof console<"u"&&console.error(i,c)},zl=(i,c)=>{let g=()=>{try{let B=i();return!B||typeof B.then!="function"?null:Promise.resolve(B).catch(U=>{fh(c,U)})}catch(B){return fh(c,B),null}},f=ql,b=f?f.then(()=>g()??void 0):g();if(!b)return;let v=b.finally(()=>{ql===v&&(ql=null)});ql=v};function Ys(i){if(!K?.save)return;let c=i?vx(i):k?DS():[],g=ie&&k?.getResumableHandle();g&&(Z={...Z,durableResume:{executionId:g.executionId,after:g.lastEventId}});let f={messages:c,metadata:Z,artifacts:Gn.artifacts,selectedArtifactId:Gn.selectedId,...is?{draft:is}:{}};zl(()=>K.save(f),"[AgentWidget] Failed to persist state:")}let is,Vl=()=>!K?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,ra=hC({write:()=>{if(!Vl())return;let i=Ce.getState(),c=mC({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Nu(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(is)&&(is=c,Ys())}});function hh(){Vl()&&ra.schedule()}function qp(){ra.flush()}function yh(i){if(!Vl())return;let c=fC(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(g=>g.id),modelIds:(o.composer?.models??[]).map(g=>g.id),modes:o.composer?.modes??[]});c&&(is=i,ae&&!ae.value&&(ae.value=c.text,ae.dispatchEvent(new Event("input",{bubbles:!0})),Co()),c.selectedModelId&&(Ce.setSelectedModelId(c.selectedModelId),fr?.repaint()),Ll(c.activeModeIds??[]),c.quote&&wo(c.quote),ra.cancel())}function Kl(){ra.cancel(),is&&(is=void 0,Vl()&&Ys())}let Qs=null,bh=()=>Ge.querySelector("#persona-scroll-container")||te,Xs=()=>{Qs!==null&&(cancelAnimationFrame(Qs),Qs=null),An=!1},vh=()=>{Cr!==null&&(cancelAnimationFrame(Cr),Cr=null),$l=!1,Xs()},NS=()=>_n&&Vp()&&(Bn()!=="anchor-top"||Cf()),zp=()=>{let i=Ki()||"Jump to latest",c=NS();Dt.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),wr>0?(qr.textContent=String(wr),qr.style.display="",Dt.setAttribute("aria-label",`${i} (${wr} new)`)):(qr.textContent="",qr.style.display="none",Dt.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},Ch=()=>{wr!==0&&(wr=0,zp())},FS=()=>{let i=zt?.spacerHeight??0;return i<=0?ks(te,Vo):Xl(i)-te.scrollTop-te.clientHeight<=Vo},Vp=()=>mr()?!Dn.isFollowing():!FS(),Kp=()=>!!k&&k.getMessages().length>0,Vt=()=>{if(!mS()||iS()){Dt.parentNode&&Dt.remove(),Dt.style.display="none";return}Dt.parentNode!==de&&de.appendChild(Dt),zr();let c=Bo(te)>0&&Vp()&&Kp();c?zp():Ch(),Dt.style.display=c?"":"none"},sa=()=>{Dn.pause()&&(vh(),Vt())},Mn=()=>{Dn.resume(),Ch(),Vt()},xr=(i=!1)=>{mr()&&Kp()&&Dn.isFollowing()&&(!i&&!_n||(Cr!==null&&(cancelAnimationFrame(Cr),Cr=null),$l=!0,Cr=requestAnimationFrame(()=>{Cr=null,$l=!1,Dn.isFollowing()&&$S(bh(),i?220:140)})))},wh=(i,c,g,f=()=>!0)=>{let b=i.scrollTop,v=c(),B=v-b;if(Xs(),Math.abs(B)<1){An=!0,i.scrollTop=v,Nn=i.scrollTop,An=!1;return}let U=performance.now();An=!0;let $=Q=>1-Math.pow(1-Q,3),j=Q=>{if(!f()){Xs();return}let oe=c();oe!==v&&(v=oe,B=v-b);let ue=Q-U,Xe=Math.min(ue/g,1),dt=$(Xe),mt=b+B*dt;i.scrollTop=mt,Nn=i.scrollTop,Xe<1?Qs=requestAnimationFrame(j):(i.scrollTop=v,Nn=i.scrollTop,Qs=null,An=!1)};Qs=requestAnimationFrame(j)},$S=(i,c=500)=>{let g=Bo(i)-i.scrollTop;if(Math.abs(g)<1){Nn=i.scrollTop;return}if(Math.abs(g)>=WS){Xs(),An=!0,i.scrollTop=Bo(i),Nn=i.scrollTop,An=!1;return}wh(i,()=>Bo(i),c,()=>Dn.isFollowing())},Gl=()=>{if(!Kp()){Vt();return}let i=bh();An=!0,i.scrollTop=Bo(i),Nn=i.scrollTop,An=!1,Vt()},as=i=>{let c=0,g=i;for(;g&&g!==te;)c+=g.offsetTop,g=g.offsetParent;return c},US=()=>{let i=te.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??te.ownerDocument.getSelection()},Yl=()=>ZC(US(),te),Gp=()=>{if(fS()!=="last-user-turn")return!1;let i=k?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(v=>v.role==="user");if(!c)return!1;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=te.querySelector(`[data-message-id="${g}"]`);if(!f)return!1;let b=Math.min(Math.max(0,as(f)-Gi()),Bo(te));return An=!0,te.scrollTop=b,Nn=te.scrollTop,An=!1,Bn()==="follow"&&!ks(te,Vo)&&Dn.pause(),Vt(),!0},Ql=i=>{let c=Math.max(0,Math.round(i));Kn.style.height=`${c}px`,Kn.style.display=c>0?"":"none",zt&&(zt.spacerHeight=Math.max(0,i))},Xl=i=>{let c=parseFloat(getComputedStyle(te).paddingBottom)||0,g=0;for(let b of Array.from(te.children)){if(b===Kn||b.offsetHeight===0)continue;let v=as(b)+b.offsetHeight;v>g&&(g=v)}let f=te.scrollHeight-i;return g>0?Math.min(g+c,f):f},jS=()=>{if(!zt||zt.spacerHeight<=0)return;let i=Xl(zt.spacerHeight),c=Math.max(0,Math.round(te.scrollTop)+te.clientHeight-i+Vo);c<zt.spacerHeight&&(Ql(c),Vt())},co=()=>{os!==null&&(cancelAnimationFrame(os),os=null),Xs(),zt=null,Kn.style.height="0px",Kn.style.display="none"},xh=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Yp=i=>te.querySelector(`[data-message-id="${xh(i)}"]`),Sh=i=>{os!==null&&cancelAnimationFrame(os),os=requestAnimationFrame(()=>{os=null;let c=xh(i),g=te.querySelector(`[data-message-id="${c}"]`);if(!g)return;let f=as(g),b=zt?.spacerHeight??0,v=Xl(b),{targetScrollTop:B,spacerHeight:U}=im({anchorOffsetTop:f,topOffset:Gi(),viewportHeight:te.clientHeight,contentHeight:v,slack:Vo});zt={initialSpacerHeight:U,contentHeightAtAnchor:v,spacerHeight:U},Ql(U),wh(te,()=>g.isConnected?Math.max(0,as(g)-Gi()):B,220)})},En=()=>{if(Bn()!=="anchor-top"||!zt||!Gs)return;let i=Yp(Gs);if(!i)return;Xs();let c=zt.spacerHeight,g=Xl(c),{targetScrollTop:f,spacerHeight:b}=im({anchorOffsetTop:as(i),topOffset:Gi(),viewportHeight:te.clientHeight,contentHeight:g,slack:Vo});zt={initialSpacerHeight:b,contentHeightAtAnchor:g,spacerHeight:b},Ql(b),An=!0,te.scrollTop=f,Nn=te.scrollTop,An=!1,Vt()},qS=()=>{if(mr()){if(!Dn.isFollowing()||ks(te,1))return;xr(!_n);return}if(zt&&zt.initialSpacerHeight>0){let i=te.scrollHeight-zt.spacerHeight,c=ew({initialSpacerHeight:zt.initialSpacerHeight,contentHeightAtAnchor:zt.contentHeightAtAnchor,currentContentHeight:i});c!==zt.spacerHeight&&Ql(c)}Vt()},zS=i=>{let c=Bn();c==="follow"?(Mn(),xr(!0)):c==="anchor-top"&&(oa=!1,Ul=!0,jl=!1,Gs=i,Sh(i))},VS=()=>{if(Bn()==="anchor-top"){if(Ul){oa=!1;return}oa=!0,co(),Mn(),xr(!0)}},KS=96,GS=i=>{if(rs===null)return!0;let c=Yp(rs),g=Yp(i);if(!c||!g)return!0;let f=as(g)-as(c);return Gi()+f>te.clientHeight-KS},YS=i=>{if(Bn()!=="anchor-top"||!Ul||jl||Yl())return;let c=rs===null;for(let g of i){if(!c){g.id===rs&&(c=!0);continue}if(YC(g)){if(g.id===Gs||!GS(g.id))return;Gs=g.id,Sh(g.id);return}}},QS=i=>{let c=new Map;i.forEach(g=>{let f=jp.get(g.id);c.set(g.id,{streaming:g.streaming,role:g.role}),!f&&g.role==="assistant"&&(A.emit("assistant:message",g),!Ks&&(Bn()!=="anchor-top"||Cf())&&Vp()&&(wr+=1,zp(),Vt(),El(wr===1?"1 new message below.":`${wr} new messages below.`))),g.role==="assistant"&&f?.streaming&&g.streaming===!1&&A.emit("assistant:complete",g),g.variant==="approval"&&g.approval&&(f?g.approval.status!=="pending"&&A.emit("approval:resolved",{approval:g.approval,decision:g.approval.status}):A.emit("approval:requested",{approval:g.approval,message:g}))}),jp.clear(),c.forEach((g,f)=>{jp.set(f,g)})},ia=(i,c)=>{let g=c==="user"?"user":"assistant",f=o.layout?.messages?.[g],b=f?.width??"content",v=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),v?i.style.setProperty("--persona-message-row-max-width",v):i.style.removeProperty("--persona-message-row-max-width")},Yo=(i,c)=>{let g=document.createElement("div");return g.className="persona-flex",g.id=`wrapper-${i}`,g.setAttribute("data-wrapper-id",i),ia(g,c),g},XS=(i,c,g)=>{let f=document.createElement("div"),v=(()=>{let L=a.find($e=>$e.renderLoadingIndicator);if(L?.renderLoadingIndicator)return L.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),B=(L,$e)=>$e==null?!1:typeof $e=="string"?(L.textContent=$e,!0):(L.appendChild($e),!0),U=new Set,$=new Map,j=new Set,Q=a.some(L=>L.renderAskUserQuestion),oe=[],ue=[],Xe=o.enableComponentStreaming!==!1,dt=o.approval!==!1,mt=[],Qt=o.messageActions,$t=Qt?.showRegenerate===!0&&Qt.enabled!==!1&&ct.current?.isStreaming()!==!0?Sv(c):null,Pt=Qt?.showEdit===!0&&Qt.enabled!==!1,an=Qt?.showQuote===!0&&Qt.enabled!==!1,et=null,ln=o.features?.reasoningDisplay?.completedVisibility,Lo=L=>ln==="removed"?!0:ln==="removed-when-short"?Zb(L,o.features?.reasoningDisplay?.shortThinkThreshold):!1,or=o.features?.toolCallDisplay?.completedVisibility==="removed",po=L=>L.variant==="reasoning"&&L.reasoning?.status==="complete"?Lo(L.reasoning):or&&L.variant==="tool"&&L.toolCall?.status==="complete";if(c.forEach(L=>{if(po(L))return;if(U.add(L.id),$.set(L.id,L.role),es===L.id&&vr){let we=Yo(L.id,L.role);we.setAttribute("data-persona-message-edit-stub","true"),we.setAttribute("data-preserve-runtime","true"),f.appendChild(we),et={messageId:L.id,element:vr.element};return}let $e=Q&&Rr(L),Ae=dt&&L.variant==="approval"&&!!L.approval,re=!$e&&L.role==="assistant"&&!L.variant&&Xe&&np(L);!Ae&&br.has(L.id)&&(i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),br.delete(L.id)),!re&&Zr.has(L.id)&&(i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),Zr.delete(L.id));let kt=Rr(L)?`:${L.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${L.agentMetadata?.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ut={canRegenerate:$t===L.id,canEdit:Pt&&Eg(L),canQuote:an&&!L.variant&&(L.content?.trim().length??0)>0},nn=`${Ut.canRegenerate?"r":""}${Ut.canEdit?"e":""}${Ut.canQuote?"q":""}`,jt=qC(L,ns)+kt+`:${nn}`,Kt=$e||Ae||re?null:VC(Nt,L.id,jt);if(Kt){f.appendChild(Kt.cloneNode(!0)),Rr(L)&&L.toolCall?.id&&L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(j.add(L.toolCall.id),Fa(L,o,_e.composerOverlay));return}let Lt=null,cn=a.find(we=>!!(L.variant==="reasoning"&&we.renderReasoning||L.variant==="tool"&&we.renderToolCall||!L.variant&&we.renderMessage)),Re=o.layout?.messages;if(Rr(L)&&L.agentMetadata?.askUserQuestionAnswered===!0){Vs.delete(L.id),i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ci(L)&&Br(o).enabled)return;if(Rr(L)&&o.features?.askUserQuestion?.enabled!==!1){let we=a.find(dn=>typeof dn.renderAskUserQuestion=="function");if(we&&ct.current){let dn=Vs.get(L.id),kr=dn!==jt,Pn=null;if(kr){let{payload:pt,complete:We}=Hr(L),rr=L.id,Ot=()=>ct.current?.getMessages().find(Ln=>Ln.id===rr);Pn=we.renderAskUserQuestion({message:L,payload:pt,complete:We,resolve:Ln=>{let Ia=Ot();Ia&&ct.current?.resolveAskUserQuestion(Ia,Ln)},dismiss:()=>{let Ln=Ot();Ln?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(Ln),ct.current?.resolveAskUserQuestion(Ln,"(dismissed)"))},config:o})}let kn=dn!=null;if(kr&&Pn===null&&!kn){L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(j.add(L.toolCall.id),Fa(L,o,_e.composerOverlay));return}let at=Yo(L.id,L.role);at.setAttribute("data-ask-plugin-stub","true"),at.setAttribute("data-preserve-runtime","true"),f.appendChild(at),oe.push({messageId:L.id,fingerprint:jt,bubble:Pn});return}else{L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(j.add(L.toolCall.id),Fa(L,o,_e.composerOverlay));return}}else if(Ae){let we=P();if(!we){f.appendChild(Yo(L.id,L.role));return}let dn=a.find(at=>typeof at.renderApproval=="function")??y,Pn=br.get(L.id)!==jt,kn=null;if(Pn&&dn?.renderApproval){let at=L.id,pt=(We,rr)=>{let Ot=ct.current?.getMessages().find(Ln=>Ln.id===at);Ot?.approval&&(Ot.approval.toolType==="webmcp"?ct.current?.resolveWebMcpApproval(Ot.id,We):ct.current?.resolveApproval(Ot.approval,We,rr))};kn=dn.renderApproval({message:L,defaultRenderer:()=>we.createApprovalBubble(L,o),config:o,approve:We=>pt("approved",We),deny:We=>pt("denied",We)})}if(Pn&&kn===null)i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),br.delete(L.id),Lt=we.createApprovalBubble(L,o);else{let at=Yo(L.id,L.role);at.setAttribute("data-approval-plugin-stub","true"),at.setAttribute("data-preserve-runtime","true"),f.appendChild(at),mt.push({messageId:L.id,fingerprint:jt,bubble:kn});return}}else if(cn)if(L.variant==="reasoning"&&L.reasoning&&cn.renderReasoning){if(!vn)return;Lt=cn.renderReasoning({message:L,defaultRenderer:()=>Lm(L,o),config:o})}else if(L.variant==="tool"&&L.toolCall&&cn.renderToolCall){if(!q)return;Lt=cn.renderToolCall({message:L,defaultRenderer:()=>Rm(L,o),config:o})}else cn.renderMessage&&(Lt=cn.renderMessage({message:L,defaultRenderer:()=>{let we=hl(L,g,Re,o.messageActions,Os,{loadingIndicatorRenderer:v,widgetConfig:o,actionEligibility:Ut});return L.role!=="user"&&R(we,L,o,k),we},config:o}));if(!Lt&&re){let we=Qm(L);if(we){let dn=Zr.get(L.id),kr=dn!==jt,Pn=o.wrapComponentDirectiveInBubble!==!1&&Do.getOptions(we.component)?.bubbleChrome!==!1,kn=null;if(kr){let at=Ym(we,{config:o,message:L,transform:g});if(at&&we.component==="PersonaArtifactInline"){let pt=at.hasAttribute("data-artifact-inline")?at:at.querySelector("[data-artifact-inline]"),We=pt?.getAttribute("data-artifact-inline")??"",rr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(We):We,Ot=We?i.querySelector(`#wrapper-${L.id}`)?.querySelector(`[data-artifact-inline="${rr}"]`)??null:null;pt&&Ot&&Ot!==pt&&lr()?.hasLiveInlineArtifactBlock(Ot)&&(pt===at?at=Ot:pt.replaceWith(Ot))}if(at)if(Pn){let pt=document.createElement("div");if(pt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),pt.id=`bubble-${L.id}`,pt.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let We=document.createElement("div");We.className="persona-mb-3 persona-text-sm persona-leading-relaxed",We.innerHTML=g({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),pt.appendChild(We)}pt.appendChild(at),kn=pt}else{let pt=document.createElement("div");if(pt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",pt.id=`bubble-${L.id}`,pt.setAttribute("data-message-id",L.id),pt.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let We=document.createElement("div");We.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",We.innerHTML=g({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),pt.appendChild(We)}pt.appendChild(at),kn=pt}}if(kn||dn!=null){let at=Yo(L.id,L.role);at.setAttribute("data-component-directive-stub","true"),at.setAttribute("data-preserve-runtime","true"),f.appendChild(at),ue.push({messageId:L.id,fingerprint:jt,bubble:kn});return}}}if(!Lt)if(L.variant==="reasoning"&&L.reasoning){if(!vn)return;Lt=Lm(L,o)}else if(L.variant==="tool"&&L.toolCall){if(!q)return;Lt=Rm(L,o)}else if(L.variant==="approval"&&L.approval){if(o.approval===!1)return;let we=P();if(!we)return;Lt=we.createApprovalBubble(L,o)}else{let we=o.layout?.messages;we?.renderUserMessage&&L.role==="user"?Lt=we.renderUserMessage({message:L,config:o,streaming:!!L.streaming}):we?.renderAssistantMessage&&L.role==="assistant"?Lt=we.renderAssistantMessage({message:L,config:o,streaming:!!L.streaming}):Lt=hl(L,g,we,o.messageActions,Os,{loadingIndicatorRenderer:v,widgetConfig:o,actionEligibility:Ut}),L.role!=="user"&&Lt&&R(Lt,L,o,k)}let De=Yo(L.id,L.role);De.appendChild(Lt),KC(Nt,L.id,jt,De),f.appendChild(De)}),_e.composerOverlay&&_e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach($e=>{let Ae=$e.getAttribute("data-persona-ask-sheet-for");Ae&&!j.has(Ae)&&Es(_e.composerOverlay,Ae)}),o.features?.toolCallDisplay?.grouped){let L=[],$e=[],Ae=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(re=>{if(re.variant==="tool"&&re.toolCall&&q){if(or&&re.toolCall.status==="complete")return;$e.push(re);return}re.variant==="reasoning"&&(!vn||re.reasoning?.status==="complete"&&Lo(re.reasoning))||(($e.length>1||Ae&&$e.length>0)&&L.push($e),$e=[])}),($e.length>1||Ae&&$e.length>0)&&L.push($e),L.forEach(re=>{let kt=re.map(Re=>Array.from(f.children).find(De=>De instanceof HTMLElement&&De.getAttribute("data-wrapper-id")===Re.id)).filter(Re=>!!Re);if(kt.length<(Ae?1:2))return;let Ut=Yo(`tool-group-${re[0].id}`,"assistant");Ut.setAttribute("data-persona-tool-group-row","true");let nn=document.createElement("div");nn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",nn.setAttribute("data-persona-tool-group","true");let jt=document.createElement("div");jt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",jt.id=`tool-group-summary-${re[0].id}`;let Kt=`Called ${re.length} ${re.length===1?"tool":"tools"}`,Lt=o.toolCall?.renderGroupedSummary?.({messages:re,toolCalls:re.map(Re=>Re.toolCall).filter(Re=>!!Re),defaultSummary:Kt,config:o});B(jt,Lt)||(jt.textContent=Kt);let cn=document.createElement("div");cn.className="persona-tool-group-stack persona-flex persona-flex-col",cn.id=`tool-group-stack-${re[0].id}`,cn.setAttribute("data-persona-tool-group-stack","true"),nn.appendChild(jt),Ae||nn.appendChild(cn),Ut.appendChild(nn),kt[0].before(Ut),kt.forEach((Re,De)=>{if(Ae){Re.remove();return}Re.style.setProperty("--persona-message-row-max-width","100%");let we=document.createElement("div");we.className="persona-tool-group-item persona-relative",we.setAttribute("data-persona-tool-group-item","true"),De<kt.length-1&&we.setAttribute("data-persona-tool-group-connector","true"),we.appendChild(Re),cn.appendChild(we)})})}GC(Nt,U);let La=L=>L.variant==="tool"&&!q||L.variant==="reasoning"&&!vn||po(L),Cs=c.some(L=>L.role==="assistant"&&L.streaming&&!La(L)),uo=c.length-1;for(;uo>=0&&La(c[uo]);)uo--;let tn=uo>=0?c[uo]:void 0,go=uo<c.length-1,mi=tn?.role==="assistant"&&!tn.streaming&&tn.variant!=="approval"&&!go;if(_n&&c.some(L=>L.role==="user")&&!Cs&&!mi){let L={config:o,streaming:!0,location:"standalone",defaultRenderer:Oi},$e=a.find(re=>re.renderLoadingIndicator),Ae=null;if($e?.renderLoadingIndicator&&(Ae=$e.renderLoadingIndicator(L)),Ae===null&&o.loadingIndicator?.render&&(Ae=o.loadingIndicator.render(L)),Ae===null&&(Ae=Oi()),Ae){let re=document.createElement("div"),kt=o.loadingIndicator?.showBubble!==!1,Ut=o.layout?.messages?.layout??"bubble";re.className=kt?fl("assistant",Ut).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),re.setAttribute("data-typing-indicator","true"),kt&&(re.style.color="var(--persona-message-assistant-text, var(--persona-text))",Ut!=="flat"&&(re.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",re.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),re.appendChild(Ae);let nn=Yo("typing-indicator","assistant");nn.appendChild(re),f.appendChild(nn)}}if(!_n&&c.length>0){let L=c[c.length-1],$e={config:o,lastMessage:L,messageCount:c.length},Ae=a.find(kt=>kt.renderIdleIndicator),re=null;if(Ae?.renderIdleIndicator&&(re=Ae.renderIdleIndicator($e)),re===null&&o.loadingIndicator?.renderIdle&&(re=o.loadingIndicator.renderIdle($e)),re){let kt=document.createElement("div"),Ut=o.loadingIndicator?.showBubble!==!1;kt.className=Ut?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),kt.setAttribute("data-idle-indicator","true"),kt.appendChild(re);let nn=Yo("idle-indicator","assistant");nn.appendChild(kt),f.appendChild(nn)}}if(wb(f),Pd(i,f),sg(i),et){let{messageId:L,element:$e}=et,Ae=i.querySelector(`#wrapper-${L}`);Ae&&$e.parentElement!==Ae&&(ia(Ae,$.get(L)??"user"),Ae.replaceChildren($e))}if(oe.length>0)for(let{messageId:L,fingerprint:$e,bubble:Ae}of oe){let re=i.querySelector(`#wrapper-${L}`);re&&(ia(re,$.get(L)??"assistant"),Ae!==null&&(re.replaceChildren(Ae),re.setAttribute("data-bubble-fp",$e),Vs.set(L,$e)))}if(Vs.size>0)for(let L of Vs.keys())U.has(L)||Vs.delete(L);if(ue.length>0)for(let{messageId:L,fingerprint:$e,bubble:Ae}of ue){let re=i.querySelector(`#wrapper-${L}`);re&&(ia(re,$.get(L)??"assistant"),Ae!==null&&(re.replaceChildren(Ae),re.setAttribute("data-bubble-fp",$e),Zr.set(L,$e)))}if(Zr.size>0)for(let L of Zr.keys())U.has(L)||Zr.delete(L);if(mt.length>0)for(let{messageId:L,fingerprint:$e,bubble:Ae}of mt){let re=i.querySelector(`#wrapper-${L}`);re&&(ia(re,$.get(L)??"assistant"),Ae!==null&&(re.replaceChildren(Ae),re.setAttribute("data-bubble-fp",$e),br.set(L,$e)))}if(br.size>0)for(let L of br.keys())U.has(L)||br.delete(L)},Qp=!1,Jl=()=>{Qp||(Qp=!0,eg().catch(()=>{Qp=!1}))},Yn=(i,c,g)=>{c.length>0&&Jl(),XS(i,c,g),jf()},aa=null,JS=()=>{if(aa)return;let i=g=>{let f=g.composedPath();f.includes(Ge)||Yt&&f.includes(Yt)||gt(!1,"user")};aa=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},Ah=()=>{if(!aa)return;(e.ownerDocument??document).removeEventListener("pointerdown",aa,!0),aa=null};me.push(()=>Ah());let la=null,ZS=()=>{if(la)return;let i=g=>{g.key==="Escape"&&(g.isComposing||gt(!1,"user"))};la=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Mh=()=>{if(!la)return;(e.ownerDocument??document).removeEventListener("keydown",la,!0),la=null};me.push(()=>Mh());let ca=!1,Eh=new Set,eA=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Js=()=>{if(!be())return;let i=_e.peekBanner,c=_e.peekTextNode;if(!i||!c)return;if(ve){i.classList.remove("persona-pill-peek--visible");return}let g=k?.getMessages()??[],f;for(let $t=g.length-1;$t>=0;$t--){let Pt=g[$t];if(Pt.role==="assistant"&&Pt.content){f=Pt;break}}if(!f){i.classList.remove("persona-pill-peek--visible");return}let b=f.content,v=!!f.streaming,B=eA(),U=kd(B),$=U.type!=="none"?Fp(U.type,B?.plugins):null,j=$?.isAnimating?.(f)===!0,Q=$!==null&&(v||j);Q&&$&&!Eh.has($.name)&&(dl($,e),Eh.add($.name));let oe=Q&&$?.containerClass?$.containerClass:null,ue=c.dataset.personaPeekStreamClass??null;ue&&ue!==oe&&(c.classList.remove(ue),delete c.dataset.personaPeekStreamClass),oe&&ue!==oe&&(c.classList.add(oe),c.dataset.personaPeekStreamClass=oe),Q?(c.style.setProperty("--persona-stream-step",`${U.speed}ms`),c.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let Xe=Q?Id(b,U.buffer,$,f,v):b;if(Q&&U.placeholder==="skeleton"&&v&&(!Xe||!Xe.trim())){let $t=document.createElement("div"),Pt=cl();Pt.classList.add("persona-pill-peek__skeleton"),$t.appendChild(Pt),Pd(c,$t)}else{let $t=Math.max(0,Xe.length-100),Pt=Xe.length>100?Xe.slice(-100):Xe,an=Ir(Pt);if(!Q||!$){let et=Xe.length>100?`\u2026${Pt}`:Pt;c.textContent!==et&&(c.textContent=et)}else{let et=an;($.wrap==="char"||$.wrap==="word")&&(et=ll(an,$.wrap,`peek-${f.id}`,{skipTags:$.skipTags,startIndex:$t}));let ln=document.createElement("div");if(ln.innerHTML=et,$.useCaret&&Pt.length>0){let Lo=Rd(),or=ln.querySelectorAll(".persona-stream-char, .persona-stream-word"),po=or[or.length-1];po?.parentNode?po.parentNode.insertBefore(Lo,po.nextSibling):ln.appendChild(Lo)}Pd(c,ln),$.onAfterRender?.({container:c,bubble:i,messageId:f.id,message:f,speed:U.speed,duration:U.duration})}}let Qt=_n||ca;i.classList.toggle("persona-pill-peek--visible",Qt)};if(be()){let i=_e.peekBanner;if(i){let f=b=>{b.preventDefault(),b.stopPropagation(),gt(!0,"user")};i.addEventListener("pointerdown",f),me.push(()=>{i.removeEventListener("pointerdown",f)})}let c=()=>{ca||(ca=!0,Js())},g=()=>{ca&&(ca=!1,Js())};Se.addEventListener("pointerenter",c),Se.addEventListener("pointerleave",g),me.push(()=>{Se.removeEventListener("pointerenter",c),Se.removeEventListener("pointerleave",g)}),Yt&&(Yt.addEventListener("pointerenter",c),Yt.addEventListener("pointerleave",g),me.push(()=>{Yt.removeEventListener("pointerenter",c),Yt.removeEventListener("pointerleave",g)}))}let tA=i=>{let c=o.launcher?.composerBar??{},g=c.expandedSize??"anchored",f=c.bottomOffset??"16px",b=c.collapsedMaxWidth,v=c.expandedMaxWidth??"880px",B=c.expandedTopOffset??"5vh",U=c.modalMaxWidth??"880px",$=c.modalMaxHeight??"min(90vh, 800px)",j="calc(100vw - 32px)",Q="var(--persona-pill-area-height, 80px)",oe=Ge.style;if(oe.left="",oe.right="",oe.top="",oe.bottom="",oe.transform="",oe.width="",oe.maxWidth="",oe.height="",oe.maxHeight="",Yt){let ue=Yt.style;ue.bottom=f,ue.width=b??""}if(i&&g!=="fullscreen"){if(g==="modal"){oe.top="50%",oe.left="50%",oe.transform="translate(-50%, -50%)",oe.bottom="auto",oe.right="auto",oe.width=U,oe.maxWidth=j,oe.maxHeight=$,oe.height=$;return}oe.left="50%",oe.transform="translateX(-50%)",oe.bottom=`calc(${f} + ${Q})`,oe.top=B,oe.width=v,oe.maxWidth=j}},da=()=>{if(ve&&Jl(),!Be())return;if(be()){let j=(o.launcher?.composerBar??{}).expandedSize??"anchored",Q=ve?"expanded":"collapsed";Ge.dataset.state=Q,Ge.dataset.expandedSize=j,Yt&&(Yt.dataset.state=Q,Yt.dataset.expandedSize=j),Ge.style.removeProperty("display"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),tA(ve),de.style.display=ve?"flex":"none",Kr(),ve?(JS(),ZS()):(Ah(),Mh()),Js();return}let i=St(o),c=e.ownerDocument.defaultView??window,g=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,b=c.innerWidth<=g,v=f&&b&&ce,B=qn(o).reveal;ve?(Ge.style.removeProperty("display"),Ge.style.display=i?"flex":"",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-95","persona-opacity-0"),Se.classList.add("persona-scale-100","persona-opacity-100"),Et?(Et.setPanelOpen(!0),Et.element.style.display="none"):un&&(un.style.display="none")):(i?i&&(B==="overlay"||B==="push")&&!v?(Ge.style.removeProperty("display"),Ge.style.display="flex",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ge.style.setProperty("display","none","important"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ge.style.display="",Ge.classList.add("persona-pointer-events-none","persona-opacity-0"),Se.classList.remove("persona-scale-100","persona-opacity-100"),Se.classList.add("persona-scale-95","persona-opacity-0")),Et?(Et.setPanelOpen(!1),Et.element.style.display=i?"none":""):un&&(un.style.display=i?"none":""))},gt=(i,c="user")=>{if(!Be()||ve===i)return;let g=ve;ve=i,da();let f=(()=>{let v=o.launcher?.sidebarMode??!1,B=e.ownerDocument.defaultView??window,U=o.launcher?.mobileFullscreen??!0,$=o.launcher?.mobileBreakpoint??640,j=B.innerWidth<=$,Q=St(o)&&U&&j,oe=be()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return v||U&&j&&ce||Q||oe})();if(ve&&f){if(!Ao){let v=e.getRootNode(),B=v instanceof ShadowRoot?v.host:e.closest(".persona-host");B&&(Ao=cm(B,o.launcher?.zIndex??rn))}Mo||(Mo=dm(e.ownerDocument))}else ve||(Ao?.(),Ao=null,Mo?.(),Mo=null);ve&&(Ta(),Gp()||(Bn()==="follow"?xr(!0):Gl()));let b={open:ve,source:c,timestamp:Date.now()};ve&&!g?A.emit("widget:opened",b):!ve&&g&&A.emit("widget:closed",b),A.emit("widget:state",{open:ve,launcherEnabled:ce,voiceActive:ze.active,streaming:k.isStreaming()})},Sr={inputDisabled:!1,sendDisabled:!1},Eo=()=>Sr.inputDisabled,Xp=()=>In(o.voiceRecognition?.provider)&&!!k&&(k.isBargeInActive()||["listening","processing","speaking"].includes(k.getVoiceStatus())),ls=()=>Sr.inputDisabled||Sr.sendDisabled,nA=()=>(Sr.inputDisabled?Sr.inputReason:void 0)??(Sr.sendDisabled?Sr.sendReason:void 0);function Jp(){if(!Me)return;if(Ce.getState().phase==="streaming"){Me.disabled=!1;return}let i=Ze?!Ze.isReady():!1;Me.disabled=ls()||i}function Zl(){if(!vo)return;let i=Ce.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 oA(){let i=nA();if(be()){let c=ro??Le;i?c.setAttribute("title",i):c.removeAttribute("title"),Le.toggleAttribute(zi,!!i);return}if(i){st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.setAttribute(zi,""),st.textContent=i;return}if(st.hasAttribute(zi)&&(st.removeAttribute("role"),st.removeAttribute("aria-live"),st.removeAttribute(zi),p)){let c=k.getStatus();Sl(st,yf(c),o.statusIndicator??{},c)}}function Zp(){let i=Fg(o.composer?.inputDisabled),c=Fg(o.composer?.sendDisabled);Sr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},Ce.setInputDisabled(i.disabled),Ce.setSendDisabled(c.disabled);let g=Ce.getState().phase==="streaming",f=i.disabled,b=g||f;ae&&(ae instanceof HTMLTextAreaElement?ae.disabled=f:ae.setAttribute("contenteditable",f?"false":"true"),ae.setAttribute("aria-disabled",f?"true":"false")),xt&&(xt.disabled=f),yt&&(yt.disabled=f);for(let v of Wt?.affordanceButtons??[])v.querySelectorAll("button").forEach(B=>{B.disabled=f});ne&&(ne.disabled=f||g&&!Xp()),Qr.forEach(v=>{v.elements.forEach(B=>{B.toggleAttribute("data-disabled",b),B instanceof HTMLButtonElement||B.setAttribute("aria-disabled",b?"true":"false")}),v.buttons.forEach(B=>{B.disabled=b})}),ru.forEach(v=>{v.toggleAttribute("data-disabled",b),v instanceof HTMLButtonElement?v.disabled=b:v.setAttribute("aria-disabled",b?"true":"false"),v.querySelectorAll("button").forEach(B=>{B.disabled=b})}),Le.dataset.personaComposerStreaming=g?"true":"false",Le.dataset.personaComposerInputDisabled=f?"true":"false",Le.dataset.personaComposerSendDisabled=ls()?"true":"false",Le.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(v=>{(v instanceof HTMLButtonElement||v instanceof HTMLInputElement||v instanceof HTMLTextAreaElement||v instanceof HTMLSelectElement)&&(v.disabled=g)}),Jp(),oA()}let pa=i=>{Ce.setStreaming(i),bf(i?"stop":"send"),Zp()},cs=()=>{ze.active||ae&&ae.focus()};A.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>cs(),200)});let ds=null,ua=!1,eu=!wn.hidden,Ar=null,tu=!M,ec=null;me.push(()=>{ec?.cancel(),ec=null});let rA=i=>{let c=Pw(i);if(c===Tl)return;Tl=c,e.setAttribute("data-persona-conversation-state",c);let g=Ap();kl(),tu&&(ec?.cancel(),ec=Ew(Le,c==="active"?g:Ap(),c==="active"?"drop":"rise")),En()},Th=null,Ph,kh=null,Zs=null,nu=!1,ga=i=>{let c=_o(o),g=`${c.variant}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(g!==Th||c.icon!==Ph)&&(Th=g,Ph=c.icon,Dd({host:wn,iconHolder:aS,kicker:lS,title:cS,subtitle:dS,starterSuggestions:Cp},c));let f=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;f!==kh&&(kh=f,Nd(Wn,c.message,o));let b=i??(k?k.getMessages():o.initialMessages);rA(b);let v=ua,B=!v&&Is(c,b),U=B!==eu;if(eu=B,Zs){Ar?.cancel(),Ar=null,v!==nu&&(nu=v,v?xm(te,wn,null):wm(te,wn,Zs)),Bi(te,wn,!v);return}if(U&&!B&&!v&&c.dismiss==="on-first-message"&&tu){Ar=Mw(wn,j=>{Ar===j&&(Ar=null),!eu&&!Zs&&(Bi(te,wn,!1),En()),j?.cancel()});return}if(Ar){if(!B&&!v)return;Ar.cancel(),Ar=null}let $=!wn.hidden;Bi(te,wn,B),!B&&$&&En()},ou=[],ru=[],su=!1,Lh=null,Ih,Rh=()=>{ru.length=0;let i=ou.splice(0,ou.length);for(let c of i)try{c()}catch(g){console.warn("[persona] renderWelcome cleanup threw",g)}};me.push(Rh);let sA=(i,c)=>{let g=um(i,c);if(!g)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),E("span");let f=o.suggestions?.starters,b=gm({item:{...g,behavior:g.behavior??f?.behavior??"send"},index:c,surface:"starter",source:"config",variant:f?.variant??"card",streaming:p?k.isStreaming():!1,config:o,plugins:a,chipsConfig:o.suggestionChipsConfig,session:k,getTextarea:()=>ae,eventTarget:wn,submitPrompt:Tc});return ru.push(b),b},iu=()=>{if(su)return;su=!0;let i=_o(o);Lh=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,Ih=i.icon;try{Rh(),xm(te,wn,Zs),Zs=null,nu=!1;let c=k?k.getMessages():o.initialMessages,g=Is(i,c),f=0,b=null;for(let v of a)if(v.renderWelcome&&(b=v.renderWelcome({config:i,variant:i.variant,visible:g,defaultRenderer:()=>wn,sendMessage:B=>{if(!k||k.isStreaming())return;let U=B.trim();U&&k.sendMessage(U)},requestRender:()=>iu(),renderStarter:B=>sA(B,f++),storage:u(v.id),onCleanup:B=>{ou.push(B)}}),b))break;b&&b!==wn&&(Zs=b,wm(te,wn,b))}finally{su=!1}ga()},iA=()=>{let i=_o(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Lh&&i.icon===Ih||iu()},tc=()=>{ga(),$s||(ae.placeholder=cC(Ce.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!k?.isStreaming()&&(Me.textContent=o.copy?.sendButtonLabel??"Send")),ae.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ae.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},aA=!!o.setStoredConversationId,ei=i=>se(c=>{let g={...c};return delete g[i],g}),nc=i=>{let c=Z[i];return typeof c=="string"?c:null},Hh=()=>{let i=Z.durableResume;if(!i||typeof i!="object")return null;let c=i;return typeof c.executionId=="string"&&c.executionId.length>0&&typeof c.after=="string"&&c.after.length>0?{executionId:c.executionId,after:c.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>nc("sessionId"),setStoredSessionId:i=>{se(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ei("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>nc("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{se(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ei("conversationId"))});let Wh=()=>o.clientToken??null,Oh=i=>lx(i,Y(),o.persistState===!1),Bh=Wh(),Qn=Bh?Oh(Bh):null,Qo={...Qn?{visitorStore:Qn}:{},historyBootstrapReady:W,getStoredMessageCursor:()=>nc("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){ei("historyMessageCursor");return}se(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=Z.pendingDisplayProjections;if(!i||typeof i!="object")return null;let c=i;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(g=>typeof g=="string")}},setPendingDisplayProjections:i=>{if(!i){ei("pendingDisplayProjections");return}se(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:Hh,setStoredResumableHandle:i=>{if(!i){ei("durableResume");return}se(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>ie&&Hh()!==null,...aA?{}:{getStoredConversationRevision:()=>nc("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){ei("conversationRevision");return}se(c=>({...c,conversationRevision:i}))}}};if(ie){let i=o.onExecutionState,c=e.ownerDocument.defaultView,g=!1,f=()=>g=!0,b=()=>g=!1;c?.addEventListener("pagehide",f),c?.addEventListener("pageshow",b),me.push(()=>{c?.removeEventListener("pagehide",f),c?.removeEventListener("pageshow",b)}),o={...o,reconnectStream:o.reconnectStream??(v=>k.getClient().reconnectClientTokenStream(v)),onExecutionState:v=>{(v||!g)&&Qo.setStoredResumableHandle?.(v?{executionId:v.executionId,after:v.lastEventId}:null),i?.(v)}}}let lA=()=>{let i=Wh();if(i&&Qn?.matches(i,Y(),o.persistState===!1)||!i&&!Qn)return;Qn?.destroy(),Qn=i?Oh(i):null;let c={...Qo};Qn?c.visitorStore=Qn:delete c.visitorStore,Qo=c,k.setHistoryInternals(Qo)},ps=null,cA=()=>{ps==null&&(ps=setInterval(()=>{let i=Pe.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(ps),ps=null;return}let c=Date.now();i.forEach(g=>{let f=Number(g.getAttribute("data-tool-elapsed"));f&&(g.textContent=Qc(c-f))})},100))},au=(i,c)=>{if(Object.is(i,c))return!0;if(i===null||c===null||typeof i!="object"||typeof c!="object")return!1;if(Array.isArray(i)||Array.isArray(c))return!Array.isArray(i)||!Array.isArray(c)||i.length!==c.length?!1:i.every((B,U)=>au(B,c[U]));let g=i,f=c,b=Object.keys(g),v=Object.keys(f);return b.length===v.length&&b.every(B=>Object.prototype.hasOwnProperty.call(f,B)&&au(g[B],f[B]))},_h=i=>{let{content:c,rawContent:g,llmContent:f,...b}=i;return b},lu=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!np(i),dA=(i,c,g)=>{if(i.length!==c.length)return!1;let f=i[g.index],b=c[g.index];return!f||!b||f.id!==g.id||b.id!==g.id?!1:(!Object.is(f.content,b.content)||!Object.is(f.rawContent,b.rawContent)||!Object.is(f.llmContent,b.llmContent))&&lu(f)&&lu(b)&&au(_h(f),_h(b))},cu=null,ti=null,us=null,Xo=null,du=null,pA=i=>{if(!ie)return Ys(i);du=i,queueMicrotask(()=>{du===i&&(du=null,Ys(i))})},oc=i=>{cu=i;let c,g;ti=null;for(let b=i.length-1;b>=0;b-=1){let v=i[b];if(!c&&v.role==="user"&&(c=v),!g&&v.role==="assistant"&&(g=v),!ti&&lu(v)&&(ti={index:b,id:v.id}),c&&g&&ti)break}Yn(Pe,i,ut),lr()?.updateInlineArtifactBlocks(Pe,Gn.artifacts,{suppressTransition:_n}),cA(),ga(i),zs(i),xr(!_n),QS(i),i.length===0&&(co(),oa=!0,Ul=!1,Gs=null,jl=!1),!$p||Ks?($p=!0,rs=c?.id??null,Up=g?.id??null):c&&c.id!==rs?(rs=c.id,zS(c.id)):g&&g.id!==Up&&VS(),g&&(Up=g.id),YS(i);let f=ze.lastUserMessageId;c&&c.id!==f&&(ze.lastUserMessageId=c.id,A.emit("user:message",c)),ze.lastUserMessageWasVoice=!!c?.viaVoice,pA(i),Js()},pu=()=>{Xo!==null&&(cancelAnimationFrame(Xo),Xo=null);let i=us;us=null,i&&oc(i)},Dh=()=>{Xo!==null&&cancelAnimationFrame(Xo),Xo=null,us=null},uA=i=>{let c=us??cu;if(_n&&c&&ti&&dA(c,i,ti)){us=i,Xo===null&&(Xo=requestAnimationFrame(()=>{Xo=null;let g=us;us=null,g&&oc(g)}));return}if(i.length===0){Dh(),oc(i);return}pu(),oc(i)};k=new Qa(o,{onMessagesChanged(i){uA(i)},onStatusChanged(i){let c=o.statusIndicator??{};Sl(st,(f=>f==="idle"?c.idleText??qt.idle:f==="connecting"?c.connectingText??qt.connecting:f==="connected"?c.connectedText??qt.connected:f==="error"?c.errorText??qt.error:f==="paused"?c.pausedText??qt.paused:f==="resuming"?c.resumingText??qt.resuming:qt[f])(i),c,i),vp()},onStreamingChanged(i){i||(k?.getMessages().length===0?Dh():pu()),_n=i,pa(i),vp(),k&&Yn(Pe,k.getMessages(),ut),i||(xr(!0),jS(),dh=!0,k&&ph(k.getMessages(),Br(o))),Vt(),El(i?"Responding\u2026":"Response complete."),Js()},onVoiceStatusChanged(i){if(A.emit("voice:status",{status:i,timestamp:Date.now()}),!(i!=="disconnected"&&!In(o.voiceRecognition?.provider)))switch(i){case"listening":nr(),ui();break;case"processing":nr(),mM();break;case"speaking":nr(),fM();break;default:i==="idle"&&k.isBargeInActive()?(nr(),ui(),ne?.setAttribute("aria-label","End voice session")):(ze.active=!1,nr(),Go("system"),lo());break}},onArtifactsState(i){Gn=i,i.artifacts.length===0&&(Us=!1),lr()?.updateInlineArtifactBlocks(Pe,i.artifacts,{suppressTransition:_n}),ao(),Ys()},onHistoryStateChanged(i){ff(i)},onHistoryNotice(i){hf(i)},onReconnect(i){let{executionId:c,lastEventId:g}=i.handle;i.phase==="paused"?A.emit("stream:paused",{executionId:c,after:g}):i.phase==="resuming"?A.emit("stream:resuming",{executionId:c,after:g,attempt:i.attempt??1}):A.emit("stream:resumed",{executionId:c,after:g})}},Qo),ct.current=k,me.push(()=>k.cancel()),me.push(()=>{k.destroy(),Qn?.destroy(),Qn=null});let uu=null;if(k.onReadAloudChange((i,c)=>{$f=i,Uf=c,jf();let g=i??uu;i&&(uu=i);let f=g?k.getMessages().find(b=>b.id===g)??null:null;A.emit("message:read-aloud",{messageId:g,message:f,state:c,timestamp:Date.now()}),c==="idle"&&(uu=null)}),p=!0,$p=!0,o.voiceRecognition?.enabled===!0&&In(o.voiceRecognition.provider))try{k.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let gA=720,mA=250,Qe=Km(o.features?.history?.copy),Fn=null,gu=!1,it=null,rc=null,sc="conversation",mu=null,pn=null,To=null,ic=k.getHistoryState(),fu=null,ma=0,hu=null,ac=null,lc=null,yu=`persona-history-${Math.random().toString(36).slice(2,8)}`,bu=()=>o.features?.history?.enabled===!0,Po=()=>bu()&&!!Fn&&!gu,Nh=()=>{let i=k.getStatus();return _n||i==="paused"||i==="resuming"},vu=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",g=Fn?.capabilities.scopes;return!g||g.includes(c)?c:g[0]??c},ni=()=>rc?.scope??vu(),Fh=()=>k.getClientSession()?.targetId??null,$h=i=>`${i.state}:${"reason"in i?i.reason:""}`,fA=i=>{let c=$h(i);c!==fu&&(fu=c,A.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},cc=i=>{i&&(Uo.textContent="",Uo.textContent=i)},Uh=null,jh=null,hA=()=>{if(!bu())return null;let i=ux();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(Uh!==c&&(Uh=c,jh=c()),jh):k.isClientTokenMode()?gx({client:k.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:g=>k.bindActivatedSession(g),getClient:()=>k.getClient()}):null},qh=()=>{ac?.(),ac=null,lc?.(),lc=null,gu=!1,Fn=hA();let i={...Qo};Fn?i.historyProvider=Fn:delete i.historyProvider,Qo=i,k.setHistoryInternals(Qo),Fn&&(ac=Fn.subscribeAvailability?.(c=>{gu=!c,c||Tn({restoreFocus:!1}),Er()})??null,lc=Fn.subscribeIdentityStatus(c=>fA(c)),fu=$h(Fn.getIdentityStatus()))},Cu=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!ce||St(o)))return"panel";let c=So??de;return(c.getBoundingClientRect().width||c.clientWidth)>=gA?"rail":"panel"},Xn=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},dc="data-persona-history-suppressed",$n=null,Mr=null,gs=null,fa=null,wu=null,zh="",Vh=()=>Ee===wu?zh:o.layout?.showHeader===!1?"none":"",yA=()=>_t==="panel"&&!!gs&&fa===gs.element&&o.layout?.showHeader!==!1&&Vh()!=="none",bA=()=>{for(let i of Array.from(Ee.children))i!==$n&&i.setAttribute(dc,"")},vA=()=>{for(let i of Array.from(de.querySelectorAll(`[${dc}]`)))i.removeAttribute(dc)},CA=()=>{let i=gs;if(!i)return;if(Array.from(Ee.children).some(f=>f!==$n&&!f.hasAttribute(dc))){Mr&&Mr!==Ee&&(Mr.style.removeProperty("min-height"),Mr=null);let f=Ee.offsetHeight;f>0&&(Ee.style.minHeight=`${f}px`,Mr=Ee)}$n||($n=E("div","persona-history-header-host")),i.setHeaderPlacement("external");let g=i.getHeaderElement();g.parentNode!==$n&&$n.replaceChildren(g),$n.parentNode!==Ee&&Ee.appendChild($n),bA()},Kh=()=>{Mr&&(Mr.style.removeProperty("min-height"),Mr=null),$n&&(gs?.setHeaderPlacement("inline"),$n.remove(),$n=null,vA())},pc=null,xu=()=>{if(pc){if(te.style.display="none",Xn(te,!0),Le.hidden=!0,Xn(Le,!0),yA()){CA(),Ee.style.display=Vh(),Xn(Ee,!1);return}Kh(),Ee.style.display="none",Xn(Ee,!0)}};bp=xu;let wA=i=>{let c=te.style.display,g=Le.hidden,f=Le,b=Ee,v=Ee.style.display;wu=b,zh=v,pc=()=>{pc=null,Kh(),wu=null,te.style.display=c,Xn(te,!1),f.hidden=g,Xn(f,!1),Le!==f&&(Le.hidden=!1,Xn(Le,!1)),b.style.display=v,Xn(b,!1),Ee!==b&&(Ee.style.display=o.layout?.showHeader===!1?"none":"",Xn(Ee,!1))},Le.parentNode?.insertBefore(i,Le),xu()},oi=null,ms=null,ha=null,ri=null,Gh=()=>[Ee,_e.closeButtonWrapper,_e.clearChatButtonWrapper,te,Le],xA=52,uc=()=>o.features?.history?.rail?.collapsible!==!1,si=()=>o.features?.history?.rail?.side==="right"?"right":"left",Su=200,Au=400,Mu=i=>Math.min(Au,Math.max(Su,Math.round(i))),SA=()=>o.features?.history?.rail?.resizable===!0,ya,AA=()=>{if(ya===void 0&&(ya=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Y()}rail-width`));i&&(ya=i)}catch{}return ya},ba=()=>Mu(AA()??o.features?.history?.rail?.width??260),MA=i=>{if(ya=i,o.persistState!==!1)try{window.localStorage.setItem(`${Y()}rail-width`,String(i))}catch{}},gc=()=>uc()&&o.features?.history?.rail?.collapsedBehavior==="overlay",Ft=!1,Yh=i=>{let c=E("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},EA=()=>{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=Yh(i.iconUrl):g=i.icon?le(i.icon,20):null),g?g.cloneNode(!0):null}},TA=()=>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=Yh(f.iconUrl):b=f.icon?le(f.icon,20):null}catch(v){g(v),b=null}return b},onSelect:()=>{try{f.onSelect()}catch(v){g(v)}}}})}})??[],PA=i=>{let c=TA();for(let g of i)c.some(f=>f.id===g.id)?console.warn("[persona] duplicate history rail section id",g.id):c.push(g);return c.length?c:void 0},va=null,Qh=()=>`${Y()}rail-collapsed`,Eu=()=>{if(va===null&&(va=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(Qh());i&&(va=i==="1")}catch{}return va},Tu=i=>{if(va=i,o.persistState!==!1)try{window.localStorage.setItem(Qh(),i?"1":"0")}catch{}},Ca=()=>_t==="rail"&&uc()&&!gc()&&Eu(),Pu=()=>{},Xh=()=>{if(gc()){Pu();return}Tu(!Eu()),it?.view.setCollapsed(Ca()),$o(),En()},ku=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!Ed(i)?null:{combo:i,hint:Td(i),aria:rl(i)}},Jh=()=>{d.forEach(c=>c()),d=[];let i=ku();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>At&&_t==="rail"&&uc()||ai(),run:()=>gc()?Pu():Xh()}));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}`}))};Jh();let kA=300,mc="var(--persona-history-overlay-margin,8px)",Jn=null,Jo=null,fc=0,Zo=null,ii=null,fs=!1,Lu=0,Zh=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,ai=()=>Po()&&gc()&&(_t??Cu())==="rail",LA=()=>At&&!Ft,wa=()=>{ii!==null&&clearTimeout(ii),ii=null},IA=()=>{qm().catch(()=>{})},ey=()=>{wa(),Ft&&(ii=setTimeout(()=>{ii=null,!(fs||!Ft)&&(Zo?.contains(document.activeElement)||Tn({restoreFocus:!1}))},kA))},RA=(i,c)=>{let g=Zo?.getBoundingClientRect();if(!g)return!1;let f=Jn?.getBoundingClientRect(),b=f?Math.min(f.top,g.top):g.top;return i>=g.left&&i<=g.right&&c>=b&&c<=g.bottom||!!f&&i>=f.left&&i<=f.right&&c>=f.top&&c<=f.bottom},Iu=i=>{Ft&&(fs=RA(i.clientX,i.clientY),fs?wa():ii===null&&ey())},ty=i=>{At||!ai()||(Ft=!0,Sa({invoker:Jn,keyboard:i?.keyboard===!0}).then(()=>{At?!fs&&document.activeElement!==Jn&&Tn():Ft=!1}))},ny=()=>{let i=fa?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",Ft?Qe.expandLabel:Qe.collapseLabel),i.setAttribute("aria-expanded",Ft?"false":"true"))},oy=()=>{Tu(!1);let i=it;if(!Ft||!i){Sa({invoker:Jn});return}let c=document.activeElement===Jn;Ft=!1,hc(),i.element.remove(),Hu(i.element),ny(),c&&bc(),En(),Er()},HA=()=>{Tu(!0),Tn()};Pu=()=>{!At||Ft?oy():HA()};let WA=()=>{let i=ku(),c=Ls({ariaLabel:Qe.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":yu,...i?{"aria-keyshortcuts":i.aria}:{}}}),g=c.button;g.addEventListener("mouseenter",()=>{fs=!0,wa(),!(Zh()||Date.now()<Lu)&&ty()}),g.addEventListener("mouseleave",()=>{fs=!1,Lu=0,ey()}),g.addEventListener("focus",()=>{At||IA()}),g.addEventListener("click",f=>{Po()&&(f.detail!==0&&Zh()&&!At?ty():oy())}),Jn=g,Jo=c.wrapper},xa=()=>{if(Jo&&!Jo.isConnected&&(Jo=null,Jn=null),!ai()){Jo?.remove(),Jo=null,Jn=null;return}Jn||WA();let i=Jo,c=Jn;if(!i||!c)return;let g=si()!=="right"?Ee.firstChild:null;(g??Ee.lastChild)!==i&&Ee.insertBefore(i,g),i.style.display=LA()||fc>0?"none":"",c.setAttribute("aria-label",Qe.expandLabel),c.setAttribute("aria-expanded",At?"true":"false"),Zo&&$o()},ry=i=>{if(!Ft)return;let c=i.target;c instanceof Node&&(Zo?.contains(c)||Jo?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||Tn({restoreFocus:!1}))};document.addEventListener("pointerdown",ry,!0),me.push(()=>{document.removeEventListener("pointerdown",ry,!0),document.removeEventListener("pointermove",Iu),li?.(),wa()});let Ru=null,li=null,sy=16,iy=i=>{MA(Mu(i)),$o(),En()},OA=()=>{let i=E("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(Su)),i.setAttribute("aria-valuemax",String(Au)),i.addEventListener("pointerdown",c=>{let g=ms;if(!g||c.button!==0)return;c.preventDefault(),li?.();let f=c.clientX,b=g.getBoundingClientRect().width||ba(),v=si()==="right"?-1:1,B=b,U=e.ownerDocument;g.style.transition="none";let $=Q=>{B=Mu(b+v*(Q.clientX-f)),g.style.flex=`0 0 ${B}px`,i.setAttribute("aria-valuenow",String(B))},j=()=>{li=null,U.removeEventListener("pointermove",$),U.removeEventListener("pointerup",j),U.removeEventListener("pointercancel",j),g.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}iy(B)};li=j,U.addEventListener("pointermove",$),U.addEventListener("pointerup",j),U.addEventListener("pointercancel",j);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let g=si()==="right"?-sy:sy,f=ba(),b=c.key==="ArrowRight"?f+g:c.key==="ArrowLeft"?f-g:c.key==="Home"?Su:c.key==="End"?Au:null;b!==null&&(c.preventDefault(),iy(b))}),i},BA=(i,c)=>{if(!SA()||Ca()){li?.(),Ru?.remove();return}let g=Ru??OA();Ru=g,g.setAttribute("aria-label",Qe.resizeLabel),g.setAttribute("aria-valuenow",String(ba())),g.nextElementSibling!==c&&i.insertBefore(g,c)};$o=()=>{it?.view.setRailSide(si());let i=si()==="right",c=Zo;if(c){let U=Jn?Jn.getBoundingClientRect().bottom-de.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(U))}px + ${mc})`,c.style.width=`${ba()}px`,c.style.left=i?"":mc,c.style.right=i?mc:""}let g=ms,f=oi,b=ha;if(!g||!f||!b)return;g.style.flex=`0 0 ${Ca()?xA:ba()}px`;let v="1px solid var(--persona-divider,#e5e7eb)";g.style.borderRight=i?"":v,g.style.borderLeft=i?v:"";let B=i?b:g;f.firstElementChild!==B&&f.append(B,i?g:b),BA(f,i?g:b)};let ay=i=>{if(ri&&ms){ri.replaceWith(i),ri=null,$o();return}let c=E("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let g=E("div","persona-history-rail-conversation");g.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let f=E("div","persona-history-rail-host");f.style.cssText="display:flex;min-height:0;overflow:hidden",de.insertBefore(c,Ee.parentNode===de?Ee:te);for(let b of Gh())b?.parentNode===de&&g.appendChild(b);c.append(f,g),f.appendChild(i),oi=c,ms=f,ha=g,$o()},_A=()=>{if(oi)return;let i=E("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",ri=i,ay(i),En()},ly=()=>{ri&&(hc(),En())},DA=i=>{let c=E("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${mc};display:flex;overflow:hidden;z-index:${Ei-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,de.style.position="relative",de.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",Iu),Zo=c,$o(),ny()},hc=()=>{pc?.(),Zo&&(fs&&(Lu=Date.now()+150),document.removeEventListener("pointermove",Iu),Zo.remove(),Zo=null);let i=oi;if(i){li?.();for(let c of Gh())c&&i.contains(c)&&de.insertBefore(c,i);i.remove(),oi=null,ms=null,ha=null,ri=null}},cy=i=>{fa=i,i.id=yu,i.style.flex="1 1 auto",i.style.minHeight="0"},Hu=i=>{cy(i),(_t!=="rail"||Ft)&&ly(),_t!=="rail"?wA(i):Ft?DA(i):ay(i)},yc=()=>{if(xa(),Cy(),!At||!it)return;let i=Cu();if(i===_t)return;let c=document.activeElement,g=c instanceof HTMLElement&&(it.element.contains(c)||$n?.contains(c)===!0)?c:null;hc(),it.element.remove(),it.view.setHeaderPlacement("inline"),_t=i,it.view.setPresentation(i),it.view.setCollapsed(Ca()),it.requestRender(),it.element.isConnected||Hu(it.element),g?.isConnected?g.focus():bc(),Vt(),En(),Er()},dy=(i,c)=>$n?.querySelector(c)??i.querySelector(c),bc=()=>{let i=it?.element??fa;if(!i)return;let c=dy(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let g=dy(i,".persona-history-title")??i;g.tabIndex=-1,g.focus()},Sa=async i=>{if(!Po()||At)return;let c=Fn;if(!c)return;if(!Ft&&ai()&&Eu()){xa();return}vc();let g=++ma;sc=i?.returnSurface??"conversation",mu=i?.invoker??pn;let f=ai()&&!Ft;f&&(fc+=1,xa(),_A());let b;try{b=await qm()}catch{cc(Qe.openHistoryLabel),f&&(fc-=1,g===ma&&(ly(),xa()));return}if(f&&(fc-=1),g!==ma||At)return;rc={scope:vu()},_t=Cu(),At=!0;let v=_t==="panel"&&o.layout?.showHeader!==!1&&Ee.style.display!=="none"?"external":"inline",B=o.features?.history?.rowAvatar,U=ku(),$=U?{hint:U.hint,aria:U.aria}:null,j={provider:c,context:rc,targetId:Fh(),presentation:_t,collapsible:uc(),collapsed:Ca(),railSide:si(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:EA(),onToggleCollapse:Xh,...$?{collapseShortcut:$}:{},headerPlacement:v,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:B===!1?!1:typeof B=="string"?B:o.launcher?.iconUrl,activeConversationId:k.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:Q=>Ou(Q,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Q=>hs(Q),attachTooltip:Zt,onStartNew:()=>Bu({focusComposer:!0}),onClose:()=>Tn(),onRequestDeleteConversation:Q=>vy(Q),onRequestClearHistory:()=>qA(),...c.resetDevice?{onRequestResetIdentity:()=>zA()}:{}};it=px({plugins:a,config:o,getPresentation:()=>_t??"panel",getReturnSurface:()=>sc,close:()=>Tn(),createView:({slots:Q,renderDom:oe,onModelChange:ue,railSections:Xe})=>(gs=b.createHistoryView({...j,railSections:PA(Xe),slots:Q,renderDom:oe,onModelChange:ue,onAnnounce:cc}),gs),onElementChanged:(Q,oe)=>{if(!oe?.isConnected)return Hu(Q);cy(Q),oe.replaceWith(Q),xu()}}),it.view.setNewConversationRequired(ic.recovery==="new_conversation_required"),i?.focus!==!1&&(_t!=="rail"||i?.keyboard===!0)&&bc(),Vt(),En(),Er(),A.emit("history:opened",{presentation:_t,returnSurface:sc,timestamp:Date.now()})},vc=()=>{},Tn=i=>{if(!At)return;ma+=1;let c=sc,g=mu,f=it,b=i?.restoreFocus!==!1;At=!1;let v=!1,B=null,U=()=>{if(!v){if(v=!0,vc=()=>{},B!==null&&clearTimeout(B),Ft=!1,wa(),hc(),f?.dispose(),f?.view.destroy(),f?.element.remove(),it===f&&(it=null,gs=null,fa=null,_t=null,rc=null,mu=null),Vt(),En(),Er(),b){let j=g??pn;j?.isConnected?j.focus():cs()}A.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},$=f&&f.element===f.view.element?f.view.playExit():null;if(!$){U();return}vc=U,B=setTimeout(U,mA),$.then(U)},py=i=>{if(!(i.key!=="Escape"||!At||!it)){if(_t==="rail"){let c=i.target;if(!(c instanceof Node)||!(it.element.contains(c)||Ft&&Jo?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Tn()}};de.addEventListener("keydown",py),me.push(()=>de.removeEventListener("keydown",py));let Cc=null,uy=!1,Aa=()=>{if(!gr)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&Cc?.trim()||null;gr.textContent=c??o.launcher?.title??"Chat Assistant";let g=gr.closest(".persona-combo-btn");if(!g)return;let f=!i||k.getActiveConversationId()!==null;g.setAttribute("data-persona-menu-locked",f?"false":"true"),g.setAttribute("aria-haspopup",f?"true":"false"),f||g.setAttribute("aria-expanded","false"),g.style.cursor=f?"pointer":"default";let b=g.querySelector("svg");b&&(b.style.display=f?"":"none")},NA=i=>{i!==Cc&&(Cc=i,Aa())},hs=i=>{uy=i?.starred===!0,NA(i&&i.title.trim()||null),Aa()};Aa(),de.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,g=k.getActiveConversationId();g&&(c==="delete"?vy(g):c==="star"&&k.canUpdateConversations()&&_u(g,{starred:!uy}).catch(()=>{}))});let wc=0,FA=250,xc=null,Sc=()=>{xc&&clearTimeout(xc),xc=null};me.push(Sc);let gy=()=>{Sc();let i=ds;i&&(ua=!0,i.hidden=!1,Pe.style.display="none",ga())},Ac=()=>{wc+=1,Sc(),ds&&(ds.remove(),ds=null,ua=!1,Pe.style.removeProperty("display"),Xn(Le,!1),ga())},$A=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Pe.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Wu=(i,c)=>G("div",{className:gn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),my=()=>G("div",{className:"persona-conversation-loading-body"},Wu("58%",!1),Wu("72%",!0),Wu("44%",!1)),fy=i=>{ds?.remove(),ds=i,i.hidden=!ua,te.insertBefore(i,Pe),Sc(),ua||(xc=setTimeout(gy,FA)),Xn(Le,!0)},UA=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:my},c=null,g=a.find(f=>f.renderLoadingIndicator);g?.renderLoadingIndicator&&(c=g.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),fy(G("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Qe.openConversationLoadingLabel}},c??my()))},jA=i=>{let c=()=>{Ou(i,{focusComposer:!0}).catch(()=>{})},g=Po()?()=>{Ac(),Sa()}:void 0,f=(U,$)=>{let j=G("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:U});return j.addEventListener("click",$),j},b=()=>G("div",{className:"persona-conversation-loading-error-body"},G("p",{className:"persona-conversation-loading-error-title",text:Qe.openConversationErrorTitle}),G("div",{className:"persona-conversation-loading-error-actions"},f(Qe.openConversationRetryLabel,c),g?f(Qe.openConversationBackLabel,g):null)),v=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Qe.openConversationErrorTitle,retryLabel:Qe.openConversationRetryLabel,backLabel:Qe.openConversationBackLabel}),retry:c,...g?{back:g}:{},defaultRenderer:b}),B=null;for(let U of a)if(U.renderHistoryOpenError){try{B=U.renderHistoryOpenError(v)}catch($){console.warn("[persona] renderHistoryOpenError threw",$),B=null}if(B)break}fy(G("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},B??b())),gy()};A.on("history:closed",()=>{ds&&Xn(Le,!0)});let Ou=async(i,{focusComposer:c=!1}={})=>{let g=ni(),f=!!it;it?.view.setActiveConversationId(i),Ac();let b=wc;UA(),At&&(_t==="panel"||Ft)&&Tn({restoreFocus:!1}),Ks=!0;try{await k.openConversation(i,{scope:g})}catch(v){throw b===wc&&jA(i),v}finally{Ks=!1}b===wc&&(Ac(),Nt.clear(),co(),Mn(),Gp()||Gl(),$A(),er(),f||hs(null),A.emit("history:conversationOpened",{conversationId:i,title:Cc,scope:g,timestamp:Date.now()}),c&&cs())},Bu=async({focusComposer:i=!1}={})=>{Ac(),await k.startNewConversation({scope:ni()}),hs(null),Nt.clear(),co(),Mn(),Gl(),er();let c=k.getActiveConversationId();it?.view.setActiveConversationId(c),A.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),At&&(_t==="panel"||Ft)&&Tn({restoreFocus:!1}),i&&cs()},_u=async(i,c)=>{let g=await k.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return it?.view.applyConversationSummary(g),!it&&i===k.getActiveConversationId()&&hs(g),g},hy=async i=>{let c=ni(),g=k.getActiveConversationId()===i;await k.deleteConversation(i,{scope:c}),it?.view.removeConversationSummary(i),g&&(hs(null),Nt.clear(),co(),Mn(),er()),A.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:g,timestamp:Date.now()})},yy=async i=>{let c=i?.scope??ni(),g=i?.allTargets?null:i?.targetId??Fh(),f=await k.clearConversationHistory({...g?{targetId:g}:{},scope:c});return hs(null),Nt.clear(),co(),Mn(),er(),A.emit("history:cleared",{deleted:f.deleted,scope:c,targetId:g,timestamp:Date.now()}),f},by=async()=>{if(!Fn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await k.resetHistoryDevice()).remoteRevocationConfirmed}finally{hs(null),k.clearArtifacts(),Nt.clear(),cu=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),Z={},ye.syncFromMetadata(),K?.clear&&zl(()=>K.clear(),"[AgentWidget] Failed to clear storage adapter:"),co(),Mn(),er(),Tn({restoreFocus:!1}),cs(),ve||Et?.launcher.element.focus()}return cc(i?Qe.identityResetNotice:Qe.identityResetUnconfirmedNotice),A.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},Du=()=>So?Se:de,vy=async i=>await tp({host:Du(),title:Qe.deleteConversationConfirmTitle,description:Qe.deleteConversationConfirm,confirmLabel:Qe.deleteConversationConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await hy(i),"deleted"):"cancelled",qA=async()=>{let i=ni()==="verified-user";return await tp({host:Du(),title:Qe.clearHistoryConfirmTitle,description:i?Qe.clearHistoryVerifiedConfirm:Qe.clearHistoryConfirm,confirmLabel:Qe.clearHistoryConfirmLabel,cancelLabel:Qe.confirmCancelLabel})?(await yy(),"cleared"):"cancelled"},zA=async()=>{if(!await tp({host:Du(),title:Qe.resetIdentityConfirmTitle,description:Qe.resetIdentityConfirm,confirmLabel:Qe.resetIdentityConfirmLabel,cancelLabel:Qe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await by();return{outcome:"reset",remoteRevocationConfirmed:c}},Zn=E("button","persona-history-earlier");Zn.type="button",Zn.textContent=Qe.showEarlierMessagesLabel,Zn.setAttribute("data-persona-history-earlier",""),Object.assign(Zn.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let er=()=>{if(!(Po()&&!!ic.nextMessageCursor&&!!k.getActiveConversationId())){Zn.remove();return}Zn.textContent=Qe.showEarlierMessagesLabel,Zn.parentNode!==te&&te.insertBefore(Zn,te.firstChild)};Zn.addEventListener("click",()=>{let i=k.getActiveConversationId(),c=ic.nextMessageCursor;if(!i||!c||Zn.disabled)return;Zn.disabled=!0;let g=te.scrollHeight,f=te.scrollTop;k.loadOlderMessages(i,c,{scope:ni()}).then(()=>{te.scrollTop=f+(te.scrollHeight-g),En()}).catch(()=>{}).finally(()=>{Zn.disabled=!1,er()})});let VA=()=>{let i=Ls({ariaLabel:Qe.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return i.button.addEventListener("click",c=>{if(!(!Po()||Nh())){if(At){Tn();return}Sa({invoker:i.button,keyboard:c.detail===0})}}),i},Cy=()=>{if(!Po()){To?.remove(),pn=null,To=null;return}if(To&&!To.isConnected&&(pn=null,To=null),!pn&&Ee){let f=VA();pn=f.button,To=f.wrapper;let b=_e.clearChatButtonWrapper||_e.closeButtonWrapper;b?.parentNode&&Ee.contains(b)?b.parentNode.insertBefore(To,b):Ee.appendChild(To)}if(!pn||!To)return;let i=ai()||At&&_t==="rail";if(To.style.display=i?"none":"",i){document.activeElement===pn&&bc();return}let c=Nh();pn.disabled=c,pn.setAttribute("aria-disabled",c?"true":"false");let g=c?Qe.openHistoryBusyLabel:Qe.openHistoryLabel;pn.setAttribute("aria-label",g),(o.features?.history?.presentation??"panel")==="panel"?(pn.removeAttribute("aria-expanded"),pn.removeAttribute("aria-controls")):(pn.setAttribute("aria-expanded",At?"true":"false"),pn.setAttribute("aria-controls",yu))},Mc=!1,KA=()=>{let i=_e.clearChatButton;if(i){if(Po()){Mc||(hu=i.getAttribute("aria-label")??"",Mc=!0),i.setAttribute("aria-label",Qe.newConversationLabel),i.removeAttribute("title");return}Mc&&(Mc=!1,hu&&i.setAttribute("aria-label",hu))}},Er=()=>{Qe=Km(o.features?.history?.copy),Cy(),xa(),KA(),er()};vp=Er,ff=i=>{ic=i,it?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),pa(i.sendBlocked||_n),er()},hf=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(Nt.clear(),co(),Mn()),cc(i.message),it?.view.refresh()},qh(),Er(),me.push(()=>{ac?.(),lc?.(),ma+=1,vc(),it?.dispose(),it?.view.destroy(),it=null}),o.clientToken&&k.initClientSession().then(()=>{if(Po())return k.reconcileBootConversation({scope:vu()})}).then(()=>{er()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(x||o.onSSEEvent)&&k.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),yp(i,c)});let wy=()=>{let i=o.resume??(ie?Qo.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&k.resumeFromHandle(i)};M?M.then(i=>{if(i){if(i.metadata&&(Z=Zm(i.metadata),ye.syncFromMetadata()),i.messages?.length){Ks=!0;try{k.hydrateMessages(i.messages)}finally{Ks=!1}Jl()}i.artifacts?.length&&k.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),yh(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{tu=!0,_(),wy()}):(yh(H),wy());let GA=()=>{!be()||ve||!(o.launcher?.composerBar?.expandOnSubmit??!0)||gt(!0,"auto")},YA=(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),KI(b)}}:i:c,Nu=()=>{let c=ae.getInlineMessageFields?.();return c&&c.contentSegments.some(f=>f.kind==="mention")?c.contentSegments:void 0},tr=!1,ys=null,Ec=()=>{ae.value="",ae.style.height="auto",Co(),Ea()},Fu="data-persona-composer-notice",ci=null;function QA(i){El(i),!(be()||!st)&&(st.hasAttribute(zi)||(st.setAttribute(Fu,""),st.setAttribute("role","status"),st.setAttribute("aria-live","polite"),st.textContent=i,ci&&clearTimeout(ci),ci=setTimeout(()=>{if(ci=null,!!st?.hasAttribute(Fu)&&(st.removeAttribute(Fu),st.removeAttribute("role"),st.removeAttribute("aria-live"),p)){let c=k.getStatus();Sl(st,yf(c),o.statusIndicator??{},c)}},4e3)))}function XA(){let i=Ce.getState().pendingSubmission;i&&(Ns(void 0),ae&&(ae.value=i.text,ae.dispatchEvent(new Event("input",{bubbles:!0})),Co()),i.options.selectedModelId&&(Ce.setSelectedModelId(i.options.selectedModelId),fr?.repaint()),i.options.activeModeIds?.length&&Ll(i.options.activeModeIds),i.options.quote&&wo(i.options.quote),ae?.focus())}let JA=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},xy=(i={})=>{let c=(i.overrideText??ae?.value??"").trim();return i.resolveInlineCommand&&c?(Wt?.takeInlineCommand(c)??Promise.resolve(null)).then(g=>Sy(i,c,g)):Sy(i,c,null)},Sy=(i,c,g)=>{if(g?.kind==="action"){Ec(),Wt?.clear(),Vr();return}let f=g?.kind==="server"?g.mentions:null,b=g?.kind==="prompt"?g.sendText:c,v=i.pending?.contentParts,B=(Ze?.hasAttachments()??!1)||(v?.length??0)>0;if(!xC({text:b,hasAttachments:B,attachmentsReady:Ze?.isReady()??!0,hasMentions:Wt?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:Eo(),sendDisabled:ls()}))return;let U=k.isStreaming()?Pp():"block";if(U==="defer-one"&&!i.pending){if(Ce.getState().pendingSubmission){QA("One message is already queued. Edit or remove it first.");return}ZA({intent:i,sendText:b,serverMentions:f});return}let $={text:b,mentionRefs:[...Wt?.getMentionRefs()??[],...f?.refs??[]],contentSegments:g?.kind==="prompt"?void 0:Nu(),options:{...Ce.getState().selectedModelId&&{selectedModelId:Ce.getState().selectedModelId},...Ce.getState().activeModeIds.length>0&&{activeModeIds:[...Ce.getState().activeModeIds]},...Ce.getState().quote&&{quote:{...Ce.getState().quote}}},viaVoice:i.viaVoice};i.pending&&($.options={...i.pending.options},$.contentSegments=i.pending.contentSegments,$.mentionRefs=[...i.pending.mentionRefs],$.viaVoice=i.pending.viaVoice);let j=()=>{if(v?.length)return[...v];if(!Ze?.hasAttachments())return;let mt=[...Ze.getContentParts()];return $.text&&mt.push(fo($.text)),mt};$.contentParts=j();let Q=()=>{ts(),GA();let mt=Wt?.collectForSubmit()??null,Qt=YA(mt,f),$t=j();i.consumeDraft!==!1&&Ec();let Pt={selectedModelId:$.options.selectedModelId,activeModeIds:$.options.activeModeIds},an=U==="interrupt";an&&k.cancel(),k.sendMessage($.text,{contentParts:$t,mentions:Qt??void 0,contentSegments:$.contentSegments,viaVoice:$.viaVoice,composerOptions:Pt,...$.options.quote&&{quote:$.options.quote},...an&&{interrupt:!0}}),Ze?.hasAttachments()&&Ze.clearAttachments(),mt&&Wt?.clear(),Vr();let et=Ce.getState().activeModeIds,ln=lC(et,o.composer?.modes);ln.length!==et.length&&Ll(ln),Ce.getState().quote&&wo(void 0),Kl(),Hp.release(),so()},oe=o.composer?.onBeforeSend;if(!oe){Q();return}let ue=new AbortController;ys=ue;let Xe=mt=>{if(ys=null,mt.status==="error"){JA(mt.error);return}mt.status==="proceed"&&Q()},dt=SC(oe,$,ue.signal);if(!(dt instanceof Promise)){Xe(dt);return}return Ce.setPreparing(!0),dt.then(Xe).finally(()=>Ce.setPreparing(!1))};function ZA(i){let c=Ce.getState(),g=Ze?.hasAttachments()??!1,f=g?[...Ze.getContentParts()]:[];g&&i.sendText&&f.push(fo(i.sendText));let b=Xg({text:i.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Wt?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Nu(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});Ns(b),i.intent.consumeDraft!==!1&&Ec(),g&&Ze.clearAttachments(),Wt?.clear(),Vr(),c.quote&&wo(void 0),Kl(),Hp.release(),so(),El("Message queued. It sends when the response finishes.")}function eM(){let i=Ce.getState().pendingSubmission;i&&(Ns(void 0),Pc(i.text,{consumeDraft:!1,pending:i}))}function tM(i){if(o.messageActions?.showEdit!==!0)return;let c=k.getMessages().find(g=>g.id===i);!c||!Eg(c)||es!==i&&(ts(),es=i,vr=gC({messageId:i,initialText:c.content,onSave:g=>nM(i,g),onCancel:()=>ts()}),Nt.delete(i),Yn(Pe,k.getMessages(),ut),vr.focus())}function nM(i,c){let g=vr;if(es=null,vr=null,g?.destroy(),Nt.delete(i),!k.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){Yn(Pe,k.getMessages(),ut);return}En()}function oM(i){if(k.isStreaming())return;let c=Mg(k.getMessages(),i);c&&(ts(),k.resubmitFrom(c,{reason:"retry"})&&En())}Il={regenerate:oM,edit:tM,quote:i=>{let g=k.getMessages().find(f=>f.id===i)?.content?.trim();g&&(wo({text:g,messageId:i}),ae?.focus())}};let Ma=async i=>{if(!tr){tr=!0;try{await xy({resolveInlineCommand:!0,...i})}finally{tr=!1}}};function Tc(i){ls()||(Ec(),Pc(i,{consumeDraft:!1}))}let Pc=(i,c)=>{if(tr)return;tr=!0;let g=()=>{tr=!1};try{let f=xy({...c,overrideText:i});f instanceof Promise?f.finally(g):g()}catch(f){throw g(),f}},rM=i=>{if(i.preventDefault(),k.isStreaming()){k.cancel(),rt?.reset(),ht?.update();return}tr||Ma()},sM=()=>o.features?.composerHistory!==!1,$u={...sm},Uu=!1,Ea=()=>{$u={...sm}},iM=()=>k.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),aM=i=>{if(!ae)return;Uu=!0,ae.value=i,ae.dispatchEvent(new Event("input",{bubbles:!0})),Uu=!1;let c=ae.value.length;ae.setSelectionRange(c,c)},lM=i=>{Uu||(i.isComposing||Wt?.handleInput(i.inputType??void 0),Ea())},cM=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:el(ae)}),dM=i=>{if(ae&&!Eo()&&!(!i.isComposing&&Wt?.handleKeydown(i))){if(sM()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let c=ae.selectionStart===0&&ae.selectionEnd===0,g=jC({direction:i.key==="ArrowUp"?"up":"down",history:iM(),currentValue:ae.value,atStart:c,state:$u});if($u=g.state,g.handled){i.preventDefault(),g.value!==void 0&&aM(g.value);return}}if(Vv(i,cM())){if(k.isStreaming()){if(i.preventDefault(),Pp()==="block"||tr||ls())return;Ea(),Ma();return}if(tr){i.preventDefault();return}if(ls()){i.preventDefault();return}Ea(),i.preventDefault(),Me.click()}}},Ay=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(de)){if(ys){ys.abort(),ys=null,i.preventDefault(),i.stopImmediatePropagation();return}k.isStreaming()&&(k.cancel(),rt?.reset(),ht?.update(),Ea(),i.preventDefault(),i.stopImmediatePropagation())}},pM=async i=>{if(o.attachments?.enabled!==!0||!Ze||Eo())return;let c=jI(i.clipboardData);c.length!==0&&(i.preventDefault(),await Ze.handleFiles(c))},eo=null,ko=!1,di=null,Ct=null,ju=()=>o.voiceRecognition?.completionBehavior==="review";function bs(i){ne?.setAttribute("data-state",i),i==="recording"?gM():Ku()}let My="--persona-voice-level",qu=.5,pi=null,zu=-1,kc=0,Ey=()=>{let i=[],c=On??ne?.parentElement??null;return c&&i.push(c),Le&&i.push(Le),i},Vu=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==zu){zu=c;for(let g of Ey())g.style.setProperty(My,String(c))}},uM=()=>{zu=-1,kc=0;for(let i of Ey())i.style.removeProperty(My)};function gM(){if(pi!==null)return;if(typeof requestAnimationFrame!="function"){Vu(p?k.getVoiceLevel()??qu:qu);return}let i=()=>{pi=requestAnimationFrame(i);let c=p?k.getVoiceLevel():null;if(c===null){Vu(qu);return}kc+=(c-kc)*.3,Vu(kc)};pi=requestAnimationFrame(i)}function Ku(){pi!==null&&(cancelAnimationFrame(pi),pi=null),uM()}let Ty=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Lc=(i="user")=>{if(ko||k.isStreaming())return;let c=Ty();if(!c)return;eo=new c;let g=o.voiceRecognition??{},f=g.pauseDuration??2e3;eo.continuous=g.provider?.browser?.continuous??!0,eo.interimResults=!0,eo.lang=g.provider?.browser?.language??"en-US";let b=ae.value;eo.onresult=v=>{let B="",U="";for(let j=0;j<v.results.length;j++){let Q=v.results[j],oe=Q[0].transcript;Q.isFinal?B+=oe+" ":U=oe}let $=b+B+U;ae.value=$,Co(),di&&clearTimeout(di),(B||U)&&(di=window.setTimeout(()=>{if(ae.value.trim()&&eo&&ko){if(Tr(),ju())return;Ma({viaVoice:!0})}},f))},eo.onerror=v=>{v.error!=="no-speech"&&Tr()},eo.onend=()=>{if(ko){let v=ae.value.trim();!ju()&&v&&v!==b.trim()&&Ma({viaVoice:!0}),Tr()}};try{if(eo.start(),ko=!0,ze.active=!0,i!=="system"&&(ze.manuallyDeactivated=!1),Go(i),lo(),so(),ne){let v=o.voiceRecognition??{};Ct={backgroundColor:ne.style.backgroundColor,color:ne.style.color,borderColor:ne.style.borderColor,iconName:v.iconName??"mic",iconSize:parseFloat(v.iconSize??"")||mn};let B=v.recordingBackgroundColor,U=v.recordingIconColor,$=v.recordingBorderColor;if(ne.classList.add("persona-voice-recording"),bs("recording"),ne.style.backgroundColor=B??"var(--persona-voice-recording-bg, #ef4444)",ne.style.color=U??"var(--persona-voice-recording-indicator, #ffffff)",U){let j=ne.querySelector("svg");j&&j.setAttribute("stroke",U)}$&&(ne.style.borderColor=$),ne.setAttribute("aria-label","Stop voice recognition")}}catch{Tr("system")}},Tr=(i="user")=>{if(ko){if(ko=!1,di&&(clearTimeout(di),di=null),eo){try{eo.stop()}catch{}eo=null}if(ze.active=!1,Go(i),lo(),so(),ne){if(ne.classList.remove("persona-voice-recording"),bs("idle"),Ct){ne.style.backgroundColor=Ct.backgroundColor,ne.style.color=Ct.color,ne.style.borderColor=Ct.borderColor;let c=ne.querySelector("svg");c&&c.setAttribute("stroke",Ct.color||"currentColor"),Ct=null}ne.setAttribute("aria-label","Start voice recognition")}}},Gu=()=>{if(!ne||Ct)return;let i=o.voiceRecognition??{};Ct={backgroundColor:ne.style.backgroundColor,color:ne.style.color,borderColor:ne.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||mn}},Yu=(i,c)=>{if(!ne)return;let g=ne.querySelector("svg");g&&g.remove();let f=Ct?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||mn),b=le(i,f,c,1.5);b&&ne.appendChild(b)},Ic=()=>{ne&&ne.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ui=()=>{if(!ne)return;Gu();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,g=i.recordingIconColor,f=i.recordingBorderColor;if(Ic(),ne.classList.add("persona-voice-recording"),bs("recording"),ne.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",ne.style.color=g??"var(--persona-voice-recording-indicator, #ffffff)",g){let b=ne.querySelector("svg");b&&b.setAttribute("stroke",g)}f&&(ne.style.borderColor=f),ne.setAttribute("aria-label","Stop voice recognition")},mM=()=>{if(!ne)return;Gu();let i=o.voiceRecognition??{},c=k.getVoiceInterruptionMode(),g=i.processingIconName??"loader",f=i.processingIconColor??Ct?.color??"",b=i.processingBackgroundColor??Ct?.backgroundColor??"",v=i.processingBorderColor??Ct?.borderColor??"";Ic(),ne.classList.add("persona-voice-processing"),bs("processing"),ne.style.backgroundColor=b,ne.style.borderColor=v;let B=f||"currentColor";ne.style.color=B,Yu(g,B),ne.setAttribute("aria-label","Processing voice input"),c==="none"&&(ne.style.cursor="default")},fM=()=>{if(!ne)return;Gu();let i=o.voiceRecognition??{},c=k.getVoiceInterruptionMode(),g=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",f=i.speakingIconName??g,b=i.speakingIconColor??(c==="barge-in"?i.recordingIconColor??Ct?.color??"":Ct?.color??""),v=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Ct?.backgroundColor??""),B=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":Ct?.borderColor??"");Ic(),ne.classList.add("persona-voice-speaking"),bs("speaking"),ne.style.backgroundColor=v,ne.style.borderColor=B;let U=b||"currentColor";ne.style.color=U,Yu(f,U);let $=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";ne.setAttribute("aria-label",$),c==="none"&&(ne.style.cursor="default"),c==="barge-in"&&ne.classList.add("persona-voice-recording")},nr=()=>{ne&&(Ic(),bs("idle"),Ct&&(ne.style.backgroundColor=Ct.backgroundColor??"",ne.style.color=Ct.color??"",ne.style.borderColor=Ct.borderColor??"",Yu(Ct.iconName,Ct.color||"currentColor"),Ct=null),ne.style.cursor="",ne.setAttribute("aria-label","Start voice recognition"))},Qu=()=>{if(!Eo()){if(In(o.voiceRecognition?.provider)){let i=k.getVoiceStatus(),c=k.getVoiceInterruptionMode();if(c==="none"&&(i==="processing"||i==="speaking"))return;if(c==="cancel"&&(i==="processing"||i==="speaking")){k.stopVoicePlayback();return}if(k.isBargeInActive()){k.stopVoicePlayback(),k.deactivateBargeIn().then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,lo(),Go("user"),nr()});return}k.toggleVoice().then(()=>{ze.active=k.isVoiceActive(),ze.manuallyDeactivated=!k.isVoiceActive(),lo(),Go("user"),k.isVoiceActive()?ui():nr()});return}if(ko){let i=ae.value.trim();ze.manuallyDeactivated=!0,lo(),Tr("user"),i&&!ju()&&Ma()}else ze.manuallyDeactivated=!1,lo(),Lc("user")}};kp=Qu,ne&&me.push(()=>{In(o.voiceRecognition?.provider)?(k.isVoiceActive()&&k.toggleVoice(),nr()):Tr("system")});let hM=A.on("assistant:complete",()=>{Ce.getState().pendingSubmission&&setTimeout(()=>{k.isStreaming()||eM()},0)});me.push(hM);let yM=A.on("assistant:complete",()=>{mh&&(ze.active||ze.manuallyDeactivated||mh==="assistant"&&!ze.lastUserMessageWasVoice||setTimeout(()=>{!ze.active&&!ze.manuallyDeactivated&&(In(o.voiceRecognition?.provider)?k.toggleVoice().then(()=>{ze.active=k.isVoiceActive(),Go("auto"),k.isVoiceActive()&&ui()}):Lc("auto"))},600))});me.push(yM);let bM=A.on("action:resubmit",()=>{setTimeout(()=>{k&&!k.isStreaming()&&k.continueConversation()},100)});me.push(bM);let Py=()=>{gt(!ve,"user")},Et=null,un=null;if(ce&&!be()){let{instance:i,element:c}=Pm({config:o,plugins:a,onToggle:Py});Et=i,i||(un=c)}Et?e.appendChild(Et.element):un&&e.appendChild(un),da(),zs(),tc(),iu(),pa(k.isStreaming()),Gp()||(Bn()==="follow"?xr(!0):Gl()),_S(),fe&&(!ce||be()?setTimeout(()=>cs(),0):ve&&setTimeout(()=>cs(),200));let vs=null,ky=()=>{vs&&(vs.disconnect(),vs.observe(Le),vs.observe(de))},Ta=()=>{if(be()){zr(),da();return}let i=St(o),c=o.launcher?.sidebarMode??!1,g=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640,v=g.innerWidth<=b,B=f&&v&&ce;try{if(B){Kr(),ea=Nl();return}let U=!1;Bt&&(Bt=!1,Kr(),U=!0);let $=Nl();if(!U&&$!==ea&&(Kr(),U=!0),ea=$,U&&Ol(),!ce&&!i){Se.style.height="",Se.style.width="";return}if(!c&&!i){let Q=o?.launcher?.width??o?.launcherWidth??oo;Se.style.width=Q,Se.style.maxWidth=Q}Dl(),Jf()}finally{if(zr(),kl(),da(),ve&&ce){let $=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),j=o.launcher?.sidebarMode??!1,Q=o.launcher?.mobileFullscreen??!0,oe=St(o)&&Q&&$,ue=j||Q&&$&&ce||oe;if(ue&&!Mo){let Xe=e.getRootNode(),dt=Xe instanceof ShadowRoot?Xe.host:e.closest(".persona-host");dt&&!Ao&&(Ao=cm(dt,o.launcher?.zIndex??rn)),Mo=dm(e.ownerDocument)}else ue||(Ao?.(),Ao=null,Mo?.(),Mo=null)}}};Ta();let Rc=e.ownerDocument.defaultView??window;if(Rc.addEventListener("resize",Ta),me.push(()=>Rc.removeEventListener("resize",Ta)),typeof ResizeObserver<"u"){vs=new ResizeObserver(()=>{kl()}),ky(),me.push(()=>{vs?.disconnect(),vs=null});let i=new ResizeObserver(()=>{yc()});i.observe(de),me.push(()=>i.disconnect())}Rc.addEventListener("resize",yc),me.push(()=>Rc.removeEventListener("resize",yc)),Nn=te.scrollTop;let Ly=Bo(te),Iy=()=>{let i=te.scrollTop,c=Bo(te),g=c<Ly;if(Ly=c,!mr()){Nn=i,Vt();return}let{action:f,nextLastScrollTop:b}=XC({following:Dn.isFollowing(),currentScrollTop:i,lastScrollTop:Nn,nearBottom:ks(te,Vo),userScrollThreshold:HS,isAutoScrolling:An||$l||g,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Nn=b,f==="resume"){Yl()||Mn();return}f==="pause"&&sa()};if(te.addEventListener("scroll",Iy,{passive:!0}),me.push(()=>te.removeEventListener("scroll",Iy)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{qS(),sg(Pe)});i.observe(Pe),i.observe(te),me.push(()=>i.disconnect())}let Ry=()=>{mr()&&Dn.isFollowing()&&Yl()&&sa()},Hy=te.ownerDocument;Hy.addEventListener("selectionchange",Ry),me.push(()=>{Hy.removeEventListener("selectionchange",Ry)});let vM=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Wy=i=>{vM.has(i.key)&&(ss(),vf()&&mr()&&Dn.isFollowing()&&sa())},Oy=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(ss(),vf()&&mr()&&Dn.isFollowing()&&sa())};te.addEventListener("keydown",Wy),te.addEventListener("focusin",Oy),me.push(()=>{te.removeEventListener("keydown",Wy),te.removeEventListener("focusin",Oy)});let By=i=>{if(i.deltaY!==0&&ss(),!mr())return;let c=JC({following:Dn.isFollowing(),deltaY:i.deltaY,nearBottom:ks(te,Vo),resumeWhenNearBottom:!0});c==="pause"?sa():c==="resume"&&!Yl()&&Mn()};te.addEventListener("wheel",By,{passive:!0}),te.addEventListener("touchmove",ss,{passive:!0}),te.addEventListener("pointerdown",ss,{passive:!0}),me.push(()=>{te.removeEventListener("touchmove",ss),te.removeEventListener("pointerdown",ss)}),me.push(()=>te.removeEventListener("wheel",By)),Dt.addEventListener("click",()=>{co(),te.scrollTop=te.scrollHeight,Nn=te.scrollTop,Mn(),xr(!0),Vt()}),me.push(()=>Dt.remove()),me.push(()=>{vh(),co()});let _y=()=>{Fe&&(Xr&&(Fe.removeEventListener("click",Xr),Xr=null),Be()?(Fe.style.display="",Xr=()=>{gt(!1,"user")},Fe.addEventListener("click",Xr)):Fe.style.display="none")};_y(),(()=>{let{clearChatButton:i}=_e;i&&i.addEventListener("click",()=>{if(Po()){Bu({focusComposer:!0}).catch(g=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",g)});return}k.clearMessages(),Nt.clear(),Mn(),Es(_e.composerOverlay);try{localStorage.removeItem(qi),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qi}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==qi)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),K?.clear&&zl(()=>K.clear(),"[AgentWidget] Failed to clear storage adapter:"),Z={},ye.syncFromMetadata(),Ze?.clearAttachments(),Kl(),Ns(void 0),wo(void 0),ts(),He?.clear(),rt?.reset(),ht?.update()})})();let Dy=[["keydown",dM],["input",lM],["input",Co],["input",Vr],["keyup",Vr],["paste",pM],["focus",wS]],Ny=i=>{if(i)for(let[c,g]of Dy)nt?.addListener(i,c,g)},CM=i=>{if(i)for(let[c,g]of Dy)nt?.removeListener(i,c,g)},Fy=()=>{nt&&(nt.addListener(nt.form,"submit",rM),nt.addListener(nt.footer,"click",Vr),Ny(ae),ne&&nt.addListener(ne,"click",Qu))};Fy();let $y=()=>{Wt?.onComposerSwap((i,c)=>{CM(c),ae=i,nt&&(nt.input=i),Ny(i),Ip(),Zp(),Co()})};$y();let Xu=!1;function Uy(){if(!Xu){Xu=!0;try{let i=ae?.value??"",c=Le.ownerDocument??document,g=ae?c.activeElement===ae:!1;Ku(),nt?.destroy(),nt=null,Wt?.destroy(),Wt=null;let f=null,b=()=>(f=be()?Od({config:o}):Wi({config:o}),f.footer),v=kf(b)??b();Hn.replaceComposer(v),Le=Hn.composer.footer;let B=f!==null&&v===f.footer;$s=!B,bf=B?f.setSendButtonMode:()=>{},Pf(Le),If(Le),Rf(),Hf(),Wf(),$y(),Of(),Rp(),Bf(),Fy();let U=Qr.indexOf(zo);zo.destroy(),zo=gl(ur),U>=0&&(Qr[U]=zo),ae&&(ae.value=i),Co(),Vr(),tc(),zs(),pa(k.isStreaming()),ze.active&&bs("recording"),Kr(),ky(),zr(),so(),Zl(),g&&ae?.focus()}finally{Xu=!1}}}let Pa=e.ownerDocument??document;Pa.addEventListener("keydown",Ay,!0);let jy=()=>{qp()},qy=()=>{Pa.visibilityState==="hidden"&&qp()};typeof window<"u"&&(window.addEventListener("pagehide",jy),Pa.addEventListener("visibilitychange",qy),me.push(()=>{window.removeEventListener("pagehide",jy),Pa.removeEventListener("visibilitychange",qy)}));let zy="persona-attachment-drop-active",ka=0,Ju=()=>{ka=0,de.classList.remove(zy)},gi=()=>o.attachments?.enabled===!0&&Ze!==null&&!Eo(),Vy=i=>{!op(i.dataTransfer)||!gi()||(ka++,ka===1&&de.classList.add(zy))},Ky=i=>{!op(i.dataTransfer)||!gi()||(ka--,ka<=0&&Ju())},Gy=i=>{!op(i.dataTransfer)||!gi()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Yy=i=>{if(!op(i.dataTransfer)||!gi())return;i.preventDefault(),i.stopPropagation(),Ju();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&Ze.handleFiles(c)},Pr=!0;de.addEventListener("dragenter",Vy,Pr),de.addEventListener("dragleave",Ky,Pr),e.addEventListener("dragover",Gy,Pr),e.addEventListener("drop",Yy,Pr);let Hc=e.ownerDocument,Qy=i=>{gi()&&i.preventDefault()},Xy=i=>{gi()&&i.preventDefault()};Hc.addEventListener("dragover",Qy),Hc.addEventListener("drop",Xy),me.push(()=>{nt?.destroy(),nt=null,Ku(),xo?.destroy(),xo=null,jo?.destroy(),jo=null,hr?.destroy(),hr=null,yr?.destroy(),yr=null,fr=null,Tp=null,qp(),ra.destroy(),ci&&clearTimeout(ci),ts(),ys?.abort(),ys=null,Ze?.destroy(),Ze=null,Ce.destroy(),Pa.removeEventListener("keydown",Ay,!0),Wt?.destroy()}),me.push(()=>{de.removeEventListener("dragenter",Vy,Pr),de.removeEventListener("dragleave",Ky,Pr),e.removeEventListener("dragover",Gy,Pr),e.removeEventListener("drop",Yy,Pr),Hc.removeEventListener("dragover",Qy),Hc.removeEventListener("drop",Xy),Ju()}),me.push(()=>{k.cancel()}),Et?me.push(()=>{Et?.destroy()}):un&&me.push(()=>{un?.remove()});let Tt={update(i){let c=o.toolCall,g=o.messageActions,f=o.layout?.messages,b=o.colorScheme,v=o.loadingIndicator,B=o.iterationDisplay,U=o.features?.showReasoning,$=o.features?.showToolCalls,j=o.features?.toolCallDisplay,Q=o.features?.reasoningDisplay,oe=o.features?.streamAnimation?.type,ue=o.features?.history?.enabled===!0,Xe=o.features?.history?.provider,dt=o.getIdentityProof,mt=o.clientToken,Qt=o.contextMentions;o=Jd({...o,features:s},i),s=o.features,o=Qd(o),r(),Dp(),ki(e,o),yl(e,o),bl(e,o),$o(),ao(),o.colorScheme!==b&&Zf();let $t=Xd.getForInstance(o.plugins);a.length=0,a.push(...$t),Jh(),ce=o.launcher?.enabled??!0,Je=o.launcher?.autoExpand??!1,vn=o.features?.showReasoning??!0,q=o.features?.showToolCalls??!0,N=o.features?.scrollToBottom??{};let Pt=Bn();z=o.features?.scrollBehavior??{},Pt!==Bn()&&(co(),Mn()),gh(),xf(),Vt();let an=x;if(x=o.features?.showEventStreamToggle??!1,x&&!an){if(He||(xl(),k.setSSEEventCallback((X,Ve)=>{o.onSSEEvent?.(X,Ve),yp(X,Ve)})),!tt&&Ee){let X=o.features?.eventStream?.classNames,Ve="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(X?.toggleButton?" "+X.toggleButton:"");tt=E("button",Ve),tt.style.width="28px",tt.style.height="28px",tt.style.color=hn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Ye=It(hx,"18px","currentColor",1.5);Ye&&tt.appendChild(Ye);let ot=_e.clearChatButtonWrapper,wt=_e.closeButtonWrapper,on=ot||wt;on&&on.parentNode===Ee?Ee.insertBefore(tt,on):Ee.appendChild(tt),tt.addEventListener("click",()=>{Gt?Fs():Lp()})}}else!x&&an&&(Fs(),tt&&(tt.remove(),tt=null),He?.clear(),Te?.destroy(),He=null,Te=null,rt?.reset(),rt=null,Ke=null);if(o.launcher?.enabled===!1&&Et&&(Et.destroy(),Et=null),o.launcher?.enabled===!1&&un&&(un.remove(),un=null),o.launcher?.enabled!==!1&&!Et&&!un){let{instance:X,element:Ve}=Pm({config:o,plugins:a,onToggle:Py});Et=X,X||(un=Ve),e.appendChild(Ve)}Et&&Et.update(o),Aa(),jr&&o.launcher?.subtitle!==void 0&&(jr.textContent=o.launcher.subtitle);let et=o.layout?.header;if(et?.layout!==Ue&&Ee){let X=et?ml(o,et,{showClose:Be(),onClose:()=>gt(!1,"user")}):$r({config:o,showClose:Be(),onClose:()=>gt(!1,"user")});Hn.replaceHeader(X),Ee=Hn.header.element,Mt=Hn.header.iconHolder,gr=Hn.header.headerTitle,jr=Hn.header.headerSubtitle,Fe=Hn.header.closeButton,Ue=et?.layout,Aa()}else if(et){if(Mt&&(Mt.style.display=et.showIcon===!1?"none":""),gr&&(gr.style.display=et.showTitle===!1?"none":""),jr&&(jr.style.display=et.showSubtitle===!1?"none":""),Fe){let X=Be()&&et.showCloseButton!==!1;Fe.style.display=X?"":"none"}if(_e.clearChatButtonWrapper){let X=et.showClearChat;if(X!==void 0){_e.clearChatButtonWrapper.style.display=X?"":"none";let{closeButtonWrapper:Ve}=_e;Ve&&!Ve.classList.contains("persona-absolute")&&(X?Ve.classList.remove("persona-ml-auto"):Ve.classList.add("persona-ml-auto"))}}}let Lo=o.layout?.showHeader!==!1;Ee&&(Ee.style.display=Lo?"":"none");let or=o.layout?.showFooter!==!1;Le&&(Le.style.display=or?"":"none"),zr(),Vt(),ce!==Oe?ce?gt(Je,"auto"):(ve=!0,da()):Je!==F&>(Je,"auto"),F=Je,Oe=ce,Ta(),_y();let Cs=JSON.stringify(o.toolCall)!==JSON.stringify(c),uo=JSON.stringify(o.messageActions)!==JSON.stringify(g),tn=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),go=o.loadingIndicator?.render!==v?.render||o.loadingIndicator?.renderIdle!==v?.renderIdle||o.loadingIndicator?.showBubble!==v?.showBubble,mi=o.iterationDisplay!==B,L=(o.features?.showReasoning??!0)!==(U??!0)||(o.features?.showToolCalls??!0)!==($??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(j)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(Q);(Cs||uo||tn||go||mi||L)&&k&&(ns++,Yn(Pe,k.getMessages(),ut));let Ae=o.features?.streamAnimation?.type;if(Ae!==oe&&Ae&&Ae!=="none"){let X=Fp(Ae,o.features?.streamAnimation?.plugins);X&&dl(X,e)}let re=o.launcher??{},kt=re.headerIconHidden??!1,Ut=o.layout?.header?.showIcon,nn=kt||Ut===!1,jt=re.headerIconName,Kt=re.headerIconSize??"48px";if(Mt){let X=Ee,Ve=X?.querySelector(".persona-flex-col");if(nn)Mt.style.display="none",X&&Ve&&!X.contains(Ve)&&X.insertBefore(Ve,X.firstChild);else{if(Mt.style.display="",Mt.style.height=Kt,Mt.style.width=Kt,X&&Ve&&(X.contains(Mt)?Mt.nextSibling!==Ve&&(Mt.remove(),X.insertBefore(Mt,Ve)):X.insertBefore(Mt,Ve)),jt){let ot=parseFloat(Kt)||24,wt=le(jt,ot*.6,"currentColor",1);wt?Mt.replaceChildren(wt):Mt.textContent=re.agentIconText??"\u{1F4AC}"}else if(re.iconUrl){let ot=Mt.querySelector("img");if(ot)ot.src=re.iconUrl,ot.style.height=Kt,ot.style.width=Kt;else{let wt=document.createElement("img");wt.src=re.iconUrl,wt.alt="",wt.className="persona-rounded-xl persona-object-cover",wt.style.height=Kt,wt.style.width=Kt,Mt.replaceChildren(wt)}}else{let ot=Mt.querySelector("svg"),wt=Mt.querySelector("img");(ot||wt)&&Mt.replaceChildren(),Mt.textContent=re.agentIconText??"\u{1F4AC}"}let Ye=Mt.querySelector("img");Ye&&(Ye.style.height=Kt,Ye.style.width=Kt)}}let Lt=o.layout?.header?.showTitle,cn=o.layout?.header?.showSubtitle;if(gr&&(gr.style.display=Lt===!1?"none":""),jr&&(jr.style.display=cn===!1?"none":""),Fe){let X=Be()&&o.layout?.header?.showCloseButton!==!1;if(Fe.style.display=X?"":"none",!be()){let Xt=re.closeButtonSize??"";Fe.style.height=Xt,Fe.style.width=Xt,Fe.style.minWidth=Xt,Fe.style.minHeight=Xt}let Ve=re.closeButtonPlacement??"inline",{closeButtonWrapper:Ye}=_e,ot=Ve==="top-right",wt=Ye?.classList.contains("persona-absolute");if(Ye&&ot!==wt)if(Ye.remove(),ot){Ye.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Xt=ha??de;Xt.style.position="relative",Xt.appendChild(Ye)}else{let Xt=re.clearChat?.placement??"inline",Jt=re.clearChat?.enabled??!0;Ye.className=Jt&&Xt==="inline"?"":"persona-ml-auto",Ee&&Ee.appendChild(Ye)}if(Fe.style.color=re.closeButtonColor||hn.actionIconColor,re.closeButtonBackgroundColor?(Fe.style.backgroundColor=re.closeButtonBackgroundColor,Fe.classList.remove("hover:persona-bg-gray-100")):(Fe.style.backgroundColor="",Fe.classList.add("hover:persona-bg-gray-100")),re.closeButtonBorderWidth||re.closeButtonBorderColor){let Xt=re.closeButtonBorderWidth||"0px",Jt=re.closeButtonBorderColor||"transparent";Fe.style.border=`${Xt} solid ${Jt}`,Fe.classList.remove("persona-border-none")}else Fe.style.border="",Fe.classList.add("persona-border-none");re.closeButtonBorderRadius?(Fe.style.borderRadius=re.closeButtonBorderRadius,Fe.classList.remove("persona-rounded-full")):(Fe.style.borderRadius="",Fe.classList.add("persona-rounded-full")),re.closeButtonPaddingX?(Fe.style.paddingLeft=re.closeButtonPaddingX,Fe.style.paddingRight=re.closeButtonPaddingX):(Fe.style.paddingLeft="",Fe.style.paddingRight=""),re.closeButtonPaddingY?(Fe.style.paddingTop=re.closeButtonPaddingY,Fe.style.paddingBottom=re.closeButtonPaddingY):(Fe.style.paddingTop="",Fe.style.paddingBottom=""),Hd(Fe,re.closeButtonIconName??"x",{iconSize:be()?Am:void 0,iconText:re.closeButtonIconText??"\xD7"});let on=re.closeButtonTooltipText??"Close chat",mo=re.closeButtonShowTooltip??!0;Fe.setAttribute("aria-label",on),Ye&&Zt({anchor:Fe,trigger:Ye,text:()=>Fe?.getAttribute("aria-label")??on,enabled:mo})}let{clearChatButton:Re,clearChatButtonWrapper:De}=_e;if(Re){let X=re.clearChat??{},Ve=X.enabled??!0,Ye=o.layout?.header?.showClearChat,ot=Ye!==void 0?Ye:Ve,wt=X.placement??"inline";if(De){De.style.display=ot?"":"none";let{closeButtonWrapper:on}=_e;!be()&&on&&!on.classList.contains("persona-absolute")&&(ot?on.classList.remove("persona-ml-auto"):on.classList.add("persona-ml-auto"));let mo=wt==="top-right",Xt=De.classList.contains("persona-absolute");if(!be()&&mo!==Xt&&ot){if(De.remove(),mo){De.className="persona-absolute persona-top-4 persona-z-50",De.style.right="48px";let Io=ha??de;Io.style.position="relative",Io.appendChild(De)}else{De.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",De.style.right="";let Io=_e.closeButtonWrapper;Ee&&Io&&Io.parentElement===Ee?Ee.insertBefore(De,Io):Ee&&Ee.appendChild(De)}let Jt=_e.closeButtonWrapper;Jt&&!Jt.classList.contains("persona-absolute")&&(mo?Jt.classList.add("persona-ml-auto"):Jt.classList.remove("persona-ml-auto"))}}if(ot){if(!be()){let Jt=X.size??"";Re.style.height=Jt,Re.style.width=Jt,Re.style.minWidth=Jt,Re.style.minHeight=Jt}let on=X.iconColor??"";if(Re.style.color=on||hn.actionIconColor,Hd(Re,X.iconName??"refresh-cw",{iconSize:be()?Mm:void 0}),X.backgroundColor?(Re.style.backgroundColor=X.backgroundColor,Re.classList.remove("hover:persona-bg-gray-100")):(Re.style.backgroundColor="",Re.classList.add("hover:persona-bg-gray-100")),X.borderWidth||X.borderColor){let Jt=X.borderWidth||"0px",Io=X.borderColor||"transparent";Re.style.border=`${Jt} solid ${Io}`,Re.classList.remove("persona-border-none")}else Re.style.border="",Re.classList.add("persona-border-none");X.borderRadius?(Re.style.borderRadius=X.borderRadius,Re.classList.remove("persona-rounded-full")):(Re.style.borderRadius="",Re.classList.add("persona-rounded-full")),X.paddingX?(Re.style.paddingLeft=X.paddingX,Re.style.paddingRight=X.paddingX):(Re.style.paddingLeft="",Re.style.paddingRight=""),X.paddingY?(Re.style.paddingTop=X.paddingY,Re.style.paddingBottom=X.paddingY):(Re.style.paddingTop="",Re.style.paddingBottom="");let mo=X.tooltipText??"Clear chat",Xt=X.showTooltip??!0;Re.setAttribute("aria-label",mo),De&&Zt({anchor:Re,trigger:De,text:()=>Re?.getAttribute("aria-label")??mo,enabled:Xt})}}let we=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zd],dn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ji.message,ji.messageAndClick];ye=ep({parsers:we,handlers:dn,getSessionMetadata:pe,updateSessionMetadata:se,emit:A.emit,documentRef:typeof document<"u"?document:null}),ut=Cx(o,ye,Rt),lA(),k.updateConfig(o),(o.features?.history?.enabled===!0!==ue||o.features?.history?.provider!==Xe||o.getIdentityProof!==dt||o.clientToken!==mt)&&(Tn({restoreFocus:!1}),qh()),Er(),yc(),Yn(Pe,k.getMessages(),ut),zs(),tc(),iA(),pa(k.isStreaming()),Qt!==o.contextMentions&&Uy();let kr=o.voiceRecognition?.enabled===!0,Pn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),kn=In(o.voiceRecognition?.provider);if(kr&&(Pn||kn))if(!ne||!On){let X=Pi(o);if(X){ne=X.button,On=X.wrapper;let Ve=vo&&vo.parentElement===Al?vo:null;Al?Al.insertBefore(On,Ve):ro?.appendChild(On),nt&&(nt.micButton=ne),nt?.addListener(ne,"click",Qu),ne.disabled=Eo()||k.isStreaming()&&!Xp()}}else{let X=o.voiceRecognition??{},Ve=o.sendButton??{},Ye=X.iconName??"mic",ot=X.iconSize,wt=parseFloat(ot??"")||mn;ne.classList.add(jn),ne.classList.toggle(yo,!ot),ne.style.width=ot??"",ne.style.height=ot??"",ne.style.minWidth=ot??"",ne.style.minHeight=ot??"";let on=X.iconColor??Ve.textColor;ne.innerHTML="";let mo=le(Ye,wt,on||"currentColor",1.5);mo?ne.appendChild(mo):ne.textContent="\u{1F3A4}";let Xt=X.backgroundColor??Ve.backgroundColor;Xt?ne.style.backgroundColor=Xt:ne.style.backgroundColor="",on?ne.style.color=on:ne.style.color="var(--persona-text, #111827)",X.borderWidth?(ne.style.borderWidth=X.borderWidth,ne.style.borderStyle="solid"):(ne.style.borderWidth="",ne.style.borderStyle=""),X.borderColor?ne.style.borderColor=X.borderColor:ne.style.borderColor="",X.paddingX?(ne.style.paddingLeft=X.paddingX,ne.style.paddingRight=X.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),X.paddingY?(ne.style.paddingTop=X.paddingY,ne.style.paddingBottom=X.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let Jt=X.tooltipText??"Start voice recognition",Io=X.showTooltip??!1;ne.setAttribute("aria-label",Jt),On&&Zt({anchor:ne,trigger:On,text:()=>ne?.getAttribute("aria-label")??Jt,enabled:Io}),On.style.display="",ne.disabled=Eo()||k.isStreaming()&&!Xp()}else ne&&On&&(On.style.display="none",In(o.voiceRecognition?.provider)?k.isVoiceActive()&&k.toggleVoice():ko&&Tr());if(o.attachments?.enabled===!0){if(!xn||!xt){let X=o.attachments??{};Sn||(Sn=E("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Sn.style.display="none",(ae.parentElement??ro).insertBefore(Sn,ae)),yt||(yt=document.createElement("input"),yt.type="file",yt.accept=(X.allowedTypes??ar).join(","),yt.multiple=(X.maxFiles??4)>1,yt.style.display="none",yt.setAttribute("aria-label","Attach files"),(ae.parentElement??ro).insertBefore(yt,ae)),xn=E("div","persona-send-button-wrapper"),xt=E("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${jn} ${yo}`),xt.type="button",xt.setAttribute("aria-label",X.buttonTooltipText??"Attach file");let Ve=X.buttonIconName??"paperclip";xt.style.fontSize="18px",xt.style.lineHeight="1";let Ye=le(Ve,mn,"currentColor",1.5);Ye?xt.appendChild(Ye):xt.textContent="\u{1F4CE}",xt.addEventListener("click",wt=>{wt.preventDefault(),yt?.click()}),xn.appendChild(xt);let ot=X.buttonTooltipText??"Attach file";Zt({anchor:xt,trigger:xn,text:()=>xt?.getAttribute("aria-label")??ot}),wp?wp.append(xn):ro.appendChild(xn),nt&&(nt.attachmentButton=xt,nt.attachmentInput=yt??void 0,nt.attachmentPreviews=Sn??void 0),!Ze&&yt&&Sn&&(Ze=Mi.fromConfig(X,Sf),Ze.setPreviewsContainer(Sn),nt?.addListener(yt,"change",async()=>{Ze&&yt?.files&&(await Ze.handleFileSelect(yt.files),yt.value="")}))}else{xn.style.display="";let X=o.attachments??{};yt&&(yt.accept=(X.allowedTypes??ar).join(","),yt.multiple=(X.maxFiles??4)>1),Ze&&Ze.updateConfig({allowedTypes:X.allowedTypes,maxFileSize:X.maxFileSize,maxFiles:X.maxFiles,adapter:X.adapter})}if(de.querySelector(".persona-attachment-drop-overlay")?.remove(),de.appendChild(wx(o.attachments?.dropOverlay)),xt){let X=o.attachments??{},Ve=X.buttonTooltipText??"Attach file";xt.setAttribute("aria-label",Ve),xt.textContent="";let Ye=le(X.buttonIconName??"paperclip",mn,"currentColor",1.5);Ye?xt.appendChild(Ye):xt.textContent="\u{1F4CE}",xn&&Zt({anchor:xt,trigger:xn,text:()=>xt?.getAttribute("aria-label")??Ve})}}else xn&&(xn.style.display="none"),Ze&&Ze.clearAttachments(),de.querySelector(".persona-attachment-drop-overlay")?.remove();let We=o.sendButton??{},rr=We.useIcon??!1,Ot=We.iconText??"\u2191",Ln=We.iconName,Ia=We.tooltipText??"Send message",SM=We.showTooltip??!1,Ra=We.size,AM=parseFloat(Ra??"")||Ug,Wc=We.backgroundColor,Ha=We.textColor;if(rr){if(Me.style.width=Ra??"",Me.style.height=Ra??"",Me.style.minWidth=Ra??"",Me.style.minHeight=Ra??"",Me.style.fontSize="18px",Me.style.lineHeight="1",Ha?Me.style.color=Ha:Me.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!k.isStreaming())if(Me.innerHTML="",Ln){let X=parseFloat(We.iconSize??"")||Math.round(AM*.5),Ve=Ha?.trim()||"currentColor",Ye=We.iconStrokeWidth??2,ot=le(Ln,X,Ve,Ye),wt=le(We.stopIconName??"square",X,Ve,Ye);ot&&wt?Me.appendChild(jg(ot,wt)):ot?Me.appendChild(ot):Me.textContent=Ot}else Me.textContent=Ot;Me.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${jn}`,Wc?(Me.style.backgroundColor=Wc,Me.classList.remove("persona-bg-persona-primary")):(Me.style.backgroundColor="",Me.classList.add("persona-bg-persona-primary"))}else Me.textContent=o.copy?.sendButtonLabel??"Send",Me.style.width="",Me.style.height="",Me.style.minWidth="",Me.style.minHeight="",Me.style.fontSize="",Me.style.lineHeight="",Me.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wc?(Me.style.backgroundColor=Wc,Me.classList.remove("persona-bg-persona-accent")):Me.classList.add("persona-bg-persona-accent"),Ha?Me.style.color=Ha:Me.classList.add("persona-text-white");We.borderWidth?(Me.style.borderWidth=We.borderWidth,Me.style.borderStyle="solid"):(Me.style.borderWidth="",Me.style.borderStyle=""),We.borderColor?Me.style.borderColor=We.borderColor:Me.style.borderColor="",We.paddingX?(Me.style.paddingLeft=We.paddingX,Me.style.paddingRight=We.paddingX):(Me.style.paddingLeft="",Me.style.paddingRight=""),We.paddingY?(Me.style.paddingTop=We.paddingY,Me.style.paddingBottom=We.paddingY):(Me.style.paddingTop="",Me.style.paddingBottom=""),k.isStreaming()||Me.setAttribute("aria-label",Ia),Zl(),vo&&Zt({anchor:Me,trigger:vo,text:()=>Me.getAttribute("aria-label")??Ia,enabled:SM}),Df();let Jy=vd(Ce.getState().activeModeIds,o.composer?.modes);Ce.setActiveModeIds(Jy),_s().length>0!==!!jo&&Rp(),jo?.render(Jy,_s());for(let X of[...Ds.keys()])bd(X,o.composer?.modeGroups)||Ds.delete(X);Ds.forEach(X=>X.repaint()),fr?.repaint(),xo?.resolve();let Oc=Dr(o,be());if(Np(),Oc){Pe.style.maxWidth=Oc,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%",Wn.style.maxWidth=Oc,Wn.style.marginLeft="auto",Wn.style.marginRight="auto",Wn.style.width="100%";for(let X of[ro,ur,Sn,st])X&&(X.style.maxWidth=Oc,X.style.marginLeft="auto",X.style.marginRight="auto",X.style.width="100%")}else{Pe.style.maxWidth="",Pe.style.marginLeft="",Pe.style.marginRight="",Pe.style.width="",Wn.style.maxWidth="",Wn.style.marginLeft="",Wn.style.marginRight="",Wn.style.width="";for(let X of[ro,ur,Sn,st])X&&(X.style.maxWidth="",X.style.marginLeft="",X.style.marginRight="",X.style.width="")}let Lr=o.statusIndicator??{},MM=Lr.visible??!0;if(st.style.display=MM?"":"none",k){let X=k.getStatus();Sl(st,(Ye=>Ye==="idle"?Lr.idleText??qt.idle:Ye==="connecting"?Lr.connectingText??qt.connecting:Ye==="connected"?Lr.connectedText??qt.connected:Ye==="error"?Lr.errorText??qt.error:qt[Ye])(X),Lr,X)}st.classList.remove("persona-text-left","persona-text-center","persona-text-right");let EM=Lr.align==="left"?"persona-text-left":Lr.align==="center"?"persona-text-center":"persona-text-right";st.classList.add(EM),Ip(),Zp(),so(),bp()},open(){Be()&>(!0,"api")},close(){Be()&>(!1,"api")},toggle(){Be()&>(!ve,"api")},reconnect(){k.reconnectNow()},clearChat(){qo=!1,k.clearMessages(),Nt.clear(),Mn();try{localStorage.removeItem(qi),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qi}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==qi)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),K?.clear&&zl(()=>K.clear(),"[AgentWidget] Failed to clear storage adapter:"),Z={},ye.syncFromMetadata(),Ze?.clearAttachments(),Kl(),Ns(void 0),wo(void 0),ts(),He?.clear(),rt?.reset(),ht?.update()},setMessage(i){return!ae||k.isStreaming()||Eo()?!1:(!ve&&Be()&>(!0,"system"),ae.value=i,ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(k.isStreaming()||ls())return!1;let c=i?.trim()||ae.value.trim();return c?(!ve&&Be()&>(!0,"system"),ae.value="",ae.style.height="auto",Co(),Pc(c,{consumeDraft:!1}),!0):!1},getComposerState(){return Ce.getState()},setQuote(i){let c=i?.text?.trim();c&&wo({...i,text:c})},clearQuote(){wo(void 0)},startVoiceRecognition(){return k.isStreaming()?!1:In(o.voiceRecognition?.provider)?(k.isVoiceActive()||k.isBargeInActive()||(!ve&&Be()&>(!0,"system"),ze.manuallyDeactivated=!1,lo(),k.toggleVoice().then(()=>{ze.active=k.isVoiceActive(),Go("user"),k.isVoiceActive()&&ui()})),!0):ko?!0:Ty()?(!ve&&Be()&>(!0,"system"),ze.manuallyDeactivated=!1,lo(),Lc("user"),!0):!1},stopVoiceRecognition(){return In(o.voiceRecognition?.provider)?!k.isVoiceActive()&&!k.isBargeInActive()?!1:((k.isBargeInActive()?k.deactivateBargeIn():k.toggleVoice()).then(()=>{ze.active=!1,ze.manuallyDeactivated=!0,lo(),Go("user"),nr()}),!0):ko?(ze.manuallyDeactivated=!0,lo(),Tr("user"),!0):!1},injectMessage(i){return!ve&&Be()&>(!0,"system"),k.injectMessage(i)},injectAssistantMessage(i){!ve&&Be()&>(!0,"system");let c=k.injectAssistantMessage(i);return xe&&(xe=!1,bt&&(clearTimeout(bt),bt=null),setTimeout(()=>{k&&!k.isStreaming()&&k.continueConversation()},100)),c},injectUserMessage(i){return!ve&&Be()&>(!0,"system"),k.injectUserMessage(i)},injectSystemMessage(i){return!ve&&Be()&>(!0,"system"),k.injectSystemMessage(i)},injectMessageBatch(i){return!ve&&Be()&>(!0,"system"),k.injectMessageBatch(i)},injectComponentDirective(i){return!ve&&Be()&>(!0,"system"),k.injectComponentDirective(i)},injectTestMessage(i){!ve&&Be()&>(!0,"system"),k.injectTestEvent(i)},async connectStream(i,c){return k.connectStream(i,c)},__pushEventStreamEvent(i){x&&(xl(),yp(i.type,i.payload))},showEventStream(){x&&Lp()},hideEventStream(){Gt&&Fs()},isEventStreamVisible(){return Gt},listConversations(i){return k.listConversations(i)},getActiveConversationId(){return k.getActiveConversationId()},openConversation(i,c){return Ou(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return Bu({focusComposer:i?.focus===!0})},deleteConversation(i){return hy(i)},renameConversation(i,c){return _u(i,{title:c})},setConversationStarred(i,c){return _u(i,{starred:c})},clearConversationHistory(i){return yy(i)},resetHistoryIdentity(){return by()},async getVisitorToken(){let i=Qn;if(!i)return null;let c=await i.get();return i===Qn?c:null},getHistoryIdentityStatus(){return Fn?Fn.getIdentityStatus():bu()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return Sa({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){Tn(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return At},showArtifacts(){bn(o)&&(qo=!1,Us=!0,ao(),qe?.setMobileOpen(!0))},hideArtifacts(){bn(o)&&(qo=!0,ao())},upsertArtifact(i){return bn(o)?(sr(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(qo=!1,Us=!0),k.upsertArtifact(i)):null},selectArtifact(i){bn(o)&&k.selectArtifact(i)},clearArtifacts(){bn(o)&&k.clearArtifacts()},getArtifacts(){return k?.getArtifacts()??[]},getSelectedArtifactId(){return k?.getSelectedArtifactId()??null},focusInput(){return ce&&!ve&&!be()||!ae?!1:(ae.focus(),!0)},async resolveApproval(i,c,g){let b=k.getMessages().find(v=>v.variant==="approval"&&v.approval?.id===i);if(!b?.approval)throw new Error(`Approval not found: ${i}`);if(b.approval.toolType==="webmcp"){k.resolveWebMcpApproval(b.id,c);return}return k.resolveApproval(b.approval,c,g)},setFollowUpSuggestions(i){IS(i)},clearFollowUpSuggestions(){uh()},getMessages(){return k.getMessages()},getStatus(){return k.getStatus()},getPersistentMetadata(){return{...Z}},updatePersistentMetadata(i){se(i)},on(i,c){return A.on(i,c)},off(i,c){A.off(i,c)},isOpen(){return Be()&&ve},isVoiceActive(){return ze.active},toggleReadAloud(i){k.toggleReadAloud(i)},stopReadAloud(){k.stopSpeaking()},getReadAloudState(i){return k.getReadAloudState(i)},onReadAloudChange(i){return k.onReadAloudChange(i)},getState(){return{open:Be()&&ve,launcherEnabled:ce,voiceActive:ze.active,streaming:k.isStreaming()}},showCSATFeedback(i){!ve&&Be()&>(!0,"system");let c=Pe.querySelector(".persona-feedback-container");c&&c.remove();let g=Xm({onSubmit:async(f,b)=>{k.isClientTokenMode()&&await k.submitCSATFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});Pe.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!ve&&Be()&>(!0,"system");let c=Pe.querySelector(".persona-feedback-container");c&&c.remove();let g=Jm({onSubmit:async(f,b)=>{k.isClientTokenMode()&&await k.submitNPSFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});Pe.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,c){return k.submitCSATFeedback(i,c)},async submitNPSFeedback(i,c){return k.submitNPSFeedback(i,c)},destroy(){pu(),ps!=null&&(clearInterval(ps),ps=null),me.forEach(i=>i()),Ge.remove(),Yt?.remove(),Et?.destroy(),un?.remove(),Xr&&Fe.removeEventListener("click",Xr)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:Tt,getMessages:Tt.getMessages,getStatus:Tt.getStatus,getMetadata:Tt.getPersistentMetadata,updateMetadata:Tt.updatePersistentMetadata,clearHistory:()=>Tt.clearChat(),setVoiceActive:g=>g?Tt.startVoiceRecognition():Tt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,me.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),c=j=>{let Q=j.detail;(!Q?.instanceId||Q.instanceId===i)&&Tt.focusInput()};if(window.addEventListener("persona:focusInput",c),me.push(()=>{window.removeEventListener("persona:focusInput",c)}),x){let j=oe=>{let ue=oe.detail;(!ue?.instanceId||ue.instanceId===i)&&Tt.showEventStream()},Q=oe=>{let ue=oe.detail;(!ue?.instanceId||ue.instanceId===i)&&Tt.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",Q),me.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",Q)})}let g=j=>{let Q=j.detail;(!Q?.instanceId||Q.instanceId===i)&&Tt.showHistory()},f=j=>{let Q=j.detail;(!Q?.instanceId||Q.instanceId===i)&&Tt.hideHistory()};window.addEventListener("persona:showHistory",g),window.addEventListener("persona:hideHistory",f),me.push(()=>{window.removeEventListener("persona:showHistory",g),window.removeEventListener("persona:hideHistory",f)});let b=j=>{let Q=j.detail;(!Q?.instanceId||Q.instanceId===i)&&Tt.showArtifacts()},v=j=>{let Q=j.detail;(!Q?.instanceId||Q.instanceId===i)&&Tt.hideArtifacts()},B=j=>{let Q=j.detail;Q?.instanceId&&Q.instanceId!==i||Q?.artifact&&Tt.upsertArtifact(Q.artifact)},U=j=>{let Q=j.detail;Q?.instanceId&&Q.instanceId!==i||typeof Q?.id=="string"&&Tt.selectArtifact(Q.id)},$=j=>{let Q=j.detail;(!Q?.instanceId||Q.instanceId===i)&&Tt.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",B),window.addEventListener("persona:selectArtifact",U),window.addEventListener("persona:clearArtifacts",$),me.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",B),window.removeEventListener("persona:selectArtifact",U),window.removeEventListener("persona:clearArtifacts",$)})}let to=qI(o.persistState);if(to&&Be()){let i=zI(to.storage),c=`${to.keyPrefix}widget-open`,g=`${to.keyPrefix}widget-voice`,f=`${to.keyPrefix}widget-voice-mode`;if(i){let b=to.persist?.openState&&i.getItem(c)==="true",v=to.persist?.voiceState&&i.getItem(g)==="true",B=to.persist?.voiceState&&i.getItem(f)==="true";if(b&&(Et?.setPanelOpen(!0,"auto"),setTimeout(()=>{Tt.open(),setTimeout(()=>{if(v||B)Tt.startVoiceRecognition();else if(to.persist?.focusInput){let U=e.querySelector("textarea");U&&U.focus()}},100)},0)),to.persist?.openState&&(A.on("widget:opened",()=>{i.setItem(c,"true")}),A.on("widget:closed",()=>{i.setItem(c,"false")})),to.persist?.voiceState&&(A.on("voice:state",U=>{i.setItem(g,U.active?"true":"false")}),A.on("user:message",U=>{i.setItem(f,U.viaVoice?"true":"false")})),to.clearOnChatClear){let U=()=>{i.removeItem(c),i.removeItem(g),i.removeItem(f)},$=()=>U();window.addEventListener("persona:clear-chat",$),me.push(()=>{window.removeEventListener("persona:clear-chat",$)})}}}if(J&&Be()&&(Et?.setPanelOpen(!0,"auto"),setTimeout(()=>{Tt.open()},0)),Js(),!RS){let i=Oa(()=>{k&&(ns++,Nt.clear(),Yn(Pe,k.getMessages(),ut))});me.push(i)}w=()=>{k&&(ns++,Nt.clear(),Yn(Pe,k.getMessages(),ut))},k.getMessages().length>0&&Jl(),T=()=>{k&&(ns++,Nt.clear(),Yn(Pe,k.getMessages(),ut))};let wM=sb(()=>{k&&(ns++,Nt.clear(),Yn(Pe,k.getMessages(),ut))});me.push(wM);let xM=Bm(()=>{k&&(ns++,Nt.clear(),Yn(Pe,k.getMessages(),ut),lr()?.updateInlineArtifactBlocks(Pe,Gn.artifacts,{suppressTransition:!0}),ao())});return me.push(xM),Tt};var xx=(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},GI=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},YI=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},QI=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Sx=(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"},rf=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=""},Ax=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",rf(e)},tf=e=>{e.style.transition=""},nf=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=""},of=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=""},XI=(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))},JI=(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)},ZI=e=>{let t=Ps(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:fn(t,r)??r;return{inset:o(n?.inset,Cd),canvasBackground:o(n?.canvasBackground,wd)}},Mx=(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},eR=(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??"";XI(e,t,n,o,p),JI(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,w=s?.launcher?.mobileBreakpoint??640,S=h!=null?h.innerWidth<=w:!1;if(C&&S&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),nf(t),tf(o),Ax(o),of(n),rp(r,o),Mx(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"),Ax(o),GI(o,d.maxHeight),Mx(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",nf(t),tf(o),of(n),rp(r,o);let I=d.animate?"transform 180ms ease":"none",O=d.side==="right"?"translateX(100%)":"translateX(-100%)",T=a?"translateX(0)":O;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=I,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",tf(o),rf(o),rp(r,o);let I=xx(d.width,e.clientWidth),O=Math.max(0,e.clientWidth),T=d.animate?"margin-left 180ms ease":"none",R=d.side==="right"?a?-I:0:a?0:-I;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${O+I}px`,t.style.transition=T,t.style.marginLeft=`${R}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${O}px`,n.style.maxWidth=`${O}px`,n.style.minWidth=`${O}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="",nf(t),rf(o),of(n),rp(r,o);let I=d.reveal==="emerge";I?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let O=a?d.width:"0px",T=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",R=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${O}`,o.style.width=O,o.style.maxWidth=O,o.style.minWidth=O,o.style.minHeight="0",YI(o,d.maxHeight),o.style.overflow=I||R?"hidden":"visible",o.style.transition=T,I){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let A=u?`calc(${xx(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"}}},tR=(e,t)=>{let n=e.ownerDocument.createElement("div");return Sx(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Sx(n,o)},destroy(){n.remove()}}},nR=(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,w=()=>{C=t?.launcher?.detachedPanel===!0?ZI(t):null};w();let S=()=>{eR(a,l,d,p,u,t,m,C)},P=null,I=()=>{P?.(),P=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(P=nl(()=>{w(),S()}))},O=()=>{h(),qn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{S()}),y.observe(a)))},T=!1,R=()=>{S(),O(),m&&!T&&a.dataset.personaDockMobileFullscreen!=="true"&&(T=!0,QI(a,qn(t)))},A=a.ownerDocument.defaultView,D=()=>{R()};return A?.addEventListener("resize",D),qn(t).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),R(),I(),{mode:"docked",host:u,shell:a,syncWidgetState(K){let ie=K.launcherEnabled?K.open:!0;m!==ie&&(m=ie,R())},updateConfig(K){t=K,(t?.launcher?.enabled??!0)===!1&&(m=!0),w(),R(),I()},destroy(){A?.removeEventListener("resize",D),P?.(),P=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},sp=(e,t)=>St(t)?nR(e,t):tR(e,t);var oR=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},Ex=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},ip=[],rR=()=>[...ip],Tx=e=>{let t=oR(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=sp(t,r),a,l=[],d=(S,P)=>{let O=!(P?.launcher?.enabled??!0)||St(P),T=o.createElement("div");if(T.setAttribute("data-persona-root","true"),O&&(T.style.height="100%",T.style.display="flex",T.style.flexDirection="column",T.style.flex="1",T.style.minHeight="0",T.style.minWidth="0"),n){let R=S.attachShadow({mode:"open"});R.appendChild(T),Ex(R,o)}else S.appendChild(T),Ex(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=ef(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 P=Jd(r??{},S),I=St(r),O=St(P),T=Fr(r),R=Fr(P);if(I!==O||T!==R){h(P);return}r=P,s.updateConfig(r),a.update(S),p()},destroy(){y(),s.destroy();let S=ip.indexOf(w);S!==-1&&ip.splice(S,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},w=new Proxy(C,{get(S,P,I){if(P==="host")return s.host;if(P in S)return Reflect.get(S,P,I);let O=a[P];return typeof O=="function"?O.bind(a):O}});return ip.push(w),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=w),w};var Rx=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),sR=new Set(["button","a","input","select","textarea","details","summary"]),iR=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),sf=/\b(product|card|item|listing|result)\b/i,lf=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,aR=3e3,lR=100;function Hx(e){let t=typeof e.className=="string"?e.className:"";if(sf.test(t)||e.id&&sf.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&sf.test(o.value))return!0}return!1}function Wx(e){return lf.test((e.textContent??"").trim())}function Ox(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 cR(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Px(e){let t=e.match(lf);return t?t[0]:null}function kx(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 dR(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 pR="commerce-card",uR="result-card";function Lx(e){return!Hx(e)||!Wx(e)||!Ox(e)&&!cR(e)?0:5200}function Ix(e){return!Hx(e)||Wx(e)||!Ox(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Bx=[{id:pR,scoreElement(e){return Lx(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||lf.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Lx(e)===0)return null;let{title:n,href:o}=kx(e),r=Px((e.textContent??"").trim())??Px(t.text)??"",s=dR(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:
|
|
139
|
-
`)}}];function
|
|
137
|
+
${ht?"background: transparent !important;":""}
|
|
138
|
+
`)}if(!b&&!c){let Le="max-height: -moz-available !important; max-height: stretch !important;",Fe=g?"":"padding-top: 1.25em !important;",Be=g?"":`z-index: ${o.launcher?.zIndex??cn} !important;`;Ge.style.cssText+=Le+Fe+Be}Jp(),ro()},gu=()=>{e.style.setProperty("--persona-content-max-width",Xr(o,ve()))},Fh=!1;function $h(){o.layout?.topFade&&ee.scrollTop>1?ee.setAttribute("data-persona-top-fade","true"):ee.removeAttribute("data-persona-top-fade")}let mu=()=>{$h();let i=zm(o,ve());ve()&&o.composer?.placement&&o.debug===!0&&!Fh&&(Fh=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=rs();e.setAttribute("data-persona-composer-placement",i),e.setAttribute("data-persona-conversation-state",Kl),e.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",c.composerGap??ep),Yl()},Uh=()=>{if(ve())return;let i=Ct(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!D)return;let f=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640;if(b&&f.innerWidth<=w)return;let W=Qs(o);Ce.style.height=W.height,Ce.style.maxHeight=W.maxHeight};uu(),Qi(e,o),_l(e,o),Nl(e,o),gu(),mu(),as=()=>{uu(),Uh(),Qi(e,o),_l(e,o),Nl(e,o),gu(),mu(),Jl?e.style.setProperty("--persona-artifact-welded-outer-radius",Jl):e.style.removeProperty("--persona-artifact-welded-outer-radius"),qo(),Vp()};let me=[];me.push(()=>{Hh=!0}),me.push(()=>{h.forEach(i=>i()),m.destroy()}),me.push(()=>{document.removeEventListener("keydown",Bh)}),me.push(()=>{ha!==null&&clearTimeout(ha)});let Eo=null,To=null;me.push(()=>{Eo?.(),Eo=null,To?.(),To=null}),Ca&&me.push(()=>{Ca?.disconnect(),Ca=null}),me.push(()=>{Sa?.(),Sa=null,pu(),Mt&&(Mt.remove(),Mt=null),qe?.element.style.removeProperty("width"),qe?.element.style.removeProperty("maxWidth"),qe?.destroy()}),Q&&me.push(()=>{pn=!0,kt=null,vr!==null&&(cancelAnimationFrame(vr),vr=null),mt?.destroy(),mt=null,gt?.destroy(),gt=null,Je=null});let cs=null,jh=()=>{cs&&(cs(),cs=null),o.colorScheme==="auto"&&(cs=xl(()=>{Qi(e,o)}))};jh(),me.push(()=>{cs&&(cs(),cs=null)}),me.push(()=>{H=!0,E?.()}),me.push(()=>{L=!0});let Vh=!1;me.push(()=>{Vh=!0});let fu=(i,c)=>{let g=Tl(i,c);return g||!ax.includes(i)?g:(cx().then(f=>{if(Vh)return;ip(f.wipe),ip(f.glyphCycle);let b=Tl(i,c);b&&Ll(b,e)}).catch(()=>{}),null)},ic=o.features?.streamAnimation;if(ic?.type&&ic.type!=="none"){let i=fu(ic.type,ic.plugins);i&&Ll(i,e),me.push(()=>lx(e))}let Yo=Hl(Cr),qh=Hl(Kp),zh=Hl(ua),ds=[Yo,qh,zh];me.push(()=>{ds.forEach(i=>i.destroy())});let ps=null,T,us=null,Kh=!1,Gh=0,Yh=null,Qh=i=>i.reduce((c,g)=>g.role==="user"?c+1:c,0),Xh=i=>{for(let c=i.length-1;c>=0;c--)if(Fi(i[c]))return i[c].id??null;return null},Jh=!1,OA=()=>{Jh||o.debug!==!0||(Jh=!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".'))},Zh=!1,ey=!1,ty=(i,c)=>{Zh||o.debug!==!0||!c.enabled||c.expose||Kh||ey&&(T.isStreaming()||i.some(Fi)||(Zh=!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(!T)return;let c=i??T.getMessages(),g=oe=>{oe.render([],T,ie,c)},f=oe=>{ds.forEach(ue=>{ue!==oe&&g(ue)})};us&&(Qh(c)>Gh||Xh(c)!==Yh)&&(us=null);let b=Yr(o);ty(c,b);let w=b.enabled?nm(c):null,W=us??w,V=us?"host":"agent";if(W){let oe=o.suggestions?.followUps,ue=oe?.placement??(oe?"auto":"composer"),ot=(ue==="auto"?ve()?"composer":"after-message":ue)==="after-message"?zh:Yo;f(ot),ot.render(W,T,ie,c,o.suggestionChipsConfig,{source:V,surface:"followUp",variant:oe?.variant??"chip",behavior:oe?.behavior??"send",overflow:oe?.overflow??"wrap",maxItems:oe?.maxItems??4,config:o,plugins:u,submitPrompt:Kc});return}if(c.some(oe=>oe.role==="user")){ds.forEach(g);return}let F=o.future?.v5Defaults===!0,q=ya(),Y=o.suggestions?.starters??(F?{}:void 0);if(Y){let oe=Ys(rs(),c),ue=Y.placement??"auto",Ue=ue==="auto"?oe?"welcome":"composer":ue;if(Ue==="welcome"&&!oe){OA(),ds.forEach(g);return}let ot=Ue==="welcome"?qh:Yo;f(ot),ot.render(Y.items??o.suggestionChips,T,ie,c,o.suggestionChipsConfig,{surface:"starter",variant:Y.variant??(F&&!q?"chip":"card"),behavior:Y.behavior??"send",overflow:Y.overflow??"wrap",maxItems:Y.maxItems??(F&&!q?3:4),config:o,plugins:u,submitPrompt:Kc});return}f(Yo),Yo.render(o.suggestionChips,T,ie,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:u,submitPrompt:Kc})},ny=()=>{us&&(us=null,gs())},BA=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){ny();return}let g=T?T.getMessages():[];us=c,Kh=!0,Gh=Qh(g),Yh=Xh(g),gs(g)},Bn=!1,Nt=Yw(),ci=new Map,ms=new Map,Er=new Map,fs=null,Tr=null;function hs(){if(!fs)return;let i=fs;fs=null,Tr?.destroy(),Tr=null,Nt.delete(i),le.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),T&&Yn(he,T.getMessages(),N)}let ys=0,DA=Bo()!==null,Dn=ex(),_n=0,Pr=null,An=!1,ac=!1,kr=0,Kt=null,bs=null,hu=!1,di=!1,vs=null,Aa=!0,lc=!1,pi=null,cc=!1,Lr=()=>{cc=!0,$A()},yu=null,_A=4,Qo=24,NA=80,FA=1e3,Xo=null,oy=()=>{e.setAttribute("data-persona-scrollbar",Yp()),Yp()!=="on-scroll"&&(Xo!==null&&clearTimeout(Xo),Xo=null,ee.removeAttribute("data-persona-scrollbar-visible"))},$A=()=>{Yp()==="on-scroll"&&(ee.setAttribute("data-persona-scrollbar-visible",""),Xo!==null&&clearTimeout(Xo),Xo=setTimeout(()=>{Xo=null,Ks(ee,Qo)&&ee.removeAttribute("data-persona-scrollbar-visible")},FA))};oy(),me.push(()=>{Xo!==null&&clearTimeout(Xo)});let bu=new Map,Ye={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};ao();let ry=o.voiceRecognition?.autoResume??!1,Jo=i=>{te.emit("voice:state",{active:Ye.active,source:i,timestamp:Date.now()})},po=()=>{fe(i=>({...i,voiceState:{active:Ye.active,timestamp:Date.now(),manuallyDeactivated:Ye.manuallyDeactivated}}))},UA=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=qf(I.voiceState),c=!!i.active,g=Number(i.timestamp??0);Ye.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-g<uH&&setTimeout(()=>{Ye.active||(Ye.manuallyDeactivated=!1,Ln(o.voiceRecognition?.provider)?T.toggleVoice().then(()=>{Ye.active=T.isVoiceActive(),Jo("restore"),T.isVoiceActive()&&Ii()}):Qc("restore"))},1e3)},jA=()=>T?MS(T.getMessages()).filter(i=>!i.__skipPersist):[],dc=null,sy=(i,c)=>{typeof console<"u"&&console.error(i,c)},pc=(i,c)=>{let g=()=>{try{let W=i();return!W||typeof W.then!="function"?null:Promise.resolve(W).catch(V=>{sy(c,V)})}catch(W){return sy(c,W),null}},f=dc,b=f?f.then(()=>g()??void 0):g();if(!b)return;let w=b.finally(()=>{dc===w&&(dc=null)});dc=w};function ui(i){if(!k?.save)return;let c=i?MS(i):T?jA():[],g=_&&T?.getResumableHandle();g&&(I={...I,durableResume:{executionId:g.executionId,after:g.lastEventId}});let f={messages:c,metadata:I,artifacts:Gn.artifacts,selectedArtifactId:Gn.selectedId,...Cs?{draft:Cs}:{}};pc(()=>k.save(f),"[AgentWidget] Failed to persist state:")}let Cs,uc=()=>!k?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Ma=Cw({write:()=>{if(!uc())return;let i=ye.getState(),c=bw({text:i.text,mentionRefs:i.mentionRefs,contentSegments:hg(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(Cs)&&(Cs=c,ui())}});function iy(){uc()&&Ma.schedule()}function vu(){Ma.flush()}function ay(i){if(!uc())return;let c=vw(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(g=>g.id),modelIds:(o.composer?.models??[]).map(g=>g.id),modes:o.composer?.modes??[]});c&&(Cs=i,ie&&!ie.value&&(ie.value=c.text,ie.dispatchEvent(new Event("input",{bubbles:!0})),xo()),c.selectedModelId&&(ye.setSelectedModelId(c.selectedModelId),Sr?.repaint()),Ql(c.activeModeIds??[]),c.quote&&So(c.quote),Ma.cancel())}function gc(){Ma.cancel(),Cs&&(Cs=void 0,uc()&&ui())}let gi=null,ly=()=>Ge.querySelector("#persona-scroll-container")||ee,mi=()=>{gi!==null&&(cancelAnimationFrame(gi),gi=null),An=!1},cy=()=>{Pr!==null&&(cancelAnimationFrame(Pr),Pr=null),ac=!1,mi()},VA=()=>Bn&&wu()&&(On()!=="anchor-top"||ph()),Cu=()=>{let i=ga()||"Jump to latest",c=VA();jt.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),kr>0?(os.textContent=String(kr),os.style.display="",jt.setAttribute("aria-label",`${i} (${kr} new)`)):(os.textContent="",os.style.display="none",jt.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},dy=()=>{kr!==0&&(kr=0,Cu())},qA=()=>{let i=Kt?.spacerHeight??0;return i<=0?Ks(ee,Qo):yc(i)-ee.scrollTop-ee.clientHeight<=Qo},wu=()=>xr()?!Dn.isFollowing():!qA(),xu=()=>!!T&&T.getMessages().length>0,Gt=()=>{if(!CA()||uA()){jt.parentNode&&jt.remove(),jt.style.display="none";return}jt.parentNode!==le&&le.appendChild(jt),ss();let c=$o(ee)>0&&wu()&&xu();c?Cu():dy(),jt.style.display=c?"":"none"},fi=()=>{Dn.pause()&&(cy(),Gt())},Mn=()=>{Dn.resume(),dy(),Gt()},Ir=(i=!1)=>{xr()&&xu()&&Dn.isFollowing()&&(!i&&!Bn||(Pr!==null&&(cancelAnimationFrame(Pr),Pr=null),ac=!0,Pr=requestAnimationFrame(()=>{Pr=null,ac=!1,Dn.isFollowing()&&zA(ly(),i?220:140)})))},py=(i,c,g,f=()=>!0)=>{let b=i.scrollTop,w=c(),W=w-b;if(mi(),Math.abs(W)<1){An=!0,i.scrollTop=w,_n=i.scrollTop,An=!1;return}let V=performance.now();An=!0;let F=Y=>1-Math.pow(1-Y,3),q=Y=>{if(!f()){mi();return}let oe=c();oe!==w&&(w=oe,W=w-b);let ue=Y-V,Ue=Math.min(ue/g,1),ot=F(Ue),et=b+W*ot;i.scrollTop=et,_n=i.scrollTop,Ue<1?gi=requestAnimationFrame(q):(i.scrollTop=w,_n=i.scrollTop,gi=null,An=!1)};gi=requestAnimationFrame(q)},zA=(i,c=500)=>{let g=$o(i)-i.scrollTop;if(Math.abs(g)<1){_n=i.scrollTop;return}if(Math.abs(g)>=NA){mi(),An=!0,i.scrollTop=$o(i),_n=i.scrollTop,An=!1;return}py(i,()=>$o(i),c,()=>Dn.isFollowing())},mc=()=>{if(!xu()){Gt();return}let i=ly();An=!0,i.scrollTop=$o(i),_n=i.scrollTop,An=!1,Gt()},ws=i=>{let c=0,g=i;for(;g&&g!==ee;)c+=g.offsetTop,g=g.offsetParent;return c},KA=()=>{let i=ee.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ee.ownerDocument.getSelection()},fc=()=>ox(KA(),ee),Su=()=>{if(wA()!=="last-user-turn")return!1;let i=T?.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=ee.querySelector(`[data-message-id="${g}"]`);if(!f)return!1;let b=Math.min(Math.max(0,ws(f)-ma()),$o(ee));return An=!0,ee.scrollTop=b,_n=ee.scrollTop,An=!1,On()==="follow"&&!Ks(ee,Qo)&&Dn.pause(),Gt(),!0},hc=i=>{let c=Math.max(0,Math.round(i));Kn.style.height=`${c}px`,Kn.style.display=c>0?"":"none",Kt&&(Kt.spacerHeight=Math.max(0,i))},yc=i=>{let c=parseFloat(getComputedStyle(ee).paddingBottom)||0,g=0;for(let b of Array.from(ee.children)){if(b===Kn||b.offsetHeight===0)continue;let w=ws(b)+b.offsetHeight;w>g&&(g=w)}let f=ee.scrollHeight-i;return g>0?Math.min(g+c,f):f},GA=()=>{if(!Kt||Kt.spacerHeight<=0)return;let i=yc(Kt.spacerHeight),c=Math.max(0,Math.round(ee.scrollTop)+ee.clientHeight-i+Qo);c<Kt.spacerHeight&&(hc(c),Gt())},uo=()=>{bs!==null&&(cancelAnimationFrame(bs),bs=null),mi(),Kt=null,Kn.style.height="0px",Kn.style.display="none"},uy=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Au=i=>ee.querySelector(`[data-message-id="${uy(i)}"]`),gy=i=>{bs!==null&&cancelAnimationFrame(bs),bs=requestAnimationFrame(()=>{bs=null;let c=uy(i),g=ee.querySelector(`[data-message-id="${c}"]`);if(!g)return;let f=ws(g),b=Kt?.spacerHeight??0,w=yc(b),{targetScrollTop:W,spacerHeight:V}=Ym({anchorOffsetTop:f,topOffset:ma(),viewportHeight:ee.clientHeight,contentHeight:w,slack:Qo});Kt={initialSpacerHeight:V,contentHeightAtAnchor:w,spacerHeight:V},hc(V),py(ee,()=>g.isConnected?Math.max(0,ws(g)-ma()):W,220)})},En=()=>{if(On()!=="anchor-top"||!Kt||!pi)return;let i=Au(pi);if(!i)return;mi();let c=Kt.spacerHeight,g=yc(c),{targetScrollTop:f,spacerHeight:b}=Ym({anchorOffsetTop:ws(i),topOffset:ma(),viewportHeight:ee.clientHeight,contentHeight:g,slack:Qo});Kt={initialSpacerHeight:b,contentHeightAtAnchor:g,spacerHeight:b},hc(b),An=!0,ee.scrollTop=f,_n=ee.scrollTop,An=!1,Gt()},YA=()=>{if(xr()){if(!Dn.isFollowing()||Ks(ee,1))return;Ir(!Bn);return}if(Kt&&Kt.initialSpacerHeight>0){let i=ee.scrollHeight-Kt.spacerHeight,c=rx({initialSpacerHeight:Kt.initialSpacerHeight,contentHeightAtAnchor:Kt.contentHeightAtAnchor,currentContentHeight:i});c!==Kt.spacerHeight&&hc(c)}Gt()},QA=i=>{let c=On();c==="follow"?(Mn(),Ir(!0)):c==="anchor-top"&&(Aa=!1,lc=!0,cc=!1,pi=i,gy(i))},XA=()=>{if(On()==="anchor-top"){if(lc){Aa=!1;return}Aa=!0,uo(),Mn(),Ir(!0)}},JA=96,ZA=i=>{if(vs===null)return!0;let c=Au(vs),g=Au(i);if(!c||!g)return!0;let f=ws(g)-ws(c);return ma()+f>ee.clientHeight-JA},eM=i=>{if(On()!=="anchor-top"||!lc||cc||fc())return;let c=vs===null;for(let g of i){if(!c){g.id===vs&&(c=!0);continue}if(Zw(g)){if(g.id===pi||!ZA(g.id))return;pi=g.id,gy(g.id);return}}},tM=i=>{let c=new Map;i.forEach(g=>{let f=bu.get(g.id);c.set(g.id,{streaming:g.streaming,role:g.role}),!f&&g.role==="assistant"&&(te.emit("assistant:message",g),!di&&(On()!=="anchor-top"||ph())&&wu()&&(kr+=1,Cu(),Gt(),zl(kr===1?"1 new message below.":`${kr} new messages below.`))),g.role==="assistant"&&f?.streaming&&g.streaming===!1&&te.emit("assistant:complete",g),g.variant==="approval"&&g.approval&&(f?g.approval.status!=="pending"&&te.emit("approval:resolved",{approval:g.approval,decision:g.approval.status}):te.emit("approval:requested",{approval:g.approval,message:g}))}),bu.clear(),c.forEach((g,f)=>{bu.set(f,g)})},Ea=(i,c)=>{let g=c==="user"?"user":"assistant",f=o.layout?.messages?.[g],b=f?.width??"content",w=f?.maxWidth??(b==="full"?`var(--persona-message-${g}-max-width, 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")},Zo=(i,c)=>{let g=document.createElement("div");return g.className="persona-flex",g.id=`wrapper-${i}`,g.setAttribute("data-wrapper-id",i),Ea(g,c),g},nM=(i,c,g)=>{let f=new Set;for(let R of c){let Re=R.variant==="tool"?"tool":R.variant==="reasoning"?"reasoning":null;if(!Re||jr(o,Re)!=="row")continue;let He=Re==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;He?.expandable!==!1&&(f.add(R.id),a.observe(R,Re,Re==="tool"?r:s,He))}let b=document.createElement("div"),W=(()=>{let R=u.find(Re=>Re.renderLoadingIndicator);if(R?.renderLoadingIndicator)return R.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),V=(R,Re)=>Re==null?!1:typeof Re=="string"?(R.textContent=Re,!0):(R.appendChild(Re),!0),F=new Set,q=new Map,Y=new Set,oe=u.some(R=>R.renderAskUserQuestion),ue=[],Ue=[],ot=o.enableComponentStreaming!==!1,et=o.approval!==!1,Pn=[],xt=o.messageActions,Pt=xt?.showRegenerate===!0&&xt.enabled!==!1&&at.current?.isStreaming()!==!0?kC(c):null,mn=xt?.showEdit===!0&&xt.enabled!==!1,Wt=xt?.showQuote===!0&&xt.enabled!==!1,ct=null,Ro=o.features?.reasoningDisplay?.completedVisibility,Ho=R=>Ro==="removed"?!0:Ro==="removed-when-short"?iC(R,o.features?.reasoningDisplay?.shortThinkThreshold):!1,no=o.features?.toolCallDisplay?.completedVisibility==="removed",oo=R=>R.variant==="reasoning"&&R.reasoning?.status==="complete"?Ho(R.reasoning):no&&R.variant==="tool"&&R.toolCall?.status==="complete";if(c.forEach(R=>{if(oo(R))return;if(F.add(R.id),q.set(R.id,R.role),fs===R.id&&Tr){let Oe=Zo(R.id,R.role);Oe.setAttribute("data-persona-message-edit-stub","true"),Oe.setAttribute("data-preserve-runtime","true"),b.appendChild(Oe),ct={messageId:R.id,element:Tr.element};return}let Re=oe&&qr(R),He=et&&R.variant==="approval"&&!!R.approval,ne=!Re&&R.role==="assistant"&&!R.variant&&ot&&Ep(R);!He&&Er.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),Er.delete(R.id)),!ne&&ms.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),ms.delete(R.id));let dt=qr(R)?`:${R.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${R.agentMetadata?.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ft={canRegenerate:Pt===R.id,canEdit:mn&&hm(R),canQuote:Wt&&!R.variant&&(R.content?.trim().length??0)>0},dn=`${Ft.canRegenerate?"r":""}${Ft.canEdit?"e":""}${Ft.canQuote?"q":""}`,en=Gw(R,ys)+dt+`:${dn}`,ht=Re||He||ne?null:Qw(Nt,R.id,en);if(ht){b.appendChild(ht.cloneNode(!0)),qr(R)&&R.toolCall?.id&&R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(Y.add(R.toolCall.id),al(R,o,Ne.composerOverlay));return}let Ot=null,Yt=u.find(Oe=>!!(R.variant==="reasoning"&&Oe.renderReasoning||R.variant==="tool"&&Oe.renderToolCall||!R.variant&&Oe.renderMessage)),Pe=o.layout?.messages;if(qr(R)&&R.agentMetadata?.askUserQuestionAnswered===!0){ci.delete(R.id),i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime");return}if(Fi(R)&&Yr(o).enabled)return;if(qr(R)&&o.features?.askUserQuestion?.enabled!==!1){let Oe=u.find(Qt=>typeof Qt.renderAskUserQuestion=="function");if(Oe&&at.current){let Qt=ci.get(R.id),ro=Qt!==en,tn=null;if(ro){let{payload:Fe,complete:Be}=zr(R),$r=R.id,qt=()=>at.current?.getMessages().find(kn=>kn.id===$r);tn=Oe.renderAskUserQuestion({message:R,payload:Fe,complete:Be,resolve:kn=>{let ar=qt();ar&&at.current?.resolveAskUserQuestion(ar,kn)},dismiss:()=>{let kn=qt();kn?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(kn),at.current?.resolveAskUserQuestion(kn,"(dismissed)"))},config:o})}let pt=Qt!=null;if(ro&&tn===null&&!pt){R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(Y.add(R.toolCall.id),al(R,o,Ne.composerOverlay));return}let Le=Zo(R.id,R.role);Le.setAttribute("data-ask-plugin-stub","true"),Le.setAttribute("data-preserve-runtime","true"),b.appendChild(Le),ue.push({messageId:R.id,fingerprint:en,bubble:tn});return}else{R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(Y.add(R.toolCall.id),al(R,o,Ne.composerOverlay));return}}else if(He){let Oe=O();if(!Oe){b.appendChild(Zo(R.id,R.role));return}let Qt=u.find(Le=>typeof Le.renderApproval=="function")??x,tn=Er.get(R.id)!==en,pt=null;if(tn&&Qt?.renderApproval){let Le=R.id,Fe=(Be,$r)=>{let qt=at.current?.getMessages().find(kn=>kn.id===Le);qt?.approval&&(qt.approval.toolType==="webmcp"?at.current?.resolveWebMcpApproval(qt.id,Be):at.current?.resolveApproval(qt.approval,Be,$r))};pt=Qt.renderApproval({message:R,defaultRenderer:()=>Oe.createApprovalBubble(R,o,l),config:o,approve:Be=>Fe("approved",Be),deny:Be=>Fe("denied",Be)})}if(tn&&pt===null)i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),Er.delete(R.id),Ot=Oe.createApprovalBubble(R,o,l);else{let Le=Zo(R.id,R.role);Le.setAttribute("data-approval-plugin-stub","true"),Le.setAttribute("data-preserve-runtime","true"),b.appendChild(Le),Pn.push({messageId:R.id,fingerprint:en,bubble:pt});return}}else if(Yt)if(R.variant==="reasoning"&&R.reasoning&&Yt.renderReasoning){if(!z)return;Ot=Yt.renderReasoning({message:R,defaultRenderer:()=>Cf(R,o,s),config:o})}else if(R.variant==="tool"&&R.toolCall&&Yt.renderToolCall){if(!X)return;Ot=Yt.renderToolCall({message:R,defaultRenderer:()=>Af(R,o,r),config:o})}else Yt.renderMessage&&(Ot=Yt.renderMessage({message:R,defaultRenderer:()=>{let Oe=Bl(R,g,Pe,o.messageActions,ei,{loadingIndicatorRenderer:W,widgetConfig:o,actionEligibility:Ft});return R.role!=="user"&&se(Oe,R,o,T),Oe},config:o}));if(!Ot&&ne){let Oe=Uf(R);if(Oe){let Qt=ms.get(R.id),ro=Qt!==en,tn=o.wrapComponentDirectiveInBubble!==!1&&Uo.getOptions(Oe.component)?.bubbleChrome!==!1,pt=null;if(ro){let Le=$f(Oe,{config:o,message:R,transform:g});if(Le&&Oe.component==="PersonaArtifactInline"){let Fe=Le.hasAttribute("data-artifact-inline")?Le:Le.querySelector("[data-artifact-inline]"),Be=Fe?.getAttribute("data-artifact-inline")??"",$r=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Be):Be,qt=Be?i.querySelector(`#wrapper-${R.id}`)?.querySelector(`[data-artifact-inline="${$r}"]`)??null:null;Fe&&qt&&qt!==Fe&&fr()?.hasLiveInlineArtifactBlock(qt)&&(Fe===Le?Le=qt:Fe.replaceWith(qt))}if(Le)if(tn){let Fe=document.createElement("div");if(Fe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Fe.id=`bubble-${R.id}`,Fe.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let Be=document.createElement("div");Be.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Be.innerHTML=g({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Fe.appendChild(Be)}Fe.appendChild(Le),pt=Fe}else{let Fe=document.createElement("div");if(Fe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Fe.id=`bubble-${R.id}`,Fe.setAttribute("data-message-id",R.id),Fe.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let Be=document.createElement("div");Be.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Be.innerHTML=g({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Fe.appendChild(Be)}Fe.appendChild(Le),pt=Fe}}if(pt||Qt!=null){let Le=Zo(R.id,R.role);Le.setAttribute("data-component-directive-stub","true"),Le.setAttribute("data-preserve-runtime","true"),b.appendChild(Le),Ue.push({messageId:R.id,fingerprint:en,bubble:pt});return}}}if(!Ot)if(R.variant==="reasoning"&&R.reasoning){if(!z)return;Ot=Cf(R,o,s)}else if(R.variant==="tool"&&R.toolCall){if(!X)return;Ot=Af(R,o,r)}else if(R.variant==="approval"&&R.approval){if(o.approval===!1)return;let Oe=O();if(!Oe)return;Ot=Oe.createApprovalBubble(R,o,l)}else{let Oe=o.layout?.messages;Oe?.renderUserMessage&&R.role==="user"?Ot=Oe.renderUserMessage({message:R,config:o,streaming:!!R.streaming}):Oe?.renderAssistantMessage&&R.role==="assistant"?Ot=Oe.renderAssistantMessage({message:R,config:o,streaming:!!R.streaming}):Ot=Bl(R,g,Oe,o.messageActions,ei,{loadingIndicatorRenderer:W,widgetConfig:o,actionEligibility:Ft}),R.role!=="user"&&Ot&&se(Ot,R,o,T)}let yt=Zo(R.id,R.role);yt.appendChild(Ot),Xw(Nt,R.id,en,yt),b.appendChild(yt)}),Ne.composerOverlay&&Ne.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let He=Re.getAttribute("data-persona-ask-sheet-for");He&&!Y.has(He)&&qs(Ne.composerOverlay,He)}),o.features?.toolCallDisplay?.grouped){let R=[],Re=[],He=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(ne=>{if(ne.variant==="tool"&&ne.toolCall&&X){if(no&&ne.toolCall.status==="complete")return;Re.push(ne);return}ne.variant==="reasoning"&&(!z||ne.reasoning?.status==="complete"&&Ho(ne.reasoning))||((Re.length>1||He&&Re.length>0)&&R.push(Re),Re=[])}),(Re.length>1||He&&Re.length>0)&&R.push(Re),R.forEach(ne=>{let dt=ne.map(Pe=>Array.from(b.children).find(yt=>yt instanceof HTMLElement&&yt.getAttribute("data-wrapper-id")===Pe.id)).filter(Pe=>!!Pe);if(dt.length<(He?1:2))return;let Ft=Zo(`tool-group-${ne[0].id}`,"assistant");if(Ft.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let Pe=`tool-group-${ne[0].id}`,yt=ne.some(pt=>pt.toolCall?.status!=="complete"),Oe={...ne[0],id:Pe,toolCall:{id:Pe,name:`${ne.length} tools`,status:yt?"running":"complete",chunks:ne.flatMap(pt=>pt.toolCall?.chunks??[]),success:!ne.some(pt=>pt.toolCall?.success===!1)}};f.add(Pe),a.observe(Oe,"tool",r,o.features.toolCallDisplay);let Qt=`${yt?"Using":"Used"} ${ne.length} tools`,ro=o.toolCall?.renderGroupedSummary?.({messages:ne,toolCalls:ne.map(pt=>pt.toolCall),defaultSummary:Qt,config:o}),tn=gv(Oe,o,r.has(Pe),ro??Qt);tn.bubble.classList.add("persona-tool-group"),tn.body.dataset.personaToolGroupStack="true",dt[0].before(Ft),Ft.appendChild(tn.bubble),dt.forEach((pt,Le)=>{pt.style.setProperty("--persona-message-row-max-width","100%"),pt.style.setProperty("--persona-activity-stagger",`${Le*40}ms`),pt.classList.add("persona-activity-group-child"),tn.body.appendChild(pt)});return}let dn=document.createElement("div");dn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",dn.setAttribute("data-persona-tool-group","true");let en=document.createElement("div");en.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",en.id=`tool-group-summary-${ne[0].id}`;let ht=`Called ${ne.length} ${ne.length===1?"tool":"tools"}`,Ot=o.toolCall?.renderGroupedSummary?.({messages:ne,toolCalls:ne.map(Pe=>Pe.toolCall).filter(Pe=>!!Pe),defaultSummary:ht,config:o});V(en,Ot)||(en.textContent=ht);let Yt=document.createElement("div");Yt.className="persona-tool-group-stack persona-flex persona-flex-col",Yt.id=`tool-group-stack-${ne[0].id}`,Yt.setAttribute("data-persona-tool-group-stack","true"),dn.appendChild(en),He||dn.appendChild(Yt),Ft.appendChild(dn),dt[0].before(Ft),dt.forEach((Pe,yt)=>{if(He){Pe.remove();return}Pe.style.setProperty("--persona-message-row-max-width","100%");let Oe=document.createElement("div");Oe.className="persona-tool-group-item persona-relative",Oe.setAttribute("data-persona-tool-group-item","true"),yt<dt.length-1&&Oe.setAttribute("data-persona-tool-group-connector","true"),Oe.appendChild(Pe),Yt.appendChild(Oe)})})}a.prune(f),Jw(Nt,F);let Nr=R=>R.variant==="tool"&&!X||R.variant==="reasoning"&&!z||oo(R),Wo=c.some(R=>R.role==="assistant"&&R.streaming&&!Nr(R)),go=c.length-1;for(;go>=0&&Nr(c[go]);)go--;let Fr=go>=0?c[go]:void 0,Ya=go<c.length-1,Hs=Fr?.role==="assistant"&&!Fr.streaming&&Fr.variant!=="approval"&&!Ya;if(Bn&&c.some(R=>R.role==="user")&&!Wo&&!Hs){let R={config:o,streaming:!0,location:"standalone",defaultRenderer:na},Re=u.find(ne=>ne.renderLoadingIndicator),He=null;if(Re?.renderLoadingIndicator&&(He=Re.renderLoadingIndicator(R)),He===null&&o.loadingIndicator?.render&&(He=o.loadingIndicator.render(R)),He===null&&(He=na()),He){let ne=document.createElement("div"),dt=o.loadingIndicator?.showBubble!==!1,Ft=o.layout?.messages?.layout??"bubble";ne.className=dt?Ol("assistant",Ft).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),ne.setAttribute("data-typing-indicator","true"),dt&&(ne.style.color="var(--persona-message-assistant-text, var(--persona-text))",Ft!=="flat"&&(ne.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",ne.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),ne.appendChild(He);let dn=Zo("typing-indicator","assistant");dn.appendChild(ne),b.appendChild(dn)}}if(!Bn&&c.length>0){let R=c[c.length-1],Re={config:o,lastMessage:R,messageCount:c.length},He=u.find(dt=>dt.renderIdleIndicator),ne=null;if(He?.renderIdleIndicator&&(ne=He.renderIdleIndicator(Re)),ne===null&&o.loadingIndicator?.renderIdle&&(ne=o.loadingIndicator.renderIdle(Re)),ne){let dt=document.createElement("div"),Ft=o.loadingIndicator?.showBubble!==!1;dt.className=Ft?["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(" "),dt.setAttribute("data-idle-indicator","true"),dt.appendChild(ne);let dn=Zo("idle-indicator","assistant");dn.appendChild(dt),b.appendChild(dn)}}if(Pv(b),rp(i,b),Gg(i),ct){let{messageId:R,element:Re}=ct,He=i.querySelector(`#wrapper-${R}`);He&&Re.parentElement!==He&&(Ea(He,q.get(R)??"user"),He.replaceChildren(Re))}if(ue.length>0)for(let{messageId:R,fingerprint:Re,bubble:He}of ue){let ne=i.querySelector(`#wrapper-${R}`);ne&&(Ea(ne,q.get(R)??"assistant"),He!==null&&(ne.replaceChildren(He),ne.setAttribute("data-bubble-fp",Re),ci.set(R,Re)))}if(ci.size>0)for(let R of ci.keys())F.has(R)||ci.delete(R);if(Ue.length>0)for(let{messageId:R,fingerprint:Re,bubble:He}of Ue){let ne=i.querySelector(`#wrapper-${R}`);ne&&(Ea(ne,q.get(R)??"assistant"),He!==null&&(ne.replaceChildren(He),ne.setAttribute("data-bubble-fp",Re),ms.set(R,Re)))}if(ms.size>0)for(let R of ms.keys())F.has(R)||ms.delete(R);if(Pn.length>0)for(let{messageId:R,fingerprint:Re,bubble:He}of Pn){let ne=i.querySelector(`#wrapper-${R}`);ne&&(Ea(ne,q.get(R)??"assistant"),He!==null&&(ne.replaceChildren(He),ne.setAttribute("data-bubble-fp",Re),Er.set(R,Re)))}if(Er.size>0)for(let R of Er.keys())F.has(R)||Er.delete(R)},Mu=!1,bc=()=>{Mu||(Mu=!0,Hg().catch(()=>{Mu=!1}))},Yn=(i,c,g)=>{c.length>0&&bc(),nM(i,c,g),Rh()},Ta=null,oM=()=>{if(Ta)return;let i=g=>{let f=g.composedPath();f.includes(Ge)||Jt&&f.includes(Jt)||ft(!1,"user")};Ta=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},my=()=>{if(!Ta)return;(e.ownerDocument??document).removeEventListener("pointerdown",Ta,!0),Ta=null};me.push(()=>my());let Pa=null,rM=()=>{if(Pa)return;let i=g=>{g.key==="Escape"&&(g.isComposing||ft(!1,"user"))};Pa=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},fy=()=>{if(!Pa)return;(e.ownerDocument??document).removeEventListener("keydown",Pa,!0),Pa=null};me.push(()=>fy());let ka=!1,hy=new Set,sM=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},hi=()=>{if(!ve())return;let i=Ne.peekBanner,c=Ne.peekTextNode;if(!i||!c)return;if(Ae){i.classList.remove("persona-pill-peek--visible");return}let g=T?.getMessages()??[],f;for(let xt=g.length-1;xt>=0;xt--){let Pt=g[xt];if(Pt.role==="assistant"&&Pt.content){f=Pt;break}}if(!f){i.classList.remove("persona-pill-peek--visible");return}let b=f.content,w=!!f.streaming,W=sM(),V=sp(W),F=V.type!=="none"?fu(V.type,W?.plugins):null,q=F?.isAnimating?.(f)===!0,Y=F!==null&&(w||q);Y&&F&&!hy.has(F.name)&&(Ll(F,e),hy.add(F.name));let oe=Y&&F?.containerClass?F.containerClass:null,ue=c.dataset.personaPeekStreamClass??null;ue&&ue!==oe&&(c.classList.remove(ue),delete c.dataset.personaPeekStreamClass),oe&&ue!==oe&&(c.classList.add(oe),c.dataset.personaPeekStreamClass=oe),Y?(c.style.setProperty("--persona-stream-step",`${V.speed}ms`),c.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let Ue=Y?ap(b,V.buffer,F,f,w):b;if(Y&&V.placeholder==="skeleton"&&w&&(!Ue||!Ue.trim())){let xt=document.createElement("div"),Pt=kl();Pt.classList.add("persona-pill-peek__skeleton"),xt.appendChild(Pt),rp(c,xt)}else{let xt=Math.max(0,Ue.length-100),Pt=Ue.length>100?Ue.slice(-100):Ue,mn=Vr(Pt);if(!Y||!F){let Wt=Ue.length>100?`\u2026${Pt}`:Pt;c.textContent!==Wt&&(c.textContent=Wt)}else{let Wt=mn;(F.wrap==="char"||F.wrap==="word")&&(Wt=Pl(mn,F.wrap,`peek-${f.id}`,{skipTags:F.skipTags,startIndex:xt}));let ct=document.createElement("div");if(ct.innerHTML=Wt,F.useCaret&&Pt.length>0){let Ro=lp(),Ho=ct.querySelectorAll(".persona-stream-char, .persona-stream-word"),no=Ho[Ho.length-1];no?.parentNode?no.parentNode.insertBefore(Ro,no.nextSibling):ct.appendChild(Ro)}rp(c,ct),F.onAfterRender?.({container:c,bubble:i,messageId:f.id,message:f,speed:V.speed,duration:V.duration})}}let Pn=Bn||ka;i.classList.toggle("persona-pill-peek--visible",Pn)};if(ve()){let i=Ne.peekBanner;if(i){let f=b=>{b.preventDefault(),b.stopPropagation(),ft(!0,"user")};i.addEventListener("pointerdown",f),me.push(()=>{i.removeEventListener("pointerdown",f)})}let c=()=>{ka||(ka=!0,hi())},g=()=>{ka&&(ka=!1,hi())};Ce.addEventListener("pointerenter",c),Ce.addEventListener("pointerleave",g),me.push(()=>{Ce.removeEventListener("pointerenter",c),Ce.removeEventListener("pointerleave",g)}),Jt&&(Jt.addEventListener("pointerenter",c),Jt.addEventListener("pointerleave",g),me.push(()=>{Jt.removeEventListener("pointerenter",c),Jt.removeEventListener("pointerleave",g)}))}let iM=i=>{let c=o.launcher?.composerBar??{},g=c.expandedSize??"anchored",f=c.bottomOffset??"16px",b=c.collapsedMaxWidth,w=c.expandedMaxWidth??"880px",W=c.expandedTopOffset??"5vh",V=c.modalMaxWidth??"880px",F=c.modalMaxHeight??"min(90vh, 800px)",q="calc(100vw - 32px)",Y="var(--persona-pill-area-height, 80px)",oe=Ge.style;if(oe.left="",oe.right="",oe.top="",oe.bottom="",oe.transform="",oe.width="",oe.maxWidth="",oe.height="",oe.maxHeight="",Jt){let ue=Jt.style;ue.bottom=f,ue.width=b??""}if(i&&g!=="fullscreen"){if(g==="modal"){oe.top="50%",oe.left="50%",oe.transform="translate(-50%, -50%)",oe.bottom="auto",oe.right="auto",oe.width=V,oe.maxWidth=q,oe.maxHeight=F,oe.height=F;return}oe.left="50%",oe.transform="translateX(-50%)",oe.bottom=`calc(${f} + ${Y})`,oe.top=W,oe.width=w,oe.maxWidth=q}},La=()=>{if(Ae&&bc(),!We())return;if(ve()){let q=(o.launcher?.composerBar??{}).expandedSize??"anchored",Y=Ae?"expanded":"collapsed";Ge.dataset.state=Y,Ge.dataset.expandedSize=q,Jt&&(Jt.dataset.state=Y,Jt.dataset.expandedSize=q),Ge.style.removeProperty("display"),Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),iM(Ae),le.style.display=Ae?"flex":"none",as(),Ae?(oM(),rM()):(my(),fy()),hi();return}let i=Ct(o),c=e.ownerDocument.defaultView??window,g=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,b=c.innerWidth<=g,w=f&&b&&D,W=Vn(o).reveal;Ae?(Ge.style.removeProperty("display"),Ge.style.display=i?"flex":"",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-95","persona-opacity-0"),Ce.classList.add("persona-scale-100","persona-opacity-100"),Rt?(Rt.setPanelOpen(!0),Rt.element.style.display="none"):gn&&(gn.style.display="none")):(i?i&&(W==="overlay"||W==="push")&&!w?(Ge.style.removeProperty("display"),Ge.style.display="flex",Ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.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"),Ce.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"),Ce.classList.remove("persona-scale-100","persona-opacity-100"),Ce.classList.add("persona-scale-95","persona-opacity-0")),Rt?(Rt.setPanelOpen(!1),Rt.element.style.display=i?"none":""):gn&&(gn.style.display=i?"none":""))},ft=(i,c="user")=>{if(!We()||Ae===i)return;let g=Ae;Ae=i,La();let f=(()=>{let w=o.launcher?.sidebarMode??!1,W=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,F=o.launcher?.mobileBreakpoint??640,q=W.innerWidth<=F,Y=Ct(o)&&V&&q,oe=ve()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return w||V&&q&&D||Y||oe})();if(Ae&&f){if(!Eo){let w=e.getRootNode(),W=w instanceof ShadowRoot?w.host:e.closest(".persona-host");W&&(Eo=Jm(W,o.launcher?.zIndex??cn))}To||(To=Zm(e.ownerDocument))}else Ae||(Eo?.(),Eo=null,To?.(),To=null);Ae&&(za(),Su()||(On()==="follow"?Ir(!0):mc()));let b={open:Ae,source:c,timestamp:Date.now()};Ae&&!g?te.emit("widget:opened",b):!Ae&&g&&te.emit("widget:closed",b),te.emit("widget:state",{open:Ae,launcherEnabled:D,voiceActive:Ye.active,streaming:T.isStreaming()})},Rr={inputDisabled:!1,sendDisabled:!1},Po=()=>Rr.inputDisabled,Eu=()=>Ln(o.voiceRecognition?.provider)&&!!T&&(T.isBargeInActive()||["listening","processing","speaking"].includes(T.getVoiceStatus())),xs=()=>Rr.inputDisabled||Rr.sendDisabled,aM=()=>(Rr.inputDisabled?Rr.inputReason:void 0)??(Rr.sendDisabled?Rr.sendReason:void 0);function Tu(){if(!Me)return;if(ye.getState().phase==="streaming"){Me.disabled=!1;return}let i=nt?!nt.isReady():!1;Me.disabled=xs()||i}function vc(){if(!wo)return;let i=ye.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;wo.toggleAttribute("data-persona-send-hidden",c)}function lM(){let i=aM();if(ve()){let c=wn??Ie;i?c.setAttribute("title",i):c.removeAttribute("title"),Ie.toggleAttribute(da,!!i);return}if(i){Qe.setAttribute("role","status"),Qe.setAttribute("aria-live","polite"),Qe.setAttribute(da,""),Qe.textContent=i,Fs(Qe,o.statusIndicator??{},"idle");return}if(Qe.hasAttribute(da)&&(Qe.removeAttribute("role"),Qe.removeAttribute("aria-live"),Qe.removeAttribute(da),y)){let c=T.getStatus();pa(Qe,zp(c),o.statusIndicator??{},c)}}function Pu(){let i=Pm(o.composer?.inputDisabled),c=Pm(o.composer?.sendDisabled);Rr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},ye.setInputDisabled(i.disabled),ye.setSendDisabled(c.disabled);let g=ye.getState().phase==="streaming",f=i.disabled,b=g||f;ie&&(ie instanceof HTMLTextAreaElement?ie.disabled=f:ie.setAttribute("contenteditable",f?"false":"true"),ie.setAttribute("aria-disabled",f?"true":"false")),Tt&&(Tt.disabled=f),wt&&(wt.disabled=f);for(let w of _t?.affordanceButtons??[])w.querySelectorAll("button").forEach(W=>{W.disabled=f});re&&(re.disabled=f||g&&!Eu()),ds.forEach(w=>{w.elements.forEach(W=>{W.toggleAttribute("data-disabled",b),W instanceof HTMLButtonElement||W.setAttribute("aria-disabled",b?"true":"false")}),w.buttons.forEach(W=>{W.disabled=b})}),Hu.forEach(w=>{w.toggleAttribute("data-disabled",b),w instanceof HTMLButtonElement?w.disabled=b:w.setAttribute("aria-disabled",b?"true":"false"),w.querySelectorAll("button").forEach(W=>{W.disabled=b})}),Ie.dataset.personaComposerStreaming=g?"true":"false",Ie.dataset.personaComposerInputDisabled=f?"true":"false",Ie.dataset.personaComposerSendDisabled=xs()?"true":"false",Ie.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(w=>{(w instanceof HTMLButtonElement||w instanceof HTMLInputElement||w instanceof HTMLTextAreaElement||w instanceof HTMLSelectElement)&&(w.disabled=g)}),Tu(),lM()}let Ia=i=>{ye.setStreaming(i),ch(i?"stop":"send"),Pu()},Ss=()=>{Ye.active||ie&&ie.focus()};te.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Ss(),200)});let As=null,Ra=!1,ku=!Zt.hidden,Hr=null,Lu=!Z,Cc=null;me.push(()=>{Cc?.cancel(),Cc=null});let cM=i=>{let c=Rx(i);if(c===Kl)return;Kl=c,e.setAttribute("data-persona-conversation-state",c);let g=Xp();Yl(),Lu&&(Cc?.cancel(),Cc=Lx(Ie,c==="active"?g:Xp(),c==="active"?"drop":"rise",rs().layout==="centered"?320:260)),En()},yy=null,by,vy=null,yi=null,Iu=!1,bi=i=>{let c=rs(),g=`${c.variant}|${c.layout}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(g!==yy||c.icon!==by)&&(yy=g,by=c.icon,mp({host:Zt,iconHolder:gA,kicker:mA,title:fA,subtitle:hA,starterSuggestions:Kp},c));let f=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;f!==vy&&(vy=f,fp(Hn,c.message,o));let b=i??(T?T.getMessages():o.initialMessages);cM(b);let w=Ra,W=!w&&Ys(c,b),V=W!==ku;if(ku=W,yi){Hr?.cancel(),Hr=null,w!==Iu&&(Iu=w,w?uf(ee,Zt,null):pf(ee,Zt,yi)),oa(ee,Zt,!w);return}if(V&&!W&&!w&&c.dismiss==="on-first-message"&&Lu){Hr=kx(Zt,q=>{Hr===q&&(Hr=null),!ku&&!yi&&(oa(ee,Zt,!1),En()),q?.cancel()});return}if(Hr){if(!W&&!w)return;Hr.cancel(),Hr=null}let F=!Zt.hidden;oa(ee,Zt,W),!W&&F&&En()},Ru=[],Hu=[],Wu=!1,Cy=null,wy,xy=()=>{Hu.length=0;let i=Ru.splice(0,Ru.length);for(let c of i)try{c()}catch(g){console.warn("[persona] renderWelcome cleanup threw",g)}};me.push(xy);let dM=(i,c)=>{let g=tf(i,c);if(!g)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),S("span");let f=o.suggestions?.starters,b=nf({item:{...g,behavior:g.behavior??f?.behavior??"send"},index:c,surface:"starter",source:"config",variant:f?.variant??"card",streaming:y?T.isStreaming():!1,config:o,plugins:u,chipsConfig:o.suggestionChipsConfig,session:T,getTextarea:()=>ie,eventTarget:Zt,submitPrompt:Kc});return Hu.push(b),b},Ou=()=>{if(Wu)return;Wu=!0;let i=rs();Cy=`${i.variant}|${i.layout}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,wy=i.icon;try{xy(),uf(ee,Zt,yi),yi=null,Iu=!1;let c=T?T.getMessages():o.initialMessages,g=Ys(i,c),f=0,b=null;for(let w of u)if(w.renderWelcome&&(b=w.renderWelcome({config:i,variant:i.variant,visible:g,defaultRenderer:()=>Zt,sendMessage:W=>{if(!T||T.isStreaming())return;let V=W.trim();V&&T.sendMessage(V)},requestRender:()=>Ou(),renderStarter:W=>dM(W,f++),storage:v(w.id),onCleanup:W=>{Ru.push(W)}}),b))break;b&&b!==Zt&&(yi=b,pf(ee,Zt,b))}finally{Wu=!1}bi()},pM=()=>{let i=rs();`${i.variant}|${i.layout}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Cy&&i.icon===wy||Ou()},wc=()=>{bi(),si||(ie.placeholder=gw(ye.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!T?.isStreaming()&&(Me.textContent=o.copy?.sendButtonLabel??"Send")),ie.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ie.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},uM=!!o.setStoredConversationId,vi=i=>fe(c=>{let g={...c};return delete g[i],g}),xc=i=>{let c=I[i];return typeof c=="string"?c:null},Sy=()=>{let i=I.durableResume;if(!i||typeof i!="object")return null;let c=i;return typeof c.executionId=="string"&&c.executionId.length>0&&typeof c.after=="string"&&c.after.length>0?{executionId:c.executionId,after:c.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>xc("sessionId"),setStoredSessionId:i=>{fe(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>vi("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>xc("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{fe(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>vi("conversationId"))});let Ay=()=>o.clientToken??null,My=i=>mS(i,Se(),o.persistState===!1),Ey=Ay(),Qn=Ey?My(Ey):null,er={...Qn?{visitorStore:Qn}:{},historyBootstrapReady:ce,getStoredMessageCursor:()=>xc("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){vi("historyMessageCursor");return}fe(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=I.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){vi("pendingDisplayProjections");return}fe(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:Sy,setStoredResumableHandle:i=>{if(!i){vi("durableResume");return}fe(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>_&&Sy()!==null,...uM?{}:{getStoredConversationRevision:()=>xc("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){vi("conversationRevision");return}fe(c=>({...c,conversationRevision:i}))}}};if(_){let i=o.onExecutionState,c=e.ownerDocument.defaultView,g=!1,f=()=>g=!0,b=()=>g=!1;c?.addEventListener("pagehide",f),c?.addEventListener("pageshow",b),me.push(()=>{c?.removeEventListener("pagehide",f),c?.removeEventListener("pageshow",b)}),o={...o,reconnectStream:o.reconnectStream??(w=>T.getClient().reconnectClientTokenStream(w)),onExecutionState:w=>{(w||!g)&&er.setStoredResumableHandle?.(w?{executionId:w.executionId,after:w.lastEventId}:null),i?.(w)}}}let gM=()=>{let i=Ay();if(i&&Qn?.matches(i,Se(),o.persistState===!1)||!i&&!Qn)return;Qn?.destroy(),Qn=i?My(i):null;let c={...er};Qn?c.visitorStore=Qn:delete c.visitorStore,er=c,T.setHistoryInternals(er)},Ms=null,mM=()=>{Ms==null&&(Ms=setInterval(()=>{let i=he.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Ms),Ms=null;return}let c=Date.now();i.forEach(g=>{let f=Number(g.getAttribute("data-tool-elapsed"));f&&(g.textContent=g.closest(".persona-activity-row")?nl(c-f):xd(c-f))})},100))},Bu=(i,c)=>{if(Object.is(i,c))return!0;if(i===null||c===null||typeof i!="object"||typeof c!="object")return!1;if(Array.isArray(i)||Array.isArray(c))return!Array.isArray(i)||!Array.isArray(c)||i.length!==c.length?!1:i.every((W,V)=>Bu(W,c[V]));let g=i,f=c,b=Object.keys(g),w=Object.keys(f);return b.length===w.length&&b.every(W=>Object.prototype.hasOwnProperty.call(f,W)&&Bu(g[W],f[W]))},Ty=i=>{let{content:c,rawContent:g,llmContent:f,...b}=i;return b},Du=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Ep(i),fM=(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))&&Du(f)&&Du(b)&&Bu(Ty(f),Ty(b))},_u=null,Ci=null,Es=null,tr=null,Nu=null,hM=i=>{if(!_)return ui(i);Nu=i,queueMicrotask(()=>{Nu===i&&(Nu=null,ui(i))})},Sc=i=>{_u=i;let c,g;Ci=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),!Ci&&Du(w)&&(Ci={index:b,id:w.id}),c&&g&&Ci)break}Yn(he,i,N),fr()?.updateInlineArtifactBlocks(he,Gn.artifacts,{suppressTransition:Bn}),mM(),bi(i),gs(i),Ir(!Bn),tM(i),i.length===0&&(uo(),Aa=!0,lc=!1,pi=null,cc=!1),!hu||di?(hu=!0,vs=c?.id??null,yu=g?.id??null):c&&c.id!==vs?(vs=c.id,QA(c.id)):g&&g.id!==yu&&XA(),g&&(yu=g.id),eM(i);let f=Ye.lastUserMessageId;c&&c.id!==f&&(Ye.lastUserMessageId=c.id,te.emit("user:message",c)),Ye.lastUserMessageWasVoice=!!c?.viaVoice,hM(i),hi()},Fu=()=>{tr!==null&&(cancelAnimationFrame(tr),tr=null);let i=Es;Es=null,i&&Sc(i)},Py=()=>{tr!==null&&cancelAnimationFrame(tr),tr=null,Es=null},yM=i=>{let c=Es??_u;if(Bn&&c&&Ci&&fM(c,i,Ci)){Es=i,tr===null&&(tr=requestAnimationFrame(()=>{tr=null;let g=Es;Es=null,g&&Sc(g)}));return}if(i.length===0){Py(),Sc(i);return}Fu(),Sc(i)};T=new yl(o,{onMessagesChanged(i){yM(i)},onStatusChanged(i){let c=o.statusIndicator??{};pa(Qe,(f=>f==="idle"?c.idleText??Bt.idle:f==="connecting"?c.connectingText??Bt.connecting:f==="connected"?c.connectedText??Bt.connected:f==="error"?c.errorText??Bt.error:f==="paused"?c.pausedText??Bt.paused:f==="resuming"?c.resumingText??Bt.resuming:Bt[f])(i),c,i),qp()},onStreamingChanged(i){i||(T?.getMessages().length===0?Py():Fu()),Bn=i,Ia(i),qp(),T&&Yn(he,T.getMessages(),N),i||(Ir(!0),GA(),ey=!0,T&&ty(T.getMessages(),Yr(o))),Gt(),zl(i?"Responding\u2026":"Response complete."),hi()},onVoiceStatusChanged(i){if(te.emit("voice:status",{status:i,timestamp:Date.now()}),!(i!=="disconnected"&&!Ln(o.voiceRecognition?.provider)))switch(i){case"listening":ir(),Ii();break;case"processing":ir(),vE();break;case"speaking":ir(),CE();break;default:i==="idle"&&T.isBargeInActive()?(ir(),Ii(),re?.setAttribute("aria-label","End voice session")):(Ye.active=!1,ir(),Jo("system"),po());break}},onArtifactsState(i){Gn=i,i.artifacts.length===0&&(ii=!1),fr()?.updateInlineArtifactBlocks(he,i.artifacts,{suppressTransition:Bn}),co(),ui()},onHistoryStateChanged(i){ah(i)},onHistoryNotice(i){lh(i)},onReconnect(i){let{executionId:c,lastEventId:g}=i.handle;i.phase==="paused"?te.emit("stream:paused",{executionId:c,after:g}):i.phase==="resuming"?te.emit("stream:resuming",{executionId:c,after:g,attempt:i.attempt??1}):te.emit("stream:resumed",{executionId:c,after:g})}},er),at.current=T,me.push(()=>T.cancel()),me.push(()=>{T.destroy(),Qn?.destroy(),Qn=null});let $u=null;if(T.onReadAloudChange((i,c)=>{Lh=i,Ih=c,Rh();let g=i??$u;i&&($u=i);let f=g?T.getMessages().find(b=>b.id===g)??null:null;te.emit("message:read-aloud",{messageId:g,message:f,state:c,timestamp:Date.now()}),c==="idle"&&($u=null)}),y=!0,hu=!0,o.voiceRecognition?.enabled===!0&&Ln(o.voiceRecognition.provider))try{T.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let bM=720,vM=250,Xe=Nf(o.features?.history?.copy),Nn=null,Uu=!1,it=null,Ac=null,Mc="conversation",ju=null,un=null,ko=null,Ec=T.getHistoryState(),Vu=null,Ha=0,qu=null,Tc=null,Pc=null,zu=`persona-history-${Math.random().toString(36).slice(2,8)}`,Ku=()=>o.features?.history?.enabled===!0,Lo=()=>Ku()&&!!Nn&&!Uu,ky=()=>{let i=T.getStatus();return Bn||i==="paused"||i==="resuming"},Gu=()=>{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},wi=()=>Ac?.scope??Gu(),Ly=()=>T.getClientSession()?.targetId??null,Iy=i=>`${i.state}:${"reason"in i?i.reason:""}`,CM=i=>{let c=Iy(i);c!==Vu&&(Vu=c,te.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},kc=i=>{i&&(zo.textContent="",zo.textContent=i)},Ry=null,Hy=null,wM=()=>{if(!Ku())return null;let i=bS();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(Ry!==c&&(Ry=c,Hy=c()),Hy):T.isClientTokenMode()?vS({client:T.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:g=>T.bindActivatedSession(g),getClient:()=>T.getClient()}):null},Wy=()=>{Tc?.(),Tc=null,Pc?.(),Pc=null,Uu=!1,Nn=wM();let i={...er};Nn?i.historyProvider=Nn:delete i.historyProvider,er=i,T.setHistoryInternals(er),Nn&&(Tc=Nn.subscribeAvailability?.(c=>{Uu=!c,c||Tn({restoreFocus:!1}),Or()})??null,Pc=Nn.subscribeIdentityStatus(c=>CM(c)),Vu=Iy(Nn.getIdentityStatus()))},Yu=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!D||Ct(o)))return"panel";let c=Mo??le;return(c.getBoundingClientRect().width||c.clientWidth)>=bM?"rail":"panel"},Xn=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},Lc="data-persona-history-suppressed",Fn=null,Wr=null,Ts=null,Wa=null,Qu=null,Oy="",By=()=>Ee===Qu?Oy:o.layout?.showHeader===!1?"none":"",xM=()=>Ut==="panel"&&!!Ts&&Wa===Ts.element&&o.layout?.showHeader!==!1&&By()!=="none",SM=()=>{for(let i of Array.from(Ee.children))i!==Fn&&i.setAttribute(Lc,"")},AM=()=>{for(let i of Array.from(le.querySelectorAll(`[${Lc}]`)))i.removeAttribute(Lc)},MM=()=>{let i=Ts;if(!i)return;if(Array.from(Ee.children).some(f=>f!==Fn&&!f.hasAttribute(Lc))){Wr&&Wr!==Ee&&(Wr.style.removeProperty("min-height"),Wr=null);let f=Ee.offsetHeight;f>0&&(Ee.style.minHeight=`${f}px`,Wr=Ee)}Fn||(Fn=S("div","persona-history-header-host")),i.setHeaderPlacement("external");let g=i.getHeaderElement();g.parentNode!==Fn&&Fn.replaceChildren(g),Fn.parentNode!==Ee&&Ee.appendChild(Fn),SM()},Dy=()=>{Wr&&(Wr.style.removeProperty("min-height"),Wr=null),Fn&&(Ts?.setHeaderPlacement("inline"),Fn.remove(),Fn=null,AM())},Ic=null,Xu=()=>{if(Ic){if(ee.style.display="none",Xn(ee,!0),Ie.hidden=!0,Xn(Ie,!0),xM()){MM(),Ee.style.display=By(),Xn(Ee,!1);return}Dy(),Ee.style.display="none",Xn(Ee,!0)}};Vp=Xu;let EM=i=>{let c=ee.style.display,g=Ie.hidden,f=Ie,b=Ee,w=Ee.style.display;Qu=b,Oy=w,Ic=()=>{Ic=null,Dy(),Qu=null,ee.style.display=c,Xn(ee,!1),f.hidden=g,Xn(f,!1),Ie!==f&&(Ie.hidden=!1,Xn(Ie,!1)),b.style.display=w,Xn(b,!1),Ee!==b&&(Ee.style.display=o.layout?.showHeader===!1?"none":"",Xn(Ee,!1))},Ie.parentNode?.insertBefore(i,Ie),Xu()},xi=null,Ps=null,Oa=null,Si=null,_y=()=>[Ee,Ne.closeButtonWrapper,Ne.clearChatButtonWrapper,ee,Ie],TM=52,Rc=()=>o.features?.history?.rail?.collapsible!==!1,Ai=()=>o.features?.history?.rail?.side==="right"?"right":"left",Ju=200,Zu=400,eg=i=>Math.min(Zu,Math.max(Ju,Math.round(i))),PM=()=>o.features?.history?.rail?.resizable===!0,Ba,kM=()=>{if(Ba===void 0&&(Ba=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Se()}rail-width`));i&&(Ba=i)}catch{}return Ba},Da=()=>eg(kM()??o.features?.history?.rail?.width??260),LM=i=>{if(Ba=i,o.persistState!==!1)try{window.localStorage.setItem(`${Se()}rail-width`,String(i))}catch{}},Hc=()=>Rc()&&o.features?.history?.rail?.collapsedBehavior==="overlay",Vt=!1,Ny=i=>{let c=S("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},IM=()=>{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=Ny(i.iconUrl):g=i.icon?ae(i.icon,20):null),g?g.cloneNode(!0):null}},RM=()=>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=Ny(f.iconUrl):b=f.icon?ae(f.icon,20):null}catch(w){g(w),b=null}return b},onSelect:()=>{try{f.onSelect()}catch(w){g(w)}}}})}})??[],HM=i=>{let c=RM();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},_a=null,Fy=()=>`${Se()}rail-collapsed`,tg=()=>{if(_a===null&&(_a=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(Fy());i&&(_a=i==="1")}catch{}return _a},ng=i=>{if(_a=i,o.persistState!==!1)try{window.localStorage.setItem(Fy(),i?"1":"0")}catch{}},Na=()=>Ut==="rail"&&Rc()&&!Hc()&&tg(),og=()=>{},$y=()=>{if(Hc()){og();return}ng(!tg()),it?.view.setCollapsed(Na()),qo(),En()},rg=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!np(i)?null:{combo:i,hint:op(i),aria:Al(i)}},Uy=()=>{h.forEach(c=>c()),h=[];let i=rg();i&&h.push(m.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Lt&&Ut==="rail"&&Rc()||Ei(),run:()=>Hc()?og():$y()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&h.push(m.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 u)for(let g of c.shortcuts??[])h.push(m.register({...g,id:`${c.id}:${g.id}`}))};Uy();let WM=300,Wc="var(--persona-history-overlay-margin,8px)",Jn=null,nr=null,Oc=0,or=null,Mi=null,ks=!1,sg=0,jy=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Ei=()=>Lo()&&Hc()&&(Ut??Yu())==="rail",OM=()=>Lt&&!Vt,Fa=()=>{Mi!==null&&clearTimeout(Mi),Mi=null},BM=()=>{Bf().catch(()=>{})},Vy=()=>{Fa(),Vt&&(Mi=setTimeout(()=>{Mi=null,!(ks||!Vt)&&(or?.contains(document.activeElement)||Tn({restoreFocus:!1}))},WM))},DM=(i,c)=>{let g=or?.getBoundingClientRect();if(!g)return!1;let f=Jn?.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},ig=i=>{Vt&&(ks=DM(i.clientX,i.clientY),ks?Fa():Mi===null&&Vy())},qy=i=>{Lt||!Ei()||(Vt=!0,Ua({invoker:Jn,keyboard:i?.keyboard===!0}).then(()=>{Lt?!ks&&document.activeElement!==Jn&&Tn():Vt=!1}))},zy=()=>{let i=Wa?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",Vt?Xe.expandLabel:Xe.collapseLabel),i.setAttribute("aria-expanded",Vt?"false":"true"))},Ky=()=>{ng(!1);let i=it;if(!Vt||!i){Ua({invoker:Jn});return}let c=document.activeElement===Jn;Vt=!1,Bc(),i.element.remove(),lg(i.element),zy(),c&&_c(),En(),Or()},_M=()=>{ng(!0),Tn()};og=()=>{!Lt||Vt?Ky():_M()};let NM=()=>{let i=rg(),c=Gs({ariaLabel:Xe.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":zu,...i?{"aria-keyshortcuts":i.aria}:{}}}),g=c.button;g.addEventListener("mouseenter",()=>{ks=!0,Fa(),!(jy()||Date.now()<sg)&&qy()}),g.addEventListener("mouseleave",()=>{ks=!1,sg=0,Vy()}),g.addEventListener("focus",()=>{Lt||BM()}),g.addEventListener("click",f=>{Lo()&&(f.detail!==0&&jy()&&!Lt?qy():Ky())}),Jn=g,nr=c.wrapper},$a=()=>{if(nr&&!nr.isConnected&&(nr=null,Jn=null),!Ei()){nr?.remove(),nr=null,Jn=null;return}Jn||NM();let i=nr,c=Jn;if(!i||!c)return;let g=Ai()!=="right"?Ee.firstChild:null;(g??Ee.lastChild)!==i&&Ee.insertBefore(i,g),i.style.display=OM()||Oc>0?"none":"",c.setAttribute("aria-label",Xe.expandLabel),c.setAttribute("aria-expanded",Lt?"true":"false"),or&&qo()},Gy=i=>{if(!Vt)return;let c=i.target;c instanceof Node&&(or?.contains(c)||nr?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||Tn({restoreFocus:!1}))};document.addEventListener("pointerdown",Gy,!0),me.push(()=>{document.removeEventListener("pointerdown",Gy,!0),document.removeEventListener("pointermove",ig),Ti?.(),Fa()});let ag=null,Ti=null,Yy=16,Qy=i=>{LM(eg(i)),qo(),En()},FM=()=>{let i=S("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(Ju)),i.setAttribute("aria-valuemax",String(Zu)),i.addEventListener("pointerdown",c=>{let g=Ps;if(!g||c.button!==0)return;c.preventDefault(),Ti?.();let f=c.clientX,b=g.getBoundingClientRect().width||Da(),w=Ai()==="right"?-1:1,W=b,V=e.ownerDocument;g.style.transition="none";let F=Y=>{W=eg(b+w*(Y.clientX-f)),g.style.flex=`0 0 ${W}px`,i.setAttribute("aria-valuenow",String(W))},q=()=>{Ti=null,V.removeEventListener("pointermove",F),V.removeEventListener("pointerup",q),V.removeEventListener("pointercancel",q),g.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}Qy(W)};Ti=q,V.addEventListener("pointermove",F),V.addEventListener("pointerup",q),V.addEventListener("pointercancel",q);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let g=Ai()==="right"?-Yy:Yy,f=Da(),b=c.key==="ArrowRight"?f+g:c.key==="ArrowLeft"?f-g:c.key==="Home"?Ju:c.key==="End"?Zu:null;b!==null&&(c.preventDefault(),Qy(b))}),i},$M=(i,c)=>{if(!PM()||Na()){Ti?.(),ag?.remove();return}let g=ag??FM();ag=g,g.setAttribute("aria-label",Xe.resizeLabel),g.setAttribute("aria-valuenow",String(Da())),g.nextElementSibling!==c&&i.insertBefore(g,c)};qo=()=>{it?.view.setRailSide(Ai());let i=Ai()==="right",c=or;if(c){let V=Jn?Jn.getBoundingClientRect().bottom-le.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(V))}px + ${Wc})`,c.style.width=`${Da()}px`,c.style.left=i?"":Wc,c.style.right=i?Wc:""}let g=Ps,f=xi,b=Oa;if(!g||!f||!b)return;g.style.flex=`0 0 ${Na()?TM:Da()}px`;let w="1px solid var(--persona-divider,#e5e7eb)";g.style.borderRight=i?"":w,g.style.borderLeft=i?w:"";let W=i?b:g;f.firstElementChild!==W&&f.append(W,i?g:b),$M(f,i?g:b)};let Xy=i=>{if(Si&&Ps){Si.replaceWith(i),Si=null,qo();return}let c=S("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let g=S("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=S("div","persona-history-rail-host");f.style.cssText="display:flex;min-height:0;overflow:hidden",le.insertBefore(c,Ee.parentNode===le?Ee:ee);for(let b of _y())b?.parentNode===le&&g.appendChild(b);c.append(f,g),f.appendChild(i),xi=c,Ps=f,Oa=g,qo()},UM=()=>{if(xi)return;let i=S("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",Si=i,Xy(i),En()},Jy=()=>{Si&&(Bc(),En())},jM=i=>{let c=S("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${Wc};display:flex;overflow:hidden;z-index:${Ki-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))`,le.style.position="relative",le.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",ig),or=c,qo(),zy()},Bc=()=>{Ic?.(),or&&(ks&&(sg=Date.now()+150),document.removeEventListener("pointermove",ig),or.remove(),or=null);let i=xi;if(i){Ti?.();for(let c of _y())c&&i.contains(c)&&le.insertBefore(c,i);i.remove(),xi=null,Ps=null,Oa=null,Si=null}},Zy=i=>{Wa=i,i.id=zu,i.style.flex="1 1 auto",i.style.minHeight="0"},lg=i=>{Zy(i),(Ut!=="rail"||Vt)&&Jy(),Ut!=="rail"?EM(i):Vt?jM(i):Xy(i)},Dc=()=>{if($a(),db(),!Lt||!it)return;let i=Yu();if(i===Ut)return;let c=document.activeElement,g=c instanceof HTMLElement&&(it.element.contains(c)||Fn?.contains(c)===!0)?c:null;Bc(),it.element.remove(),it.view.setHeaderPlacement("inline"),Ut=i,it.view.setPresentation(i),it.view.setCollapsed(Na()),it.requestRender(),it.element.isConnected||lg(it.element),g?.isConnected?g.focus():_c(),Gt(),En(),Or()},eb=(i,c)=>Fn?.querySelector(c)??i.querySelector(c),_c=()=>{let i=it?.element??Wa;if(!i)return;let c=eb(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let g=eb(i,".persona-history-title")??i;g.tabIndex=-1,g.focus()},Ua=async i=>{if(!Lo()||Lt)return;let c=Nn;if(!c)return;if(!Vt&&Ei()&&tg()){$a();return}Nc();let g=++Ha;Mc=i?.returnSurface??"conversation",ju=i?.invoker??un;let f=Ei()&&!Vt;f&&(Oc+=1,$a(),UM());let b;try{b=await Bf()}catch{kc(Xe.openHistoryLabel),f&&(Oc-=1,g===Ha&&(Jy(),$a()));return}if(f&&(Oc-=1),g!==Ha||Lt)return;Ac={scope:Gu()},Ut=Yu(),Lt=!0;let w=Ut==="panel"&&o.layout?.showHeader!==!1&&Ee.style.display!=="none"?"external":"inline",W=o.features?.history?.rowAvatar,V=rg(),F=V?{hint:V.hint,aria:V.aria}:null,q={provider:c,context:Ac,targetId:Ly(),presentation:Ut,collapsible:Rc(),collapsed:Na(),railSide:Ai(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:IM(),onToggleCollapse:$y,...F?{collapseShortcut:F}:{},headerPlacement:w,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:W===!1?!1:typeof W=="string"?W:o.launcher?.iconUrl,activeConversationId:T.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:Y=>dg(Y,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Y=>Ls(Y),attachTooltip:rn,onStartNew:()=>pg({focusComposer:!0}),onClose:()=>Tn(),onRequestDeleteConversation:Y=>cb(Y),onRequestClearHistory:()=>YM(),...c.resetDevice?{onRequestResetIdentity:()=>QM()}:{}};it=yS({plugins:u,config:o,getPresentation:()=>Ut??"panel",getReturnSurface:()=>Mc,close:()=>Tn(),createView:({slots:Y,renderDom:oe,onModelChange:ue,railSections:Ue})=>(Ts=b.createHistoryView({...q,railSections:HM(Ue),slots:Y,renderDom:oe,onModelChange:ue,onAnnounce:kc}),Ts),onElementChanged:(Y,oe)=>{if(!oe?.isConnected)return lg(Y);Zy(Y),oe.replaceWith(Y),Xu()}}),it.view.setNewConversationRequired(Ec.recovery==="new_conversation_required"),i?.focus!==!1&&(Ut!=="rail"||i?.keyboard===!0)&&_c(),Gt(),En(),Or(),te.emit("history:opened",{presentation:Ut,returnSurface:Mc,timestamp:Date.now()})},Nc=()=>{},Tn=i=>{if(!Lt)return;Ha+=1;let c=Mc,g=ju,f=it,b=i?.restoreFocus!==!1;Lt=!1;let w=!1,W=null,V=()=>{if(!w){if(w=!0,Nc=()=>{},W!==null&&clearTimeout(W),Vt=!1,Fa(),Bc(),f?.dispose(),f?.view.destroy(),f?.element.remove(),it===f&&(it=null,Ts=null,Wa=null,Ut=null,Ac=null,ju=null),Gt(),En(),Or(),b){let q=g??un;q?.isConnected?q.focus():Ss()}te.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},F=f&&f.element===f.view.element?f.view.playExit():null;if(!F){V();return}Nc=V,W=setTimeout(V,vM),F.then(V)},tb=i=>{if(!(i.key!=="Escape"||!Lt||!it)){if(Ut==="rail"){let c=i.target;if(!(c instanceof Node)||!(it.element.contains(c)||Vt&&nr?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Tn()}};le.addEventListener("keydown",tb),me.push(()=>le.removeEventListener("keydown",tb));let Fc=null,nb=!1,ja=()=>{if(!wr)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&Fc?.trim()||null;wr.textContent=c??o.launcher?.title??"Chat Assistant";let g=wr.closest(".persona-combo-btn");if(!g)return;let f=!i||T.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")},VM=i=>{i!==Fc&&(Fc=i,ja())},Ls=i=>{nb=i?.starred===!0,VM(i&&i.title.trim()||null),ja()};ja(),le.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,g=T.getActiveConversationId();g&&(c==="delete"?cb(g):c==="star"&&T.canUpdateConversations()&&ug(g,{starred:!nb}).catch(()=>{}))});let $c=0,qM=250,Uc=null,jc=()=>{Uc&&clearTimeout(Uc),Uc=null};me.push(jc);let ob=()=>{jc();let i=As;i&&(Ra=!0,i.hidden=!1,he.style.display="none",bi())},Vc=()=>{$c+=1,jc(),As&&(As.remove(),As=null,Ra=!1,he.style.removeProperty("display"),Xn(Ie,!1),bi())},zM=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;he.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},cg=(i,c)=>G("div",{className:fn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),rb=()=>G("div",{className:"persona-conversation-loading-body"},cg("58%",!1),cg("72%",!0),cg("44%",!1)),sb=i=>{As?.remove(),As=i,i.hidden=!Ra,ee.insertBefore(i,he),jc(),Ra||(Uc=setTimeout(ob,qM)),Xn(Ie,!0)},KM=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:rb},c=null,g=u.find(f=>f.renderLoadingIndicator);g?.renderLoadingIndicator&&(c=g.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),sb(G("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Xe.openConversationLoadingLabel}},c??rb()))},GM=i=>{let c=()=>{dg(i,{focusComposer:!0}).catch(()=>{})},g=Lo()?()=>{Vc(),Ua()}:void 0,f=(V,F)=>{let q=G("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:V});return q.addEventListener("click",F),q},b=()=>G("div",{className:"persona-conversation-loading-error-body"},G("p",{className:"persona-conversation-loading-error-title",text:Xe.openConversationErrorTitle}),G("div",{className:"persona-conversation-loading-error-actions"},f(Xe.openConversationRetryLabel,c),g?f(Xe.openConversationBackLabel,g):null)),w=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Xe.openConversationErrorTitle,retryLabel:Xe.openConversationRetryLabel,backLabel:Xe.openConversationBackLabel}),retry:c,...g?{back:g}:{},defaultRenderer:b}),W=null;for(let V of u)if(V.renderHistoryOpenError){try{W=V.renderHistoryOpenError(w)}catch(F){console.warn("[persona] renderHistoryOpenError threw",F),W=null}if(W)break}sb(G("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},W??b())),ob()};te.on("history:closed",()=>{As&&Xn(Ie,!0)});let dg=async(i,{focusComposer:c=!1}={})=>{let g=wi(),f=!!it;it?.view.setActiveConversationId(i),Vc();let b=$c;KM(),Lt&&(Ut==="panel"||Vt)&&Tn({restoreFocus:!1}),di=!0;try{await T.openConversation(i,{scope:g})}catch(w){throw b===$c&&GM(i),w}finally{di=!1}b===$c&&(Vc(),Nt.clear(),uo(),Mn(),Su()||mc(),zM(),rr(),f||Ls(null),te.emit("history:conversationOpened",{conversationId:i,title:Fc,scope:g,timestamp:Date.now()}),c&&Ss())},pg=async({focusComposer:i=!1}={})=>{Vc(),await T.startNewConversation({scope:wi()}),Ls(null),Nt.clear(),uo(),Mn(),mc(),rr();let c=T.getActiveConversationId();it?.view.setActiveConversationId(c),te.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),Lt&&(Ut==="panel"||Vt)&&Tn({restoreFocus:!1}),i&&Ss()},ug=async(i,c)=>{let g=await T.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return it?.view.applyConversationSummary(g),!it&&i===T.getActiveConversationId()&&Ls(g),g},ib=async i=>{let c=wi(),g=T.getActiveConversationId()===i;await T.deleteConversation(i,{scope:c}),it?.view.removeConversationSummary(i),g&&(Ls(null),Nt.clear(),uo(),Mn(),rr()),te.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:g,timestamp:Date.now()})},ab=async i=>{let c=i?.scope??wi(),g=i?.allTargets?null:i?.targetId??Ly(),f=await T.clearConversationHistory({...g?{targetId:g}:{},scope:c});return Ls(null),Nt.clear(),uo(),Mn(),rr(),te.emit("history:cleared",{deleted:f.deleted,scope:c,targetId:g,timestamp:Date.now()}),f},lb=async()=>{if(!Nn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await T.resetHistoryDevice()).remoteRevocationConfirmed}finally{Ls(null),T.clearArtifacts(),Nt.clear(),_u=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),I={},be.syncFromMetadata(),k?.clear&&pc(()=>k.clear(),"[AgentWidget] Failed to clear storage adapter:"),uo(),Mn(),rr(),Tn({restoreFocus:!1}),Ss(),Ae||Rt?.launcher.element.focus()}return kc(i?Xe.identityResetNotice:Xe.identityResetUnconfirmedNotice),te.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},gg=()=>Mo?Ce:le,cb=async i=>await Mp({host:gg(),title:Xe.deleteConversationConfirmTitle,description:Xe.deleteConversationConfirm,confirmLabel:Xe.deleteConversationConfirmLabel,cancelLabel:Xe.confirmCancelLabel})?(await ib(i),"deleted"):"cancelled",YM=async()=>{let i=wi()==="verified-user";return await Mp({host:gg(),title:Xe.clearHistoryConfirmTitle,description:i?Xe.clearHistoryVerifiedConfirm:Xe.clearHistoryConfirm,confirmLabel:Xe.clearHistoryConfirmLabel,cancelLabel:Xe.confirmCancelLabel})?(await ab(),"cleared"):"cancelled"},QM=async()=>{if(!await Mp({host:gg(),title:Xe.resetIdentityConfirmTitle,description:Xe.resetIdentityConfirm,confirmLabel:Xe.resetIdentityConfirmLabel,cancelLabel:Xe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await lb();return{outcome:"reset",remoteRevocationConfirmed:c}},Zn=S("button","persona-history-earlier");Zn.type="button",Zn.textContent=Xe.showEarlierMessagesLabel,Zn.setAttribute("data-persona-history-earlier",""),Object.assign(Zn.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let rr=()=>{if(!(Lo()&&!!Ec.nextMessageCursor&&!!T.getActiveConversationId())){Zn.remove();return}Zn.textContent=Xe.showEarlierMessagesLabel,Zn.parentNode!==ee&&ee.insertBefore(Zn,ee.firstChild)};Zn.addEventListener("click",()=>{let i=T.getActiveConversationId(),c=Ec.nextMessageCursor;if(!i||!c||Zn.disabled)return;Zn.disabled=!0;let g=ee.scrollHeight,f=ee.scrollTop;T.loadOlderMessages(i,c,{scope:wi()}).then(()=>{ee.scrollTop=f+(ee.scrollHeight-g),En()}).catch(()=>{}).finally(()=>{Zn.disabled=!1,rr()})});let XM=()=>{let i=Gs({ariaLabel:Xe.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return i.button.addEventListener("click",c=>{if(!(!Lo()||ky())){if(Lt){Tn();return}Ua({invoker:i.button,keyboard:c.detail===0})}}),i},db=()=>{if(!Lo()){ko?.remove(),un=null,ko=null;return}if(ko&&!ko.isConnected&&(un=null,ko=null),!un&&Ee){let f=XM();un=f.button,ko=f.wrapper;let b=Ne.clearChatButtonWrapper||Ne.closeButtonWrapper;b?.parentNode&&Ee.contains(b)?b.parentNode.insertBefore(ko,b):Ee.appendChild(ko)}if(!un||!ko)return;let i=Ei()||Lt&&Ut==="rail";if(ko.style.display=i?"none":"",i){document.activeElement===un&&_c();return}let c=ky();un.disabled=c,un.setAttribute("aria-disabled",c?"true":"false");let g=c?Xe.openHistoryBusyLabel:Xe.openHistoryLabel;un.setAttribute("aria-label",g),(o.features?.history?.presentation??"panel")==="panel"?(un.removeAttribute("aria-expanded"),un.removeAttribute("aria-controls")):(un.setAttribute("aria-expanded",Lt?"true":"false"),un.setAttribute("aria-controls",zu))},qc=!1,JM=()=>{let i=Ne.clearChatButton;if(i){if(Lo()){qc||(qu=i.getAttribute("aria-label")??"",qc=!0),i.setAttribute("aria-label",Xe.newConversationLabel),i.removeAttribute("title");return}qc&&(qc=!1,qu&&i.setAttribute("aria-label",qu))}},Or=()=>{Xe=Nf(o.features?.history?.copy),db(),$a(),JM(),rr()};qp=Or,ah=i=>{Ec=i,it?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),Ia(i.sendBlocked||Bn),rr()},lh=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(Nt.clear(),uo(),Mn()),kc(i.message),it?.view.refresh()},Wy(),Or(),me.push(()=>{Tc?.(),Pc?.(),Ha+=1,Nc(),it?.dispose(),it?.view.destroy(),it=null}),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&T.initClientSession().then(()=>{if(Lo())return T.reconcileBootConversation({scope:Gu()})}).then(()=>{rr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)});let mg=()=>T.warmClientSession(),pb=i=>{let c=o.sessionInit??"input",g=Ze?.input??ie,f=i.target;g&&(i.type==="input"?(c==="input"||c==="focus")&&f===g&&i.inputType&&g.value.trim():c==="focus"&&(i.type==="keyup"?f===g&&i.key==="Tab":(Ze?.form??wn)?.contains(f)))&&mg()},ub=["input","pointerdown","keyup"];ub.forEach(i=>e.addEventListener(i,pb));let gb,fg,mb=()=>{let i=fg;fg=void 0;try{typeof i=="function"&&i()}catch{}},fb=()=>{let i=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(i!==gb){mb(),gb=i;try{fg=i?.({warm:mg,mount:e})}catch{}}};fb(),me.push(()=>{ub.forEach(i=>e.removeEventListener(i,pb)),mb()}),(Q||o.onSSEEvent)&&T.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),jp(i,c)});let hb=()=>{let i=o.resume??(_?er.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&T.resumeFromHandle(i)};Z?Z.then(i=>{if(i){if(i.metadata&&(I=qf(i.metadata),be.syncFromMetadata()),i.messages?.length){di=!0;try{T.hydrateMessages(i.messages)}finally{di=!1}bc()}i.artifacts?.length&&T.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),ay(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{Lu=!0,U(),hb()}):(ay(de),hb());let ZM=()=>{!ve()||Ae||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ft(!0,"auto")},eE=(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),vH(b)}}:i:c,hg=()=>{let c=ie.getInlineMessageFields?.();return c&&c.contentSegments.some(f=>f.kind==="mention")?c.contentSegments:void 0},sr=!1,Is=null,zc=()=>{ie.value="",ie.style.height="auto",xo(),qa()},yg="data-persona-composer-notice",Pi=null;function tE(i){zl(i),!(ve()||!Qe)&&(Qe.hasAttribute(da)||(Qe.setAttribute(yg,""),Qe.setAttribute("role","status"),Qe.setAttribute("aria-live","polite"),Qe.textContent=i,Fs(Qe,o.statusIndicator??{},"idle"),Pi&&clearTimeout(Pi),Pi=setTimeout(()=>{if(Pi=null,!!Qe?.hasAttribute(yg)&&(Qe.removeAttribute(yg),Qe.removeAttribute("role"),Qe.removeAttribute("aria-live"),y)){let c=T.getStatus();pa(Qe,zp(c),o.statusIndicator??{},c)}},4e3)))}function nE(){let i=ye.getState().pendingSubmission;i&&(oi(void 0),ie&&(ie.value=i.text,ie.dispatchEvent(new Event("input",{bubbles:!0})),xo()),i.options.selectedModelId&&(ye.setSelectedModelId(i.options.selectedModelId),Sr?.repaint()),i.options.activeModeIds?.length&&Ql(i.options.activeModeIds),i.options.quote&&So(i.options.quote),ie?.focus())}let oE=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},yb=(i={})=>{let c=(i.overrideText??ie?.value??"").trim();return i.resolveInlineCommand&&c?(_t?.takeInlineCommand(c)??Promise.resolve(null)).then(g=>bb(i,c,g)):bb(i,c,null)},bb=(i,c,g)=>{if(g?.kind==="action"){zc(),_t?.clear(),is();return}let f=g?.kind==="server"?g.mentions:null,b=g?.kind==="prompt"?g.sendText:c,w=i.pending?.contentParts,W=(nt?.hasAttachments()??!1)||(w?.length??0)>0;if(!Ew({text:b,hasAttachments:W,attachmentsReady:nt?.isReady()??!0,hasMentions:_t?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:Po(),sendDisabled:xs()}))return;let V=T.isStreaming()?tu():"block";if(V==="defer-one"&&!i.pending){if(ye.getState().pendingSubmission){tE("One message is already queued. Edit or remove it first.");return}rE({intent:i,sendText:b,serverMentions:f});return}let F={text:b,mentionRefs:[..._t?.getMentionRefs()??[],...f?.refs??[]],contentSegments:g?.kind==="prompt"?void 0:hg(),options:{...ye.getState().selectedModelId&&{selectedModelId:ye.getState().selectedModelId},...ye.getState().activeModeIds.length>0&&{activeModeIds:[...ye.getState().activeModeIds]},...ye.getState().quote&&{quote:{...ye.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(F.options={...i.pending.options},F.contentSegments=i.pending.contentSegments,F.mentionRefs=[...i.pending.mentionRefs],F.viaVoice=i.pending.viaVoice);let q=()=>{if(w?.length)return[...w];if(!nt?.hasAttachments())return;let et=[...nt.getContentParts()];return F.text&&et.push(yo(F.text)),et};F.contentParts=q();let Y=()=>{hs(),ZM();let et=_t?.collectForSubmit()??null,Pn=eE(et,f),xt=q();i.consumeDraft!==!1&&zc();let Pt={selectedModelId:F.options.selectedModelId,activeModeIds:F.options.activeModeIds},mn=V==="interrupt";mn&&T.cancel(),T.sendMessage(F.text,{contentParts:xt,mentions:Pn??void 0,contentSegments:F.contentSegments,viaVoice:F.viaVoice,composerOptions:Pt,...F.options.quote&&{quote:F.options.quote},...mn&&{interrupt:!0}}),nt?.hasAttachments()&&nt.clearAttachments(),et&&_t?.clear(),is();let Wt=ye.getState().activeModeIds,ct=uw(Wt,o.composer?.modes);ct.length!==Wt.length&&Ql(ct),ye.getState().quote&&So(void 0),gc(),iu.release(),ao()},oe=o.composer?.onBeforeSend;if(!oe){Y();return}let ue=new AbortController;Is=ue;let Ue=et=>{if(Is=null,et.status==="error"){oE(et.error);return}et.status==="proceed"&&Y()},ot=Tw(oe,F,ue.signal);if(!(ot instanceof Promise)){Ue(ot);return}return ye.setPreparing(!0),ot.then(Ue).finally(()=>ye.setPreparing(!1))};function rE(i){let c=ye.getState(),g=nt?.hasAttachments()??!1,f=g?[...nt.getContentParts()]:[];g&&i.sendText&&f.push(yo(i.sendText));let b=Nm({text:i.sendText,contentParts:f.length?f:void 0,mentionRefs:[..._t?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:hg(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});oi(b),i.intent.consumeDraft!==!1&&zc(),g&&nt.clearAttachments(),_t?.clear(),is(),c.quote&&So(void 0),gc(),iu.release(),ao(),zl("Message queued. It sends when the response finishes.")}function sE(){let i=ye.getState().pendingSubmission;i&&(oi(void 0),Gc(i.text,{consumeDraft:!1,pending:i}))}function iE(i){if(o.messageActions?.showEdit!==!0)return;let c=T.getMessages().find(g=>g.id===i);!c||!hm(c)||fs!==i&&(hs(),fs=i,Tr=yw({messageId:i,initialText:c.content,onSave:g=>aE(i,g),onCancel:()=>hs()}),Nt.delete(i),Yn(he,T.getMessages(),N),Tr.focus())}function aE(i,c){let g=Tr;if(fs=null,Tr=null,g?.destroy(),Nt.delete(i),!T.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){Yn(he,T.getMessages(),N);return}En()}function lE(i){if(T.isStreaming())return;let c=fm(T.getMessages(),i);c&&(hs(),T.resubmitFrom(c,{reason:"retry"})&&En())}Xl={regenerate:lE,edit:iE,quote:i=>{let g=T.getMessages().find(f=>f.id===i)?.content?.trim();g&&(So({text:g,messageId:i}),ie?.focus())}};let Va=async i=>{if(!sr){sr=!0;try{await yb({resolveInlineCommand:!0,...i})}finally{sr=!1}}};function Kc(i){xs()||(zc(),Gc(i,{consumeDraft:!1}))}let Gc=(i,c)=>{if(sr)return;sr=!0;let g=()=>{sr=!1};try{let f=yb({...c,overrideText:i});f instanceof Promise?f.finally(g):g()}catch(f){throw g(),f}},cE=i=>{if(i.preventDefault(),T.isStreaming()){T.cancel(),Xt?.reset(),mt?.update();return}sr||Va()},dE=()=>o.features?.composerHistory!==!1,bg={...Gm},vg=!1,qa=()=>{bg={...Gm}},pE=()=>T.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),uE=i=>{if(!ie)return;vg=!0,ie.value=i,ie.dispatchEvent(new Event("input",{bubbles:!0})),vg=!1;let c=ie.value.length;ie.setSelectionRange(c,c)},gE=i=>{vg||(i.isComposing||_t?.handleInput(i.inputType??void 0),qa())},mE=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:bl(ie)}),fE=i=>{if(ie&&!Po()&&!(!i.isComposing&&_t?.handleKeydown(i))){if(dE()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let c=ie.selectionStart===0&&ie.selectionEnd===0,g=Kw({direction:i.key==="ArrowUp"?"up":"down",history:pE(),currentValue:ie.value,atStart:c,state:bg});if(bg=g.state,g.handled){i.preventDefault(),g.value!==void 0&&uE(g.value);return}}if(QC(i,mE())){if(T.isStreaming()){if(i.preventDefault(),tu()==="block"||sr||xs())return;qa(),Va();return}if(sr){i.preventDefault();return}if(xs()){i.preventDefault();return}qa(),i.preventDefault(),Me.click()}}},vb=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(le)){if(Is){Is.abort(),Is=null,i.preventDefault(),i.stopImmediatePropagation();return}T.isStreaming()&&(T.cancel(),Xt?.reset(),mt?.update(),qa(),i.preventDefault(),i.stopImmediatePropagation())}},hE=async i=>{if(o.attachments?.enabled!==!0||!nt||Po())return;let c=fH(i.clipboardData);c.length!==0&&(i.preventDefault(),await nt.handleFiles(c))},eo=null,Io=!1,ki=null,Et=null,Cg=()=>o.voiceRecognition?.completionBehavior==="review";function Rs(i){re?.setAttribute("data-state",i),i==="recording"?bE():Ag()}let Cb="--persona-voice-level",wg=.5,Li=null,xg=-1,Yc=0,wb=()=>{let i=[],c=Wn??re?.parentElement??null;return c&&i.push(c),Ie&&i.push(Ie),i},Sg=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==xg){xg=c;for(let g of wb())g.style.setProperty(Cb,String(c))}},yE=()=>{xg=-1,Yc=0;for(let i of wb())i.style.removeProperty(Cb)};function bE(){if(Li!==null)return;if(typeof requestAnimationFrame!="function"){Sg(y?T.getVoiceLevel()??wg:wg);return}let i=()=>{Li=requestAnimationFrame(i);let c=y?T.getVoiceLevel():null;if(c===null){Sg(wg);return}Yc+=(c-Yc)*.3,Sg(Yc)};Li=requestAnimationFrame(i)}function Ag(){Li!==null&&(cancelAnimationFrame(Li),Li=null),yE()}let xb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Qc=(i="user")=>{if(Io||T.isStreaming())return;let c=xb();if(!c)return;eo=new c;let g=o.voiceRecognition??{},f=g.pauseDuration??2e3;eo.continuous=g.provider?.browser?.continuous??!0,eo.interimResults=!0,eo.lang=g.provider?.browser?.language??"en-US";let b=ie.value;eo.onresult=w=>{let W="",V="";for(let q=0;q<w.results.length;q++){let Y=w.results[q],oe=Y[0].transcript;Y.isFinal?W+=oe+" ":V=oe}let F=b+W+V;ie.value=F,xo(),ki&&clearTimeout(ki),(W||V)&&(ki=window.setTimeout(()=>{if(ie.value.trim()&&eo&&Io){if(Br(),Cg())return;Va({viaVoice:!0})}},f))},eo.onerror=w=>{w.error!=="no-speech"&&Br()},eo.onend=()=>{if(Io){let w=ie.value.trim();!Cg()&&w&&w!==b.trim()&&Va({viaVoice:!0}),Br()}};try{if(eo.start(),Io=!0,Ye.active=!0,i!=="system"&&(Ye.manuallyDeactivated=!1),Jo(i),po(),ao(),re){let w=o.voiceRecognition??{};Et={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:w.iconName??"mic",iconSize:parseFloat(w.iconSize??"")||hn};let W=w.recordingBackgroundColor,V=w.recordingIconColor,F=w.recordingBorderColor;if(re.classList.add("persona-voice-recording"),Rs("recording"),re.style.backgroundColor=W??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=V??"var(--persona-voice-recording-indicator, #ffffff)",V){let q=re.querySelector("svg");q&&q.setAttribute("stroke",V)}F&&(re.style.borderColor=F),re.setAttribute("aria-label","Stop voice recognition")}}catch{Br("system")}},Br=(i="user")=>{if(Io){if(Io=!1,ki&&(clearTimeout(ki),ki=null),eo){try{eo.stop()}catch{}eo=null}if(Ye.active=!1,Jo(i),po(),ao(),re){if(re.classList.remove("persona-voice-recording"),Rs("idle"),Et){re.style.backgroundColor=Et.backgroundColor,re.style.color=Et.color,re.style.borderColor=Et.borderColor;let c=re.querySelector("svg");c&&c.setAttribute("stroke",Et.color||"currentColor"),Et=null}re.setAttribute("aria-label","Start voice recognition")}}},Mg=()=>{if(!re||Et)return;let i=o.voiceRecognition??{};Et={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||hn}},Eg=(i,c)=>{if(!re)return;let g=re.querySelector("svg");g&&g.remove();let f=Et?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||hn),b=ae(i,f,c,1.5);b&&re.appendChild(b)},Xc=()=>{re&&re.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ii=()=>{if(!re)return;Mg();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,g=i.recordingIconColor,f=i.recordingBorderColor;if(Xc(),re.classList.add("persona-voice-recording"),Rs("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")},vE=()=>{if(!re)return;Mg();let i=o.voiceRecognition??{},c=T.getVoiceInterruptionMode(),g=i.processingIconName??"loader",f=i.processingIconColor??Et?.color??"",b=i.processingBackgroundColor??Et?.backgroundColor??"",w=i.processingBorderColor??Et?.borderColor??"";Xc(),re.classList.add("persona-voice-processing"),Rs("processing"),re.style.backgroundColor=b,re.style.borderColor=w;let W=f||"currentColor";re.style.color=W,Eg(g,W),re.setAttribute("aria-label","Processing voice input"),c==="none"&&(re.style.cursor="default")},CE=()=>{if(!re)return;Mg();let i=o.voiceRecognition??{},c=T.getVoiceInterruptionMode(),g=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",f=i.speakingIconName??g,b=i.speakingIconColor??(c==="barge-in"?i.recordingIconColor??Et?.color??"":Et?.color??""),w=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Et?.backgroundColor??""),W=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":Et?.borderColor??"");Xc(),re.classList.add("persona-voice-speaking"),Rs("speaking"),re.style.backgroundColor=w,re.style.borderColor=W;let V=b||"currentColor";re.style.color=V,Eg(f,V);let F=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";re.setAttribute("aria-label",F),c==="none"&&(re.style.cursor="default"),c==="barge-in"&&re.classList.add("persona-voice-recording")},ir=()=>{re&&(Xc(),Rs("idle"),Et&&(re.style.backgroundColor=Et.backgroundColor??"",re.style.color=Et.color??"",re.style.borderColor=Et.borderColor??"",Eg(Et.iconName,Et.color||"currentColor"),Et=null),re.style.cursor="",re.setAttribute("aria-label","Start voice recognition"))},Tg=()=>{if(!Po()){if(Ln(o.voiceRecognition?.provider)){let i=T.getVoiceStatus(),c=T.getVoiceInterruptionMode();if(c==="none"&&(i==="processing"||i==="speaking"))return;if(c==="cancel"&&(i==="processing"||i==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,po(),Jo("user"),ir()});return}T.toggleVoice().then(()=>{Ye.active=T.isVoiceActive(),Ye.manuallyDeactivated=!T.isVoiceActive(),po(),Jo("user"),T.isVoiceActive()?Ii():ir()});return}if(Io){let i=ie.value.trim();Ye.manuallyDeactivated=!0,po(),Br("user"),i&&!Cg()&&Va()}else Ye.manuallyDeactivated=!1,po(),Qc("user")}};nu=Tg,re&&me.push(()=>{Ln(o.voiceRecognition?.provider)?(T.isVoiceActive()&&T.toggleVoice(),ir()):Br("system")});let wE=te.on("assistant:complete",()=>{ye.getState().pendingSubmission&&setTimeout(()=>{T.isStreaming()||sE()},0)});me.push(wE);let xE=te.on("assistant:complete",()=>{ry&&(Ye.active||Ye.manuallyDeactivated||ry==="assistant"&&!Ye.lastUserMessageWasVoice||setTimeout(()=>{!Ye.active&&!Ye.manuallyDeactivated&&(Ln(o.voiceRecognition?.provider)?T.toggleVoice().then(()=>{Ye.active=T.isVoiceActive(),Jo("auto"),T.isVoiceActive()&&Ii()}):Qc("auto"))},600))});me.push(xE);let SE=te.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});me.push(SE);let Sb=()=>{ft(!Ae,"user")},Rt=null,gn=null;if(D&&!ve()){let{instance:i,element:c}=bf({config:o,plugins:u,onToggle:Sb});Rt=i,i||(gn=c)}Rt?e.appendChild(Rt.element):gn&&e.appendChild(gn),La(),gs(),wc(),Ou(),Ia(T.isStreaming()),Su()||(On()==="follow"?Ir(!0):mc()),UA(),_e&&(!D||ve()?setTimeout(()=>Ss(),0):Ae&&setTimeout(()=>Ss(),200));let Dr=null,Ab=()=>{Dr&&(Dr.disconnect(),Dr.observe(Ie),Dr.observe(le),Dr.observe(Zt))},Mb=ya(),za=()=>{if(ve()){ss(),La();return}let i=Ct(o),c=o.launcher?.sidebarMode??!1,g=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640,w=g.innerWidth<=b,W=f&&w&&D;try{if(W){as(),wa=sc();return}let V=!1;Te&&(Te=!1,as(),V=!0);let F=sc();if(!V&&F!==wa&&(as(),V=!0),wa=F,V&&tc(),!D&&!i){Ce.style.height="",Ce.style.width="";return}if(!c&&!i){let q=Qs(o);Ce.style.width=q.width,Ce.style.maxWidth=q.maxWidth}rc(),Uh()}finally{ss(),Yl();let V=ya();if(V!==Mb&&(Mb=V,bi(),gs()),La(),Ae&&D){let q=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),Y=o.launcher?.sidebarMode??!1,oe=o.launcher?.mobileFullscreen??!0,ue=Ct(o)&&oe&&q,Ue=Y||oe&&q&&D||ue;if(Ue&&!To){let ot=e.getRootNode(),et=ot instanceof ShadowRoot?ot.host:e.closest(".persona-host");et&&!Eo&&(Eo=Jm(et,o.launcher?.zIndex??cn)),To=Zm(e.ownerDocument)}else Ue||(Eo?.(),Eo=null,To?.(),To=null)}}};za();let Jc=e.ownerDocument.defaultView??window;if(Jc.addEventListener("resize",za),me.push(()=>Jc.removeEventListener("resize",za)),typeof ResizeObserver<"u"){Dr=new ResizeObserver(()=>{Yl()}),Ab(),me.push(()=>{Dr?.disconnect(),Dr=null});let i=new ResizeObserver(()=>{Dc()});i.observe(le),me.push(()=>i.disconnect())}Jc.addEventListener("resize",Dc),me.push(()=>Jc.removeEventListener("resize",Dc)),_n=ee.scrollTop;let Eb=$o(ee),Tb=()=>{$h();let i=ee.scrollTop,c=$o(ee),g=c<Eb;if(Eb=c,!xr()){_n=i,Gt();return}let{action:f,nextLastScrollTop:b}=tx({following:Dn.isFollowing(),currentScrollTop:i,lastScrollTop:_n,nearBottom:Ks(ee,Qo),userScrollThreshold:_A,isAutoScrolling:An||ac||g,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(_n=b,f==="resume"){fc()||Mn();return}f==="pause"&&fi()};if(ee.addEventListener("scroll",Tb,{passive:!0}),me.push(()=>ee.removeEventListener("scroll",Tb)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{YA(),Gg(he)});i.observe(he),i.observe(ee),me.push(()=>i.disconnect())}let Pb=()=>{xr()&&Dn.isFollowing()&&fc()&&fi()},kb=ee.ownerDocument;kb.addEventListener("selectionchange",Pb),me.push(()=>{kb.removeEventListener("selectionchange",Pb)});let AE=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Lb=i=>{AE.has(i.key)&&(Lr(),dh()&&xr()&&Dn.isFollowing()&&fi())},Ib=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Lr(),dh()&&xr()&&Dn.isFollowing()&&fi())};ee.addEventListener("keydown",Lb),ee.addEventListener("focusin",Ib),me.push(()=>{ee.removeEventListener("keydown",Lb),ee.removeEventListener("focusin",Ib)});let Rb=i=>{if(i.deltaY!==0&&Lr(),!xr())return;let c=nx({following:Dn.isFollowing(),deltaY:i.deltaY,nearBottom:Ks(ee,Qo),resumeWhenNearBottom:!0});c==="pause"?fi():c==="resume"&&!fc()&&Mn()};ee.addEventListener("wheel",Rb,{passive:!0}),ee.addEventListener("touchmove",Lr,{passive:!0}),ee.addEventListener("pointerdown",Lr,{passive:!0}),me.push(()=>{ee.removeEventListener("touchmove",Lr),ee.removeEventListener("pointerdown",Lr)}),me.push(()=>ee.removeEventListener("wheel",Rb)),jt.addEventListener("click",()=>{uo(),ee.scrollTop=ee.scrollHeight,_n=ee.scrollTop,Mn(),Ir(!0),Gt()}),me.push(()=>jt.remove()),me.push(()=>{cy(),uo()});let Hb=()=>{je&&(ps&&(je.removeEventListener("click",ps),ps=null),We()?(je.style.display="",ps=()=>{ft(!1,"user")},je.addEventListener("click",ps)):je.style.display="none")};Hb(),(()=>{let{clearChatButton:i}=Ne;i&&i.addEventListener("click",()=>{if(Lo()){pg({focusComposer:!0}).catch(g=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",g)});return}T.clearMessages(),o.layout?.topFade&&(ee.scrollTop=0),ee.removeAttribute("data-persona-top-fade"),Nt.clear(),Mn(),qs(Ne.composerOverlay);try{localStorage.removeItem(ca),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ca}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ca)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),k?.clear&&pc(()=>k.clear(),"[AgentWidget] Failed to clear storage adapter:"),I={},be.syncFromMetadata(),nt?.clearAttachments(),gc(),oi(void 0),So(void 0),hs(),gt?.clear(),Xt?.reset(),mt?.update()})})();let Wb=[["keydown",fE],["input",gE],["input",xo],["input",is],["keyup",is],["paste",hE],["focus",TA]],Ob=i=>{if(i)for(let[c,g]of Wb)Ze?.addListener(i,c,g)},ME=i=>{if(i)for(let[c,g]of Wb)Ze?.removeListener(i,c,g)},Bb=()=>{Ze&&(Ze.addListener(Ze.form,"submit",cE),Ze.addListener(Ze.footer,"click",is),Ob(ie),re&&Ze.addListener(re,"click",Tg))};Bb();let Db=()=>{_t?.onComposerSwap((i,c)=>{ME(c),ie=i,Ze&&(Ze.input=i),Ob(i),ru(),Pu(),xo()})};Db();let Pg=!1;function _b(){if(!Pg){Pg=!0;try{let i=ie?.value??"",c=Ie.ownerDocument??document,g=ie?c.activeElement===ie:!1;Ag(),Ze?.destroy(),Ze=null,_t?.destroy(),_t=null;let f=null,b=()=>(f=ve()?pp({config:o}):ta({config:o}),f.footer),w=Ch(b)??b();Rn.replaceComposer(w),Ie=Rn.composer.footer;let W=f!==null&&w===f.footer;si=!W,ch=W?f.setSendButtonMode:()=>{},vh(Ie),xh(Ie),Sh(),Ah(),Mh(),Db(),Eh(),su(),Th(),Bb();let V=ds.indexOf(Yo);if(Yo.destroy(),Yo=Hl(Cr),V>=0&&(ds[V]=Yo),ie&&(ie.value=i),xo(),is(),wc(),gs(),Ia(T.isStreaming()),o.statusIndicator?.mode==="transient"&&!ve()){let F=T.getStatus();pa(Qe,zp(F),o.statusIndicator,F)}Ye.active&&Rs("recording"),as(),Ab(),ss(),ao(),vc(),g&&ie?.focus()}finally{Pg=!1}}}let Ka=e.ownerDocument??document;Ka.addEventListener("keydown",vb,!0);let Nb=()=>{vu()},Fb=()=>{Ka.visibilityState==="hidden"&&vu()};typeof window<"u"&&(window.addEventListener("pagehide",Nb),Ka.addEventListener("visibilitychange",Fb),me.push(()=>{window.removeEventListener("pagehide",Nb),Ka.removeEventListener("visibilitychange",Fb)}));let $b="persona-attachment-drop-active",Ga=0,kg=()=>{Ga=0,le.classList.remove($b)},Ri=()=>o.attachments?.enabled===!0&&nt!==null&&!Po(),Ub=i=>{!Tp(i.dataTransfer)||!Ri()||(Ga++,Ga===1&&le.classList.add($b))},jb=i=>{!Tp(i.dataTransfer)||!Ri()||(Ga--,Ga<=0&&kg())},Vb=i=>{!Tp(i.dataTransfer)||!Ri()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},qb=i=>{if(!Tp(i.dataTransfer)||!Ri())return;i.preventDefault(),i.stopPropagation(),kg();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&nt.handleFiles(c)},_r=!0;le.addEventListener("dragenter",Ub,_r),le.addEventListener("dragleave",jb,_r),e.addEventListener("dragover",Vb,_r),e.addEventListener("drop",qb,_r);let Zc=e.ownerDocument,zb=i=>{Ri()&&i.preventDefault()},Kb=i=>{Ri()&&i.preventDefault()};Zc.addEventListener("dragover",zb),Zc.addEventListener("drop",Kb),me.push(()=>{Ze?.destroy(),Ze=null,Ag(),Ao?.destroy(),Ao=null,Ko?.destroy(),Ko=null,Ar?.destroy(),Ar=null,Mr?.destroy(),Mr=null,Sr=null,eu=null,vu(),Ma.destroy(),Pi&&clearTimeout(Pi),hs(),Is?.abort(),Is=null,nt?.destroy(),nt=null,ye.destroy(),Ka.removeEventListener("keydown",vb,!0),_t?.destroy()}),me.push(()=>{le.removeEventListener("dragenter",Ub,_r),le.removeEventListener("dragleave",jb,_r),e.removeEventListener("dragover",Vb,_r),e.removeEventListener("drop",qb,_r),Zc.removeEventListener("dragover",zb),Zc.removeEventListener("drop",Kb),kg()}),me.push(()=>{T.cancel()}),Rt?me.push(()=>{Rt?.destroy()}):gn&&me.push(()=>{gn?.remove()});let Ht={update(i){let c=o.future?.v5Defaults===!0,g=o.toolCall,f=o.messageActions,b=o.layout?.messages,w=o.colorScheme,W=o.loadingIndicator,V=o.iterationDisplay,F=o.features?.showReasoning,q=o.features?.showToolCalls,Y=o.features?.toolCallDisplay,oe=o.features?.reasoningDisplay,ue=o.features?.streamAnimation?.type,Ue=o.features?.history?.enabled===!0,ot=o.features?.history?.provider,et=o.getIdentityProof,Pn=o.clientToken,xt=o.contextMentions;o=xp({...o,features:p},i),p=o.features,o=Cp(o),d(),uu(),Qi(e,o),_l(e,o),Nl(e,o),qo(),co(),o.colorScheme!==w&&jh();let Pt=wp.getForInstance(o.plugins);u.length=0,u.push(...Pt),Uy(),D=o.launcher?.enabled??!0,De=o.launcher?.autoExpand??!1,z=o.features?.showReasoning??!0,X=o.features?.showToolCalls??!0,ge=o.features?.scrollToBottom??{};let mn=On();xe=o.features?.scrollBehavior??{},mn!==On()&&(uo(),Mn()),oy(),gh(),Gt();let Wt=Q;if(Q=o.features?.showEventStreamToggle??!1,Q&&!Wt){if(gt||(jl(),T.setSSEEventCallback((J,ze)=>{o.onSSEEvent?.(J,ze),jp(J,ze)})),!st&&Ee){let J=o.features?.eventStream?.classNames,ze="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:"");st=S("button",ze),st.style.width="28px",st.style.height="28px",st.style.color=yn.actionIconColor,st.type="button",st.setAttribute("aria-label","Event Stream"),st.title="Event Stream";let Ke=St(xS,"18px","currentColor",1.5);Ke&&st.appendChild(Ke);let tt=Ne.clearChatButtonWrapper,bt=Ne.closeButtonWrapper,ln=tt||bt;ln&&ln.parentNode===Ee?Ee.insertBefore(st,ln):Ee.appendChild(st),st.addEventListener("click",()=>{io?ri():ou()})}}else!Q&&Wt&&(ri(),st&&(st.remove(),st=null),gt?.clear(),Je?.destroy(),gt=null,Je=null,Xt?.reset(),Xt=null,kt=null);if(o.launcher?.enabled===!1&&Rt&&(Rt.destroy(),Rt=null),o.launcher?.enabled===!1&&gn&&(gn.remove(),gn=null),o.launcher?.enabled!==!1&&!Rt&&!gn){let{instance:J,element:ze}=bf({config:o,plugins:u,onToggle:Sb});Rt=J,J||(gn=ze),e.appendChild(ze)}Rt&&Rt.update(o),ja(),ns&&o.launcher?.subtitle!==void 0&&(ns.textContent=o.launcher.subtitle);let ct=o.layout?.header;if(ct?.layout!==$t&&Ee){let J=ct?Wl(o,ct,{showClose:We(),onClose:()=>ft(!1,"user")}):es({config:o,showClose:We(),onClose:()=>ft(!1,"user")});Rn.replaceHeader(J),Ee=Rn.header.element,It=Rn.header.iconHolder,wr=Rn.header.headerTitle,ns=Rn.header.headerSubtitle,je=Rn.header.closeButton,$t=ct?.layout,ja()}else if(ct){if(It&&(It.style.display=ct.showIcon===!1?"none":""),wr&&(wr.style.display=ct.showTitle===!1?"none":""),ns&&(ns.style.display=ct.showSubtitle===!1?"none":""),je){let J=We()&&ct.showCloseButton!==!1;je.style.display=J?"":"none"}if(Ne.clearChatButtonWrapper){let J=ct.showClearChat;if(J!==void 0){Ne.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:ze}=Ne;ze&&!ze.classList.contains("persona-absolute")&&(J?ze.classList.remove("persona-ml-auto"):ze.classList.add("persona-ml-auto"))}}}let Ho=o.layout?.showHeader!==!1;Ee&&(Ee.style.display=Ho?"":"none");let no=o.layout?.showFooter!==!1;Ie&&(Ie.style.display=no?"":"none"),ss(),Gt(),D!==zt?D?ft(De,"auto"):(Ae=!0,La()):De!==At&&ft(De,"auto"),At=De,zt=D,za(),Hb();let Wo=JSON.stringify(o.toolCall)!==JSON.stringify(g),go=JSON.stringify(o.messageActions)!==JSON.stringify(f),Fr=JSON.stringify(o.layout?.messages)!==JSON.stringify(b),Ya=o.loadingIndicator?.render!==W?.render||o.loadingIndicator?.renderIdle!==W?.renderIdle||o.loadingIndicator?.showBubble!==W?.showBubble,Hs=o.iterationDisplay!==V,R=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(q??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(Y)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(oe);(o.future?.v5Defaults===!0!==c||Wo||go||Fr||Ya||Hs||R)&&T&&(ys++,Yn(he,T.getMessages(),N));let He=o.features?.streamAnimation?.type;if(He!==ue&&He&&He!=="none"){let J=fu(He,o.features?.streamAnimation?.plugins);J&&Ll(J,e)}let ne=o.launcher??{},dt=ne.headerIconHidden??!1,Ft=o.layout?.header?.showIcon,dn=dt||Ft===!1,en=ne.headerIconName,ht=ne.headerIconSize??el;if(It){let J=Ee,ze=J?.querySelector(".persona-flex-col");if(dn)It.style.display="none",J&&ze&&!J.contains(ze)&&J.insertBefore(ze,J.firstChild);else{if(It.style.display="",It.style.height=ht,It.style.width=ht,J&&ze&&(J.contains(It)?It.nextSibling!==ze&&(It.remove(),J.insertBefore(It,ze)):J.insertBefore(It,ze)),en){let tt=parseFloat(ht)||24,bt=ae(en,tt*.6,"currentColor",1);bt?(bt.style.width=`calc(${tt}px * var(--persona-components-header-iconScale, 0.6))`,bt.style.height=`calc(${tt}px * var(--persona-components-header-iconScale, 0.6))`,It.replaceChildren(bt)):It.textContent=ne.agentIconText??"\u{1F4AC}"}else if(ne.iconUrl){let tt=It.querySelector("img");if(tt)tt.src=ne.iconUrl,tt.style.height=ht,tt.style.width=ht;else{let bt=document.createElement("img");bt.src=ne.iconUrl,bt.alt="",bt.className="persona-rounded-xl persona-object-cover",bt.style.height=ht,bt.style.width=ht,It.replaceChildren(bt)}}else{let tt=It.querySelector("svg"),bt=It.querySelector("img");(tt||bt)&&It.replaceChildren(),It.textContent=ne.agentIconText??"\u{1F4AC}"}let Ke=It.querySelector("img");Ke&&(Ke.style.height=ht,Ke.style.width=ht)}}let Ot=o.layout?.header?.showTitle,Yt=o.layout?.header?.showSubtitle;if(wr&&(wr.style.display=Ot===!1?"none":""),ns&&(ns.style.display=Yt===!1?"none":""),je){let J=We()&&o.layout?.header?.showCloseButton!==!1;if(je.style.display=J?"":"none",!ve()){let nn=ne.closeButtonSize??"";je.style.height=nn,je.style.width=nn,je.style.minWidth=nn,je.style.minHeight=nn}let ze=ne.closeButtonPlacement??"inline",{closeButtonWrapper:Ke}=Ne,tt=ze==="top-right",bt=Ke?.classList.contains("persona-absolute");if(Ke&&tt!==bt)if(Ke.remove(),tt){Ke.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let nn=Oa??le;nn.style.position="relative",nn.appendChild(Ke)}else{let nn=ne.clearChat?.placement??"inline",on=ne.clearChat?.enabled??!0;Ke.className=on&&nn==="inline"?"":"persona-ml-auto",Ee&&Ee.appendChild(Ke)}if(je.style.color=ne.closeButtonColor||yn.actionIconColor,ne.closeButtonBackgroundColor?(je.style.backgroundColor=ne.closeButtonBackgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),ne.closeButtonBorderWidth||ne.closeButtonBorderColor){let nn=ne.closeButtonBorderWidth||"0px",on=ne.closeButtonBorderColor||"transparent";je.style.border=`${nn} solid ${on}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");ne.closeButtonBorderRadius?(je.style.borderRadius=ne.closeButtonBorderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),ne.closeButtonPaddingX?(je.style.paddingLeft=ne.closeButtonPaddingX,je.style.paddingRight=ne.closeButtonPaddingX):(je.style.paddingLeft="",je.style.paddingRight=""),ne.closeButtonPaddingY?(je.style.paddingTop=ne.closeButtonPaddingY,je.style.paddingBottom=ne.closeButtonPaddingY):(je.style.paddingTop="",je.style.paddingBottom=""),cp(je,ne.closeButtonIconName??"x",{iconSize:ve()?mf:void 0,iconText:ne.closeButtonIconText??"\xD7"});let ln=ne.closeButtonTooltipText??"Close chat",fo=ne.closeButtonShowTooltip??!0;je.setAttribute("aria-label",ln),Ke&&rn({anchor:je,trigger:Ke,text:()=>je?.getAttribute("aria-label")??ln,enabled:fo})}let{clearChatButton:Pe,clearChatButtonWrapper:yt}=Ne;if(Pe){let J=ne.clearChat??{},ze=J.enabled??!0,Ke=o.layout?.header?.showClearChat,tt=Ke!==void 0?Ke:ze,bt=J.placement??"inline";if(yt){yt.style.display=tt?"":"none";let{closeButtonWrapper:ln}=Ne;!ve()&&ln&&!ln.classList.contains("persona-absolute")&&(tt?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let fo=bt==="top-right",nn=yt.classList.contains("persona-absolute");if(!ve()&&fo!==nn&&tt){if(yt.remove(),fo){yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px";let Oo=Oa??le;Oo.style.position="relative",Oo.appendChild(yt)}else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let Oo=Ne.closeButtonWrapper;Ee&&Oo&&Oo.parentElement===Ee?Ee.insertBefore(yt,Oo):Ee&&Ee.appendChild(yt)}let on=Ne.closeButtonWrapper;on&&!on.classList.contains("persona-absolute")&&(fo?on.classList.add("persona-ml-auto"):on.classList.remove("persona-ml-auto"))}}if(tt){if(!ve()){let on=J.size??"";Pe.style.height=on,Pe.style.width=on,Pe.style.minWidth=on,Pe.style.minHeight=on}let ln=J.iconColor??"";if(Pe.style.color=ln||yn.actionIconColor,cp(Pe,J.iconName??"refresh-cw",{iconSize:ve()?ff:void 0}),J.backgroundColor?(Pe.style.backgroundColor=J.backgroundColor,Pe.classList.remove("hover:persona-bg-gray-100")):(Pe.style.backgroundColor="",Pe.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let on=J.borderWidth||"0px",Oo=J.borderColor||"transparent";Pe.style.border=`${on} solid ${Oo}`,Pe.classList.remove("persona-border-none")}else Pe.style.border="",Pe.classList.add("persona-border-none");J.borderRadius?(Pe.style.borderRadius=J.borderRadius,Pe.classList.remove("persona-rounded-full")):(Pe.style.borderRadius="",Pe.classList.add("persona-rounded-full")),J.paddingX?(Pe.style.paddingLeft=J.paddingX,Pe.style.paddingRight=J.paddingX):(Pe.style.paddingLeft="",Pe.style.paddingRight=""),J.paddingY?(Pe.style.paddingTop=J.paddingY,Pe.style.paddingBottom=J.paddingY):(Pe.style.paddingTop="",Pe.style.paddingBottom="");let fo=J.tooltipText??"Clear chat",nn=J.showTooltip??!0;Pe.setAttribute("aria-label",fo),yt&&rn({anchor:Pe,trigger:yt,text:()=>Pe?.getAttribute("aria-label")??fo,enabled:nn})}}let Oe=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Sp],Qt=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[la.message,la.messageAndClick];be=Ap({parsers:Oe,handlers:Qt,getSessionMetadata:we,updateSessionMetadata:fe,emit:te.emit,documentRef:typeof document<"u"?document:null}),N=ES(o,be,M),gM(),T.updateConfig(o),fb(),(o.features?.history?.enabled===!0!==Ue||o.features?.history?.provider!==ot||o.getIdentityProof!==et||o.clientToken!==Pn)&&(Tn({restoreFocus:!1}),Wy()),Or(),Dc(),Yn(he,T.getMessages(),N),gs(),wc(),pM(),Ia(T.isStreaming()),xt!==o.contextMentions&&_b();let ro=o.voiceRecognition?.enabled===!0,tn=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),pt=Ln(o.voiceRecognition?.provider);if(ro&&(tn||pt))if(!re||!Wn){let J=Gi(o);if(J){re=J.button,Wn=J.wrapper;let ze=wo&&wo.parentElement===Vl?wo:null;Vl?Vl.insertBefore(Wn,ze):wn?.appendChild(Wn),Ze&&(Ze.micButton=re),Ze?.addListener(re,"click",Tg),re.disabled=Po()||T.isStreaming()&&!Eu()}}else{let J=o.voiceRecognition??{},ze=o.sendButton??{},Ke=J.iconName??"mic",tt=J.iconSize,bt=parseFloat(tt??"")||hn;re.classList.add(Un),re.classList.toggle(vo,!tt),re.style.width=tt??"",re.style.height=tt??"",re.style.minWidth=tt??"",re.style.minHeight=tt??"";let ln=J.iconColor??ze.textColor;re.innerHTML="";let fo=ae(Ke,bt,ln||"currentColor",1.5);fo?re.appendChild(fo):re.textContent="\u{1F3A4}";let nn=J.backgroundColor??ze.backgroundColor;nn?re.style.backgroundColor=nn:re.style.backgroundColor="",ln?re.style.color=ln: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 on=J.tooltipText??"Start voice recognition",Oo=J.showTooltip??!1;re.setAttribute("aria-label",on),Wn&&rn({anchor:re,trigger:Wn,text:()=>re?.getAttribute("aria-label")??on,enabled:Oo}),Wn.style.display="",re.disabled=Po()||T.isStreaming()&&!Eu()}else re&&Wn&&(Wn.style.display="none",Ln(o.voiceRecognition?.provider)?T.isVoiceActive()&&T.toggleVoice():Io&&Br());if(o.attachments?.enabled===!0){if(!xn||!Tt){let J=o.attachments??{};Sn||(Sn=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Sn.style.display="none",(ie.parentElement??wn).insertBefore(Sn,ie)),wt||(wt=document.createElement("input"),wt.type="file",wt.accept=(J.allowedTypes??mr).join(","),wt.multiple=(J.maxFiles??4)>1,wt.style.display="none",wt.setAttribute("aria-label","Attach files"),(ie.parentElement??wn).insertBefore(wt,ie)),xn=S("div","persona-send-button-wrapper"),Tt=S("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Un} ${vo}`),Tt.type="button",Tt.setAttribute("aria-label",J.buttonTooltipText??"Attach file");let ze=J.buttonIconName??"paperclip";Tt.style.fontSize="18px",Tt.style.lineHeight="1";let Ke=ae(ze,hn,"currentColor",1.5);Ke?Tt.appendChild(Ke):Tt.textContent="\u{1F4CE}",Tt.addEventListener("click",bt=>{bt.preventDefault(),wt?.click()}),xn.appendChild(Tt);let tt=J.buttonTooltipText??"Attach file";rn({anchor:Tt,trigger:xn,text:()=>Tt?.getAttribute("aria-label")??tt}),Gp?Gp.append(xn):wn.appendChild(xn),Ze&&(Ze.attachmentButton=Tt,Ze.attachmentInput=wt??void 0,Ze.attachmentPreviews=Sn??void 0),!nt&&wt&&Sn&&(nt=zi.fromConfig(J,mh),nt.setPreviewsContainer(Sn),Ze?.addListener(wt,"change",async()=>{nt&&wt?.files&&(await nt.handleFileSelect(wt.files),wt.value="")}))}else{xn.style.display="";let J=o.attachments??{};wt&&(wt.accept=(J.allowedTypes??mr).join(","),wt.multiple=(J.maxFiles??4)>1),nt&&nt.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles,adapter:J.adapter})}if(le.querySelector(".persona-attachment-drop-overlay")?.remove(),le.appendChild(TS(o.attachments?.dropOverlay)),Tt){let J=o.attachments??{},ze=J.buttonTooltipText??"Attach file";Tt.setAttribute("aria-label",ze),Tt.textContent="";let Ke=ae(J.buttonIconName??"paperclip",hn,"currentColor",1.5);Ke?Tt.appendChild(Ke):Tt.textContent="\u{1F4CE}",xn&&rn({anchor:Tt,trigger:xn,text:()=>Tt?.getAttribute("aria-label")??ze})}}else xn&&(xn.style.display="none"),nt&&nt.clearAttachments(),le.querySelector(".persona-attachment-drop-overlay")?.remove();let Be=o.sendButton??{},$r=Be.useIcon??!1,qt=Be.iconText??"\u2191",kn=Be.iconName,ar=Be.tooltipText??"Send message",Lg=Be.showTooltip??!1,Ws=Be.size,Ig=parseFloat(Ws??"")||Lm,lr=Be.backgroundColor,Os=Be.textColor;if($r){if(Me.style.width=Ws??"",Me.style.height=Ws??"",Me.style.minWidth=Ws??"",Me.style.minHeight=Ws??"",Me.style.fontSize="18px",Me.style.lineHeight="1",Os?Me.style.color=Os:Me.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!T.isStreaming())if(Me.innerHTML="",kn){let J=parseFloat(Be.iconSize??"")||Math.round(Ig*.5),ze=Os?.trim()||"currentColor",Ke=Be.iconStrokeWidth??2,tt=ae(kn,J,ze,Ke),bt=ae(Be.stopIconName??"square",J,ze,Ke);tt&&bt?Me.appendChild(Im(tt,bt)):tt?Me.appendChild(tt):Me.textContent=qt}else Me.textContent=qt;Me.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Un}`,lr?(Me.style.backgroundColor=lr,Me.classList.remove("persona-bg-persona-primary")):(Me.style.backgroundColor="",Me.classList.add("persona-bg-persona-primary"))}else Me.textContent=o.copy?.sendButtonLabel??"Send",Me.style.width="",Me.style.height="",Me.style.minWidth="",Me.style.minHeight="",Me.style.fontSize="",Me.style.lineHeight="",Me.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",lr?(Me.style.backgroundColor=lr,Me.classList.remove("persona-bg-persona-accent")):Me.classList.add("persona-bg-persona-accent"),Os?Me.style.color=Os:Me.classList.add("persona-text-white");Be.borderWidth?(Me.style.borderWidth=Be.borderWidth,Me.style.borderStyle="solid"):(Me.style.borderWidth="",Me.style.borderStyle=""),Be.borderColor?Me.style.borderColor=Be.borderColor:Me.style.borderColor="",Be.paddingX?(Me.style.paddingLeft=Be.paddingX,Me.style.paddingRight=Be.paddingX):(Me.style.paddingLeft="",Me.style.paddingRight=""),Be.paddingY?(Me.style.paddingTop=Be.paddingY,Me.style.paddingBottom=Be.paddingY):(Me.style.paddingTop="",Me.style.paddingBottom=""),T.isStreaming()||Me.setAttribute("aria-label",ar),vc(),wo&&rn({anchor:Me,trigger:wo,text:()=>Me.getAttribute("aria-label")??ar,enabled:Lg}),Ph(),mu();let Gb=qd(ye.getState().activeModeIds,o.composer?.modes);ye.setActiveModeIds(Gb),ti().length>0!==!!Ko&&su(),Ko?.render(Gb,ti());for(let J of[...ni.keys()])Vd(J,o.composer?.modeGroups)||ni.delete(J);ni.forEach(J=>J.repaint()),Sr?.repaint(),Ao?.resolve();let ed=Xr(o,ve());if(gu(),ed){he.style.maxWidth=ed,he.style.marginLeft="auto",he.style.marginRight="auto",he.style.width="100%",Hn.style.maxWidth=ed,Hn.style.marginLeft="auto",Hn.style.marginRight="auto",Hn.style.width="100%";for(let J of[wn,Cr,Sn,Qe])J&&(J.style.maxWidth=ed,J.style.marginLeft="auto",J.style.marginRight="auto",J.style.width="100%")}else{he.style.maxWidth="",he.style.marginLeft="",he.style.marginRight="",he.style.width="",Hn.style.maxWidth="",Hn.style.marginLeft="",Hn.style.marginRight="",Hn.style.width="";for(let J of[wn,Cr,Sn,Qe])J&&(J.style.maxWidth="",J.style.marginLeft="",J.style.marginRight="",J.style.width="")}let mo=o.statusIndicator??{};if(zg(Qe,wn,mo),Fs(Qe,mo,T?.getStatus()??"idle"),T){let J=T.getStatus();pa(Qe,(Ke=>Ke==="idle"?mo.idleText??Bt.idle:Ke==="connecting"?mo.connectingText??Bt.connecting:Ke==="connected"?mo.connectedText??Bt.connected:Ke==="error"?mo.errorText??Bt.error:Ke==="paused"?mo.pausedText??Bt.paused:Ke==="resuming"?mo.resumingText??Bt.resuming:Bt[Ke])(J),mo,J)}Qe.classList.remove("persona-text-left","persona-text-center","persona-text-right");let PE=mo.align==="left"?"persona-text-left":mo.align==="center"?"persona-text-center":"persona-text-right";Qe.classList.add(PE),ru(),Pu(),ao(),Vp()},open(){We()&&ft(!0,"api")},close(){We()&&ft(!1,"api")},toggle(){We()&&ft(!Ae,"api")},reconnect(){T.reconnectNow()},clearChat(){Go=!1,a.clear(),r.clear(),s.clear(),l.clear(),T.clearMessages(),o.layout?.topFade&&(ee.scrollTop=0),ee.removeAttribute("data-persona-top-fade"),Nt.clear(),Mn();try{localStorage.removeItem(ca),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ca}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ca)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),k?.clear&&pc(()=>k.clear(),"[AgentWidget] Failed to clear storage adapter:"),I={},be.syncFromMetadata(),nt?.clearAttachments(),gc(),oi(void 0),So(void 0),hs(),gt?.clear(),Xt?.reset(),mt?.update()},setMessage(i){return!ie||T.isStreaming()||Po()?!1:(!Ae&&We()&&ft(!0,"system"),ie.value=i,ie.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(T.isStreaming()||xs())return!1;let c=i?.trim()||ie.value.trim();return c?(!Ae&&We()&&ft(!0,"system"),ie.value="",ie.style.height="auto",xo(),Gc(c,{consumeDraft:!1}),!0):!1},getComposerState(){return ye.getState()},setQuote(i){let c=i?.text?.trim();c&&So({...i,text:c})},clearQuote(){So(void 0)},startVoiceRecognition(){return T.isStreaming()?!1:Ln(o.voiceRecognition?.provider)?(T.isVoiceActive()||T.isBargeInActive()||(!Ae&&We()&&ft(!0,"system"),Ye.manuallyDeactivated=!1,po(),T.toggleVoice().then(()=>{Ye.active=T.isVoiceActive(),Jo("user"),T.isVoiceActive()&&Ii()})),!0):Io?!0:xb()?(!Ae&&We()&&ft(!0,"system"),Ye.manuallyDeactivated=!1,po(),Qc("user"),!0):!1},stopVoiceRecognition(){return Ln(o.voiceRecognition?.provider)?!T.isVoiceActive()&&!T.isBargeInActive()?!1:((T.isBargeInActive()?T.deactivateBargeIn():T.toggleVoice()).then(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,po(),Jo("user"),ir()}),!0):Io?(Ye.manuallyDeactivated=!0,po(),Br("user"),!0):!1},injectMessage(i){return!Ae&&We()&&ft(!0,"system"),T.injectMessage(i)},injectAssistantMessage(i){!Ae&&We()&&ft(!0,"system");let c=T.injectAssistantMessage(i);return Cn&&(Cn=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),c},injectUserMessage(i){return!Ae&&We()&&ft(!0,"system"),T.injectUserMessage(i)},injectSystemMessage(i){return!Ae&&We()&&ft(!0,"system"),T.injectSystemMessage(i)},injectMessageBatch(i){return!Ae&&We()&&ft(!0,"system"),T.injectMessageBatch(i)},injectComponentDirective(i){return!Ae&&We()&&ft(!0,"system"),T.injectComponentDirective(i)},injectTestMessage(i){!Ae&&We()&&ft(!0,"system"),T.injectTestEvent(i)},async connectStream(i,c){return T.connectStream(i,c)},__pushEventStreamEvent(i){Q&&(jl(),jp(i.type,i.payload))},showEventStream(){Q&&ou()},hideEventStream(){io&&ri()},isEventStreamVisible(){return io},listConversations(i){return T.listConversations(i)},getActiveConversationId(){return T.getActiveConversationId()},openConversation(i,c){return dg(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return pg({focusComposer:i?.focus===!0})},warmSession(){mg()},deleteConversation(i){return ib(i)},renameConversation(i,c){return ug(i,{title:c})},setConversationStarred(i,c){return ug(i,{starred:c})},clearConversationHistory(i){return ab(i)},resetHistoryIdentity(){return lb()},async getVisitorToken(){let i=Qn;if(!i)return null;let c=await i.get();return i===Qn?c:null},getHistoryIdentityStatus(){return Nn?Nn.getIdentityStatus():Ku()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return Ua({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){Tn(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return Lt},showArtifacts(){vn(o)&&(Go=!1,ii=!0,co(),qe?.setMobileOpen(!0))},hideArtifacts(){vn(o)&&(Go=!0,co())},upsertArtifact(i){return vn(o)?(ur(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Go=!1,ii=!0),T.upsertArtifact(i)):null},selectArtifact(i){vn(o)&&T.selectArtifact(i)},clearArtifacts(){vn(o)&&T.clearArtifacts()},getArtifacts(){return T?.getArtifacts()??[]},getSelectedArtifactId(){return T?.getSelectedArtifactId()??null},focusInput(){return D&&!Ae&&!ve()||!ie?!1:(ie.focus(),!0)},async resolveApproval(i,c,g){let b=T.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"){T.resolveWebMcpApproval(b.id,c);return}return T.resolveApproval(b.approval,c,g)},setFollowUpSuggestions(i){BA(i)},clearFollowUpSuggestions(){ny()},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...I}},updatePersistentMetadata(i){fe(i)},on(i,c){return te.on(i,c)},off(i,c){te.off(i,c)},isOpen(){return We()&&Ae},isVoiceActive(){return Ye.active},toggleReadAloud(i){T.toggleReadAloud(i)},stopReadAloud(){T.stopSpeaking()},getReadAloudState(i){return T.getReadAloudState(i)},onReadAloudChange(i){return T.onReadAloudChange(i)},getState(){return{open:We()&&Ae,launcherEnabled:D,voiceActive:Ye.active,streaming:T.isStreaming()}},showCSATFeedback(i){!Ae&&We()&&ft(!0,"system");let c=he.querySelector(".persona-feedback-container");c&&c.remove();let g=jf({onSubmit:async(f,b)=>{T.isClientTokenMode()&&await T.submitCSATFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});he.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Ae&&We()&&ft(!0,"system");let c=he.querySelector(".persona-feedback-container");c&&c.remove();let g=Vf({onSubmit:async(f,b)=>{T.isClientTokenMode()&&await T.submitNPSFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});he.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,c){return T.submitCSATFeedback(i,c)},async submitNPSFeedback(i,c){return T.submitNPSFeedback(i,c)},destroy(){Fu(),Ms!=null&&(clearInterval(Ms),Ms=null),a.clear(),r.clear(),s.clear(),l.clear(),me.forEach(i=>i()),Ge.remove(),Jt?.remove(),Rt?.destroy(),gn?.remove(),ps&&je.removeEventListener("click",ps)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:Ht,getMessages:Ht.getMessages,getStatus:Ht.getStatus,getMetadata:Ht.getPersistentMetadata,updateMetadata:Ht.updatePersistentMetadata,clearHistory:()=>Ht.clearChat(),setVoiceActive:g=>g?Ht.startVoiceRecognition():Ht.stopVoiceRecognition()};window.AgentWidgetBrowser=c,me.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),c=q=>{let Y=q.detail;(!Y?.instanceId||Y.instanceId===i)&&Ht.focusInput()};if(window.addEventListener("persona:focusInput",c),me.push(()=>{window.removeEventListener("persona:focusInput",c)}),Q){let q=oe=>{let ue=oe.detail;(!ue?.instanceId||ue.instanceId===i)&&Ht.showEventStream()},Y=oe=>{let ue=oe.detail;(!ue?.instanceId||ue.instanceId===i)&&Ht.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",Y),me.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",Y)})}let g=q=>{let Y=q.detail;(!Y?.instanceId||Y.instanceId===i)&&Ht.showHistory()},f=q=>{let Y=q.detail;(!Y?.instanceId||Y.instanceId===i)&&Ht.hideHistory()};window.addEventListener("persona:showHistory",g),window.addEventListener("persona:hideHistory",f),me.push(()=>{window.removeEventListener("persona:showHistory",g),window.removeEventListener("persona:hideHistory",f)});let b=q=>{let Y=q.detail;(!Y?.instanceId||Y.instanceId===i)&&Ht.showArtifacts()},w=q=>{let Y=q.detail;(!Y?.instanceId||Y.instanceId===i)&&Ht.hideArtifacts()},W=q=>{let Y=q.detail;Y?.instanceId&&Y.instanceId!==i||Y?.artifact&&Ht.upsertArtifact(Y.artifact)},V=q=>{let Y=q.detail;Y?.instanceId&&Y.instanceId!==i||typeof Y?.id=="string"&&Ht.selectArtifact(Y.id)},F=q=>{let Y=q.detail;(!Y?.instanceId||Y.instanceId===i)&&Ht.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",w),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",V),window.addEventListener("persona:clearArtifacts",F),me.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",w),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",V),window.removeEventListener("persona:clearArtifacts",F)})}let to=hH(o.persistState);if(to&&We()){let i=yH(to.storage),c=`${to.keyPrefix}widget-open`,g=`${to.keyPrefix}widget-voice`,f=`${to.keyPrefix}widget-voice-mode`;if(i){let b=to.persist?.openState&&i.getItem(c)==="true",w=to.persist?.voiceState&&i.getItem(g)==="true",W=to.persist?.voiceState&&i.getItem(f)==="true";if(b&&(Rt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Ht.open(),setTimeout(()=>{if(w||W)Ht.startVoiceRecognition();else if(to.persist?.focusInput){let V=e.querySelector("textarea");V&&V.focus()}},100)},0)),to.persist?.openState&&(te.on("widget:opened",()=>{i.setItem(c,"true")}),te.on("widget:closed",()=>{i.setItem(c,"false")})),to.persist?.voiceState&&(te.on("voice:state",V=>{i.setItem(g,V.active?"true":"false")}),te.on("user:message",V=>{i.setItem(f,V.viaVoice?"true":"false")})),to.clearOnChatClear){let V=()=>{i.removeItem(c),i.removeItem(g),i.removeItem(f)},F=()=>V();window.addEventListener("persona:clear-chat",F),me.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}if(pe&&We()&&(Rt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Ht.open()},0)),hi(),!DA){let i=Xa(()=>{T&&(ys++,Nt.clear(),Yn(he,T.getMessages(),N))});me.push(i)}B=()=>{T&&(ys++,Nt.clear(),Yn(he,T.getMessages(),N))},T.getMessages().length>0&&bc(),K=()=>{T&&(ys++,Nt.clear(),Yn(he,T.getMessages(),N))};let EE=tv(()=>{T&&(ys++,Nt.clear(),Yn(he,T.getMessages(),N))});me.push(EE);let TE=Pf(()=>{T&&(ys++,Nt.clear(),Yn(he,T.getMessages(),N),fr()?.updateInlineArtifactBlocks(he,Gn.artifacts,{suppressTransition:!0}),co())});return me.push(TE),Ht};var PS=(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},CH=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},wH=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},xH=(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.")},kS=(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"},Qf=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=""},LS=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Qf(e)},Kf=e=>{e.style.transition=""},Gf=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=""},Yf=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Pp=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},SH=(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))},AH=(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)},MH=e=>{let t=Fo(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:an(t,r)??r;return{inset:o(n?.inset,Yd),canvasBackground:o(n?.canvasBackground,Qd)}},IS=(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},EH=(e,t,n,o,r,s,a,l)=>{let d=Vn(s),p=d.reveal==="push",u=l!=null,m=l?.inset??"",h=l?.canvasBackground??"";SH(e,t,n,o,p),AH(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 y=e.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,x=y!=null?y.innerWidth<=C:!1;if(v&&x&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Gf(t),Kf(o),LS(o),Yf(n),Pp(r,o),IS(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??cn),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"),LS(o),CH(o,d.maxHeight),IS(o,u&&a,m,h),d.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Gf(t),Kf(o),Yf(n),Pp(r,o);let H=d.animate?"transform 180ms ease":"none",B=d.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":B;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=H,o.style.transform=A,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",Kf(o),Qf(o),Pp(r,o);let H=PS(d.width,e.clientWidth),B=Math.max(0,e.clientWidth),A=d.animate?"margin-left 180ms ease":"none",O=d.side==="right"?a?-H:0:a?0:-H;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+H}px`,t.style.transition=A,t.style.marginLeft=`${O}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}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="",Gf(t),Qf(o),Yf(n),Pp(r,o);let H=d.reveal==="emerge";H?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let B=a?d.width:"0px",A=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",O=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",wH(o,d.maxHeight),o.style.overflow=H||O?"hidden":"visible",o.style.transition=A,H){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let L=u?`calc(${PS(d.width,e.clientWidth)}px - (2 * ${m}))`:d.width;r.style.width=L,r.style.minWidth=L,r.style.maxWidth=L,r.style.boxSizing="border-box"}}},TH=(e,t)=>{let n=e.ownerDocument.createElement("div");return kS(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){kS(n,o)},destroy(){n.remove()}}},PH=(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 h=null,y=()=>{h?.disconnect(),h=null},v=null,C=()=>{v=t?.launcher?.detachedPanel===!0?MH(t):null};C();let x=()=>{EH(a,l,d,p,u,t,m,v)},E=null,H=()=>{E?.(),E=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(E=xl(()=>{C(),x()}))},B=()=>{y(),Vn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{x()}),h.observe(a)))},A=!1,O=()=>{x(),B(),m&&!A&&a.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,xH(a,Vn(t)))},L=a.ownerDocument.defaultView,$=()=>{O()};return L?.addEventListener("resize",$),Vn(t).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),O(),H(),{mode:"docked",host:u,shell:a,syncWidgetState(K){let se=K.launcherEnabled?K.open:!0;m!==se&&(m=se,O())},updateConfig(K){t=K,(t?.launcher?.enabled??!0)===!1&&(m=!0),C(),O(),H()},destroy(){L?.removeEventListener("resize",$),E?.(),E=null,y(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},kp=(e,t)=>Ct(t)?PH(e,t):TH(e,t);var kH=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},RS=(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)},Lp=[],LH=()=>[...Lp],HS=e=>{let t=kH(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=kp(t,r),a,l=[],d=(x,E)=>{let B=!(E?.launcher?.enabled??!0)||Ct(E),A=o.createElement("div");if(A.setAttribute("data-persona-root","true"),B&&(A.style.height="100%",A.style.display="flex",A.style.flexDirection="column",A.style.flex="1",A.style.minHeight="0",A.style.minWidth="0"),n){let O=x.attachShadow({mode:"open"});O.appendChild(A),RS(O,o)}else x.appendChild(A),RS(x,o);return t.id&&A.setAttribute("data-persona-instance",t.id),A},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=zf(x,r,{debugTools:e.debugTools}),u()},h=()=>{l.forEach(x=>x()),l=[],a.destroy()};m(),e.onChatReady?.();let y=x=>{h(),s.destroy(),s=kp(t,x),r=x,m()},v={update(x){let E=xp(r??{},x),H=Ct(r),B=Ct(E),A=Zr(r),O=Zr(E);if(H!==B||A!==O){y(E);return}r=E,s.updateConfig(r),a.update(x),p()},destroy(){h(),s.destroy();let x=Lp.indexOf(C);x!==-1&&Lp.splice(x,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(v,{get(x,E,H){if(E==="host")return s.host;if(E in x)return Reflect.get(x,E,H);let B=a[E];return typeof B=="function"?B.bind(a):B}});return Lp.push(C),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};var _S=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),IH=new Set(["button","a","input","select","textarea","details","summary"]),RH=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Xf=/\b(product|card|item|listing|result)\b/i,Zf=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,HH=3e3,WH=100;function NS(e){let t=typeof e.className=="string"?e.className:"";if(Xf.test(t)||e.id&&Xf.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Xf.test(o.value))return!0}return!1}function FS(e){return Zf.test((e.textContent??"").trim())}function $S(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 OH(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function WS(e){let t=e.match(Zf);return t?t[0]:null}function OS(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 BH(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 DH="commerce-card",_H="result-card";function BS(e){return!NS(e)||!FS(e)||!$S(e)&&!OH(e)?0:5200}function DS(e){return!NS(e)||FS(e)||!$S(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var US=[{id:DH,scoreElement(e){return BS(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||Zf.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(BS(e)===0)return null;let{title:n,href:o}=OS(e),r=WS((e.textContent??"").trim())??WS(t.text)??"",s=BH(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(`
|
|
139
|
+
`)}},{id:_H,scoreElement(e){return DS(e)},formatSummary(e,t){if(DS(e)===0)return null;let{title:n,href:o}=OS(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
140
|
+
`)}}];function NH(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function FH(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??US;return l==="simple"&&e.rules&&e.rules.length>0?(NH(),p=[]):l==="simple"&&(p=[]),{mode:l,maxElements:n,maxCandidates:d,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:p}}function Jf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var $H=["data-testid","data-product","data-action","data-id","data-name","data-type"];function UH(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"||IH.has(t)||n&&RH.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function jS(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 jH(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 VS(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Jf(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of $H){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${Jf(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=>Jf(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 VH(e){return e==="static"?WH:HH}function qS(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:VS(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:UH(e),attributes:jH(e)}}function qH(e,t,n,o){let r=VH(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 zH(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 KH(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(_S.has(u)){l=a.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){l=a.nextNode();continue}}catch{}if(e.visibleOnly&&!jS(p)){l=a.nextNode();continue}let m=qS(p,e.maxTextLength),h=m.text.length>0,y=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(x=>x==="role");if(!h&&!y){l=a.nextNode();continue}if(o.has(m.selector)){l=a.nextNode();continue}o.add(m.selector);let{score:v,formattingRule:C}=qH(p,m,e.rules,n);r.push({el:p,domIndex:s,enriched:m,score:v,formattingRule:C}),s+=1}l=a.nextNode()}r.sort((p,u)=>{let m=p.enriched.interactivity==="static"?1:0,h=u.enriched.interactivity==="static"?1:0;return m!==h?m-h: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;zH(d,p)||d.push(p)}return d.sort((p,u)=>{let m=p.enriched.interactivity==="static"?1:0,h=u.enriched.interactivity==="static"?1:0;return m!==h?m-h:m===1&&u.score!==p.score?u.score-p.score:p.domIndex-u.domIndex}),d.map(p=>{let u;if(p.formattingRule?.formatSummary){let h=p.formattingRule.formatSummary(p.el,p.enriched,n);h&&(u=h)}let m={...p.enriched};return u&&(m.formattedSummary=u),m})}function GH(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(_S.has(p)){s=r.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!jS(d)){s=r.nextNode();continue}let u=qS(d,e.maxTextLength),m=u.text.length>0,h=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(y=>y==="role");if(!m&&!h){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 YH(e={}){let t=FH(e),n=t.root??document.body;return n?t.mode==="simple"?GH(t,n):KH(t,n):[]}var Ip=100;function QH(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
141
|
${s.map(a=>`- ${a.split(`
|
|
141
142
|
`).join(`
|
|
142
143
|
`)}`).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,
|
|
144
|
+
`)}`)}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:
|
|
144
145
|
${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,
|
|
146
|
+
`)}`)}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:
|
|
146
147
|
${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,
|
|
148
|
+
`)}`)}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:
|
|
148
149
|
${s.join(`
|
|
149
|
-
`)}`)}if(r.static.length>0){let s=r.static.map(a=>`- ${a.selector}: "${a.text.substring(0,
|
|
150
|
+
`)}`)}if(r.static.length>0){let s=r.static.map(a=>`- ${a.selector}: "${a.text.substring(0,Ip)}"`);o.push(`Content:
|
|
150
151
|
${s.join(`
|
|
151
152
|
`)}`)}return o.join(`
|
|
152
153
|
|
|
153
|
-
`)}var
|
|
154
|
+
`)}var XH={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"}}},zS={components:{panel:{borderRadius:"0",shadow:"none"}}},KS={id:"shop",label:"Shopping Assistant",config:{theme:XH,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Oi},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"]}},GS={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:zS}},YS={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:zS}},QS={shop:KS,minimal:GS,fullscreen:YS};function JH(e){return QS[e]}var ZH=HS;function eW(){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 tW(){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 nW(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:Vo(e.colors.primary,.95),100:Vo(e.colors.primary,.9),200:Vo(e.colors.primary,.8),300:Vo(e.colors.primary,.7),400:Vo(e.colors.primary,.6),500:e.colors.primary,600:Vo(e.colors.primary,.8),700:Vo(e.colors.primary,.7),800:Vo(e.colors.primary,.6),900:Vo(e.colors.primary,.5),950:Vo(e.colors.primary,.45)}}),{...t,palette:n}}}}function oW(){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 rW(){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 Vo(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 sW(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}function eh(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@${Do}/dist`}function br(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function iW(e){if(e)return{getHeaders:br(e.getHeaders),onFeedback:br(e.onFeedback),onCopy:br(e.onCopy),requestMiddleware:br(e.requestMiddleware),actionHandlers:br(e.actionHandlers),actionParsers:br(e.actionParsers),postprocessMessage:br(e.postprocessMessage),contextProviders:br(e.contextProviders),streamParser:br(e.streamParser)}}var XS=`({ text, message }: any) => {
|
|
154
155
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
155
156
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
156
157
|
let cleanJson = jsonSource
|
|
@@ -163,7 +164,7 @@ ${s.join(`
|
|
|
163
164
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
164
165
|
} catch (e) { return null; }
|
|
165
166
|
return null;
|
|
166
|
-
}`,
|
|
167
|
+
}`,JS=`function(ctx) {
|
|
167
168
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
168
169
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
169
170
|
var cleanJson = jsonSource
|
|
@@ -176,7 +177,7 @@ ${s.join(`
|
|
|
176
177
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
177
178
|
} catch (e) { return null; }
|
|
178
179
|
return null;
|
|
179
|
-
}`,
|
|
180
|
+
}`,ZS=`(action: any, context: any) => {
|
|
180
181
|
if (action.type !== 'nav_then_click') return;
|
|
181
182
|
const payload = action.payload || action.raw || {};
|
|
182
183
|
const url = payload?.page;
|
|
@@ -193,7 +194,7 @@ ${s.join(`
|
|
|
193
194
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
194
195
|
window.location.href = targetUrl;
|
|
195
196
|
return { handled: true, displayText: text };
|
|
196
|
-
}`,
|
|
197
|
+
}`,eA=`function(action, context) {
|
|
197
198
|
if (action.type !== 'nav_then_click') return;
|
|
198
199
|
var payload = action.payload || action.raw || {};
|
|
199
200
|
var url = payload.page;
|
|
@@ -210,27 +211,27 @@ ${s.join(`
|
|
|
210
211
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
211
212
|
window.location.href = targetUrl;
|
|
212
213
|
return { handled: true, displayText: text };
|
|
213
|
-
}`,
|
|
214
|
+
}`,aW=`(parsed: any) => {
|
|
214
215
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
215
216
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
216
217
|
if (parsed.action === 'message') return parsed.text || '';
|
|
217
218
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
218
219
|
return parsed.text || null;
|
|
219
|
-
}`,
|
|
220
|
+
}`,lW=`function(parsed) {
|
|
220
221
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
221
222
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
222
223
|
if (parsed.action === 'message') return parsed.text || '';
|
|
223
224
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
224
225
|
return parsed.text || null;
|
|
225
|
-
}`;function
|
|
226
|
-
`);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,a=r===n.length-1?",":"";return`${s}${o}${a}`})}function
|
|
227
|
-
`)}function
|
|
228
|
-
`)}function $R(e,t){let n=t?.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${vl(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Ur(o,"theme",e.theme," "),e.launcher&&Ur(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),o.push(...up(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...cp(e," ")),o.push(...dp(e," ",n)),o.push(...pp(e," ")),o.push(...gp(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${OR}),`)),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(` ${zx}`),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(` ${zx}`),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(` ${Kx}`),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(` ${Kx}`),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
|
|
230
|
-
`)}function
|
|
226
|
+
}`;function cW(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 Rp(e){return e.parserType??cW(e.streamParser)??"plain"}function Hp(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 Wp(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 Op(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 Bp(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
|
|
227
|
+
`);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,a=r===n.length-1?",":"";return`${s}${o}${a}`})}function Dp(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 th(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 tA(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}: {`),tA(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function ts(e,t,n,o){n&&(e.push(`${o}${t}: {`),tA(e,n,`${o} `),e.push(`${o}},`))}function _p(e,t,n){t.future?.v5Defaults!==void 0&&e.push(`${n}future: { v5Defaults: ${t.future.v5Defaults===!0} },`)}function Fl(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function dW(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:iW(n.hooks)}:void 0;return t==="esm"?pW(o,r):t==="script-installer"?mW(o,r):t==="script-advanced"?hW(o,r):t==="react-component"?uW(o,r):t==="react-advanced"?gW(o,r):fW(o,r)}function pW(e,t){let n=t?.hooks,o=Rp(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Fl(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}",`),_p(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ts(s,"theme",e.theme," "),e.launcher&&ts(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(...Bp(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(...Hp(e," ")),s.push(...Wp(e," ",n)),s.push(...Op(e," ")),s.push(...Dp(e," ")),s.push(...th(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(`
|
|
228
|
+
`)}function uW(e,t){let n=t?.hooks,o=Rp(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: '${Fl(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}",`),_p(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ts(s,"theme",e.theme," "),e.launcher&&ts(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(...Bp(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(...Hp(e," ")),s.push(...Wp(e," ",n)),s.push(...Op(e," ")),s.push(...Dp(e," ")),s.push(...th(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(`
|
|
229
|
+
`)}function gW(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: '${Fl(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}",`),_p(o,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ts(o,"theme",e.theme," "),e.launcher&&ts(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(...Bp(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(...Hp(e," ")),o.push(...Wp(e," ",n)),o.push(...Op(e," ")),o.push(...Dp(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(${aW}),`)),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(` ${XS}`),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(` ${XS}`),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(` ${ZS}`),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(` ${ZS}`),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(`
|
|
230
|
+
`)}function nA(e){let t=Rp(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.future?.v5Defaults!==void 0&&(o.future={v5Defaults:e.future.v5Defaults===!0}),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 mW(e,t){let n=nA(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,"'");return`<script src="${eh(t)}/install.global.js" data-config='${s}'></script>`}function fW(e,t){let n=t?.hooks,o=Rp(e),r=o!=="plain",s=eh(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: '${Fl(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}",`),_p(a,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ts(a,"theme",e.theme," "),e.launcher&&ts(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(...Bp(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(...Hp(e," ")),a.push(...Wp(e," ",n)),a.push(...Op(e," ")),a.push(...Dp(e," ")),a.push(...th(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(`
|
|
231
|
+
`)}function hW(e,t){let n=t?.hooks,o=nA(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
|
|
231
232
|
`).map((a,l)=>l===0?a:" "+a).join(`
|
|
232
|
-
`)};`,""," // Constants",` var CDN_BASE = '${
|
|
233
|
-
`)}import{ChevronDown as
|
|
233
|
+
`)};`,""," // Constants",` var CDN_BASE = '${eh(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(${lW});`),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(` ${JS}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${JS}`),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(` ${eA}`),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(` ${eA}`),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: '${Fl(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(`
|
|
234
|
+
`)}import{ChevronDown as yW}from"lucide";var oA={desktop:{w:1280,h:800},mobile:{w:390,h:844}},rA=.1,sA=.15,iA=1.5,nh=24,aA=40,bW=`
|
|
234
235
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
235
236
|
.persona-dc-root {
|
|
236
237
|
display: flex;
|
|
@@ -381,7 +382,7 @@ ${s.join(`
|
|
|
381
382
|
.persona-dc-stage {
|
|
382
383
|
height: 550px;
|
|
383
384
|
min-height: 400px;
|
|
384
|
-
padding: ${
|
|
385
|
+
padding: ${nh}px;
|
|
385
386
|
overflow: auto;
|
|
386
387
|
background: #f0f1f3;
|
|
387
388
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -471,10 +472,10 @@ ${s.join(`
|
|
|
471
472
|
min-height: 300px;
|
|
472
473
|
}
|
|
473
474
|
}
|
|
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=VR,document.head.appendChild(e)}function GR(e,t){let n=e.clientWidth-pf*2-tS,o=e.clientHeight-pf*2-tS;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function YR(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function QR(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:l=!0,showColorSchemeToggle:d=!0,onChange:p}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");KR();let u=Math.max(0,Math.min(o,n.length-1)),m=r,y=s,h=null,C=1,w=!1,S=E("div","persona-dc-root"),P=E("div","persona-dc-toolbar"),I=E("div","persona-dc-toolbar-lead"),O=E("div","persona-dc-toolbar-trail"),T=Vn({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ue(-1)}),R=E("div");R.style.position="relative";let A=E("button","persona-dc-title-btn");A.type="button",A.setAttribute("aria-expanded","false"),A.setAttribute("aria-haspopup","listbox");let D=E("span","persona-dc-title-text"),K=E("span","persona-dc-title-chevron"),ie=It(zR,12,"currentColor",2);ie&&K.appendChild(ie),A.append(D,K);let Z=E("div","persona-dc-dropdown");Z.setAttribute("role","listbox"),Z.style.display="none";let M=!1;function _(){Z.innerHTML="";for(let xe=0;xe<n.length;xe++){let bt=n[xe],Rt=E("button","persona-dc-dropdown-item");Rt.type="button",Rt.setAttribute("role","option"),Rt.setAttribute("aria-current",xe===u?"true":"false");let ut=E("span");if(ut.textContent=bt.title,Rt.appendChild(ut),bt.description){let vn=E("span","persona-dc-dropdown-desc");vn.textContent=bt.description,Rt.appendChild(vn)}Rt.addEventListener("click",()=>{H(),Bt(xe)}),Z.appendChild(Rt)}}function W(){M=!M,Z.style.display=M?"":"none",A.setAttribute("aria-expanded",M?"true":"false"),M&&_()}function H(){M&&(M=!1,Z.style.display="none",A.setAttribute("aria-expanded","false"))}A.addEventListener("click",xe=>{xe.stopPropagation(),W()});let J=()=>H();document.addEventListener("click",J),R.append(A,Z);let V=Vn({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ue(1)}),pe=E("span","persona-dc-counter");I.append(T,R,V,pe);let se=null;l&&(se=Wd({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:xe=>{m=xe,Je.dataset.device=m,h=null,be()}}),O.appendChild(se.element));let ge=null;if(a){let xe=E("div","persona-dc-zoom-controls"),bt=Vn({icon:"minus",label:"Zoom out",size:14,onClick:()=>{h=Math.max(Zx,(h??C)-Jx),be()}});ge=E("span","persona-dc-zoom-level"),ge.title="Reset to 100%",ge.style.cursor="pointer",ge.addEventListener("click",()=>{h=1,be()});let Rt=Vn({icon:"plus",label:"Zoom in",size:14,onClick:()=>{h=Math.min(eS,(h??C)+Jx),be()}}),ut=Vn({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{h=null,be()}});xe.append(bt,ge,Rt,ut),O.appendChild(xe)}if(d){let xe=E("div","persona-dc-separator");O.appendChild(xe);let bt=Wd({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:Rt=>{y=Rt,Je.dataset.colorScheme=y,F()}});O.appendChild(bt.element)}let Ie=E("div","persona-dc-separator");O.appendChild(Ie);let ye=Vn({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[u].url,"_blank")}});O.appendChild(ye),P.append(I,O);let ce=E("div","persona-dc-stage"),Je=E("div","persona-dc-iframe-wrapper");Je.dataset.device=m,Je.dataset.colorScheme=y;let fe=E("iframe","persona-dc-iframe");fe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),fe.setAttribute("loading","lazy"),fe.title=n[u].title,Je.appendChild(fe),ce.appendChild(Je),S.append(P,ce),e.appendChild(S);function F(){try{let xe=fe.contentDocument?.body;if(!xe)return;y==="dark"?xe.classList.add("theme-dark"):xe.classList.remove("theme-dark")}catch{}}fe.addEventListener("load",()=>F());function Oe(){let xe=n[u];D.textContent=xe.title,pe.textContent=`${u+1} / ${n.length}`,fe.title=xe.title}function Ue(xe){let bt=((u+xe)%n.length+n.length)%n.length;Bt(bt)}function Bt(xe){xe<0||xe>=n.length||(u=xe,fe.src=n[u].url,Oe(),p?.(u,n[u]))}function be(){if(w)return;let xe=Xx[m]??Xx.desktop;C=GR(ce,xe);let bt=Math.max(Zx,Math.min(eS,h??C));YR(Je,fe,xe,bt,m),ge&&(ge.textContent=`${Math.round(bt*100)}%`)}let Be=new ResizeObserver(()=>be());Be.observe(ce),Oe(),fe.src=n[u].url,requestAnimationFrame(()=>be());function ve(){w||(w=!0,Be.disconnect(),document.removeEventListener("click",J),S.remove())}return{element:S,goTo:Bt,next:()=>Ue(1),prev:()=>Ue(-1),getIndex:()=>u,setDevice(xe){m=xe,Je.dataset.device=xe,se?.setSelected(xe),h=null,be()},setColorScheme(xe){y=xe,Je.dataset.colorScheme=xe},setZoom(xe){h=xe,be()},destroy:ve}}kg();var nS=16e3,XR=24e3,JR=4096,ZR=4,eH=1380533830;function tH(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===eH?new Uint8Array(e,44):new Uint8Array(e)}function nH(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Cl=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.levelCallbacks=[];this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:nS,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:nS});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ai(XR);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=`${nH(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(JR,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*ZR));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=tH(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Ws=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function wl(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Cl(e.runtype);case"browser":if(!Ws.isSupported())throw new Error("Browser speech recognition not supported");return new Ws(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function uf(e){if(e?.type==="custom"&&e.custom)return wl({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return wl({type:"runtype",runtype:e.runtype});if(Ws.isSupported())return wl({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function oS(e){try{return uf(e),!0}catch{return!1}}var rS="webmcp:",oH=e=>e.startsWith(rS)?e.slice(rS.length):e,mp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},hp=class{constructor(t,n){this.config=t;this.deps=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return mp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.deps.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s=sH(r.annotations);return{name:r.name,description:r.description,parametersSchema:iH(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return 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=oH(t),a;try{a=await r.getTools()}catch(C){let w=C instanceof Error?C.message:String(C);return bo(`Failed to read WebMCP registry: ${w}`)}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,dH(n),{signal:u.signal});return aH(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 w=C instanceof Error?C.message:String(C);return bo(w)}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??lH;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=>rH(t,o))}},rH=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},fp={type:"object",properties:{}},sH=e=>{if(!e||typeof e!="object")return;let t={...typeof e.readOnlyHint=="boolean"?{readOnlyHint:e.readOnlyHint}:{},...typeof e.untrustedContentHint=="boolean"?{untrustedContentHint:e.untrustedContentHint}:{}};return Object.keys(t).length>0?t:void 0},iH=e=>{if(e===void 0||e==="")return{...fp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...fp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...fp}}catch{return{...fp}}},aH=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:pH(t)}]}},bo=e=>({isError:!0,content:[{type:"text",text:e}]}),lH=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=cH(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
475
|
+
`;function vW(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=bW,document.head.appendChild(e)}function CW(e,t){let n=e.clientWidth-nh*2-aA,o=e.clientHeight-nh*2-aA;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function wW(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 xW(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");vW();let u=Math.max(0,Math.min(o,n.length-1)),m=r,h=s,y=null,v=1,C=!1,x=S("div","persona-dc-root"),E=S("div","persona-dc-toolbar"),H=S("div","persona-dc-toolbar-lead"),B=S("div","persona-dc-toolbar-trail"),A=zn({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>De(-1)}),O=S("div");O.style.position="relative";let L=S("button","persona-dc-title-btn");L.type="button",L.setAttribute("aria-expanded","false"),L.setAttribute("aria-haspopup","listbox");let $=S("span","persona-dc-title-text"),K=S("span","persona-dc-title-chevron"),se=St(yW,12,"currentColor",2);se&&K.appendChild(se),L.append($,K);let te=S("div","persona-dc-dropdown");te.setAttribute("role","listbox"),te.style.display="none";let P=!1;function k(){te.innerHTML="";for(let Te=0;Te<n.length;Te++){let ve=n[Te],We=S("button","persona-dc-dropdown-item");We.type="button",We.setAttribute("role","option"),We.setAttribute("aria-current",Te===u?"true":"false");let Ae=S("span");if(Ae.textContent=ve.title,We.appendChild(Ae),ve.description){let Cn=S("span","persona-dc-dropdown-desc");Cn.textContent=ve.description,We.appendChild(Cn)}We.addEventListener("click",()=>{I(),_e(Te)}),te.appendChild(We)}}function _(){P=!P,te.style.display=P?"":"none",L.setAttribute("aria-expanded",P?"true":"false"),P&&k()}function I(){P&&(P=!1,te.style.display="none",L.setAttribute("aria-expanded","false"))}L.addEventListener("click",Te=>{Te.stopPropagation(),_()});let Z=()=>I();document.addEventListener("click",Z),O.append(L,te);let U=zn({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>De(1)}),ce=S("span","persona-dc-counter");H.append(A,O,U,ce);let de=null;l&&(de=dp({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:Te=>{m=Te,lt.dataset.device=m,y=null,At()}}),B.appendChild(de.element));let pe=null;if(a){let Te=S("div","persona-dc-zoom-controls"),ve=zn({icon:"minus",label:"Zoom out",size:14,onClick:()=>{y=Math.max(sA,(y??v)-rA),At()}});pe=S("span","persona-dc-zoom-level"),pe.title="Reset to 100%",pe.style.cursor="pointer",pe.addEventListener("click",()=>{y=1,At()});let We=zn({icon:"plus",label:"Zoom in",size:14,onClick:()=>{y=Math.min(iA,(y??v)+rA),At()}}),Ae=zn({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{y=null,At()}});Te.append(ve,pe,We,Ae),B.appendChild(Te)}if(d){let Te=S("div","persona-dc-separator");B.appendChild(Te);let ve=dp({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:h,onSelect:We=>{h=We,lt.dataset.colorScheme=h,be()}});B.appendChild(ve.element)}let ke=S("div","persona-dc-separator");B.appendChild(ke);let we=zn({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[u].url,"_blank")}});B.appendChild(we),E.append(H,B);let fe=S("div","persona-dc-stage"),lt=S("div","persona-dc-iframe-wrapper");lt.dataset.device=m,lt.dataset.colorScheme=h;let rt=S("iframe","persona-dc-iframe");rt.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),rt.setAttribute("loading","lazy"),rt.title=n[u].title,lt.appendChild(rt),fe.appendChild(lt),x.append(E,fe),e.appendChild(x);function be(){try{let Te=rt.contentDocument?.body;if(!Te)return;h==="dark"?Te.classList.add("theme-dark"):Te.classList.remove("theme-dark")}catch{}}rt.addEventListener("load",()=>be());function D(){let Te=n[u];$.textContent=Te.title,ce.textContent=`${u+1} / ${n.length}`,rt.title=Te.title}function De(Te){let ve=((u+Te)%n.length+n.length)%n.length;_e(ve)}function _e(Te){Te<0||Te>=n.length||(u=Te,rt.src=n[u].url,D(),p?.(u,n[u]))}function At(){if(C)return;let Te=oA[m]??oA.desktop;v=CW(fe,Te);let ve=Math.max(sA,Math.min(iA,y??v));wW(lt,rt,Te,ve,m),pe&&(pe.textContent=`${Math.round(ve*100)}%`)}let zt=new ResizeObserver(()=>At());zt.observe(fe),D(),rt.src=n[u].url,requestAnimationFrame(()=>At());function $t(){C||(C=!0,zt.disconnect(),document.removeEventListener("click",Z),x.remove())}return{element:x,goTo:_e,next:()=>De(1),prev:()=>De(-1),getIndex:()=>u,setDevice(Te){m=Te,lt.dataset.device=Te,de?.setSelected(Te),y=null,At()},setColorScheme(Te){h=Te,lt.dataset.colorScheme=Te},setZoom(Te){y=Te,At()},destroy:$t}}vm();var lA=16e3,SW=24e3,AW=4096,MW=4,EW=1380533830;function TW(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===EW?new Uint8Array(e,44):new Uint8Array(e)}function PW(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 $l=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:lA,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:lA});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new qi(SW);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=`${PW(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 h=m.code?` (code ${m.code})`:"";this.emitError(new Error(`Voice connection closed${h}`)),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(AW,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 h=Math.max(-1,Math.min(1,d[m]));u+=h*h,p[m]=h<0?h*32768:h*32767}if(o.send(p.buffer),this.levelCallbacks.length>0){let m=Math.sqrt(u/d.length),h=Math.max(0,Math.min(1,m*MW));for(let y of this.levelCallbacks)y(h)}},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=TW(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 Zs=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 Ul(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new $l(e.runtype);case"browser":if(!Zs.isSupported())throw new Error("Browser speech recognition not supported");return new Zs(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 oh(e){if(e?.type==="custom"&&e.custom)return Ul({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Ul({type:"runtype",runtype:e.runtype});if(Zs.isSupported())return Ul({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function cA(e){try{return oh(e),!0}catch{return!1}}var dA="webmcp:",kW=e=>e.startsWith(dA)?e.slice(dA.length):e,Np={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},$p=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 Np.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=IW(r.annotations);return{name:r.name,description:r.description,parametersSchema:RW(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Co("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let v=typeof document<"u"&&!!document.modelContext;return Co(v?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=kW(t),a;try{a=await r.getTools()}catch(v){let C=v instanceof Error?v.message:String(v);return Co(`Failed to read WebMCP registry: ${C}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(v=>v.name===s);if(!l)return Co(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Co(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Co("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 Co("User declined the tool call.");if(o?.aborted)return Co("Aborted by cancel()");let u=new AbortController,m=!1,h=setTimeout(()=>{m=!0,u.abort()},this.timeoutMs),y=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",y,{once:!0}));try{let v=await r.executeTool(l,BW(n),{signal:u.signal});return HW(v)}catch(v){if(m)return Co(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Co("Aborted by cancel()");let C=v instanceof Error?v.message:String(v);return Co(C)}finally{clearTimeout(h),o&&o.removeEventListener("abort",y)}}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){Np.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,Np.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??WW;try{return await n(t)}catch(o){return Np.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=>LW(t,o))}},LW=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Fp={type:"object",properties:{}},IW=e=>{if(!e||typeof e!="object")return;let t={...typeof e.readOnlyHint=="boolean"?{readOnlyHint:e.readOnlyHint}:{},...typeof e.untrustedContentHint=="boolean"?{untrustedContentHint:e.untrustedContentHint}:{}};return Object.keys(t).length>0?t:void 0},RW=e=>{if(e===void 0||e==="")return{...Fp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Fp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Fp}}catch{return{...Fp}}},HW=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:DW(t)}]}},Co=e=>({isError:!0,content:[{type:"text",text:e}]}),WW=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=OW(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
475
476
|
|
|
476
477
|
Arguments:
|
|
477
478
|
${t}`:"")+(e.description?`
|
|
478
479
|
|
|
479
|
-
${e.description}`:"");return window.confirm(n)},
|
|
480
|
+
${e.description}`:"");return window.confirm(n)},OW=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)}},BW=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},DW=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var rh=class extends $p{constructor(t){super(t,{recordToolDisplayTitles:fd,getToolDisplayTitle:Di,loadPolyfill:hd})}};function _W(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 NW(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:_W(o,n)?2:3}function pA(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function sh(e,t){let n=t.trim();if(!n)return[...e].sort(pA);let o=[];for(let r of e){let s=NW(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:pA(r.item,s.item)),o.map(r=>r.item)}function FW(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 $W(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>sh(e.items,t),resolve:e.resolve}}function UW(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=>sh(t,FW(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 jW(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 h=m;return s.findIndex(y=>y===h||y.contains(h))},p=m=>{let h=d(m.target);if(h<0)return;let y=h;if(m.key===r)y=Math.min(h+1,s.length-1);else if(m.key===o)y=Math.max(h-1,0);else if(m.key==="Home")y=0;else if(m.key==="End")y=s.length-1;else return;m.preventDefault(),y!==h&&t.onSelect(y)},u=m=>{let h=d(m.target);h>=0&&l(s[h])};return e.addEventListener("keydown",p),e.addEventListener("focusin",u),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(m,h){if(s=m,m.forEach((y,v)=>{y.setAttribute("role","tab");let C=v===h;y.setAttribute("aria-selected",C?"true":"false"),y.tabIndex=C||h<0&&v===0?0:-1}),a){let y=(h>=0?m[h]:void 0)??m[0];y&&typeof y.focus=="function"&&(l(y),y.focus())}},destroy(){e.removeEventListener("keydown",p),e.removeEventListener("focusin",u)}}}export{tC as ASK_USER_QUESTION_CLIENT_TOOL,eC as ASK_USER_QUESTION_PARAMETERS_SCHEMA,yd as ASK_USER_QUESTION_TOOL_NAME,ji as AgentWidgetClient,yl as AgentWidgetSession,zi as AttachmentManager,zs as BrowserSpeechEngine,UL as DEFAULT_COMPONENTS,ek as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,Oi as DEFAULT_FLOATING_LAUNCHER_WIDTH,_L as DEFAULT_PALETTE,FL as DEFAULT_SEMANTIC,sk as DEFAULT_WIDGET_CONFIG,bo as HistoryProviderError,QS as PRESETS,YS as PRESET_FULLSCREEN,GS as PRESET_MINIMAL,KS as PRESET_SHOP,Vi as ReadAloudController,tm as SUGGEST_REPLIES_CLIENT_TOOL,Xv as SUGGEST_REPLIES_PARAMETERS_SCHEMA,gr as SUGGEST_REPLIES_TOOL_NAME,KL as THEME_ZONES,Do as VERSION,md as WEBMCP_TOOL_PREFIX,rh as WebMcpBridge,eW as accessibilityPlugin,tW as animationsPlugin,sS as applyFeaturePreferences,Qi as applyThemeVariables,Zi as attachHeaderToContainer,nW as brandPlugin,ta as buildComposer,gx as buildDefaultHeader,es as buildHeader,Wl as buildHeaderWithLayout,mx as buildMinimalHeader,ll as builtInClientToolsForDispatch,$n as canonicalArtifactDisplayMode,YH as collectEnrichedPageContext,Uo as componentRegistry,Ap as createActionManager,zf as createAgentExperience,n0 as createAskUserQuestionBubble,oh as createBestAvailableVoiceProvider,JI as createBubbleWithLayout,jf as createCSATFeedback,rf as createComboButton,lH as createComponentMiddleware,Ff as createComponentStreamParser,Cv as createDefaultSanitizer,xW as createDemoCarousel,bk as createDirectivePostprocessor,ea as createDropdownMenu,u0 as createFlexibleJsonStreamParser,zn as createIconButton,dm as createImagePart,am as createJsonStreamParser,ux as createLabelButton,Of as createLocalStorageAdapter,ud as createMarkdownProcessor,gd as createMarkdownProcessorFromConfig,Ax as createMessageActions,Vf as createNPSFeedback,sm as createPlainTextParser,sW as createPlugin,im as createRegexJsonParser,jW as createRovingTablist,UW as createSlashCommandsSource,LI as createSplitButton,Bl as createStandardBubble,$W as createStaticMentionSource,yo as createTextPart,Jd as createTheme,xl as createThemeObserver,dp as createToggleGroup,na as createTypingIndicator,Ul as createVoiceProvider,kp as createWidgetHostLayout,lm as createXmlParser,ZH as default,la as defaultActionHandlers,Sp as defaultJsonActionParser,sh as defaultMentionFilter,US as defaultParseRules,Zd as detectColorScheme,vk as directivePostprocessor,al as ensureAskUserQuestionSheet,Vr as escapeHtml,Uf as extractComponentDirectiveFromMessage,h0 as fileToImagePart,QH as formatEnrichedContext,js as generateAssistantMessageId,dW as generateCodeSnippet,Lk as generateMessageId,VS as generateStableSelector,rl as generateUserMessageId,Fo as getActiveTheme,LH as getAgentWidgetHandles,Yi as getColorScheme,cm as getDisplayText,fx as getHeaderLayout,f0 as getImageParts,JH as getPreset,Ep as hasComponentDirective,ul as hasImages,sf as headerLayouts,rW as highContrastPlugin,HS as initAgentWidget,qr as isAskUserQuestionMessage,aH as isComponentDirectiveType,Ct as isDockedMountMode,R0 as isHistoryProviderError,Fi as isSuggestRepliesMessage,cA as isVoiceSupported,$s as isWebMcpToolName,Ys as isWelcomeVisible,nm as latestAgentSuggestions,pI as listRegisteredStreamAnimations,Hg as loadMarkdownParsers,yv as markdownPostprocessor,tl as mergeWithDefaults,m0 as normalizeContent,Us as normalizeMediaType,Xa as onMarkdownParsersReady,zr as parseAskUserQuestionPayload,Zv as parseSuggestRepliesPayload,nS as parseWidgetPreferenceSlice,fl as pickBestVoice,wp as pluginRegistry,oW as reducedMotionPlugin,QP as registerIcons,ip as registerStreamAnimationPlugin,qs as removeAskUserQuestionSheet,$f as renderComponentDirective,xx as renderLoadingIndicatorWithFallback,ae as renderLucideIcon,Wv as resolveArtifactDisplay,ur as resolveArtifactDisplayMode,Cp as resolveConfigPreferences,Vn as resolveDockConfig,Kg as resolveSanitizer,jm as resolveTokens,Dl as resolveWelcomeConfig,Rv as stripWebMcpPrefix,Vm as themeToCssVariables,dI as unregisterStreamAnimationPlugin,y0 as validateImageFile,_w as validateTheme};
|
|
480
481
|
//# sourceMappingURL=index.js.map
|