@runtypelabs/persona 4.22.0 → 4.22.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-B_JdVK9o.d.cts → types-9Vxm-PPz.d.cts} +136 -6
- package/dist/animations/{types-B_JdVK9o.d.ts → types-9Vxm-PPz.d.ts} +136 -6
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/animations-extra.d.cts +136 -6
- package/dist/animations-extra.d.ts +136 -6
- package/dist/approval-ui.d.cts +148 -14
- package/dist/approval-ui.d.ts +148 -14
- package/dist/artifacts-ui.d.cts +148 -14
- package/dist/artifacts-ui.d.ts +148 -14
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions.d.cts +148 -14
- package/dist/context-mentions.d.ts +148 -14
- package/dist/event-stream-view-GL3ADRY2.js +1 -0
- package/dist/event-stream-view.cjs +1 -1
- package/dist/event-stream-view.d.cts +148 -14
- package/dist/event-stream-view.d.ts +148 -14
- package/dist/event-stream-view.js +1 -1
- package/dist/forms-ui.d.cts +161 -23
- package/dist/forms-ui.d.ts +161 -23
- package/dist/history-view.d.cts +136 -6
- package/dist/history-view.d.ts +136 -6
- package/dist/index.cjs +67 -67
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +166 -27
- package/dist/index.d.ts +166 -27
- package/dist/index.global.js +51 -51
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +67 -67
- package/dist/index.js.map +1 -1
- package/dist/session-reconnect.d.cts +148 -14
- package/dist/session-reconnect.d.ts +148 -14
- package/dist/smart-dom-reader.d.cts +148 -14
- package/dist/smart-dom-reader.d.ts +148 -14
- package/dist/testing.cjs +3 -3
- package/dist/testing.d.cts +3 -4
- package/dist/testing.d.ts +3 -4
- package/dist/testing.js +3 -3
- package/dist/theme-editor-preview.cjs +71 -71
- package/dist/theme-editor-preview.d.cts +148 -14
- package/dist/theme-editor-preview.d.ts +148 -14
- package/dist/theme-editor-preview.js +48 -48
- package/dist/theme-editor.d.cts +148 -14
- package/dist/theme-editor.d.ts +148 -14
- package/dist/voice-runtime.d.cts +6 -2
- package/dist/voice-runtime.d.ts +6 -2
- package/package.json +1 -1
- package/src/ask-user-question-tool.ts +1 -1
- package/src/client-history-rest.test.ts +2 -1
- package/src/client-visitor-history.test.ts +20 -4
- package/src/client.composer-options.test.ts +1 -1
- package/src/client.interrupt.test.ts +2 -2
- package/src/client.test.ts +477 -915
- package/src/client.ts +134 -494
- package/src/client.unified-tools.test.ts +76 -0
- package/src/components/event-stream-badge-theming.test.ts +3 -0
- package/src/components/event-stream-view.test.ts +76 -76
- package/src/components/event-stream-view.ts +5 -0
- package/src/components/tool-bubble.test.ts +12 -0
- package/src/components/tool-bubble.ts +13 -2
- package/src/event-stream-view-bundle.test.ts +2 -2
- package/src/generated/runtype-openapi-contract.ts +129 -1
- package/src/internal/runtype-history-provider.test.ts +2 -2
- package/src/session-history.test.ts +1 -1
- package/src/session.quote.test.ts +1 -1
- package/src/session.resubmit-from.test.ts +1 -1
- package/src/session.test.ts +5 -5
- package/src/session.ts +95 -36
- package/src/suggest-replies-tool.ts +1 -1
- package/src/testing/mock-stream.test.ts +37 -16
- package/src/testing/mock-stream.ts +14 -9
- package/src/types.ts +19 -14
- package/src/ui.ask-user-question-plugin.test.ts +7 -7
- package/src/ui.composer-defer-one.test.ts +6 -34
- package/src/ui.composer-draft-persistence.test.ts +1 -1
- package/src/ui.composer-quote.test.ts +1 -1
- package/src/ui.message-history-actions.test.ts +1 -1
- package/src/ui.streaming-coalescing.test.ts +10 -13
- package/src/ui.ts +67 -32
- package/src/ui.typing-indicator.test.ts +216 -0
- package/src/ui.voice-custom-provider.test.ts +211 -0
- package/src/utils/event-stream-buffer.test.ts +13 -13
- package/src/utils/event-stream-capture.test.ts +20 -20
- package/src/utils/throughput-tracker.test.ts +100 -142
- package/src/utils/throughput-tracker.ts +18 -132
- package/src/utils/voice-support.ts +18 -1
- package/src/voice/voice-turn-tracker.ts +18 -0
- package/src/webmcp-bridge.ts +1 -1
- package/dist/event-stream-view-FKWDY3UB.js +0 -1
- package/src/utils/__fixtures__/unified-translator.oracle.ts +0 -717
package/dist/index.cjs
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
"use strict";var uE=Object.create;var ad=Object.defineProperty;var gE=Object.getOwnPropertyDescriptor;var mE=Object.getOwnPropertyNames;var fE=Object.getPrototypeOf,hE=Object.prototype.hasOwnProperty;var rl=(e,t)=>()=>(e&&(t=e(e=0)),t);var Bg=(e,t)=>{for(var n in t)ad(e,n,{get:t[n],enumerable:!0})},Ob=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of mE(t))!hE.call(e,r)&&r!==n&&ad(e,r,{get:()=>t[r],enumerable:!(o=gE(t,r))||o.enumerable});return e};var hn=(e,t,n)=>(n=e!=null?uE(fE(e)):{},Ob(t||!e||!e.__esModule?ad(n,"default",{value:e,enumerable:!0}):n,e)),yE=e=>Ob(ad({},"__esModule",{value:!0}),e);var Db={};Bg(Db,{DOMPurify:()=>_b.default,Marked:()=>Bb.Marked});var Bb,_b,Nb=rl(()=>{"use strict";Bb=require("marked"),_b=hn(require("dompurify"),1)});var Qi,dm=rl(()=>{"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 kT(e){return e.replace(/\/+$/,"")}async function PT(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 Wd,lC=rl(()=>{"use strict";dm();Wd=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=`${kT(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 PT(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,cC=rl(()=>{"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 dC={};Bg(dC,{FallbackSpeechEngine:()=>Od,RuntypeSpeechEngine:()=>Wd});var pC=rl(()=>{"use strict";lC();cC()});var VL={};Bg(VL,{ASK_USER_QUESTION_CLIENT_TOOL:()=>tm,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>em,ASK_USER_QUESTION_TOOL_NAME:()=>dl,AgentWidgetClient:()=>zs,AgentWidgetSession:()=>Xi,AttachmentManager:()=>Ks,BrowserSpeechEngine:()=>es,DEFAULT_COMPONENTS:()=>Om,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Nd,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Vn,DEFAULT_PALETTE:()=>Hm,DEFAULT_SEMANTIC:()=>Wm,DEFAULT_WIDGET_CONFIG:()=>at,HistoryProviderError:()=>co,PRESETS:()=>Gf,PRESET_FULLSCREEN:()=>Kf,PRESET_MINIMAL:()=>Vf,PRESET_SHOP:()=>zf,ReadAloudController:()=>Vs,SUGGEST_REPLIES_CLIENT_TOOL:()=>bd,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Jg,SUGGEST_REPLIES_TOOL_NAME:()=>jo,THEME_ZONES:()=>hw,VERSION:()=>ao,WEBMCP_TOOL_PREFIX:()=>al,WebMcpBridge:()=>tu,accessibilityPlugin:()=>CS,animationsPlugin:()=>wS,applyFeaturePreferences:()=>Ef,applyThemeVariables:()=>Gs,attachHeaderToContainer:()=>Xs,brandPlugin:()=>xS,buildComposer:()=>Zs,buildDefaultHeader:()=>Qm,buildHeader:()=>Cr,buildHeaderWithLayout:()=>sa,buildMinimalHeader:()=>Xm,builtInClientToolsForDispatch:()=>Vi,canonicalArtifactDisplayMode:()=>In,collectEnrichedPageContext:()=>fS,componentRegistry:()=>Ao,createActionManager:()=>Ul,createAgentExperience:()=>$p,createAskUserQuestionBubble:()=>Tv,createBestAvailableVoiceProvider:()=>Xp,createBubbleWithLayout:()=>ex,createCSATFeedback:()=>Dp,createComboButton:()=>gp,createComponentMiddleware:()=>Gx,createComponentStreamParser:()=>Op,createDefaultSanitizer:()=>Ug,createDemoCarousel:()=>NS,createDirectivePostprocessor:()=>Xb,createDropdownMenu:()=>Js,createFlexibleJsonStreamParser:()=>Hv,createIconButton:()=>Wn,createImagePart:()=>Ld,createJsonStreamParser:()=>Td,createLabelButton:()=>Ym,createLocalStorageAdapter:()=>Hp,createMarkdownProcessor:()=>sl,createMarkdownProcessorFromConfig:()=>il,createMessageActions:()=>of,createNPSFeedback:()=>Np,createPlainTextParser:()=>Md,createPlugin:()=>MS,createRegexJsonParser:()=>Ed,createRovingTablist:()=>zS,createSlashCommandsSource:()=>qS,createSplitButton:()=>Vw,createStandardBubble:()=>ia,createStaticMentionSource:()=>jS,createTextPart:()=>lo,createTheme:()=>wl,createThemeObserver:()=>na,createToggleGroup:()=>Ol,createTypingIndicator:()=>ei,createVoiceProvider:()=>ya,createWidgetHostLayout:()=>ql,createXmlParser:()=>kd,default:()=>vS,defaultActionHandlers:()=>oi,defaultJsonActionParser:()=>$l,defaultMentionFilter:()=>nu,defaultParseRules:()=>jf,detectColorScheme:()=>xl,directivePostprocessor:()=>Jb,ensureAskUserQuestionSheet:()=>zi,escapeHtml:()=>fr,extractComponentDirectiveFromMessage:()=>_p,fileToImagePart:()=>_v,formatEnrichedContext:()=>hS,generateAssistantMessageId:()=>Gr,generateCodeSnippet:()=>IS,generateMessageId:()=>gv,generateStableSelector:()=>qf,generateUserMessageId:()=>Ui,getActiveTheme:()=>ns,getAgentWidgetHandles:()=>rS,getColorScheme:()=>op,getDisplayText:()=>Pd,getHeaderLayout:()=>Jm,getImageParts:()=>Bv,getPreset:()=>bS,hasComponentDirective:()=>jl,hasImages:()=>Gi,headerLayouts:()=>mp,highContrastPlugin:()=>AS,initAgentWidget:()=>Nf,isAskUserQuestionMessage:()=>hr,isComponentDirectiveType:()=>Kx,isDockedMountMode:()=>Et,isHistoryProviderError:()=>sC,isSuggestRepliesMessage:()=>qs,isVoiceSupported:()=>Jf,isWebMcpToolName:()=>Vr,isWelcomeVisible:()=>is,latestAgentSuggestions:()=>vd,listRegisteredStreamAnimations:()=>Fw,loadMarkdownParsers:()=>cd,markdownPostprocessor:()=>$g,mergeWithDefaults:()=>ea,normalizeContent:()=>Ov,normalizeMediaType:()=>Kr,onMarkdownParsersReady:()=>Di,parseAskUserQuestionPayload:()=>yr,parseSuggestRepliesPayload:()=>Zg,parseWidgetPreferenceSlice:()=>Mf,pickBestVoice:()=>Yi,pluginRegistry:()=>Fl,reducedMotionPlugin:()=>SS,registerIcons:()=>Vb,registerStreamAnimationPlugin:()=>Tl,removeAskUserQuestionSheet:()=>Xr,renderComponentDirective:()=>Bp,renderLoadingIndicatorWithFallback:()=>nf,renderLucideIcon:()=>ge,resolveArtifactDisplay:()=>Vg,resolveArtifactDisplayMode:()=>Uo,resolveConfigPreferences:()=>Nl,resolveDockConfig:()=>Hn,resolveSanitizer:()=>ud,resolveTokens:()=>tp,resolveWelcomeConfig:()=>So,stripWebMcpPrefix:()=>zg,themeToCssVariables:()=>np,unregisterStreamAnimationPlugin:()=>Nw,validateImageFile:()=>Dv,validateTheme:()=>Bm});module.exports=yE(VL);var Ub=require("marked"),jb=hn(require("dompurify"),1);var wt=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:tI,load:bE,provide:vE,getSync:_g}=wt({fallbackImport:()=>Promise.resolve().then(()=>(Nb(),Db))}),ld=new Set,Fb=()=>{let e=[...ld];ld.clear();for(let t of e)try{t()}catch{}};var cd=()=>{let e=_g();return e?Promise.resolve(e):bE().then(t=>(Fb(),t))},Di=e=>_g()?()=>{}:(ld.add(e),()=>{ld.delete(e)}),$b=e=>{vE(e),Fb()},$o=_g;$b({Marked:Ub.Marked,DOMPurify:jb.default});var G=require("lucide"),qb={user:G.User,mail:G.Mail,phone:G.Phone,calendar:G.Calendar,clock:G.Clock,building:G.Building,"map-pin":G.MapPin,lock:G.Lock,key:G.Key,"credit-card":G.CreditCard,hash:G.Hash,globe:G.Globe,link:G.Link,"circle-check":G.CircleCheck,"circle-x":G.CircleX,"triangle-alert":G.TriangleAlert,info:G.Info,ban:G.Ban,shield:G.Shield,house:G.House,"pen-line":G.PenLine,save:G.Save,share:G.Share,funnel:G.Funnel,settings:G.Settings,"rotate-cw":G.RotateCw,"shopping-cart":G.ShoppingCart,"shopping-bag":G.ShoppingBag,package:G.Package,truck:G.Truck,tag:G.Tag,gift:G.Gift,receipt:G.Receipt,wallet:G.Wallet,store:G.Store,"dollar-sign":G.DollarSign,percent:G.Percent,play:G.Play,pause:G.Pause,"volume-x":G.VolumeX,camera:G.Camera,image:G.Image,film:G.Film,headphones:G.Headphones,"message-circle":G.MessageCircle,bell:G.Bell,heart:G.Heart,"eye-off":G.EyeOff,bookmark:G.Bookmark,"calendar-days":G.CalendarDays,timer:G.Timer,folder:G.Folder,"folder-open":G.FolderOpen,files:G.Files,"chart-column":G.ChartColumn,sparkles:G.Sparkles,zap:G.Zap,sun:G.Sun,moon:G.Moon,flag:G.Flag,lightbulb:G.Lightbulb,monitor:G.Monitor,smartphone:G.Smartphone};var Bt=(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:aI,load:CE}=wt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")});var dd=CE;var ne=require("lucide"),wE={activity:ne.Activity,"arrow-down":ne.ArrowDown,"arrow-up":ne.ArrowUp,"arrow-up-right":ne.ArrowUpRight,bot:ne.Bot,"chevron-down":ne.ChevronDown,"chevron-up":ne.ChevronUp,"chevron-right":ne.ChevronRight,"chevron-left":ne.ChevronLeft,check:ne.Check,clipboard:ne.Clipboard,"clipboard-copy":ne.ClipboardCopy,"code-xml":ne.CodeXml,copy:ne.Copy,file:ne.File,"file-code":ne.FileCode,"file-spreadsheet":ne.FileSpreadsheet,"file-text":ne.FileText,"image-plus":ne.ImagePlus,loader:ne.Loader,"loader-circle":ne.LoaderCircle,mic:ne.Mic,paperclip:ne.Paperclip,quote:ne.Quote,"refresh-cw":ne.RefreshCw,search:ne.Search,send:ne.Send,"shield-alert":ne.ShieldAlert,"shield-check":ne.ShieldCheck,"shield-x":ne.ShieldX,square:ne.Square,"thumbs-down":ne.ThumbsDown,"thumbs-up":ne.ThumbsUp,upload:ne.Upload,"volume-2":ne.Volume2,x:ne.X,"at-sign":ne.AtSign,"arrow-left":ne.ArrowLeft,"arrow-right":ne.ArrowRight,"external-link":ne.ExternalLink,ellipsis:ne.Ellipsis,"ellipsis-vertical":ne.EllipsisVertical,menu:ne.Menu,"panel-left":ne.PanelLeft,plus:ne.Plus,minus:ne.Minus,pencil:ne.Pencil,trash:ne.Trash,"trash-2":ne.Trash2,download:ne.Download,maximize:ne.Maximize,minimize:ne.Minimize,"message-square":ne.MessageSquare,star:ne.Star,eye:ne.Eye,history:ne.History},xE=["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"],Us=new Map(Object.entries(wE)),Ni=new Set,Fi=!1,pd=new Set,Ng=e=>{let t=[...pd];e&&pd.clear();for(let n of t)try{n()}catch{}},zb=e=>Fi?()=>{}:(pd.add(e),()=>{pd.delete(e)}),Fg=()=>{let e=0;for(let t of[...Ni]){let n=Us.get(t.name);if(!n)continue;Ni.delete(t),e++;let o=Bt(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},Vb=e=>{for(let[t,n]of Object.entries(e))Us.set(t,n);Fg()>0&&!Fi&&Ng(!1)},Kb=e=>{if(!Fi){for(let[t,n]of Object.entries(e))Us.has(t)||Us.set(t,n);Fi=!0,Fg(),Ng(!0)}},Dg=!1,SE=()=>{dd().then(e=>{if(!Fi){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))Us.has(t)||Us.set(t,n);Fi=!0,Fg(),Ng(!0)}}).catch(e=>{Dg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},AE=(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},ge=(e,t=24,n="currentColor",o=2)=>{let r=Us.get(e);if(r)return Bt(r,t,n,o);if(xE.includes(e)){Dg&&(Dg=!1);let s=AE(t,n,o);if(Ni.size>=500){let a=Ni.values().next().value;a&&Ni.delete(a)}return Ni.add({el:s,name:e,size:t,color:n,strokeWidth:o}),SE(),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};Kb(qb);var ME=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},sl=e=>{let t=null;return n=>{let o=$o();if(!o)return fr(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=ME(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},il=e=>e?sl({markedOptions:e.options,renderer:e.renderer}):sl(),EE=sl(),$g=e=>EE(e),fr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Yb=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Gb=e=>`%%FORM_PLACEHOLDER_${e}%%`,Qb=(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=Gb(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=Gb(t.length);return t.push({token:s,type:r}),s}),n},Xb=e=>{let t=il(e);return n=>{let o=[],r=Qb(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="${Yb(l)}"></div>`;s=s.replace(d,u)}),s}},Jb=e=>{let t=[],n=Qb(e,t),o=$g(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="${Yb(s)}"></div>`;o=o.replace(a,d)}),o};var TE={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"]},kE=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ug=()=>{let e=null;return t=>{let n=$o();if(!n)return fr(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:")&&!kE.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,TE)}},ud=e=>e===!1?null:typeof e=="function"?e:Ug();var Zb=/^\s*\|?[\s:|-]*-[\s:|-]*$/,ev=e=>e.includes("|"),tv=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())},PE=e=>`| ${e.join(" | ")} |`,LE=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,IE=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),nv=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 ov="var(--persona-md-table-scroll-fade, 24px)",rv=new WeakSet;function iv(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 sv(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":ov),e.style.setProperty("--persona-fade-r",r<=1?"0px":ov)}function jg(e){rv.has(e)||(rv.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&sv(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(sv)}var al="webmcp:",qg=new Map,gd=e=>{qg.clear();for(let t of e){let n=t.title?.trim();n&&qg.set(t.name,n)}},$i=e=>qg.get(zg(e)),av=null;function cv(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}:${RE(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 RE(e){let t=lv(e,0).toString(36),n=lv(e,2654435761).toString(36);return`${t}.${n}`}var zg=e=>e.startsWith(al)?e.slice(al.length):e,Vr=e=>e.startsWith(al),md=()=>av?av():import("@mcp-b/webmcp-polyfill");var{setLoader:SI,load:HE}=wt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var dv=HE;function In(e){return e==="card"?"collapsed":e}function Kr(e){return e.split(";",1)[0].trim().toLowerCase()}function WE(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Kr(r)===t)return{mode:In(s),selector:Kr(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Kr(r)===o)return{mode:In(s),selector:o}}function Vg(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:In(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Kr(t.file.mimeType):void 0,d=l?WE(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:In(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:In(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:In(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:In(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:In(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Uo(e,t){return Vg(e,t).mode}function ll(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 OE="agent_",BE="flow_";function pv(e){return e.startsWith(OE)?{kind:"agentId",agentId:e}:e.startsWith(BE)?{kind:"flowId",flowId:e}:null}function uv(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=pv(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=pv(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 gv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ui(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Gr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function mv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}var Yr=require("partial-json");var M=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var X=(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},yn=(...e)=>e.filter(Boolean).join(" ");var dl="ask_user_question",cl=8,ji="data-persona-ask-sheet-for",_E="Other",DE="Other\u2026",hv="Type your own answer here",yv="Send",NE="Next",FE="Back",$E="Submit all",UE="Skip",jE=3,Kg="data-ask-current-index",Gg="data-ask-question-count",bv="data-ask-answers",Yg="data-ask-grouped",vv="data-ask-layout",qE=e=>e.layout==="pills"?"pills":"rows",zE=e=>e.getAttribute(vv)==="pills"?"pills":"rows",fv=!1,Cv=e=>e.replace(/["\\]/g,"\\$&"),hr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===dl,fd=e=>e?.features?.askUserQuestion??{},yr=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=(0,Yr.parse)(r,Yr.STR|Yr.OBJ|Yr.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},pl=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>cl&&!fv&&(fv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${cl}.`)),t.slice(0,cl)},VE=e=>pl(e)[0]??null,KE=(e,t)=>pl(e)[t]??null,wv=(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))},xv=(e,t,n)=>{if(e!=="rows")return null;let o=M("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=M("span","persona-ask-row-check");o.appendChild(r)}else{let r=M("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},GE=(e,t,n,o)=>{let s=M("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=M("span","persona-ask-row-content"),l=M("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let p=M("span","persona-ask-row-description");p.textContent=e.description,a.appendChild(p)}s.appendChild(a);let d=xv(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},YE=e=>{let n=M("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},QE=(e,t,n,o)=>{let s=M("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,d=(Array.isArray(e?.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<jE;u++)s.appendChild(YE(o));return s}if(d.forEach((u,m)=>{s.appendChild(GE(u,m,o,a))}),e?.allowFreeText!==!1){let u=o==="rows"?_E:DE;if(o==="rows"){let m=M("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(d.length)),m.setAttribute("data-ask-other-row","true");let y=M("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=t.freeTextPlaceholder??hv,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??u),y.appendChild(h),m.appendChild(y);let C=xv(o,a,d.length);C&&m.appendChild(C),s.appendChild(m)}else{let m=M("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=t.freeTextLabel??u,s.appendChild(m)}}return s},Sv=(e,t)=>{let o=M("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??hv,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=M("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??yv,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},XE=e=>{let t=M("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=M("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??yv,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},JE=(e,t,n)=>{let o=M("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=M("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??FE,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=M("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=M("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??UE,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=M("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=e===t-1;return l.textContent=d?n.submitAllLabel??$E:n.nextLabel??NE,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},js=e=>{let t=e.getAttribute(bv);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Av=(e,t)=>{e.setAttribute(bv,JSON.stringify(t))},io=e=>{let t=Number(e.getAttribute(Kg)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ZE=(e,t)=>{e.setAttribute(Kg,String(Math.max(0,Math.floor(t))))},qi=e=>{let t=Number(e.getAttribute(Gg)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Qr=e=>e.getAttribute(Yg)==="true",eT=(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},tT=(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)))},hd=(e,t)=>{let{payload:n}=yr(t),o=pl(n),r=js(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},Mv=e=>{let t=js(e),n=io(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="")},Ev=e=>{if(!Qr(e))return;let t=js(e),n=io(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}},Qg=(e,t,n)=>{let o=fd(n),r=zE(e),{payload:s,complete:a}=yr(t),l=Qr(e),d=io(e),p=qi(e),u=l?KE(s,d):VE(s),m=!!u?.multiSelect,y=e.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=l?`${d+1}/${p}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let C=e.querySelector('[data-ask-question="true"]');if(C){let O=typeof u?.question=="string"?u.question:"";C.textContent=O,C.classList.toggle("persona-ask-question-skeleton",!O&&!a)}let S=e.querySelector('[data-ask-pill-list="true"]');if(S){let O=QE(u,o,a,r);S.replaceWith(O)}if(r!=="rows"){let O=e.querySelector('[data-ask-free-text-row="true"]');O&&O.replaceWith(Sv(o,r))}let x=e.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!x?e.appendChild(XE(o)):(!m||l)&&x&&x.remove(),e.setAttribute("data-multi-select",m?"true":"false");let P=e.querySelector('[data-ask-nav-row="true"]');if(l){let O=JE(d,p,o);P?P.replaceWith(O):e.appendChild(O)}else P&&P.remove();Mv(e),Ev(e)},nT=(e,t,n)=>{let o=fd(t),r=qE(o),s=e.toolCall.id,a=pl(n),l=Math.max(1,a.length),d=l>1,p=eT(e,a),u=d?tT(e,l):0,m=M("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(ji,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",e.id),m.setAttribute(Gg,String(l)),m.setAttribute(Kg,String(u)),m.setAttribute(Yg,d?"true":"false"),m.setAttribute(vv,r),Av(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`),wv(m,o);let y=M("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=M("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",y.appendChild(h);let C=M("span","persona-ask-sheet-step-inline");C.setAttribute("data-ask-step-inline","true"),C.textContent="",y.appendChild(C),m.appendChild(y);let x=M("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return x.setAttribute("data-ask-pill-list","true"),x.setAttribute("role","group"),m.appendChild(x),r!=="rows"&&m.appendChild(Sv(o,r)),Qg(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},oT=(e,t,n)=>{let{payload:o}=yr(t),r=Math.max(1,pl(o).length);r>qi(e)&&(e.setAttribute(Gg,String(r)),r>1&&!Qr(e)&&e.setAttribute(Yg,"true")),Qg(e,t,n)},Tv=(e,t)=>{let n=M("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=fd(t);wv(n,o);let r=M("span","persona-ask-stub-label"),{complete:s}=yr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},zi=(e,t,n)=>{if(!n||!hr(e)||fd(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ji}]`).forEach(p=>{p.getAttribute(ji)!==r&&p.remove()});let a=n.querySelector(`[${ji}="${Cv(r)}"]`);if(a){oT(a,e,t);return}let{payload:l}=yr(e),d=nT(e,t,l);n.appendChild(d)},Xr=(e,t)=>{if(!e)return;let n=t?`[${ji}="${Cv(t)}"]`:`[${ji}]`;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)})},Xg=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),Jr=(e,t)=>{let n=js(e),o=io(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Av(e,n),Mv(e),Ev(e)},yd=(e,t,n,o)=>{let r=qi(e),s=Math.max(0,Math.min(r-1,o));ZE(e,s),Qg(e,t,n)};var jo="suggest_replies";var Jg={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},bd={name:jo,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:Jg,origin:"sdk",annotations:{readOnlyHint:!0}},Pv=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),qs=e=>e.variant==="tool"&&e.toolCall?.name===jo,Zg=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},vd=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!qs(n))continue;let o=Zg(n.toolCall?.args);return o.length>0?o:null}return null},kv=new Set,rT=(e,t,n)=>{let o=`${e}:${t}:${n}`;kv.has(o)||(kv.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Zr=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&&rT(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 em={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:cl,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},tm={name:dl,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:em,origin:"sdk",annotations:{readOnlyHint:!0}},Vi=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(tm),Zr(e).expose&&t.push(bd),t};var br=require("partial-json"),Cd=e=>e.replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
1
|
+
"use strict";var hE=Object.create;var rd=Object.defineProperty;var yE=Object.getOwnPropertyDescriptor;var bE=Object.getOwnPropertyNames;var vE=Object.getPrototypeOf,CE=Object.prototype.hasOwnProperty;var el=(e,t)=>()=>(e&&(t=e(e=0)),t);var Bg=(e,t)=>{for(var n in t)rd(e,n,{get:t[n],enumerable:!0})},_b=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of bE(t))!CE.call(e,r)&&r!==n&&rd(e,r,{get:()=>t[r],enumerable:!(o=yE(t,r))||o.enumerable});return e};var fn=(e,t,n)=>(n=e!=null?hE(vE(e)):{},_b(t||!e||!e.__esModule?rd(n,"default",{value:e,enumerable:!0}):n,e)),wE=e=>_b(rd({},"__esModule",{value:!0}),e);var Fb={};Bg(Fb,{DOMPurify:()=>Nb.default,Marked:()=>Db.Marked});var Db,Nb,$b=el(()=>{"use strict";Db=require("marked"),Nb=fn(require("dompurify"),1)});var qi,dm=el(()=>{"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 RT(e){return e.replace(/\/+$/,"")}async function HT(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 Id,pC=el(()=>{"use strict";dm();Id=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=`${RT(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 HT(a));let l=a.body.getReader();for(;;){let{done:d,value:p}=await l.read();if(t!==this.generation){await l.cancel().catch(()=>{});return}if(d)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(t!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var Rd,uC=el(()=>{"use strict";Rd=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var gC={};Bg(gC,{FallbackSpeechEngine:()=>Rd,RuntypeSpeechEngine:()=>Id});var mC=el(()=>{"use strict";pC();uC()});var QL={};Bg(QL,{ASK_USER_QUESTION_CLIENT_TOOL:()=>tm,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>em,ASK_USER_QUESTION_TOOL_NAME:()=>il,AgentWidgetClient:()=>Ds,AgentWidgetSession:()=>zi,AttachmentManager:()=>Fs,BrowserSpeechEngine:()=>Yr,DEFAULT_COMPONENTS:()=>Om,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Bd,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Gn,DEFAULT_PALETTE:()=>Hm,DEFAULT_SEMANTIC:()=>Wm,DEFAULT_WIDGET_CONFIG:()=>it,HistoryProviderError:()=>ao,PRESETS:()=>Gf,PRESET_FULLSCREEN:()=>Kf,PRESET_MINIMAL:()=>Vf,PRESET_SHOP:()=>zf,ReadAloudController:()=>Ns,SUGGEST_REPLIES_CLIENT_TOOL:()=>fd,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Jg,SUGGEST_REPLIES_TOOL_NAME:()=>Fo,THEME_ZONES:()=>vw,VERSION:()=>Co,WEBMCP_TOOL_PREFIX:()=>ol,WebMcpBridge:()=>Jp,accessibilityPlugin:()=>SS,animationsPlugin:()=>AS,applyFeaturePreferences:()=>Ef,applyThemeVariables:()=>$s,attachHeaderToContainer:()=>qs,brandPlugin:()=>MS,buildComposer:()=>Vs,buildDefaultHeader:()=>Qm,buildHeader:()=>hr,buildHeaderWithLayout:()=>Zi,buildMinimalHeader:()=>Xm,builtInClientToolsForDispatch:()=>Fi,canonicalArtifactDisplayMode:()=>On,collectEnrichedPageContext:()=>bS,componentRegistry:()=>So,createActionManager:()=>Nl,createAgentExperience:()=>Dp,createAskUserQuestionBubble:()=>Iv,createBestAvailableVoiceProvider:()=>Gp,createBubbleWithLayout:()=>ox,createCSATFeedback:()=>Op,createComboButton:()=>dp,createComponentMiddleware:()=>Xx,createComponentStreamParser:()=>Rp,createDefaultSanitizer:()=>Ug,createDemoCarousel:()=>US,createDirectivePostprocessor:()=>tv,createDropdownMenu:()=>zs,createFlexibleJsonStreamParser:()=>_v,createIconButton:()=>Dn,createImagePart:()=>Td,createJsonStreamParser:()=>Ad,createLabelButton:()=>Ym,createLocalStorageAdapter:()=>Lp,createMarkdownProcessor:()=>tl,createMarkdownProcessorFromConfig:()=>nl,createMessageActions:()=>of,createNPSFeedback:()=>Bp,createPlainTextParser:()=>xd,createPlugin:()=>PS,createRegexJsonParser:()=>Sd,createRovingTablist:()=>GS,createSlashCommandsSource:()=>KS,createSplitButton:()=>Yw,createStandardBubble:()=>ea,createStaticMentionSource:()=>VS,createTextPart:()=>io,createTheme:()=>bl,createThemeObserver:()=>Qi,createToggleGroup:()=>Rl,createTypingIndicator:()=>Ks,createVoiceProvider:()=>pa,createWidgetHostLayout:()=>$l,createXmlParser:()=>Md,default:()=>xS,defaultActionHandlers:()=>Qs,defaultJsonActionParser:()=>Dl,defaultMentionFilter:()=>Zp,defaultParseRules:()=>jf,detectColorScheme:()=>vl,directivePostprocessor:()=>nv,ensureAskUserQuestionSheet:()=>Ni,escapeHtml:()=>pr,extractComponentDirectiveFromMessage:()=>Wp,fileToImagePart:()=>$v,formatEnrichedContext:()=>vS,generateAssistantMessageId:()=>jr,generateCodeSnippet:()=>WS,generateMessageId:()=>yv,generateStableSelector:()=>qf,generateUserMessageId:()=>Bi,getActiveTheme:()=>Xr,getAgentWidgetHandles:()=>aS,getColorScheme:()=>ep,getDisplayText:()=>Ed,getHeaderLayout:()=>Jm,getImageParts:()=>Fv,getPreset:()=>wS,hasComponentDirective:()=>Fl,hasImages:()=>Ui,headerLayouts:()=>pp,highContrastPlugin:()=>TS,initAgentWidget:()=>Nf,isAskUserQuestionMessage:()=>ur,isComponentDirectiveType:()=>Qx,isDockedMountMode:()=>At,isHistoryProviderError:()=>cC,isSuggestRepliesMessage:()=>_s,isVoiceSupported:()=>Jf,isWebMcpToolName:()=>$r,isWelcomeVisible:()=>ts,latestAgentSuggestions:()=>hd,listRegisteredStreamAnimations:()=>jw,loadMarkdownParsers:()=>id,markdownPostprocessor:()=>$g,mergeWithDefaults:()=>Gi,normalizeContent:()=>Nv,normalizeMediaType:()=>Ur,onMarkdownParsersReady:()=>Ri,parseAskUserQuestionPayload:()=>gr,parseSuggestRepliesPayload:()=>Zg,parseWidgetPreferenceSlice:()=>Mf,pickBestVoice:()=>ji,pluginRegistry:()=>_l,reducedMotionPlugin:()=>ES,registerIcons:()=>Gb,registerStreamAnimationPlugin:()=>Al,removeAskUserQuestionSheet:()=>Vr,renderComponentDirective:()=>Hp,renderLoadingIndicatorWithFallback:()=>nf,renderLucideIcon:()=>de,resolveArtifactDisplay:()=>Vg,resolveArtifactDisplayMode:()=>No,resolveConfigPreferences:()=>Bl,resolveDockConfig:()=>_n,resolveSanitizer:()=>cd,resolveTokens:()=>Jd,resolveWelcomeConfig:()=>xo,stripWebMcpPrefix:()=>zg,themeToCssVariables:()=>Zd,unregisterStreamAnimationPlugin:()=>Uw,validateImageFile:()=>Uv,validateTheme:()=>Bm});module.exports=wE(QL);var qb=require("marked"),zb=fn(require("dompurify"),1);var yt=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:sI,load:xE,provide:SE,getSync:_g}=yt({fallbackImport:()=>Promise.resolve().then(()=>($b(),Fb))}),sd=new Set,Ub=()=>{let e=[...sd];sd.clear();for(let t of e)try{t()}catch{}};var id=()=>{let e=_g();return e?Promise.resolve(e):xE().then(t=>(Ub(),t))},Ri=e=>_g()?()=>{}:(sd.add(e),()=>{sd.delete(e)}),jb=e=>{SE(e),Ub()},Do=_g;jb({Marked:qb.Marked,DOMPurify:zb.default});var K=require("lucide"),Vb={user:K.User,mail:K.Mail,phone:K.Phone,calendar:K.Calendar,clock:K.Clock,building:K.Building,"map-pin":K.MapPin,lock:K.Lock,key:K.Key,"credit-card":K.CreditCard,hash:K.Hash,globe:K.Globe,link:K.Link,"circle-check":K.CircleCheck,"circle-x":K.CircleX,"triangle-alert":K.TriangleAlert,info:K.Info,ban:K.Ban,shield:K.Shield,house:K.House,"pen-line":K.PenLine,save:K.Save,share:K.Share,funnel:K.Funnel,settings:K.Settings,"rotate-cw":K.RotateCw,"shopping-cart":K.ShoppingCart,"shopping-bag":K.ShoppingBag,package:K.Package,truck:K.Truck,tag:K.Tag,gift:K.Gift,receipt:K.Receipt,wallet:K.Wallet,store:K.Store,"dollar-sign":K.DollarSign,percent:K.Percent,play:K.Play,pause:K.Pause,"volume-x":K.VolumeX,camera:K.Camera,image:K.Image,film:K.Film,headphones:K.Headphones,"message-circle":K.MessageCircle,bell:K.Bell,heart:K.Heart,"eye-off":K.EyeOff,bookmark:K.Bookmark,"calendar-days":K.CalendarDays,timer:K.Timer,folder:K.Folder,"folder-open":K.FolderOpen,files:K.Files,"chart-column":K.ChartColumn,sparkles:K.Sparkles,zap:K.Zap,sun:K.Sun,moon:K.Moon,flag:K.Flag,lightbulb:K.Lightbulb,monitor:K.Monitor,smartphone:K.Smartphone};var Ht=(e,t=24,n="currentColor",o=2)=>{if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([p,u])=>{p!=="stroke"&&d.setAttribute(p,String(u))}),r.appendChild(d)}),r};var{setLoader:pI,load:AE}=yt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")});var ad=AE;var te=require("lucide"),ME={activity:te.Activity,"arrow-down":te.ArrowDown,"arrow-up":te.ArrowUp,"arrow-up-right":te.ArrowUpRight,bot:te.Bot,"chevron-down":te.ChevronDown,"chevron-up":te.ChevronUp,"chevron-right":te.ChevronRight,"chevron-left":te.ChevronLeft,check:te.Check,clipboard:te.Clipboard,"clipboard-copy":te.ClipboardCopy,"code-xml":te.CodeXml,copy:te.Copy,file:te.File,"file-code":te.FileCode,"file-spreadsheet":te.FileSpreadsheet,"file-text":te.FileText,"image-plus":te.ImagePlus,loader:te.Loader,"loader-circle":te.LoaderCircle,mic:te.Mic,paperclip:te.Paperclip,quote:te.Quote,"refresh-cw":te.RefreshCw,search:te.Search,send:te.Send,"shield-alert":te.ShieldAlert,"shield-check":te.ShieldCheck,"shield-x":te.ShieldX,square:te.Square,"thumbs-down":te.ThumbsDown,"thumbs-up":te.ThumbsUp,upload:te.Upload,"volume-2":te.Volume2,x:te.X,"at-sign":te.AtSign,"arrow-left":te.ArrowLeft,"arrow-right":te.ArrowRight,"external-link":te.ExternalLink,ellipsis:te.Ellipsis,"ellipsis-vertical":te.EllipsisVertical,menu:te.Menu,"panel-left":te.PanelLeft,plus:te.Plus,minus:te.Minus,pencil:te.Pencil,trash:te.Trash,"trash-2":te.Trash2,download:te.Download,maximize:te.Maximize,minimize:te.Minimize,"message-square":te.MessageSquare,star:te.Star,eye:te.Eye,history:te.History},EE=["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"],Os=new Map(Object.entries(ME)),Hi=new Set,Wi=!1,ld=new Set,Ng=e=>{let t=[...ld];e&&ld.clear();for(let n of t)try{n()}catch{}},Kb=e=>Wi?()=>{}:(ld.add(e),()=>{ld.delete(e)}),Fg=()=>{let e=0;for(let t of[...Hi]){let n=Os.get(t.name);if(!n)continue;Hi.delete(t),e++;let o=Ht(n,t.size,t.color,t.strokeWidth);if(o)for(t.el.removeAttribute("data-persona-icon-pending");o.firstChild;)t.el.appendChild(o.firstChild)}return e},Gb=e=>{for(let[t,n]of Object.entries(e))Os.set(t,n);Fg()>0&&!Wi&&Ng(!1)},Yb=e=>{if(!Wi){for(let[t,n]of Object.entries(e))Os.has(t)||Os.set(t,n);Wi=!0,Fg(),Ng(!0)}},Dg=!1,TE=()=>{ad().then(e=>{if(!Wi){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))Os.has(t)||Os.set(t,n);Wi=!0,Fg(),Ng(!0)}}).catch(e=>{Dg=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},PE=(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},de=(e,t=24,n="currentColor",o=2)=>{let r=Os.get(e);if(r)return Ht(r,t,n,o);if(EE.includes(e)){Dg&&(Dg=!1);let s=PE(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}),TE(),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};Yb(Vb);function Qb(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 Wn(e){return e?.type==="runtype"||e?.type==="custom"}var kE=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function Xb(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:kE()}catch{return!1}}var LE=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},tl=e=>{let t=null;return n=>{let o=Do();if(!o)return pr(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=LE(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},nl=e=>e?tl({markedOptions:e.options,renderer:e.renderer}):tl(),IE=tl(),$g=e=>IE(e),pr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Zb=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Jb=e=>`%%FORM_PLACEHOLDER_${e}%%`,ev=(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=Jb(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=Jb(t.length);return t.push({token:s,type:r}),s}),n},tv=e=>{let t=nl(e);return n=>{let o=[],r=ev(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="${Zb(l)}"></div>`;s=s.replace(d,u)}),s}},nv=e=>{let t=[],n=ev(e,t),o=$g(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="${Zb(s)}"></div>`;o=o.replace(a,d)}),o};var RE={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"]},HE=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ug=()=>{let e=null;return t=>{let n=Do();if(!n)return pr(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:")&&!HE.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,RE)}},cd=e=>e===!1?null:typeof e=="function"?e:Ug();var ov=/^\s*\|?[\s:|-]*-[\s:|-]*$/,rv=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())},WE=e=>`| ${e.join(" | ")} |`,OE=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,BE=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),iv=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(!rv(r)||ov.test(r)||!ov.test(s))continue;let a=sv(r).length;if(a<1)continue;let l=OE(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()===""||!rv(p))break;let u=WE(BE(sv(p),a));t[d]!==u&&(t[d]=u,n=!0)}o=d-1}return n?t.join(`
|
|
3
|
+
`):e};var av="var(--persona-md-table-scroll-fade, 24px)",lv=new WeakSet;function dv(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 cv(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":av),e.style.setProperty("--persona-fade-r",r<=1?"0px":av)}function jg(e){lv.has(e)||(lv.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&cv(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(cv)}var ol="webmcp:",qg=new Map,dd=e=>{qg.clear();for(let t of e){let n=t.title?.trim();n&&qg.set(t.name,n)}},Oi=e=>qg.get(zg(e)),pv=null;function gv(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}:${_E(t.join(""))}`}function uv(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 _E(e){let t=uv(e,0).toString(36),n=uv(e,2654435761).toString(36);return`${t}.${n}`}var zg=e=>e.startsWith(ol)?e.slice(ol.length):e,$r=e=>e.startsWith(ol),pd=()=>pv?pv():import("@mcp-b/webmcp-polyfill");var{setLoader:PI,load:DE}=yt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var mv=DE;function On(e){return e==="card"?"collapsed":e}function Ur(e){return e.split(";",1)[0].trim().toLowerCase()}function NE(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Ur(r)===t)return{mode:On(s),selector:Ur(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ur(r)===o)return{mode:On(s),selector:o}}function Vg(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:On(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Ur(t.file.mimeType):void 0,d=l?NE(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:On(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:On(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:On(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:On(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:On(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function No(e,t){return Vg(e,t).mode}function rl(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 FE="agent_",$E="flow_";function fv(e){return e.startsWith(FE)?{kind:"agentId",agentId:e}:e.startsWith($E)?{kind:"flowId",flowId:e}:null}function hv(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=fv(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=fv(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 yv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Bi(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function jr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function bv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}var qr=require("partial-json");var E=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Y=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let l of Object.keys(a)){let d=a[l];d!=null&&(s[l]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},hn=(...e)=>e.filter(Boolean).join(" ");var il="ask_user_question",sl=8,_i="data-persona-ask-sheet-for",UE="Other",jE="Other\u2026",Cv="Type your own answer here",wv="Send",qE="Next",zE="Back",VE="Submit all",KE="Skip",GE=3,Kg="data-ask-current-index",Gg="data-ask-question-count",xv="data-ask-answers",Yg="data-ask-grouped",Sv="data-ask-layout",YE=e=>e.layout==="pills"?"pills":"rows",QE=e=>e.getAttribute(Sv)==="pills"?"pills":"rows",vv=!1,Av=e=>e.replace(/["\\]/g,"\\$&"),ur=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===il,ud=e=>e?.features?.askUserQuestion??{},gr=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=(0,qr.parse)(r,qr.STR|qr.OBJ|qr.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},al=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>sl&&!vv&&(vv=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${sl}.`)),t.slice(0,sl)},XE=e=>al(e)[0]??null,JE=(e,t)=>al(e)[t]??null,Mv=(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))},Ev=(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},ZE=(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=Ev(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},eT=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},tT=(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<GE;u++)s.appendChild(eT(o));return s}if(d.forEach((u,m)=>{s.appendChild(ZE(u,m,o,a))}),e?.allowFreeText!==!1){let u=o==="rows"?UE:jE;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??Cv,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",t.freeTextLabel??u),y.appendChild(h),m.appendChild(y);let v=Ev(o,a,d.length);v&&m.appendChild(v),s.appendChild(m)}else{let m=E("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=t.freeTextLabel??u,s.appendChild(m)}}return s},Tv=(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??Cv,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??wv,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},nT=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??wv,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},oT=(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??zE,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??KE,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??VE:n.nextLabel??qE,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Bs=e=>{let t=e.getAttribute(xv);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Pv=(e,t)=>{e.setAttribute(xv,JSON.stringify(t))},so=e=>{let t=Number(e.getAttribute(Kg)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},rT=(e,t)=>{e.setAttribute(Kg,String(Math.max(0,Math.floor(t))))},Di=e=>{let t=Number(e.getAttribute(Gg)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},zr=e=>e.getAttribute(Yg)==="true",sT=(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},iT=(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)))},gd=(e,t)=>{let{payload:n}=gr(t),o=al(n),r=Bs(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},kv=e=>{let t=Bs(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="")},Lv=e=>{if(!zr(e))return;let t=Bs(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}},Qg=(e,t,n)=>{let o=ud(n),r=QE(e),{payload:s,complete:a}=gr(t),l=zr(e),d=so(e),p=Di(e),u=l?JE(s,d):XE(s),m=!!u?.multiSelect,y=e.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=l?`${d+1}/${p}`:"");let h=e.querySelector('[data-ask-stepper="true"]');h&&h.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let O=typeof u?.question=="string"?u.question:"";v.textContent=O,v.classList.toggle("persona-ask-question-skeleton",!O&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let O=tT(u,o,a,r);x.replaceWith(O)}if(r!=="rows"){let O=e.querySelector('[data-ask-free-text-row="true"]');O&&O.replaceWith(Tv(o,r))}let w=e.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!w?e.appendChild(nT(o)):(!m||l)&&w&&w.remove(),e.setAttribute("data-multi-select",m?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(l){let O=oT(d,p,o);k?k.replaceWith(O):e.appendChild(O)}else k&&k.remove();kv(e),Lv(e)},aT=(e,t,n)=>{let o=ud(t),r=YE(o),s=e.toolCall.id,a=al(n),l=Math.max(1,a.length),d=l>1,p=sT(e,a),u=d?iT(e,l):0,m=E("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(Gg,String(l)),m.setAttribute(Kg,String(u)),m.setAttribute(Yg,d?"true":"false"),m.setAttribute(Sv,r),Pv(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`),Mv(m,o);let y=E("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=E("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",y.appendChild(h);let v=E("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",y.appendChild(v),m.appendChild(y);let w=E("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),m.appendChild(w),r!=="rows"&&m.appendChild(Tv(o,r)),Qg(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},lT=(e,t,n)=>{let{payload:o}=gr(t),r=Math.max(1,al(o).length);r>Di(e)&&(e.setAttribute(Gg,String(r)),r>1&&!zr(e)&&e.setAttribute(Yg,"true")),Qg(e,t,n)},Iv=(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=ud(t);Mv(n,o);let r=E("span","persona-ask-stub-label"),{complete:s}=gr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Ni=(e,t,n)=>{if(!n||!ur(e)||ud(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}="${Av(r)}"]`);if(a){lT(a,e,t);return}let{payload:l}=gr(e),d=aT(e,t,l);n.appendChild(d)},Vr=(e,t)=>{if(!e)return;let n=t?`[${_i}="${Av(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)})},Xg=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),Kr=(e,t)=>{let n=Bs(e),o=so(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Pv(e,n),kv(e),Lv(e)},md=(e,t,n,o)=>{let r=Di(e),s=Math.max(0,Math.min(r-1,o));rT(e,s),Qg(e,t,n)};var Fo="suggest_replies";var Jg={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},fd={name:Fo,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:Jg,origin:"sdk",annotations:{readOnlyHint:!0}},Hv=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),_s=e=>e.variant==="tool"&&e.toolCall?.name===Fo,Zg=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},hd=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!_s(n))continue;let o=Zg(n.toolCall?.args);return o.length>0?o:null}return null},Rv=new Set,cT=(e,t,n)=>{let o=`${e}:${t}:${n}`;Rv.has(o)||(Rv.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Gr=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&&cT(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 em={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},tm={name:il,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:em,origin:"sdk",annotations:{readOnlyHint:!0}},Fi=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(tm),Gr(e).expose&&t.push(fd),t};var mr=require("partial-json"),yd=e=>e.replace(/\\n/g,`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),bd=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)}},dT=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`},Wv=e=>e.status==="complete"?dT(e):e.status==="pending"?"Waiting":"",pT=15e3,uT=1200,Ov=(e,t)=>{let n=t?.durationMs??pT,o=t?.chars??uT;return typeof e.durationMs=="number"?e.durationMs<n:(e.chunks??[]).join("").length<o},gT=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 Bv=e=>e.status==="complete"?gT(e):"Using tool...",vd=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},cl=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 vd(t)},Cd=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return vd(t)},nm=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=cl(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},wd=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&ll(o,n.slice(s,a.index),[]),a[1]!==void 0?ll(o,a[1],["bold"]):a[2]!==void 0?ll(o,a[2],["italic"]):a[3]!==void 0&&ll(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ll(o,n.slice(s),[]),o},ll=(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})},mT=()=>{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()=>{}}},ml=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Md=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Ed=()=>{let e=cT();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)}},Td=()=>{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=(0,br.parse)(n,br.STR|br.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Cd(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Cd(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Hv=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=l=>typeof l=="string"?Cd(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Cd(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=(0,br.parse)(s,br.STR|br.OBJ),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},kd=()=>{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 Wv="4.22.0";var ao=Wv;var Ki="[Image]";function Ov(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Pd(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Gi(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Bv(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function lo(e){return{type:"text",text:e}}function Ld(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function _v(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 Dv(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"],pT=["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"],vr=[...Nv,...pT];function uT(e){return Nv.includes(e)||e.startsWith("image/")}function Id(e){return uT(e.type)}function Fv(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function $v(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Id(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 Uv(e,t=vr,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 gT(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function jv(e,t){let n=gT(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 mT=["user","assistant","system"],fT=0;function qv(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Rd(e){return typeof e=="string"?e:void 0}function hT(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?lo(t.text):null;case"image":return typeof t.image=="string"?Ld(t.image,{mimeType:Rd(t.mimeType),alt:Rd(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?Fv(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...Rd(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...Rd(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function yT(e,t){let n=qv(t),o=e.map(a=>qv(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:fT+y;s=l+1}return r.map(a=>new Date(a).toISOString())}function zv(e,t){let n=yT(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!mT.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(hT).filter(u=>u!==null),p=Pd(d);o.push({id:r.id,role:a,content:p||(Gi(d)?Ki:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function fl(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 hl(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 bT="https://api.runtype.com/v1/dispatch",Vv="https://api.runtype.com",je=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Kv=32768,om=49152,Gv=e=>{let t=e??{},n=typeof t.targetId=="string"?t.targetId:typeof t.flowId=="string"?t.flowId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:n,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},Yv=e=>"reason"in e?e.reason:void 0,Qv="The identity proof was not admitted; account history is unavailable",Xv="The identity proof was rejected",Jv="The request carried no visitor credential",Zv="The stored visitor belongs to a different signed-in user",rm=(e,t)=>e instanceof je&&e.code===t;function vT(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 sm=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function CT(e){switch(e){case"json":return Td;case"regex-json":return Ed;case"xml":return kd;default:return Md}}var eC=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function wT(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=eC(n);if(!eC(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=ml(e);return ml(t)!==null&&a===null?t:e}var zs=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??bT,this.headers={"Content-Type":"application/json","X-Persona-Version":ao,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??CT(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 dv().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:gd,getToolDisplayTitle:$i,loadPolyfill:md});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=uv(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$/,"")||Vv}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 je("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":ao,"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&&Yv(n)===Yv(t);if(this.historyIdentityStatus=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let n=this.isHistoryCapable()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.routing(),a=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,d={token:this.config.clientToken,...a&&{flowId:a},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...l?{conversationId:l}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao},body:JSON.stringify(d)});if(p.status===400&&o){let m={...d};delete m.durableRecovery,p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao},body:JSON.stringify(m)})}if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new je("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 je("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&p.status===401&&m.error==="visitor_required"?new je("visitor_required","Visitor credential no longer resolves"):l&&p.status===404?new je("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):p.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let u=await p.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId??u.flow?.id?{targetId:u.targetId??u.flow?.id}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.createClientSession({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,t,!1)}catch(r){if(!rm(r,"not_found")&&!rm(r,"visitor_required")&&!rm(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 je("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new je("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:t,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}historyUrl(t,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new je("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new je("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new je("proof_not_admitted",Qv);return r}async readErrorCode(t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new je("invalid_identity_proof",Xv);if(r.includes("visitor token required"))throw new je("visitor_token_missing",Jv);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new je("visitor_identity_mismatch",Zv);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new je("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,n){let o=await this.readErrorCode(t);if(t.status===404)return new je("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new je("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new je("proof_not_admitted",Qv);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new je("invalid_identity_proof",Xv)):r.includes("visitor token required")?new je("visitor_token_missing",Jv):r.includes("visitor_identity_mismatch")?new je("visitor_identity_mismatch",Zv):new je("unauthorized",o||"History request was not authorized")}return new je("request_failed",o||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new je("identity_contract_violation","Server reported an ignored identity proof on a success response"):new je("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new je("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let d=a?.revision()??0,p=await this.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new je("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":ao,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),y=await u.json().catch(()=>{});if(a&&a.revision()!==d)throw new je("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),y}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new je("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let n=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Gv),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}}),r=o&&typeof o.conversation=="object"&&o.conversation!==null?o.conversation:o;return{summary:Gv(r),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(t,n){this.assertHistoryUsable();let o=0;for(let d of n){let p=d.displayContent.length;if(p>Kv)throw new je("payload_too_large",`displayContent exceeds the ${Kv} character limit`);o+=p}if(o>om)throw new je("payload_too_large",`Display projection batch exceeds the ${om} 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<=om,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=mv();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=await this.initSession();if(new Date>=new Date(a.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let C=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:C}),C}let l=await this.buildPayload(t.messages),d=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null,p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([C])=>C!=="sessionId"&&C!=="session_id")):void 0,u=this.isHistoryCapable(),m={sessionId:a.sessionId,messages:t.messages.filter(sm).map(C=>{let S=u?fl(C):void 0;return{id:C.id,role:C.role,content:C.contentParts??C.llmContent??C.rawContent??C.content,...S!==void 0&&{displayContent:S}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},{response:y,commit:h}=await this.sendWithClientToolsDiff(a.sessionId,l.clientTools,C=>{let S={...m,...C};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao,...d?{"X-Visitor-Token":d}:{}},body:JSON.stringify(S),signal:t.signal})});if(!y.ok){let C=await y.json().catch(()=>({error:"Chat request failed"}));if(y.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let x=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:x}),x}if(y.status===429){let x=new Error(C.hint||"Message limit reached for this session.");throw s({type:"error",error:x}),x}if(y.status===410&&C.error==="conversation_deleted"){let x=new je("conversation_deleted","This conversation was deleted");throw s({type:"error",error:x}),x}let S=new Error(C.error||"Failed to send message");throw s({type:"error",error:S}),S}if(!y.body){let C=new Error("No response body received");throw s({type:"error",error:C}),C}h(),s({type:"status",status:"connected"});try{await this.streamResponse(y.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof je)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let o=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?cv(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(/\/+$/,"")||Vv}/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=[...Vi(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:y}=await this.sendWithClientToolsDiff(a,u,h=>{let C={...p,...h};return this.debug&&console.debug("[AgentWidgetClient] client token resume",C),fetch(s,{method:"POST",headers:d,body:JSON.stringify(C),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&y(),m}return fetch(s,{method:"POST",headers:d,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(t,n){let o=n?.selectedModelId;return!o||!("model"in t)?t:this.config.composer?.models?.some(s=>s.id===o)?{...t,model:o}:t}async buildAgentPayload(t,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(sm).filter(p=>p.role==="user"||p.role==="assistant"||p.role==="system").filter(p=>!p.variant||p.variant==="assistant").sort((p,u)=>{let m=new Date(p.createdAt).getTime(),y=new Date(u.createdAt).getTime();return m-y}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...Vi(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(a.clientTools=l);let d=await this.buildContextAggregate(t);return d&&(a.context=d),a}async buildPayload(t,n){let o=t.slice().filter(sm).sort((p,u)=>{let m=new Date(p.createdAt).getTime(),y=new Date(u.createdAt).getTime();return m-y}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,u]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=u);let a=[...Vi(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(s.clientTools=a);let l=await this.buildContextAggregate(t);l&&(s.context=l);let d=this.normalizeComposerOptions(n);if(d&&(s.composerOptions=d),this.requestMiddleware)try{let p=await this.requestMiddleware({payload:{...s},config:this.config});if(p&&typeof p=="object"){let u=p;return s.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=s.clientTools),u}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=m,r(m),m},p=u=>o.current?o.current:d(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",d=Date.now(),p=0,u=()=>d+p++,m=D=>{let J=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,v=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,_=D.tools?D.tools.map(F=>({...F,chunks:F.chunks?[...F.chunks]:void 0})):void 0;return{...D,reasoning:J,toolCall:v,tools:_}},y=D=>{if(D.role!=="assistant"||D.variant)return!0;let J=Array.isArray(D.contentParts)&&D.contentParts.length>0,v=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||J||v||!!D.stopReason},h=D=>{y(D)&&n({type:"message",message:m(D)})},C=null,S=null,x={current:null},P={current:null},O=null,$="",T=new Map,R=new Map,A=new Map,N=new Map,Y=new Map,ce={lastId:null,byStep:new Map},Q={lastId:null,byCall:new Map},E=D=>{if(D==null)return null;try{return String(D)}catch{return null}},B=D=>E(D.stepId??D.step_id??D.step??D.parentId??D.flowStepId??D.flow_step_id),H=D=>E(D.callId??D.call_id??D.requestId??D.request_id??D.toolCallId??D.tool_call_id??D.stepId??D.step_id),L=o,te=!1,K=()=>{if(C)return C;let D,J="",v=O;return!te&&L?(D=L,te=!0,J=r??""):L&&v?D=`${L}_${v}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,C={id:D,role:"assistant",content:J,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},h(C),C},me=(D,J)=>{ce.lastId=J,D&&ce.byStep.set(D,J)},de=(D,J)=>{let v=D.reasoningId??D.id,_=B(D);if(v){let U=String(v);return me(_,U),U}if(_){let U=ce.byStep.get(_);if(U)return ce.lastId=U,U}if(ce.lastId&&!J)return ce.lastId;if(!J)return null;let F=`reason-${u()}`;return me(_,F),F},he=D=>{let J=N.get(D);if(J)return J;let v={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:D,status:"streaming",chunks:[]}};return N.set(D,v),h(v),v},We=(D,J)=>{Q.lastId=J,D&&Q.byCall.set(D,J)},Oe=new Set,we=new Map,Qe=new Set,Ce=new Map,j=D=>{if(!D)return!1;let J=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return J==="emit_artifact_markdown"||J==="emit_artifact_component"},Ne=(D,J)=>{let v=D.toolId??D.id,_=H(D);if(v){let U=String(v);return We(_,U),U}if(_){let U=Q.byCall.get(_);if(U)return Q.lastId=U,U}if(Q.lastId&&!J)return Q.lastId;if(!J)return null;let F=`tool-${u()}`;return We(_,F),F},Ue=D=>{let J=Y.get(D);if(J)return J;let v={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:D,status:"pending"}};return Y.set(D,v),h(v),v},ht=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let J=Number(D);if(!Number.isNaN(J)&&Number.isFinite(J))return J;let v=Date.parse(D);if(!Number.isNaN(v))return v}return Date.now()},xe=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},ke=new Map,be=new Map,Ie=new Map,Tt=(D,J,v)=>{let _=Ie.get(D);_||(_=[],Ie.set(D,_));let F=0,U=_.length;for(;F<U;){let ie=F+U>>>1;_[ie].seq<J?F=ie+1:U=ie}_[F]?.seq===J?_[F]={seq:J,text:v}:_.splice(F,0,{seq:J,text:v});let oe="";for(let ie=0;ie<_.length;ie++)oe+=_[ie].text;return oe},Xt=(D,J)=>{let v=xe(J),_=be.get(D.id),F=wT(_,v);D.rawContent=F;let U=ke.get(D.id),oe=_e=>{let _t=D.content??"";_e.trim()!==""&&(_t.trim().length===0||_e.startsWith(_t)||_e.trimStart().startsWith(_t.trim()))&&(D.content=_e)},ie=()=>{if(U){let _e=U.close?.();_e instanceof Promise&&_e.catch(()=>{})}ke.delete(D.id),be.delete(D.id),D.streaming=!1,h(D)};if(!U){oe(v),ie();return}let le=ml(F);if(le!==null&&le.trim()!==""){oe(le),ie();return}let pe=_e=>{let _t=typeof _e=="string"?_e:_e?.text??null;if(_t!==null&&_t.trim()!=="")return _t;let Lt=U.getExtractedText();return Lt!==null&&Lt.trim()!==""?Lt:v},qt;try{qt=U.processChunk(F)}catch{oe(v),ie();return}if(qt instanceof Promise){qt.then(_e=>{oe(pe(_e)),ie()}).catch(()=>{oe(v),ie()});return}oe(pe(qt)),ie()},yt=null,gn=(D,J,v,_)=>{D.rawContent=J,ke.has(D.id)||ke.set(D.id,this.createStreamParser());let F=ke.get(D.id),U=J.trim().startsWith("{")||J.trim().startsWith("[");if(U&&be.set(D.id,J),F.__isPlainTextParser===!0){D.content=_!==void 0?J:D.content+v,be.delete(D.id),ke.delete(D.id),D.rawContent=void 0,h(D);return}let ie=F.processChunk(J);if(ie instanceof Promise)ie.then(le=>{let pe=typeof le=="string"?le:le?.text??null;pe!==null&&pe.trim()!==""?(D.content=pe,h(D)):!U&&!J.trim().startsWith("<")&&(D.content=_!==void 0?J:D.content+v,be.delete(D.id),ke.delete(D.id),D.rawContent=void 0,h(D))}).catch(()=>{D.content=_!==void 0?J:D.content+v,be.delete(D.id),ke.delete(D.id),D.rawContent=void 0,h(D)});else{let le=typeof ie=="string"?ie:ie?.text??null;le!==null&&le.trim()!==""?(D.content=le,h(D)):!U&&!J.trim().startsWith("<")&&(D.content=_!==void 0?J:D.content+v,be.delete(D.id),ke.delete(D.id),D.rawContent=void 0,h(D))}},Yn=(D,J)=>{let v=J??D.content;if(v==null||v===""){D.streaming=!1,h(D);return}let F=be.get(D.id)??xe(v);D.rawContent=F;let U=ke.get(D.id),oe=null,ie=!1;if(U&&(oe=U.getExtractedText(),oe===null&&(oe=ml(F)),oe===null)){let le=U.processChunk(F);le instanceof Promise?(ie=!0,le.then(pe=>{let qt=typeof pe=="string"?pe:pe?.text??null;qt!==null&&(D.content=qt,D.streaming=!1,ke.delete(D.id),be.delete(D.id),h(D))}).catch(()=>{})):oe=typeof le=="string"?le:le?.text??null}if(!ie){oe!==null&&oe.trim()!==""?D.content=oe:be.has(D.id)||(D.content=xe(v));let le=ke.get(D.id);if(le){let pe=le.close?.();pe instanceof Promise&&pe.catch(()=>{}),ke.delete(D.id)}be.delete(D.id),D.streaming=!1,h(D)}},cn=(D,J,v)=>{let _=R.get(D);if(_)return _;let F={id:`nested-${J}-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:D,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:J}};return R.set(D,F),h(F),F},Eo=[],Qn,uo=new Map,si=0,To="agent",Yo=!1,ls=null,nt=null,On=new Map,go=this.config.iterationDisplay??"separate";for(Qn=()=>{for(let D=0;D<Eo.length;D++){let J=Eo[D].payloadType,v=Eo[D].payload;if(!Yo&&To!=="flow"&&typeof v.stepType=="string"&&(To="flow"),J==="reasoning_start"){let _=typeof v.id=="string"?v.id:null,F=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(_&&F){T.set(_,F),cn(_,F,"reasoning");continue}let U=de(v,!0)??`reason-${u()}`,oe=he(U);oe.reasoning=oe.reasoning??{id:U,status:"streaming",chunks:[]},oe.reasoning.startedAt=oe.reasoning.startedAt??ht(v.startedAt??v.timestamp),oe.reasoning.completedAt=void 0,oe.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(oe.reasoning.scope=v.scope),oe.streaming=!0,oe.reasoning.status="streaming",h(oe)}else if(J==="reasoning_delta"){let _=typeof v.id=="string"?v.id:null;if(_&&T.has(_)&&R.has(_)){let ie=R.get(_),le=v.reasoningText??v.text??v.delta??"";le&&v.hidden!==!0&&ie.reasoning&&(ie.reasoning.chunks.push(String(le)),h(ie));continue}let F=de(v,!1)??de(v,!0)??`reason-${u()}`,U=he(F);U.reasoning=U.reasoning??{id:F,status:"streaming",chunks:[]},U.reasoning.startedAt=U.reasoning.startedAt??ht(v.startedAt??v.timestamp);let oe=v.reasoningText??v.text??v.delta??"";if(oe&&v.hidden!==!0){let ie=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(ie!==void 0){let le=Tt(F,ie,String(oe));U.reasoning.chunks=[le]}else U.reasoning.chunks.push(String(oe))}if(U.reasoning.status=v.done?"complete":"streaming",v.done){U.reasoning.completedAt=ht(v.completedAt??v.timestamp);let ie=U.reasoning.startedAt??Date.now();U.reasoning.durationMs=Math.max(0,(U.reasoning.completedAt??Date.now())-ie)}U.streaming=U.reasoning.status!=="complete",h(U)}else if(J==="reasoning_complete"){let _=typeof v.id=="string"?v.id:null;if(_&&T.has(_)&&R.has(_)){let le=R.get(_);if(le.reasoning){let pe=typeof v.text=="string"?v.text:"";pe&&le.reasoning.chunks.length===0&&le.reasoning.chunks.push(pe),le.reasoning.status="complete",le.streaming=!1,h(le)}T.delete(_),R.delete(_);continue}let F=de(v,!1)??de(v,!0)??`reason-${u()}`,U=typeof v.text=="string"?v.text:"";!N.get(F)&&(U||v.scope==="loop")&&he(F);let oe=N.get(F);if(oe?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(oe.reasoning.scope=v.scope),U&&oe.reasoning.chunks.length===0&&oe.reasoning.chunks.push(U),oe.reasoning.status="complete",oe.reasoning.completedAt=ht(v.completedAt??v.timestamp);let le=oe.reasoning.startedAt??Date.now();oe.reasoning.durationMs=Math.max(0,(oe.reasoning.completedAt??Date.now())-le),oe.streaming=!1,h(oe)}let ie=B(v);ie&&ce.byStep.delete(ie)}else if(J==="tool_start"){C&&(C.streaming=!1,h(C),C=null),typeof v.iteration=="number"&&(si=v.iteration);let _=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??Ne(v,!0)??`tool-${u()}`,F=v.toolName??v.name;if(j(F)){Oe.add(_);continue}We(H(v),_);let U=Ue(_),oe=U.toolCall??{id:_,status:"pending"};oe.name=F??oe.name,oe.status="running",v.parameters!==void 0?oe.args=v.parameters:v.args!==void 0&&(oe.args=v.args),oe.startedAt=oe.startedAt??ht(v.startedAt??v.timestamp),oe.completedAt=void 0,oe.durationMs=void 0,U.toolCall=oe,U.streaming=!0,v.executionId&&(U.agentMetadata={executionId:v.executionId,iteration:v.iteration}),h(U)}else if(J==="tool_output_delta"){let _=Ne(v,!1)??Ne(v,!0)??`tool-${u()}`;if(Oe.has(_))continue;let F=Ue(_),U=F.toolCall??{id:_,status:"running"};U.startedAt=U.startedAt??ht(v.startedAt??v.timestamp);let oe=v.text??v.delta??v.message??"";oe&&(U.chunks=U.chunks??[],U.chunks.push(String(oe))),U.status="running",F.toolCall=U,F.streaming=!0;let ie=v.agentContext;(ie||v.executionId)&&(F.agentMetadata=F.agentMetadata??{executionId:ie?.executionId??v.executionId,iteration:ie?.iteration??v.iteration}),h(F)}else if(J==="tool_complete"){let _=Ne(v,!1)??Ne(v,!0)??`tool-${u()}`;if(Oe.has(_)){Oe.delete(_);continue}let F=Ue(_),U=F.toolCall??{id:_,status:"running"};U.status="complete",v.result!==void 0&&(U.result=v.result),typeof v.duration=="number"&&(U.duration=v.duration),U.completedAt=ht(v.completedAt??v.timestamp);let oe=v.duration??v.executionTime;if(typeof oe=="number")U.durationMs=oe;else{let pe=U.startedAt??Date.now();U.durationMs=Math.max(0,(U.completedAt??Date.now())-pe)}F.toolCall=U,F.streaming=!1;let ie=v.agentContext;(ie||v.executionId)&&(F.agentMetadata=F.agentMetadata??{executionId:ie?.executionId??v.executionId,iteration:ie?.iteration??v.iteration}),h(F);let le=H(v);le&&Q.byCall.delete(le)}else if(J==="await"&&v.toolName){let _=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,F=_??v.toolId??`local-${u()}`,U=Ue(F),oe=v.toolName,ie=v.origin==="webmcp"&&!Vr(oe)?`webmcp:${oe}`:oe,le=Vr(ie),pe=U.toolCall??{id:F,status:"pending"};pe.name=ie,pe.args=v.parameters,pe.status=le?"running":"complete",pe.chunks=pe.chunks??[],pe.startedAt=pe.startedAt??ht(v.startedAt??v.timestamp??v.awaitedAt),le?(pe.completedAt=void 0,pe.duration=void 0,pe.durationMs=void 0):pe.completedAt=pe.completedAt??pe.startedAt,U.toolCall=pe,U.streaming=!1,U.agentMetadata={...U.agentMetadata,executionId:v.executionId??U.agentMetadata?.executionId,awaitingLocalTool:!0,..._?{webMcpToolCallId:_}:{}},h(U)}else if(J==="text_start"){let _=typeof v.id=="string"?v.id:null,F=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(_&&F){T.set(_,F);continue}let U=C;U&&(To==="flow"?(Yn(U),yt=U):(U.streaming=!1,h(U)),C=null),O=typeof v.id=="string"?v.id:O,$=""}else if(J==="text_delta"){let _=typeof v.id=="string"?v.id:null,F=_?T.get(_):void 0;if(_&&F){let ie=typeof v.delta=="string"?v.delta:"",le=(A.get(_)??"")+ie;if(A.set(_,le),le.trim()==="")continue;let pe=cn(_,F);pe.agentMetadata={...pe.agentMetadata,executionId:v.executionId,parentToolId:F},gn(pe,le,ie,void 0);continue}if(O=typeof v.id=="string"?v.id:O,To==="flow"){let ie=typeof v.delta=="string"?v.delta:"";if($+=ie,$.trim()==="")continue;let le=K();le.agentMetadata={executionId:v.executionId,iteration:v.iteration},gn(le,$,ie,void 0),S=le;continue}let U=typeof v.delta=="string"?v.delta:"";$+=U;let oe=K();oe.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:ls??void 0,agentName:nt?.agentName},gn(oe,$,U,void 0),S=oe}else if(J==="text_complete"){let _=typeof v.id=="string"?v.id:null;if(_&&T.has(_)){let U=R.get(_);U&&Yn(U),T.delete(_),A.delete(_),R.delete(_);continue}let F=C;F&&(To==="flow"?(Yn(F),yt=F):((F.content??"")===""&&typeof v.text=="string"&&(F.content=v.text),F.streaming=!1,h(F)),C=null),O=null,$=""}else if(J==="step_complete"){let _=v.stepType,F=v.executionType;if(_==="tool"||F==="context")continue;if(v.success===!1){let U=v.error,oe=typeof U=="string"&&U!==""?U:U!=null&&typeof U=="object"&&Reflect.has(U,"message")?String(U.message??"Step failed"):"Step failed";n({type:"error",error:new Error(oe)});let ie=C;ie&&ie.streaming&&(ie.streaming=!1,h(ie)),n({type:"status",status:"idle"});continue}{let U=yt;yt=null;let oe=v.stopReason,ie=v.result?.response;if(U)oe&&(U.stopReason=oe),ie!=null?Xt(U,ie):U.streaming!==!1&&(ke.delete(U.id),be.delete(U.id),U.streaming=!1,h(U));else{let le=ie!=null&&ie!=="";if(le||oe){let pe=K();oe&&(pe.stopReason=oe),le?Yn(pe,ie):(pe.streaming=!1,h(pe))}}continue}}else if(J==="execution_start")To=v.kind==="flow"?"flow":"agent",Yo=!0,To==="agent"&&(nt={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:ht(v.startedAt)});else if(J==="turn_start"){let _=typeof v.iteration=="number"?v.iteration:si;if(_!==si){if(nt&&(nt.currentIteration=_),go==="separate"&&_>1){let F=C;F&&(F.streaming=!1,h(F),On.set(_-1,F),C=null)}si=_}ls=typeof v.id=="string"?v.id:null,S=null}else if(J==="tool_input_delta"){let _=v.toolCallId??Q.lastId;if(_){let F=Y.get(_);F?.toolCall&&(F.toolCall.chunks=F.toolCall.chunks??[],F.toolCall.chunks.push(v.delta??""),h(F))}}else{if(J==="tool_input_complete")continue;if(J==="turn_complete"){let _=v.stopReason,F=C??S;if(_&&F!==null){let U=v.id;(!U||F.agentMetadata?.turnId===U)&&(F.stopReason=_,h(F))}ls===v.id&&(ls=null)}else if(J==="media_start"){let _=String(v.id);uo.set(_,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(J==="media_delta"){let _=uo.get(String(v.id));_&&typeof v.delta=="string"&&_.parts.push(v.delta)}else if(J==="media_complete"){let _=String(v.id),F=uo.get(_);uo.delete(_);let U=(typeof v.mediaType=="string"?v.mediaType:void 0)??F?.mediaType??"application/octet-stream",oe=typeof v.data=="string"?v.data:void 0,ie=typeof v.url=="string"?v.url:F&&F.parts.length>0?F.parts.join(""):void 0,le=null;if(oe)le={type:"media",data:oe,mediaType:U};else if(ie){let _t=U.toLowerCase();le={type:_t==="image"||_t.startsWith("image/")?"image-url":"file-url",url:ie,mediaType:U}}let pe=v.toolCallId??F?.toolCallId,qt=le?[le]:[],_e=[];for(let _t of qt){if(!_t||typeof _t!="object")continue;let Lt=_t,Qo=typeof Lt.type=="string"?Lt.type:void 0,Er=typeof Lt.mediaType=="string"?Lt.mediaType.toLowerCase():"",zt=null,Vt="";if(Qo==="media"){let Sn=typeof Lt.data=="string"?Lt.data:void 0;if(!Sn)continue;Vt=Er.length>0?Er:"application/octet-stream",zt=`data:${Vt};base64,${Sn}`}else if(Qo==="image-url"){let Sn=typeof Lt.url=="string"?Lt.url:void 0;if(!Sn)continue;Vt=Er,zt=Sn}else if(Qo==="file-url"){let Sn=typeof Lt.url=="string"?Lt.url:void 0;if(!Sn)continue;Vt=Er,zt=Sn}else continue;if(zt)if(Qo==="image-url"||Vt.startsWith("image/"))_e.push({type:"image",image:zt,...Vt.includes("/")?{mimeType:Vt}:{}});else if(Vt.startsWith("audio/"))_e.push({type:"audio",audio:zt,mimeType:Vt});else if(Vt.startsWith("video/"))_e.push({type:"video",video:zt,mimeType:Vt});else{let Sn=Vt||"application/octet-stream";_e.push({type:"file",data:zt,mimeType:Sn,filename:vT(Sn)})}}if(_e.length>0){let _t=u(),Lt=pe,Er={id:`agent-media-${typeof Lt=="string"&&Lt.length>0?`${Lt}-${_t}`:String(_t)}`,role:"assistant",content:"",contentParts:_e,createdAt:new Date().toISOString(),streaming:!1,sequence:_t,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:si}};h(Er);let zt=C;zt&&(zt.streaming=!1,h(zt)),C=null,x.current=null}}else if(J==="execution_complete"){let _=v.kind??To;_==="agent"&&nt&&(nt.status=v.success?"complete":"error",nt.completedAt=ht(v.completedAt),nt.stopReason=v.stopReason);let F=C;F&&(_==="flow"&&F.streaming!==!1?Yn(F):(F.streaming=!1,h(F)),C=null),O=null,$="",yt=null,n({type:"status",status:"idle",terminal:!0})}else if(J==="execution_error"){let _=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(_)})}else if(J!=="ping"){if(J==="approval_start"){let _=v.approvalId??`approval-${u()}`,F={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:_,status:"pending",agentId:nt?.agentId??"virtual",executionId:v.executionId??nt?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};h(F)}else if(J==="step_await"&&v.awaitReason==="approval_required"){let _=v.approvalId??`approval-${u()}`,F={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:_,status:"pending",agentId:nt?.agentId??"virtual",executionId:v.executionId??nt?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};h(F)}else if(J==="approval_complete"){let _=v.approvalId;if(_){let U={id:`approval-${_}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:_,status:v.decision??"approved",agentId:nt?.agentId??"virtual",executionId:v.executionId??nt?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};h(U)}}else if(J==="artifact_start"||J==="artifact_delta"||J==="artifact_update"||J==="artifact_complete"){if(J==="artifact_start"){let _=v.artifactType,F=String(v.id),U=typeof v.title=="string"?v.title:void 0,oe=v.file,ie;oe&&typeof oe=="object"&&!Array.isArray(oe)&&typeof oe.path=="string"&&typeof oe.mimeType=="string"&&(ie={path:oe.path,mimeType:oe.mimeType,...typeof oe.language=="string"?{language:oe.language}:{}}),n({type:"artifact_start",id:F,artifactType:_,title:U,component:typeof v.component=="string"?v.component:void 0,...ie?{file:ie}:{}});let le=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(Ce.set(F,{markdown:"",title:U,file:ie,...le?{props:le}:{}}),!Qe.has(F)){Qe.add(F);let pe=Uo(this.config.features?.artifacts,{artifactType:_,...ie?{file:ie}:{}}),qt=typeof v.component=="string"?v.component:void 0,_e={id:`artifact-ref-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:ll(pe,{artifactId:F,title:U,artifactType:_,status:"streaming",...ie?{file:ie}:{},...qt?{component:qt}:{}})};we.set(F,_e),h(_e)}}else if(J==="artifact_delta"){let _=String(v.id),F=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:_,artDelta:F});let U=Ce.get(_);U&&(U.markdown+=F)}else if(J==="artifact_update"){let _=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:_,component:typeof v.component=="string"?v.component:void 0});let F=Ce.get(String(v.id));F&&(F.props={...F.props??{},..._})}else if(J==="artifact_complete"){let _=String(v.id);n({type:"artifact_complete",id:_});let F=we.get(_);if(F){F.streaming=!1;try{let U=JSON.parse(F.rawContent??"{}");if(U.props){U.props.status="complete";let oe=Ce.get(_);oe?.markdown&&(U.props.markdown=oe.markdown),oe?.file&&(U.props.file=oe.file),U.component==="PersonaArtifactInline"&&oe?.props&&Object.keys(oe.props).length>0&&(U.props.componentProps=oe.props)}F.rawContent=JSON.stringify(U)}catch{}Ce.delete(_),h(F),we.delete(_)}}}else if(J==="transcript_insert"){let _=v.message;if(!_||typeof _!="object")continue;let F=String(_.id??`msg-${u()}`),U=_.role,ie={id:F,role:U==="user"?"user":U==="system"?"system":"assistant",content:typeof _.content=="string"?_.content:"",rawContent:typeof _.rawContent=="string"?_.rawContent:void 0,createdAt:typeof _.createdAt=="string"?_.createdAt:new Date().toISOString(),streaming:_.streaming===!0,...typeof _.variant=="string"?{variant:_.variant}:{},sequence:u()};if(h(ie),ie.rawContent)try{let pe=JSON.parse(ie.rawContent)?.props?.artifactId;typeof pe=="string"&&Qe.add(pe)}catch{}C=null,x.current=null,ke.delete(F),be.delete(F)}else if(J==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let _=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(_)});let F=C;F&&F.streaming&&(F.streaming=!1,h(F)),n({type:"status",status:"idle"})}}else if(J==="step_error"||J==="dispatch_error"||J==="flow_error"){let _=null;if(v.error instanceof Error)_=v.error;else if(J==="dispatch_error"){let F=v.message??v.error;F!=null&&F!==""&&(_=new Error(String(F)))}else{let F=v.error;typeof F=="string"&&F!==""?_=new Error(F):F!=null&&typeof F=="object"&&Reflect.has(F,"message")&&(_=new Error(String(F.message??F)))}if(_){n({type:"error",error:_});let F=C;F&&F.streaming&&(F.streaming=!1,h(F)),n({type:"status",status:"idle"})}}}}}Eo.length=0};;){let{done:D,value:J}=await s.read();if(D)break;l+=a.decode(J,{stream:!0});let v=l.split(`
|
|
6
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},dl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},xd=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Sd=()=>{let e=mT();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)}},Ad=()=>{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=(0,mr.parse)(n,mr.STR|mr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?yd(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=yd(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},_v=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=l=>typeof l=="string"?yd(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?yd(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=(0,mr.parse)(s,mr.STR|mr.OBJ),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Md=()=>{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 Dv="4.22.1";var Co=Dv;var $i="[Image]";function Nv(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ed(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ui(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Fv(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function io(e){return{type:"text",text:e}}function Td(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function $v(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 Uv(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 jv=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],hT=["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"],fr=[...jv,...hT];function yT(e){return jv.includes(e)||e.startsWith("image/")}function Pd(e){return yT(e.type)}function qv(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function zv(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Pd(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 Vv(e,t=fr,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 bT(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Kv(e,t){let n=bT(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 vT=["user","assistant","system"],CT=0;function Gv(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function kd(e){return typeof e=="string"?e:void 0}function wT(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?io(t.text):null;case"image":return typeof t.image=="string"?Td(t.image,{mimeType:kd(t.mimeType),alt:kd(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?qv(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...kd(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...kd(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function xT(e,t){let n=Gv(t),o=e.map(a=>Gv(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:CT+y;s=l+1}return r.map(a=>new Date(a).toISOString())}function Yv(e,t){let n=xT(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!vT.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(wT).filter(u=>u!==null),p=Ed(d);o.push({id:r.id,role:a,content:p||(Ui(d)?$i:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function pl(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 ul(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 ST="https://api.runtype.com/v1/dispatch",Qv="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)}},Xv=32768,om=49152,Jv=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:""}},Zv=e=>"reason"in e?e.reason:void 0,eC="The identity proof was not admitted; account history is unavailable",tC="The identity proof was rejected",nC="The request carried no visitor credential",oC="The stored visitor belongs to a different signed-in user",rm=(e,t)=>e instanceof $e&&e.code===t;function AT(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 sm=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function MT(e){switch(e){case"json":return Ad;case"regex-json":return Sd;case"xml":return Md;default:return xd}}var rC=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ET(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=rC(n);if(!rC(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=dl(e);return dl(t)!==null&&a===null?t:e}var Ds=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??ST,this.headers={"Content-Type":"application/json","X-Persona-Version":Co,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??MT(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 mv().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:dd,getToolDisplayTitle:Oi,loadPolyfill:pd});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=hv(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$/,"")||Qv}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":Co,"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&&Zv(n)===Zv(t);if(this.historyIdentityStatus=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let n=this.isHistoryCapable()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.routing(),a=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,d={token:this.config.clientToken,...a&&{flowId:a},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...l?{conversationId:l}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Co},body:JSON.stringify(d)});if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new $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(!rm(r,"not_found")&&!rm(r,"visitor_required")&&!rm(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(t,n)):this.doOrdinaryInit(t,n)}async doOrdinaryInit(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,t,n)}async reinitWithProof(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:t}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),s}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&t.durableRecovery?.enabled!==!0)return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new $e("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new $e("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:t,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Co},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}historyUrl(t,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new $e("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new $e("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new $e("proof_not_admitted",eC);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",tC);if(r.includes("visitor token required"))throw new $e("visitor_token_missing",nC);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",oC);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",eC);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",tC)):r.includes("visitor token required")?new $e("visitor_token_missing",nC):r.includes("visitor_identity_mismatch")?new $e("visitor_identity_mismatch",oC):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":Co,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),y=await u.json().catch(()=>{});if(a&&a.revision()!==d)throw new $e("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),y}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new $e("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let n=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Jv),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:Jv(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>Xv)throw new $e("payload_too_large",`displayContent exceeds the ${Xv} character limit`);o+=p}if(o>om)throw new $e("payload_too_large",`Display projection batch exceeds the ${om} 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<=om,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=bv();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=await this.initSession();if(new Date>=new Date(a.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let v=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:v}),v}let l=await this.buildPayload(t.messages),d=a.durableRecovery?.enabled===!0?await this.readVisitorToken():null,p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([v])=>v!=="sessionId"&&v!=="session_id")):void 0,u=this.isHistoryCapable(),m={sessionId:a.sessionId,messages:t.messages.filter(sm).map(v=>{let x=u?pl(v):void 0;return{id:v.id,role:v.role,content:v.contentParts??v.llmContent??v.rawContent??v.content,...x!==void 0&&{displayContent:x}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},{response:y,commit:h}=await this.sendWithClientToolsDiff(a.sessionId,l.clientTools,v=>{let x={...m,...v};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",x),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Co,...d?{"X-Visitor-Token":d}:{}},body:JSON.stringify(x),signal:t.signal})});if(!y.ok){let v=await y.json().catch(()=>({error:"Chat request failed"}));if(y.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let w=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:w}),w}if(y.status===429){let w=new Error(v.hint||"Message limit reached for this session.");throw s({type:"error",error:w}),w}if(y.status===410&&v.error==="conversation_deleted"){let w=new $e("conversation_deleted","This conversation was deleted");throw s({type:"error",error:w}),w}let x=new Error(v.error||"Failed to send message");throw s({type:"error",error:x}),x}if(!y.body){let v=new Error("No response body received");throw s({type:"error",error:v}),v}h(),s({type:"status",status:"connected"});try{await this.streamResponse(y.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof $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?gv(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(/\/+$/,"")||Qv}/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=[...Fi(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:y}=await this.sendWithClientToolsDiff(a,u,h=>{let v={...p,...h};return this.debug&&console.debug("[AgentWidgetClient] client token resume",v),fetch(s,{method:"POST",headers:d,body:JSON.stringify(v),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&y(),m}return fetch(s,{method:"POST",headers:d,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(t,n){let o=n?.selectedModelId;return!o||!("model"in t)?t:this.config.composer?.models?.some(s=>s.id===o)?{...t,model:o}:t}async buildAgentPayload(t,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(sm).filter(p=>p.role==="user"||p.role==="assistant"||p.role==="system").filter(p=>!p.variant||p.variant==="assistant").sort((p,u)=>{let m=new Date(p.createdAt).getTime(),y=new Date(u.createdAt).getTime();return m-y}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...Fi(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];l.length>0&&(a.clientTools=l);let d=await this.buildContextAggregate(t);return d&&(a.context=d),a}async buildPayload(t,n){let o=t.slice().filter(sm).sort((p,u)=>{let m=new Date(p.createdAt).getTime(),y=new Date(u.createdAt).getTime();return m-y}).map(p=>({role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,createdAt:p.createdAt})),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,u]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=u);let a=[...Fi(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(s.clientTools=a);let l=await this.buildContextAggregate(t);l&&(s.context=l);let d=this.normalizeComposerOptions(n);if(d&&(s.composerOptions=d),this.requestMiddleware)try{let p=await this.requestMiddleware({payload:{...s},config:this.config});if(p&&typeof p=="object"){let u=p;return s.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=s.clientTools),u}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=m,r(m),m},p=u=>o.current?o.current:d(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",d=Date.now(),p=0,u=()=>d+p++,m=q=>{let S=q.reasoning?{...q.reasoning,chunks:[...q.reasoning.chunks]}:void 0,N=q.toolCall?{...q.toolCall,chunks:q.toolCall.chunks?[...q.toolCall.chunks]:void 0}:void 0,z=q.tools?q.tools.map(Q=>({...Q,chunks:Q.chunks?[...Q.chunks]:void 0})):void 0;return{...q,reasoning:S,toolCall:N,tools:z}},y=q=>{if(q.role!=="assistant"||q.variant)return!0;let S=Array.isArray(q.contentParts)&&q.contentParts.length>0,N=typeof q.rawContent=="string"&&q.rawContent.trim()!=="";return typeof q.content=="string"&&q.content.trim()!==""||S||N||!!q.stopReason},h=q=>{y(q)&&n({type:"message",message:m(q)})},v=null,x=null,w={current:null},k={current:null},O=null,D="",T=new Map,I=new Map,A=new Map,_=new Map,G=new Map,le=o,ee=!1,M=()=>{if(v)return v;let q,S="",N=O;return!ee&&le?(q=le,ee=!0,S=r??""):le&&N?q=`${le}_${N}`:q=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:q,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},h(v),v},B=q=>{let S=_.get(q);if(S)return S;let N={id:`reason-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:q,status:"streaming",chunks:[]}};return _.set(q,N),h(N),N},H=new Set,R=new Map,Z=new Set,V=new Map,ge=q=>{if(!q)return!1;let S=q.replace(/_+/g,"_").replace(/^_|_$/g,"");return S==="emit_artifact_markdown"||S==="emit_artifact_component"},ae=q=>{let S=G.get(q);if(S)return S;let N={id:`tool-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:q,status:"pending"}};return G.set(q,N),h(N),N},fe=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){let S=Number(q);if(!Number.isNaN(S)&&Number.isFinite(S))return S;let N=Date.parse(q);if(!Number.isNaN(N))return N}return Date.now()},He=q=>{if(typeof q=="string")return q;if(q==null)return"";try{return JSON.stringify(q)}catch{return String(q)}},ve=new Map,pe=new Map,et=(q,S)=>{let N=He(S),z=pe.get(q.id),Q=ET(z,N);q.rawContent=Q;let ne=ve.get(q.id),be=Ye=>{let ze=q.content??"";Ye.trim()!==""&&(ze.trim().length===0||Ye.startsWith(ze)||Ye.trimStart().startsWith(ze.trim()))&&(q.content=Ye)},ke=()=>{if(ne){let Ye=ne.close?.();Ye instanceof Promise&&Ye.catch(()=>{})}ve.delete(q.id),pe.delete(q.id),q.streaming=!1,h(q)};if(!ne){be(N),ke();return}let Ie=dl(Q);if(Ie!==null&&Ie.trim()!==""){be(Ie),ke();return}let Oe=Ye=>{let ze=typeof Ye=="string"?Ye:Ye?.text??null;if(ze!==null&&ze.trim()!=="")return ze;let bt=ne.getExtractedText();return bt!==null&&bt.trim()!==""?bt:N},at;try{at=ne.processChunk(Q)}catch{be(N),ke();return}if(at instanceof Promise){at.then(Ye=>{be(Oe(Ye)),ke()}).catch(()=>{be(N),ke()});return}be(Oe(at)),ke()},ye=null,F=(q,S,N,z)=>{q.rawContent=S,ve.has(q.id)||ve.set(q.id,this.createStreamParser());let Q=ve.get(q.id),ne=S.trim().startsWith("{")||S.trim().startsWith("[");if(ne&&pe.set(q.id,S),Q.__isPlainTextParser===!0){q.content=z!==void 0?S:q.content+N,pe.delete(q.id),ve.delete(q.id),q.rawContent=void 0,h(q);return}let ke=Q.processChunk(S);if(ke instanceof Promise)ke.then(Ie=>{let Oe=typeof Ie=="string"?Ie:Ie?.text??null;Oe!==null&&Oe.trim()!==""?(q.content=Oe,h(q)):!ne&&!S.trim().startsWith("<")&&(q.content=z!==void 0?S:q.content+N,pe.delete(q.id),ve.delete(q.id),q.rawContent=void 0,h(q))}).catch(()=>{q.content=z!==void 0?S:q.content+N,pe.delete(q.id),ve.delete(q.id),q.rawContent=void 0,h(q)});else{let Ie=typeof ke=="string"?ke:ke?.text??null;Ie!==null&&Ie.trim()!==""?(q.content=Ie,h(q)):!ne&&!S.trim().startsWith("<")&&(q.content=z!==void 0?S:q.content+N,pe.delete(q.id),ve.delete(q.id),q.rawContent=void 0,h(q))}},_e=(q,S)=>{let N=S??q.content;if(N==null||N===""){q.streaming=!1,h(q);return}let Q=pe.get(q.id)??He(N);q.rawContent=Q;let ne=ve.get(q.id),be=null,ke=!1;if(ne&&(be=ne.getExtractedText(),be===null&&(be=dl(Q)),be===null)){let Ie=ne.processChunk(Q);Ie instanceof Promise?(ke=!0,Ie.then(Oe=>{let at=typeof Oe=="string"?Oe:Oe?.text??null;at!==null&&(q.content=at,q.streaming=!1,ve.delete(q.id),pe.delete(q.id),h(q))}).catch(()=>{})):be=typeof Ie=="string"?Ie:Ie?.text??null}if(!ke){be!==null&&be.trim()!==""?q.content=be:pe.has(q.id)||(q.content=He(N));let Ie=ve.get(q.id);if(Ie){let Oe=Ie.close?.();Oe instanceof Promise&&Oe.catch(()=>{}),ve.delete(q.id)}pe.delete(q.id),q.streaming=!1,h(q)}},qe=(q,S,N)=>{let z=I.get(q);if(z)return z;let Q={id:`nested-${S}-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...N?{variant:N}:{},...N==="reasoning"?{reasoning:{id:q,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:S}};return I.set(q,Q),h(Q),Q},Dt=[],Ce,De=new Map,we=0,Ae="agent",Ct=!1,Wt=null,mt=null,xn=this.config.iterationDisplay??"separate";for(Ce=()=>{for(let q=0;q<Dt.length;q++){let S=Dt[q];if(!Ct&&Ae!=="flow"&&typeof S.stepType=="string"&&(Ae="flow"),S.type==="reasoning_start"){let N=typeof S.id=="string"?S.id:null,z=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(N&&z){T.set(N,z),qe(N,z,"reasoning");continue}let Q=S.id,ne=B(Q);ne.reasoning=ne.reasoning??{id:Q,status:"streaming",chunks:[]},ne.reasoning.startedAt=ne.reasoning.startedAt??Date.now(),ne.reasoning.completedAt=void 0,ne.reasoning.durationMs=void 0,(S.scope==="loop"||S.scope==="turn")&&(ne.reasoning.scope=S.scope),ne.streaming=!0,ne.reasoning.status="streaming",h(ne)}else if(S.type==="reasoning_delta"){let N=typeof S.id=="string"?S.id:null;if(N&&T.has(N)&&I.has(N)){let ne=I.get(N),be=S.delta;be&&ne.reasoning&&(ne.reasoning.chunks.push(String(be)),h(ne));continue}let z=S.id,Q=B(z);Q.reasoning=Q.reasoning??{id:z,status:"streaming",chunks:[]},Q.reasoning.startedAt=Q.reasoning.startedAt??Date.now(),S.delta&&Q.reasoning.chunks.push(S.delta),Q.reasoning.status="streaming",Q.streaming=!0,h(Q)}else if(S.type==="reasoning_complete"){let N=typeof S.id=="string"?S.id:null;if(N&&T.has(N)&&I.has(N)){let be=I.get(N);if(be.reasoning){let ke=typeof S.text=="string"?S.text:"";ke&&be.reasoning.chunks.length===0&&be.reasoning.chunks.push(ke),be.reasoning.status="complete",be.streaming=!1,h(be)}T.delete(N),I.delete(N);continue}let z=S.id,Q=typeof S.text=="string"?S.text:"";!_.get(z)&&(Q||S.scope==="loop")&&B(z);let ne=_.get(z);if(ne?.reasoning){(S.scope==="loop"||S.scope==="turn")&&(ne.reasoning.scope=S.scope),Q&&ne.reasoning.chunks.length===0&&ne.reasoning.chunks.push(Q),ne.reasoning.status="complete",ne.reasoning.completedAt=Date.now();let be=ne.reasoning.startedAt??Date.now();ne.reasoning.durationMs=Math.max(0,(ne.reasoning.completedAt??Date.now())-be),ne.streaming=!1,h(ne)}}else if(S.type==="tool_start"){v&&(v.streaming=!1,h(v),v=null),typeof S.iteration=="number"&&(we=S.iteration);let N=S.toolCallId,z=S.toolName;if(ge(z)){H.add(N);continue}let Q=ae(N),ne=Q.toolCall??{id:N,status:"pending"};ne.name=z??ne.name,ne.status="running",ne.success=void 0,ne.error=void 0,ne.duration=void 0,S.parameters!==void 0&&(ne.args=S.parameters),ne.startedAt=ne.startedAt??fe(S.startedAt),ne.completedAt=void 0,ne.durationMs=void 0,Q.toolCall=ne,Q.streaming=!0,S.executionId&&(Q.agentMetadata={executionId:S.executionId,iteration:S.iteration}),h(Q)}else if(S.type==="tool_output_delta"){let N=S.toolCallId;if(H.has(N))continue;let z=ae(N),Q=z.toolCall??{id:N,status:"running"};Q.startedAt=Q.startedAt??Date.now();let ne=S.delta;ne&&(Q.chunks=Q.chunks??[],Q.chunks.push(String(ne))),Q.status="running",z.toolCall=Q,z.streaming=!0,S.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:S.executionId,iteration:we}),h(z)}else if(S.type==="tool_complete"){let N=S.toolCallId;if(H.has(N)){H.delete(N);continue}let z=ae(N),Q=z.toolCall??{id:N,status:"running"};Q.status="complete",S.result!==void 0&&(Q.result=S.result),Q.name=S.toolName??Q.name,Q.success=S.success,Q.error=S.error,Q.completedAt=Date.now();let ne=S.executionTime;if(typeof ne=="number")Q.durationMs=ne,Q.duration=ne;else{let be=Q.startedAt??Date.now();Q.durationMs=Math.max(0,(Q.completedAt??Date.now())-be)}z.toolCall=Q,z.streaming=!1,S.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:S.executionId,iteration:S.iteration??we}),h(z)}else if(S.type==="await"&&S.toolName){let N=typeof S.toolCallId=="string"&&S.toolCallId.length>0?S.toolCallId:void 0,z=N??S.toolId??`local-${u()}`,Q=ae(z),ne=S.toolName,be=S.origin==="webmcp"&&!$r(ne)?`webmcp:${ne}`:ne,ke=$r(be),Ie=Q.toolCall??{id:z,status:"pending"};Ie.name=be,Ie.args=S.parameters,Ie.status=ke?"running":"complete",Ie.chunks=Ie.chunks??[],Ie.startedAt=Ie.startedAt??fe(S.awaitedAt),ke?(Ie.completedAt=void 0,Ie.duration=void 0,Ie.durationMs=void 0):Ie.completedAt=Ie.completedAt??Ie.startedAt,Q.toolCall=Ie,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:S.executionId??Q.agentMetadata?.executionId,awaitingLocalTool:!0,...N?{webMcpToolCallId:N}:{}},h(Q)}else if(S.type==="text_start"){let N=typeof S.id=="string"?S.id:null,z=typeof S.parentToolCallId=="string"&&S.parentToolCallId?S.parentToolCallId:null;if(N&&z){T.set(N,z);continue}let Q=v;Q&&(Ae==="flow"?(_e(Q),ye=Q):(Q.streaming=!1,h(Q)),v=null),O=typeof S.id=="string"?S.id:O,D=""}else if(S.type==="text_delta"){let N=typeof S.id=="string"?S.id:null,z=N?T.get(N):void 0;if(N&&z){let be=typeof S.delta=="string"?S.delta:"",ke=(A.get(N)??"")+be;if(A.set(N,ke),ke.trim()==="")continue;let Ie=qe(N,z);Ie.agentMetadata={...Ie.agentMetadata,executionId:S.executionId,parentToolId:z},F(Ie,ke,be,void 0);continue}if(O=typeof S.id=="string"?S.id:O,Ae==="flow"){let be=typeof S.delta=="string"?S.delta:"";if(D+=be,D.trim()==="")continue;let ke=M();ke.agentMetadata={executionId:S.executionId,iteration:we},F(ke,D,be,void 0),x=ke;continue}let Q=typeof S.delta=="string"?S.delta:"";D+=Q;let ne=M();ne.agentMetadata={executionId:S.executionId,iteration:we,turnId:Wt??void 0,agentName:mt?.agentName},F(ne,D,Q,void 0),x=ne}else if(S.type==="text_complete"){let N=typeof S.id=="string"?S.id:null;if(N&&T.has(N)){let Q=I.get(N);Q&&_e(Q),T.delete(N),A.delete(N),I.delete(N);continue}let z=v;z&&(Ae==="flow"?(_e(z),ye=z):((z.content??"")===""&&typeof S.text=="string"&&(z.content=S.text),z.streaming=!1,h(z)),v=null),O=null,D=""}else if(S.type==="step_complete"){if(S.stepType==="tool")continue;if(S.success===!1){let N=S.error||"Step failed";n({type:"error",error:new Error(N)});let z=v;z&&z.streaming&&(z.streaming=!1,h(z)),n({type:"status",status:"idle"});continue}{let N=ye;ye=null;let z=S.stopReason,ne=(S.result&&typeof S.result=="object"?S.result:null)?.response;if(N)z&&(N.stopReason=z),ne!=null?et(N,ne):N.streaming!==!1&&(ve.delete(N.id),pe.delete(N.id),N.streaming=!1,h(N));else{let be=ne!=null&&ne!=="";if(be||z){let ke=M();z&&(ke.stopReason=z),be?_e(ke,ne):(ke.streaming=!1,h(ke))}}continue}}else if(S.type==="execution_start")Ae=S.kind==="flow"?"flow":"agent",Ct=!0,Ae==="agent"&&(mt={executionId:S.executionId,agentId:S.agentId??"virtual",agentName:S.agentName??""});else if(S.type==="turn_start"){let N=typeof S.iteration=="number"?S.iteration:we;if(N!==we){if(xn==="separate"&&N>1){let z=v;z&&(z.streaming=!1,h(z),v=null)}we=N}Wt=typeof S.id=="string"?S.id:null,x=null}else if(S.type==="tool_input_delta"){let N=S.toolCallId;if(N){let z=G.get(N);z?.toolCall&&(z.toolCall.chunks=z.toolCall.chunks??[],z.toolCall.chunks.push(S.delta??""),h(z))}}else if(S.type==="tool_input_complete"){if(H.has(S.toolCallId))continue;let N=ae(S.toolCallId),z=N.toolCall;z.args=S.parameters,z.name=S.toolName??z.name,h(N)}else if(S.type==="turn_complete"){let N=S.stopReason,z=v??x;if(N&&z!==null){let Q=S.id;(!Q||z.agentMetadata?.turnId===Q)&&(z.stopReason=N,h(z))}Wt===S.id&&(Wt=null)}else if(S.type==="media_start"){let N=String(S.id);De.set(N,{mediaType:typeof S.mediaType=="string"?S.mediaType:void 0,toolCallId:S.toolCallId,parts:[]})}else if(S.type==="media_delta"){let N=De.get(String(S.id));N&&typeof S.delta=="string"&&N.parts.push(S.delta)}else if(S.type==="media_complete"){let N=String(S.id),z=De.get(N);De.delete(N);let Q=(typeof S.mediaType=="string"?S.mediaType:void 0)??z?.mediaType??"application/octet-stream",ne=typeof S.data=="string"?S.data:void 0,be=typeof S.url=="string"?S.url:z&&z.parts.length>0?z.parts.join(""):void 0,ke=null;if(ne)ke={type:"media",data:ne,mediaType:Q};else if(be){let Ye=Q.toLowerCase();ke={type:Ye==="image"||Ye.startsWith("image/")?"image-url":"file-url",url:be,mediaType:Q}}let Ie=S.toolCallId??z?.toolCallId,Oe=ke?[ke]:[],at=[];for(let Ye of Oe){if(!Ye||typeof Ye!="object")continue;let ze=Ye,bt=typeof ze.type=="string"?ze.type:void 0,Qt=typeof ze.mediaType=="string"?ze.mediaType.toLowerCase():"",Ot=null,ln="";if(bt==="media"){let Sn=typeof ze.data=="string"?ze.data:void 0;if(!Sn)continue;ln=Qt.length>0?Qt:"application/octet-stream",Ot=`data:${ln};base64,${Sn}`}else if(bt==="image-url"){let Sn=typeof ze.url=="string"?ze.url:void 0;if(!Sn)continue;ln=Qt,Ot=Sn}else if(bt==="file-url"){let Sn=typeof ze.url=="string"?ze.url:void 0;if(!Sn)continue;ln=Qt,Ot=Sn}else continue;if(Ot)if(bt==="image-url"||ln.startsWith("image/"))at.push({type:"image",image:Ot,...ln.includes("/")?{mimeType:ln}:{}});else if(ln.startsWith("audio/"))at.push({type:"audio",audio:Ot,mimeType:ln});else if(ln.startsWith("video/"))at.push({type:"video",video:Ot,mimeType:ln});else{let Sn=ln||"application/octet-stream";at.push({type:"file",data:Ot,mimeType:Sn,filename:AT(Sn)})}}if(at.length>0){let Ye=u(),ze=Ie,Qt={id:`agent-media-${typeof ze=="string"&&ze.length>0?`${ze}-${Ye}`:String(Ye)}`,role:"assistant",content:"",contentParts:at,createdAt:new Date().toISOString(),streaming:!1,sequence:Ye,agentMetadata:{executionId:S.executionId,iteration:we}};h(Qt);let Ot=v;Ot&&(Ot.streaming=!1,h(Ot)),v=null,w.current=null}}else if(S.type==="execution_complete"){let N=v;N&&(S.kind==="flow"&&N.streaming!==!1?_e(N):(N.streaming=!1,h(N)),v=null),O=null,D="",ye=null,n({type:"status",status:"idle",terminal:!0})}else if(S.type==="execution_error"){let N=typeof S.error=="string"?S.error:S.error?.message??"Execution error";n({type:"error",error:new Error(N)})}else if(S.type!=="ping"){if(S.type==="approval_start"){let N=S.approvalId??`approval-${u()}`,z={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:"pending",agentId:mt?.agentId??"virtual",executionId:S.executionId??mt?.executionId??"",toolName:S.toolName??"",toolType:S.toolType,description:S.description??`Execute ${S.toolName??"tool"}`,...typeof S.reason=="string"&&S.reason?{reason:S.reason}:{},parameters:S.parameters}};h(z)}else if(S.type==="approval_complete"){let N=S.approvalId;if(N){let Q={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:S.decision??"approved",agentId:mt?.agentId??"virtual",executionId:S.executionId??mt?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};h(Q)}}else if(S.type==="artifact_start"||S.type==="artifact_delta"||S.type==="artifact_update"||S.type==="artifact_complete"){if(S.type==="artifact_start"){let N=S.artifactType,z=String(S.id),Q=typeof S.title=="string"?S.title:void 0,ne=S.file,be;if(ne&&typeof ne=="object"&&!Array.isArray(ne)&&typeof ne.path=="string"&&typeof ne.mimeType=="string"&&(be={path:ne.path,mimeType:ne.mimeType,...typeof ne.language=="string"?{language:ne.language}:{}}),n({type:"artifact_start",id:z,artifactType:N,title:Q,component:typeof S.component=="string"?S.component:void 0,...be?{file:be}:{}}),V.set(z,{markdown:"",title:Q,file:be}),!Z.has(z)){Z.add(z);let ke=No(this.config.features?.artifacts,{artifactType:N,...be?{file:be}:{}}),Ie=typeof S.component=="string"?S.component:void 0,Oe={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:rl(ke,{artifactId:z,title:Q,artifactType:N,status:"streaming",...be?{file:be}:{},...Ie?{component:Ie}:{}})};R.set(z,Oe),h(Oe)}}else if(S.type==="artifact_delta"){let N=String(S.id),z=typeof S.delta=="string"?S.delta:String(S.delta??"");n({type:"artifact_delta",id:N,artDelta:z});let Q=V.get(N);Q&&(Q.markdown+=z)}else if(S.type==="artifact_update"){let N=S.props&&typeof S.props=="object"&&!Array.isArray(S.props)?S.props:{};n({type:"artifact_update",id:String(S.id),props:N,component:typeof S.component=="string"?S.component:void 0});let z=V.get(String(S.id));z&&(z.props={...z.props??{},...N})}else if(S.type==="artifact_complete"){let N=String(S.id);n({type:"artifact_complete",id:N});let z=R.get(N);if(z){z.streaming=!1;try{let Q=JSON.parse(z.rawContent??"{}");if(Q.props){Q.props.status="complete";let ne=V.get(N);ne?.markdown&&(Q.props.markdown=ne.markdown),ne?.file&&(Q.props.file=ne.file),Q.component==="PersonaArtifactInline"&&ne?.props&&Object.keys(ne.props).length>0&&(Q.props.componentProps=ne.props)}z.rawContent=JSON.stringify(Q)}catch{}V.delete(N),h(z),R.delete(N)}}}else if(S.type==="error"&&S.recoverable===!1&&S.error!=null&&S.error!==""){let N=typeof S.error=="string"?S.error:S.error?.message!=null?String(S.error.message):"Execution error";n({type:"error",error:new Error(N)});let z=v;z&&z.streaming&&(z.streaming=!1,h(z)),n({type:"status",status:"idle"})}}}Dt.length=0};;){let{done:q,value:S}=await s.read();if(q)break;l+=a.decode(S,{stream:!0});let N=l.split(`
|
|
7
7
|
|
|
8
|
-
`);l=
|
|
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 Q=z.split(`
|
|
9
|
+
`),ne="message",be="",ke=null;for(let ze of Q)ze.startsWith("event:")?ne=ze.replace("event:","").trim():ze.startsWith("data:")?be+=ze.replace("data:","").trim():ze.startsWith("id:")&&(ke=ze.slice(3).trim());let Ie=()=>{ke!==null&&ke!==""&&n({type:"cursor",id:ke})};if(!be){Ie();continue}let Oe;try{Oe=JSON.parse(be)}catch(ze){n({type:"error",error:ze instanceof Error?ze:new Error("Failed to parse chat stream payload")});continue}let at=Oe!==null&&typeof Oe=="object"&&!Array.isArray(Oe)?Oe:null,Ye=ne!=="message"?ne:typeof at?.type=="string"?at.type:"message";if(this.onSSEEvent?.(Ye,Oe),this.parseSSEEvent){w.current=v;let ze=await this.handleCustomSSEEvent(Oe,n,w,h,u,k);if(w.current&&w.current!==v&&(v=w.current),ze){Ie();continue}}at&&(Dt.push({...at,type:Ye}),Ce()),Ie()}}Ce()}};function TT(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 sC(e,t){let n="`".repeat(Math.max(3,TT(t)+1));return`${n}${e}
|
|
11
11
|
${t}
|
|
12
|
-
${n}`}var
|
|
12
|
+
${n}`}var PT=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function kT(e){let t=e?.text?.trim()??"";return t?sC(PT(e),t):""}function iC(e){let t=kT(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[io(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
13
13
|
|
|
14
|
-
`)}:{}}function
|
|
14
|
+
`)}:{}}function Ld(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function aC(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 im(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 lC(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 im(e,n.id)?n.id:null}return null}function am(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 ao=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function cC(e){return e instanceof ao}function ji(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 Yr=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):ji(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 Ns=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 gl=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:gR,load:LT}=yt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var lm=LT;function cm(e){if(!e)return"";let t=IT(e);return dC(t!==null?t:e)}function IT(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 dC(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 fC=null;var pm=()=>fC?fC():Promise.resolve().then(()=>(mC(),gC));var{setLoader:AR,load:WT}=yt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var hC=WT;var OT=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function BT(e,t){return OT.some(n=>e[n]!==t[n])}var $o=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function um(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 gm=e=>({isError:!0,content:[{type:"text",text:e}]}),HT=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,mC=e=>Vr(e)||e===jo,Xi=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceSetupPromise=null;this.voiceSetupGeneration=0;this.voiceLevel=0;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Vs(()=>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&&(Vr(n.name)||n.name===jo&&Zr(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 zs(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&&lm().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||pm().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 iC(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceLevel(){return this.voiceProvider?.onLevel?this.voiceLevel:null}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=es.isSupported()?new es({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 pm().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new d(p,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):p});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");let o=++this.voiceSetupGeneration;this.voiceSetupPromise=lm().then(r=>{o===this.voiceSetupGeneration&&this.wireVoiceProvider(r.createVoiceProvider(n))}).catch(r=>{console.error("Failed to setup voice:",r)}).finally(()=>{o===this.voiceSetupGeneration&&(this.voiceSetupPromise=null)})}catch(n){console.error("Failed to setup voice:",n)}}wireVoiceProvider(t){try{this.voiceProvider=t;let o=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(r=>{r.provider!=="runtype"&&r.text&&r.text.trim()&&this.sendMessage(r.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((r,s,a)=>{if(r==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!a});else{let l=this.injectMessage({role:"user",content:s,streaming:!1,voiceProcessing:!a});this.pendingVoiceUserMessageId=l.id}if(a){this.pendingVoiceUserMessageId=null;let l=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=l.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!a,voiceProcessing:!a});else{let l=this.injectMessage({role:"assistant",content:s,streaming:!a,voiceProcessing:!a});this.pendingVoiceAssistantMessageId=l.id}a&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onLevel&&this.voiceProvider.onLevel(r=>{this.voiceLevel=Number.isFinite(r)?Math.max(0,Math.min(1,r)):0}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(r=>{this.config.voiceRecognition?.onMetrics?.(r)}),this.voiceProvider.onError(r=>{console.error("Voice error:",r),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:o,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(r=>{this.voiceStatus=r,this.voiceActive=r==="listening",this.callbacks.onVoiceStatusChanged?.(r)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider&&this.voiceSetupPromise&&await this.voiceSetupPromise,!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceSetupGeneration++,this.voiceSetupPromise=null,this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new qo("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 co("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 qo("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 qo("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new qo("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=hl(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 qo("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 qo("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 qo("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 qo("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=hl(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=fl(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=fl(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(t,n))}enqueueProjectionFinalization(t,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,n,o){if(this.activeConversationId!==t)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===t&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(t,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(t,r,!0);return}if(s instanceof je&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(t,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof je?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,n){let o=this.readPendingProjections();if(!o||o.conversationId!==t)return;let r=new Set(n.map(a=>a.id)),s=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of t.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof je&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,n,o,r,s){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions,interrupt:s?.interrupt},this.handleEvent);return}catch(a){if(!e.isConversationDeleted(a))throw a;let l=await this.recoverFromDeletedConversation(r);if(!l)throw a;this.recordDispatchedProjections([l]),await this.client.dispatch({messages:[l],signal:n.signal,assistantMessageId:o,composerOptions:s?.composerOptions},this.handleEvent)}}async recoverFromDeletedConversation(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!RT(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new zs(this.config,this.historyInternals),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:d,streaming:p=!1,voiceProcessing:u,rawContent:m}=t,h={id:a??(n==="user"?Ui():n==="assistant"?Gr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:d,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:y,rawContent:h}=o,S={id:d??(r==="user"?Ui():r==="assistant"?Gr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...y!==void 0&&{voiceProcessing:y},...h!==void 0&&{rawContent:h}};n.push(S)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:d}=t,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
18
|
+
_Details: ${n.message}_`:o}var gm=e=>({isError:!0,content:[{type:"text",text:e}]}),_T=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,yC=e=>$r(e)||e===Fo,zi=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 gl;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new Ns(()=>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&&($r(n.name)||n.name===Fo&&Gr(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 Ds(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&&lm().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||pm().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 Xb(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=Yr.isSupported()?new Yr({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 pm().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=lm().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 gl,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 $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 ao("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=ul(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,y=this.messages.filter(h=>l.has(h.id)||h.id===m?!0:p!==void 0&&h.createdAt<p);u=ul(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=pl(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=pl(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=Qb(this.config,o),s=BT(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Wn(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 Ds(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"?Bi():n==="assistant"?jr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:d,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:y,rawContent:h}=o,x={id:d??(r==="user"?Bi():r==="assistant"?jr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...y!==void 0&&{voiceProcessing:y},...h!==void 0&&{rawContent:h}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:d}=t,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
19
19
|
|
|
20
20
|
`),a=[s,n].filter(Boolean).join(`
|
|
21
21
|
|
|
22
|
-
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,d=r.contentParts.length>0;if(l){let p=[];s&&p.push(lo(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(d){let p=[];a&&p.push(lo(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=Ui(),a=Gr();this.activeAssistantMessageId=null;let l=n?.contentParts&&Gi(n.contentParts)?Ki:"",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=nC({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=um(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=oC(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=Gr();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=um(r,this.config.errorMessage);if(a){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(u=>u.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,p=d&&typeof d=="object"?d.onDecision:void 0;try{let u;if(p?u=await p({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):u=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let y=await u.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(u=>u.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let u=t.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let y=typeof m[0]?.question=="string"?m[0].question:"";y&&(a={[y]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,d=t.toolCall?.args,p=Array.isArray(d?.questions)?d.questions:[];if(p.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=a??{};p.forEach((m,y)=>{let h=typeof m?.question=="string"?m.question:"";if(!h)return;let C=u[h],S=Array.isArray(C)?C.join(", "):typeof C=="string"?C:"";this.appendMessage({id:`ask-user-q-${l}-${y}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${y}`,role:"user",content:S||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==jo?!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===jo)return{dedupeKey:m,resumeKey:h,output:Pv(),toolMessage:d,startedAt:y,completedAt:Date.now()};let C=this.client.executeWebMcpToolCall(p,d.toolCall?.args,r.signal),S;if(!C)S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{S=await C}catch(x){let P=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));return P||this.callbacks.onError?.(x instanceof Error?x:new Error(String(x))),this.markWebMcpToolComplete(d,gm(P?"Aborted by cancel()":HT(x)),y),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,gm("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:h,output:S,toolMessage:d,startedAt:y,completedAt:Date.now()}},a;if(this.config.webmcp?.execution==="sequential"){a=[];for(let d of n)a.push(await s(d))}else a=await Promise.all(n.map(s));let l=[];try{if(l=a.filter(u=>u!==null),l.length===0)return;let d={};for(let u of l)d[u.resumeKey]=u.output;let p=await this.client.resumeFlow(t,d,{signal:r.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!p.ok){let u=await p.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${p.status}`)}for(let u of l)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt,u.toolMessage.toolCall?.name===jo?{suggestRepliesResolved:!0}:void 0);p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,gm("Aborted by cancel()"),u.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let a=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a))return;this.webMcpInflightKeys.add(a);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(a)}catch(l){this.callbacks.onError?.(l instanceof Error?l:new Error(String(l)))}finally{this.webMcpInflightKeys.delete(a)}return}let s=`${n}:${r}`;if(!(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t)))return this.resolveWebMcpToolCallBatch(n,[t])}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=Uo(this.config.features?.artifacts,t),r=ll(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=Uo(this.config.features?.artifacts,n),s=ll(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=gC().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=>um(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=Gr(),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=cm(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Yi(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=cm(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let u=r.approval,m=n.approval;a.approval={...u,...m,executionId:m.executionId||u.executionId,toolName:m.toolName||u.toolName,description:m.description||u.description,toolType:m.toolType??u.toolType,reason:m.reason??u.reason,parameters:m.parameters??u.parameters}}let l=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(l&&mC(l)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let u=`${d}:${p}`,m=this.webMcpInflightKeys.has(u),y=this.webMcpResolvedKeys.has(u),h=r.toolCall?.name,C=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&h!==void 0&&mC(h)&&r.toolCall?.status==="complete";(m||y||C)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var po=require("lucide");var WT={add:e=>$v(e)},OT=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Bd={allowedTypes:vr,maxFileSize:10*1024*1024,maxFiles:4};function BT(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function _T(e){return e==="application/pdf"?po.FileText:e.startsWith("text/")?po.FileText:e.includes("word")?po.FileText:e.includes("excel")||e.includes("spreadsheet")?po.FileSpreadsheet:e==="application/json"?po.FileCode:po.File}var Ks=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??Bd.allowedTypes,maxFileSize:t.maxFileSize??Bd.maxFileSize,maxFiles:t.maxFiles??Bd.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:WT}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:Bd.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=Uv(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:BT(),file:o,previewUrl:Id(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=OT(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=Id(t.file),o=M("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let u=M("img");u.src=t.previewUrl,u.alt=t.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=M("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=_T(t.file.type),y=Bt(m,20,"var(--persona-muted, #6b7280)",1.5);y&&u.appendChild(y);let h=M("span");h.textContent=jv(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=X("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=M("div","persona-attachment-progress");s.appendChild(M("div","persona-attachment-progress__bar"));let a=X("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=ge("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?a.appendChild(l):a.textContent="\u21BB",a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,a),o.appendChild(r);let d=M("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let p=Bt(po.X,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 fC=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),DT=(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 hC(){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=>{DT(e.attachments,u)||(e.attachments=[...u],p())},setMentionRefs:u=>{fC(e.mentionRefs,u)||(e.mentionRefs=[...u],p())},setSelectedModelId:u=>{e.selectedModelId!==u&&(e.selectedModelId=u,p())},setActiveModeIds:u=>{fC(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},yC=(e,t)=>{let n=M("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function bC(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=yC("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(a,n):e.appendChild(a));let l=r.body??o.parentElement??n,d=(x,P,O,$,T)=>{if(P)return P;s.add(x);let R=yC(O,$);return T.appendChild(R),R},p=d("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=d("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),y=d("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[],C=(x,P)=>x.target===P.target&&x.type===P.type&&x.handler===P.handler,S=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:S,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:(x,P,O,$)=>{x.addEventListener(P,O,$),h.push({target:x,type:P,handler:O,options:$})},removeListener:(x,P,O,$)=>{x.removeEventListener(P,O,$),h=h.filter(T=>!C(T,{target:x,type:P,handler:O}))},destroy:()=>{for(let x of h)x.target.removeEventListener(x.type,x.handler,x.options);h=[]}}}var jt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},ln=1e5,Ji=ln+1;var NT=8,FT=8,mm=10,vC=200,CC=300,wC=0,Dd=e=>Math.max(0,e);function xC(e){e.delayMs!==void 0&&(vC=Dd(e.delayMs)),e.skipDelayMs!==void 0&&(CC=Dd(e.skipDelayMs))}var $T=()=>Date.now()<wC,UT=e=>{wC=e>0?Date.now()+e:0},_d=new WeakMap,hm="data-persona-tooltip-suppressed",jT=e=>typeof e.closest=="function"&&e.closest(`[${hm}]`)!==null;function SC(e){_d.get(e)?.hide()}var AC=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,qT=e=>{let t=e.getRootNode?.();return AC(t)?t:e.ownerDocument.body},fm=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),zT=[...["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 on(e){_d.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:a=NT,viewportPadding:l=FT}=e,d=()=>t.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,y=null,h=null,C,S=!1,x=!1,P=!1,O=()=>(typeof o=="function"?o():o).trim(),$=()=>(typeof r=="function"?r():r??"").trim(),T=()=>Dd(e.delayMs??vC),R=()=>Dd(e.skipDelayMs??CC),A=()=>{C!==void 0&&(p().clearTimeout(C),C=void 0)},N=()=>{A();let he=u!==null;h?.(),h=null,u?.remove(),u=null,m=null,y=null,he&&UT(R())},Y=()=>{if(!u)return;let he=d(),We=p(),Oe=t.getBoundingClientRect(),we=u.getBoundingClientRect(),Qe=he.documentElement.clientWidth||We.innerWidth,Ce=he.documentElement.clientHeight||We.innerHeight,j=Qe-l-we.width,Ne=Oe.left+Oe.width/2-we.width/2,Ue=fm(Ne,l,j),ht=Oe.top-l,xe=Ce-l-Oe.bottom,ke=we.height+a,be=ht>=ke||ht>=xe?"top":"bottom",Ie=be==="top"?Oe.top-a-we.height:Oe.bottom+a,Tt=Ce-l-we.height,Xt=fm(Ie,l,Tt),yt=Oe.left+Oe.width/2,gn=Math.max(mm,we.width-mm),Yn=fm(yt-Ue,mm,gn);u.dataset.placement=be,u.style.left=`${Ue}px`,u.style.top=`${Xt}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${Yn}px`)},ce=()=>{if(P||!s||u||!t.isConnected||jT(t))return;let he=O(),We=qT(t);if(!he||!We)return;let Oe=d(),we=p();u=Oe.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Ji);let Qe=we.getComputedStyle?.(t);if(Qe){for(let ke of zT){let be=Qe.getPropertyValue(ke).trim();be&&u.style.setProperty(ke,be)}Qe.fontFamily&&(u.style.fontFamily=Qe.fontFamily)}m=Oe.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=he,u.appendChild(m);let Ce=$();Ce&&(y=Oe.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=Ce,u.appendChild(y));let j=Oe.createElement("span");j.className="persona-control-tooltip__arrow",u.appendChild(j),We.appendChild(u),Y(),u.dataset.state="open";let Ne=()=>{if(!t.isConnected){N();return}m&&(m.textContent=O()),y&&(y.textContent=$()),Y()};we.addEventListener("scroll",Ne,!0),we.addEventListener("resize",Ne);let Ue=t.getRootNode(),ht=AC(Ue)?Ue:Oe.documentElement,xe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||N()});xe?.observe(ht,{childList:!0,subtree:!0}),h=()=>{we.removeEventListener("scroll",Ne,!0),we.removeEventListener("resize",Ne),xe?.disconnect()}},Q=he=>{if(!(P||u)){if(A(),he||T()<=0||$T()){ce();return}C=p().setTimeout(()=>{C=void 0,ce()},T())}},E=()=>{S||x?Q(x):N()},B=()=>{let he=p();(!he.matchMedia||!he.matchMedia("(hover: none)").matches)&&(S=!0,E())},H=()=>{S=!1,E()},L=()=>{try{x=t.matches(":focus-visible")}catch{x=!0}E()},te=()=>{x=!1,E()},K=()=>{S=!1,x=!1,N()},me=he=>{he.key==="Escape"&&K()};n.addEventListener("mouseenter",B),n.addEventListener("mouseleave",H),t.addEventListener("focus",L),t.addEventListener("blur",te),t.addEventListener("keydown",me),t.addEventListener("click",K);let de={get isOpen(){return u!==null},show:ce,hide:N,reposition:Y,destroy:()=>{P||(P=!0,N(),n.removeEventListener("mouseenter",B),n.removeEventListener("mouseleave",H),t.removeEventListener("focus",L),t.removeEventListener("blur",te),t.removeEventListener("keydown",me),t.removeEventListener("click",K),_d.delete(t))}};return _d.set(t,de),de}var MC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Zi(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];MC(s)&&MC(r)?n[o]=Zi(s,r):n[o]=r}return n}var Vn="min(440px, calc(100vw - 24px))",Nd="440px",ym="How can I help...",VT={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Vn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},at={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:VT,copy:{inputPlaceholder:ym,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 EC(e,t){if(!(!e&&!t))return e?t?Zi(e,t):e:t}function ea(e){return e?{...at,...e,theme:EC(at.theme,e.theme),darkTheme:EC(at.darkTheme,e.darkTheme),launcher:{...at.launcher,...e.launcher,dock:{...at.launcher?.dock,...e.launcher?.dock},clearChat:{...at.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...at.tooltip,...e.tooltip},copy:{...at.copy,...e.copy},sendButton:{...at.sendButton,...e.sendButton},statusIndicator:{...at.statusIndicator,...e.statusIndicator},voiceRecognition:{...at.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=at.features?.artifacts,n=e.features?.artifacts,o=at.features?.scrollToBottom,r=e.features?.scrollToBottom,s=at.features?.scrollBehavior,a=e.features?.scrollBehavior,l=at.features?.streamAnimation,d=e.features?.streamAnimation,p=at.features?.askUserQuestion,u=e.features?.askUserQuestion,m=at.features?.history,y=e.features?.history,h=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},C=o===void 0&&r===void 0?void 0:{...o,...r},S=s===void 0&&a===void 0?void 0:{...s,...a},x=l===void 0&&d===void 0?void 0:{...l,...d},P=p===void 0&&u===void 0?void 0:{...p,...u,styles:{...p?.styles,...u?.styles}},O=m===void 0&&y===void 0?void 0:{...m,...y,copy:{...m?.copy,...y?.copy}};return{...at.features,...e.features,...C!==void 0?{scrollToBottom:C}:{},...S!==void 0?{scrollBehavior:S}:{},...h!==void 0?{artifacts:h}:{},...x!==void 0?{streamAnimation:x}:{},...P!==void 0?{askUserQuestion:P}:{},...O!==void 0?{history:O}:{}}})(),suggestionChips:e.suggestionChips??at.suggestionChips,suggestionChipsConfig:{...at.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...at.layout,...e.layout,header:{...at.layout?.header,...e.layout?.header},messages:{...at.layout?.messages,...e.layout?.messages,avatar:{...at.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...at.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...at.layout?.slots,...e.layout?.slots}},markdown:{...at.markdown,...e.markdown,options:{...at.markdown?.options,...e.markdown?.options}},messageActions:{...at.messageActions,...e.messageActions}}:at}function bm(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 Fd(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function TC(e,t){e.style.maxHeight=`${t*bm(e)}px`,e.style.overflowY="auto"}function vl(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 kC(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function PC(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||!kC(t)}function KT(e){return(e.submitKey??"enter")!=="enter"||kC(e)?"enter":"send"}function $d(e,t){e.setAttribute("enterkeyhint",KT(t))}function Ud(e,t){let n=t?.autocomplete;e.setAttribute("autocomplete",typeof n=="string"&&n?n:"off");let o=(r,s)=>{s===void 0?e.removeAttribute(r):e.setAttribute(r,s)};o("autocapitalize",typeof t?.autocapitalize=="string"?t.autocapitalize:void 0),o("spellcheck",typeof t?.spellcheck=="boolean"?String(t.spellcheck):void 0),o("inputmode",typeof t?.inputmode=="string"&&t.inputmode?t.inputmode:void 0),o("aria-label",typeof t?.ariaLabel=="string"&&t.ariaLabel?t.ariaLabel:void 0)}function vm(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 Kn="persona-composer-control",xo="persona-composer-control--glyph",wm=40,bn=24,jd=(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)}},qd=(e,t)=>{let n=M("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??ym,n.dir="auto",$d(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:vl(n)}),Ud(n,e?.composer?.inputAttributes),n.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",n.rows=1,n.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',n.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let o=Fd(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*bm(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}},YT="[data-persona-glyph-stack]",xm=(e,t,n="send")=>{let o=X("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},zd=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??"")||wm,h=t.backgroundColor,C=t.textColor,S=M("div","persona-send-button-wrapper"),x=X("button",{className:yn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Kn}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!C&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?C||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":C||void 0,backgroundColor:n&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),P=null,O=null,$=null;if(n){let A=parseFloat(t.iconSize??"")||Math.round(y*.5),N=t.iconStrokeWidth??2,Y=C?.trim()||"currentColor";r&&(P=ge(r,A,Y,N)),O=ge(s,A,Y,N),P&&O?($=xm(P,O),x.appendChild($)):P?x.appendChild(P):(x.textContent=o,O=null)}else x.textContent=d;x.setAttribute("aria-label",a),S.appendChild(x),on({anchor:x,trigger:S,text:()=>x.getAttribute("aria-label")??"",enabled:u});let T="send";return{button:x,wrapper:S,setMode:A=>{if(A===T)return;T=A;let N=A==="stop"?l:a;x.setAttribute("aria-label",N),x.setAttribute("data-persona-send-mode",A),n?(x.querySelector(YT)??$)?.setAttribute("data-mode",A):x.textContent=A==="stop"?p:d},glyphStack:$}},ta=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??"")||bn,u=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,y=M("div","persona-send-button-wrapper"),h=X("button",{className:yn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Kn,!d&&xo),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),S=ge(l,p,m||"currentColor",1.5);S?h.appendChild(S):h.textContent="\u{1F3A4}",y.appendChild(h);let x=t.tooltipText??"Start voice recognition",P=t.showTooltip??!1;return on({anchor:h,trigger:y,text:()=>h.getAttribute("aria-label")??x,enabled:P}),{button:h,wrapper:y}},Vd=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=M("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=M("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??vr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=M("div","persona-send-button-wrapper"),a=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Kn} ${xo}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=ge(r,bn,"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 on({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},Kd=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=M("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=M("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},Gd=()=>X("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function QT(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Yd(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:d=2147483e3,onOpen:p,onDismiss:u}=e,m=e.container??QT(t),y=!1,h=null,C=()=>{if(!y)return;let P=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${P.width}px`),a&&(n.style.maxWidth=`${P.width}px`);let O=n.getBoundingClientRect(),$=l?.()??null,T=$!=null?P.top+$:P.top,R=o==="top-start"||o==="top-end"?T-r-O.height:P.bottom+r,N=o==="bottom-end"||o==="top-end"?P.right-O.width:P.left,Y=a?.()??null;if(Y!=null){let ce=Math.max(P.left,P.right-O.width);N=Math.min(Math.max(P.left+Y,P.left),ce)}n.style.top=`${R}px`,n.style.left=`${N}px`},S=()=>{y&&(y=!1,h&&(h(),h=null),n.remove())},x=()=>{if(y)return;y=!0,d!=null&&(n.style.zIndex=String(d)),m.appendChild(n),C();let P=(t.ownerDocument??document).defaultView??window,O=t.ownerDocument??document,$=()=>{if(!t.isConnected){S(),u?.("anchor-removed");return}C()},T=A=>{let N=typeof A.composedPath=="function"?A.composedPath():[];N.includes(n)||N.includes(t)||(S(),u?.("outside"))},R=P.setTimeout(()=>{O.addEventListener("pointerdown",T,!0)},0);P.addEventListener("scroll",$,!0),P.addEventListener("resize",$),h=()=>{P.clearTimeout(R),O.removeEventListener("pointerdown",T,!0),P.removeEventListener("scroll",$,!0),P.removeEventListener("resize",$)},p?.()};return{get isOpen(){return y},open:x,close:S,toggle:()=>y?S():x(),reposition:C,destroy:S}}var XT='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',JT=["--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"],Sm="data-persona-menu-focus",ZT=new Set(["ArrowDown","ArrowUp","Home","End"]);function LC(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(XT)??e}var ek=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function IC(e){let t=e.label,n=!1,o=M("div","persona-send-button-wrapper"),r=X("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Kn} ${xo}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=X("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let L=e.getButtonSize?.()??"";r.style.width=L,r.style.height=L,r.style.minWidth=L,r.style.minHeight=L,r.style.lineHeight="1",r.replaceChildren();let te=ge("plus",bn,"currentColor",1.5);te?r.appendChild(te):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 te=s.getRootNode().activeElement;return te instanceof HTMLElement?te:null},y=()=>{let L=m();for(let te of d){let K=!!L&&LC(te)===L;te.toggleAttribute(Sm,K&&u)}},h=()=>d.filter(L=>L.isConnected||s.contains(L)).map(LC).filter(L=>!ek(L)),C=(L,te)=>{L.forEach((K,me)=>{K.setAttribute("tabindex",me===te?"0":"-1")})},S=L=>{let te=h();if(te.length===0)return;let K=(L%te.length+te.length)%te.length;p=K,C(te,K),te[K].focus(),y()},x=()=>o.ownerDocument??document,P=null,O=null,$=null,T=()=>{P&&(x().removeEventListener("focusin",P,!0),P=null)},R=()=>{O&&(s.removeEventListener("focusin",O),O=null),$&&(s.removeEventListener("pointerdown",$,!0),$=null)},A=null,N=()=>(A||(A=Yd({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),T()}})),A),Y=()=>A?.isOpen===!0,ce=(L=!1)=>{if(Y()){A?.close(),r.setAttribute("aria-expanded","false"),T(),R(),p=-1,u=!1;for(let te of d)te.removeAttribute(Sm);L&&r.focus()}},Q=(L=0,te=!1)=>{if(n||Y())return;u=te,jd(r,s,JT),N().open(),r.setAttribute("aria-expanded","true");let K=h();C(K,-1),S(L<0?K.length-1:L),P=me=>{let de=typeof me.composedPath=="function"?me.composedPath():[];de.includes(s)||de.includes(o)||ce()},x().addEventListener("focusin",P,!0),O=()=>y(),s.addEventListener("focusin",O),$=()=>{u=!1},s.addEventListener("pointerdown",$,!0)},E=L=>{L.preventDefault(),L.stopPropagation(),Y()?ce(!0):Q(0)},B=L=>{if(L.key==="ArrowDown"||L.key==="Enter"||L.key===" "){L.preventDefault(),u=!0,Y()?S(0):Q(0,!0);return}L.key==="ArrowUp"&&(L.preventDefault(),u=!0,Y()?S(-1):Q(-1,!0))},H=L=>{switch(ZT.has(L.key)&&(u=!0),L.key){case"ArrowDown":L.preventDefault(),S(p+1);return;case"ArrowUp":L.preventDefault(),S(p-1);return;case"Home":L.preventDefault(),S(0);return;case"End":L.preventDefault(),S(h().length-1);return;case"Escape":L.preventDefault(),L.stopPropagation(),ce(!0);return;case"Tab":ce(!0);return;default:}};return r.addEventListener("click",E),r.addEventListener("keydown",B),s.addEventListener("keydown",H),{trigger:o,triggerButton:r,panel:s,setItems:L=>{for(let K of d)L.includes(K)||K.removeAttribute(Sm);if(d=[...L],!Y())return;let te=h();C(te,Math.min(p,te.length-1)),y()},isOpen:Y,open:()=>Q(0),close:ce,setLabel:L=>{L!==t&&(t=L,l())},applyButtonSize:a,destroy:()=>{n=!0,T(),R(),r.removeEventListener("click",E),r.removeEventListener("keydown",B),s.removeEventListener("keydown",H),A?.destroy(),A=null,o.remove(),s.remove(),d=[]}}}var zo={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},RC="data-persona-composer-action",Am="data-persona-composer-disable-when-streaming",tk="core:overflow",nk=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function ok(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let o=M("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function Mm(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 HC=(e,t)=>{!e||typeof console>"u"||console.warn(t)},rk=(e,t)=>t.includes(":")?t:`${e}:${t}`;function sk(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){HC(t,`[Persona] composer action "${l.id}" is already contributed by ${WC(d)}; the ${WC(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?rk(p,l.id):l.id,m=l.order??zo.custom;l.placement==="end"&&m>=zo.send&&(HC(t,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${zo.send-1}.`),m=zo.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 WC=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",OC=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,ik=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function ak(e,t){if(!e||e==="always")return!0;let n=ik(t);return e==="when-text"?n:!n}var ts=e=>e.kind==="custom",Em=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,lk=e=>{let t=Em(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},ck='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function dk(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(ck)||o.childNodes.forEach(n)};return n(e),t.trim()}var pk=e=>dk(e).length===0;function BC(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(E,B)=>{let H=E.button;if(!H)return;H.setAttribute("role","menuitem"),H.setAttribute("tabindex","-1"),H.className="persona-composer-overflow-menu__item";for(let K of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])H.style[K]="";H.style.lineHeight="1",B.tooltipText?H.setAttribute("title",B.tooltipText):H.removeAttribute("title"),H.replaceChildren();let L=M("span","persona-composer-overflow-menu__icon");if(B.iconName){let K=ge(B.iconName,16,"currentColor",1.5);K&&L.appendChild(K)}let te=M("span","persona-composer-overflow-menu__label");te.textContent=B.shortLabel??B.label,H.append(L,te)},a=(E,B)=>{let H=E.button;if(!H)return;if(H.setAttribute("aria-label",B.label),B.pressed===void 0?H.removeAttribute("aria-pressed"):H.setAttribute("aria-pressed",B.pressed?"true":"false"),H.toggleAttribute(Am,B.disableWhenStreaming===!0),E.mode==="menu"){E.tooltip?.destroy(),E.tooltip=void 0,s(E,B);return}H.removeAttribute("role"),H.removeAttribute("tabindex"),H.removeAttribute("title");let L=r(),te=!!B.shortLabel;if(H.className=yn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Kn,xo,te&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),H.style.width=L&&!te?L:"",H.style.height=L??"",H.style.minWidth=L&&!te?L:"",H.style.minHeight=L??"",H.style.fontSize=te?"":"18px",H.style.lineHeight="1",H.style.color=B.iconColor??"",H.style.backgroundColor=B.backgroundColor??"",H.replaceChildren(),B.iconName){let K=ge(B.iconName,bn,"currentColor",1.5);K&&H.appendChild(K)}if(te){let K=M("span","persona-composer-action-button__label");K.textContent=B.shortLabel,H.appendChild(K)}else H.firstChild||(H.textContent=B.label);E.tooltip?.destroy(),E.tooltip=on({anchor:H,trigger:E.element,text:()=>B.tooltipText??B.label,enabled:!!B.tooltipText})},l=(E,B)=>{let H=E.action,L=X("button",{attrs:{type:"button"}}),te=L;if(B==="bar"){let de=M("div","persona-send-button-wrapper");de.appendChild(L),te=de}te.setAttribute(RC,E.id);let K={resolved:E,element:te,button:L,owned:!0,managed:!0,busy:!1,visible:!0,mode:B},me=de=>{if(de.preventDefault(),de.stopPropagation(),K.busy||L.disabled)return;let he=K.resolved.action;K.mode==="menu"&&h?.close(!0);let We;try{We=he.onSelect(e.actionContext,de)}catch(Oe){e.reportError(Oe,{actionId:K.resolved.id});return}!We||typeof We.then!="function"||(K.busy=!0,L.setAttribute("aria-busy","true"),We.catch(Oe=>{e.reportError(Oe,{actionId:K.resolved.id})}).finally(()=>{K.busy=!1,L.removeAttribute("aria-busy")}))};return L.addEventListener("click",me),K.detach=()=>L.removeEventListener("click",me),a(K,H),K},d=E=>{let B=E.action,H;try{H=B.render({...e.actionContext,id:E.id,action:B})}catch(L){return e.reportError(L,{actionId:E.id}),null}return H?.element?(H.element.setAttribute(RC,E.id),H.element.toggleAttribute(Am,B.disableWhenStreaming===!0),{resolved:E,element:H.element,owned:!0,managed:!0,destroy:H.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(E,B)=>{if(E.builtIn){let L=E.builtIn.element;return L?{resolved:E,element:L,owned:!1,managed:E.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let H=E.action;return H?ts(H)?d(E):l(E,B):null},u=E=>{if(E.detach?.(),E.tooltip?.destroy(),E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0,E.owned){try{E.destroy?.()}catch(B){e.reportError(B,{actionId:E.resolved.id})}E.element.remove()}},m=(E,B)=>{for(let H=0;H<B.length;H++){let L=B[H];if(!L.managed)continue;let te=null;for(let K=H+1;K<B.length;K++){let me=B[K];if(!me.managed&&me.element.parentElement===E){te=me.element;break}}te?(L.element.parentElement!==E||L.element.nextSibling!==te)&&E.insertBefore(L.element,te):E.lastChild!==L.element&&E.appendChild(L.element)}},y=(E,B)=>{if(E.button){E.button.disabled=B;return}if(!E.owned)return;let H=E.element;H.toggleAttribute("data-disabled",B),H.setAttribute("aria-disabled",B?"true":"false");let L=H instanceof HTMLButtonElement||H instanceof HTMLSelectElement||H instanceof HTMLInputElement||H instanceof HTMLTextAreaElement?H:H.querySelector("button, select, input, textarea");L&&(L.disabled=B)},h=null,C=null,S=null,x=0,P=()=>{let E=e.getOverflow?.();return E?.enabled===!0?E:void 0},O=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=IC({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),$=E=>{C!==E&&(S?.disconnect(),C=E,x=Mm(E),!(typeof ResizeObserver>"u")&&(S=new ResizeObserver(B=>{let L=B[B.length-1]?.contentRect?.width??Mm(E);L!==x&&(x=L,ce())}),S.observe(E)))},T=(E,B)=>{let H=ok(E.collapseAutoActionsBelow,B);if(H===null)return!1;let L=x||Mm(B);return L>0&&L<H},R=(E,B,H)=>{if(!B)return"bar";if(E.resolved.builtIn){let te=nk(E.resolved.id);return te&&B.includeBuiltIns?.includes(te)?"menu":"bar"}let L=E.resolved.presentation;return L==="overflow"||L==="auto"&&H?"menu":"bar"},A=E=>{let B=E.menuSlot;if(!B)return;if(!pk(E.element)){E.menuLabel?.remove(),E.menuLabel=void 0;return}let H=lk(E.element);if(!H){E.menuLabel?.remove(),E.menuLabel=void 0;return}E.menuLabel||(E.menuLabel=M("span","persona-composer-overflow-menu__label")),E.menuLabel.textContent!==H&&(E.menuLabel.textContent=H),E.menuLabel.parentElement!==B&&B.appendChild(E.menuLabel)},N=(E,B)=>{if(E.mode===B)return E;let H=E.resolved.action;if(H&&!ts(H)){u(E),t.delete(E.resolved.id);let L=l(E.resolved,B);return t.set(E.resolved.id,L),L}if(B==="menu"){let L=X("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[hm]:""}});L.appendChild(E.element),SC(Em(E.element)),E.menuSlot=L;let te=K=>{let me=Em(E.element);if(me.disabled)return;let de=K.target===me||me.contains(K.target);h?.close(!0),de||me.click()};L.addEventListener("click",te,!0),E.detachMenuSlot=()=>L.removeEventListener("click",te,!0),E.managed=!0,A(E)}else E.detachMenuSlot?.(),E.detachMenuSlot=void 0,E.menuLabel?.remove(),E.menuLabel=void 0,E.menuSlot?.remove(),E.menuSlot=void 0;return E.mode=B,E},Y=(E,B)=>{let H=B.map(L=>L.menuSlot??L.element);for(H.forEach((L,te)=>{let K=E.children[te];K!==L&&(K?E.insertBefore(L,K):E.appendChild(L))});E.children.length>H.length;)E.lastElementChild?.remove()},ce=()=>{if(o)return;let E=e.getBindings();if(!E)return;let B=e.getState(),H=B.phase==="streaming",L=P();L&&$(E.footer);let te=L?T(L,E.footer):!1,K={start:[],end:[]},me=[];for(let de of n){let he=t.get(de.id);if(!he)continue;let We=de.action,Oe=We?OC(We.visible,B,!0)&&ak(We.visibility,B):!0;if(he.visible!==Oe&&(he.visible=Oe,!Oe&&he.managed&&(he.menuSlot??he.element).remove()),!!Oe){if(he=N(he,R(he,L,te)),We){let we=OC(We.disabled,B,!1)||We.disableWhenStreaming===!0&&H;y(he,we),!ts(We)&&We.pressed!==void 0&&he.button?.setAttribute("aria-pressed",We.pressed?"true":"false")}he.mode==="menu"?(A(he),me.push(he)):K[de.placement].push(he)}}if(me.length>0){let de=O();Y(de.panel,me),de.setItems(me.map(we=>we.menuSlot??we.element)),de.applyButtonSize();let he=Number.isFinite(L?.order)?L?.order:zo.overflow,We=K.start.findIndex(we=>we.resolved.order>he),Oe={resolved:{id:tk,placement:"start",presentation:"bar",order:he,sequence:-1,source:"core"},element:de.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};K.start.splice(We<0?K.start.length:We,0,Oe)}else h&&(h.close(),h.trigger.remove(),h.setItems([]));m(E.actionsStart,K.start),m(E.actionsEnd,K.end)};return{resolve:()=>{if(o)return;let E=sk(e.collect()),B=new Set(E.map(H=>H.id));for(let[H,L]of t)B.has(H)||(u(L),t.delete(H));for(let H of E){let L=t.get(H.id);if(!L){let de=p(H,"bar");de&&t.set(H.id,de);continue}let te=L.resolved.action,K=H.action;if(!!te!=!!K||te&&K&&ts(te)!==ts(K)||te&&K&&ts(te)&&ts(K)&&te.render!==K.render){u(L),t.delete(H.id);let de=p(H,L.mode);de&&t.set(H.id,de);continue}L.resolved=H,H.builtIn?(L.managed=H.builtIn.managed===!0||L.mode==="menu",H.builtIn.element&&L.mode==="bar"&&(L.element=H.builtIn.element)):K&&!ts(K)?a(L,K):K&&L.element.toggleAttribute(Am,K.disableWhenStreaming===!0)}n=E,ce()},sync:ce,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,S?.disconnect(),S=null,C=null;for(let E of t.values())u(E);t.clear(),h?.destroy(),h=null,n=[]}}}}var uk="core:model",gk=700,_C=16,mk=["--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"],DC=()=>{let e=X("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=X("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=X("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),p="",u=()=>{let S=e.getModels(),x=S.map(P=>`${P.id}:${P.label}`).join("|");x!==p&&(p=x,d.replaceChildren(...S.map(P=>{let O=X("option",{attrs:{value:P.id}});return O.textContent=P.label,O}))),d.value=r(S)?.id??""};u(),o=u;let m=()=>{d.value&&e.onSelect(d.value)};d.addEventListener("change",m);let y=S=>S.stopPropagation();d.addEventListener("click",y);let{wrapper:h,chevron:C}=DC();return h.append(d,C),{element:h,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",y)}}},a=()=>{let d=X("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),p=M("span","persona-composer-model-picker-label"),u=M("span","persona-composer-model-picker-suffix");d.append(p,u);let m=X("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),y=new Map,h="",C=null,S=()=>C?.isOpen===!0,x=(B=!1)=>{S()&&(C?.close(),d.setAttribute("aria-expanded","false"),B&&d.focus())},P=B=>{let H=[...y.values()];if(H.length===0)return;let L=(B%H.length+H.length)%H.length;H[L].focus()},O=B=>{if(S())return;C||(C=Yd({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),jd(d,m,mk),C.open(),d.setAttribute("aria-expanded","true");let L=[...y.keys()].indexOf(r(e.getModels())?.id??"");P(B??(L>=0?L:0))},$=B=>{x(!0),e.onSelect(B)},T=B=>{B.preventDefault(),B.stopPropagation();let H=B.currentTarget.getAttribute("data-persona-model-option");H&&$(H)},R=B=>{let H=X("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":B.id}});if(B.icon){let de=ge(B.icon,_C,"currentColor",1.5);if(de){let he=M("span","persona-composer-model-option-icon");he.appendChild(de),H.appendChild(he)}}let L=M("span","persona-composer-model-option-body"),te=M("span","persona-composer-model-option-label");if(te.textContent=B.label,L.appendChild(te),B.description){let de=M("span","persona-composer-model-option-description");de.textContent=B.description,L.appendChild(de)}H.appendChild(L);let K=M("span","persona-composer-model-option-check");K.setAttribute("aria-hidden","true");let me=ge("check",_C,"currentColor",2);return me&&K.appendChild(me),H.appendChild(K),H.addEventListener("click",T),H},A=()=>{let B=e.getModels(),H=B.map(K=>`${K.id}:${K.label}:${K.icon??""}:${K.description??""}`).join("|");if(H!==h){h=H;for(let K of y.values())K.removeEventListener("click",T);y.clear(),m.replaceChildren(...B.map(K=>{let me=R(K);return y.set(K.id,me),me}))}let L=r(B);for(let[K,me]of y)me.setAttribute("aria-selected",String(K===L?.id));p.textContent=L?.label??"";let te=e.getSuffix?.()??"";u.textContent=te,d.setAttribute("aria-label",[t,[L?.label,te].filter(Boolean).join(" ")].filter(Boolean).join(": "))};A(),o=A;let N=B=>{B.preventDefault(),B.stopPropagation(),S()?x(!0):O()},Y=B=>{if(B.key==="ArrowDown"){B.preventDefault(),S()?P(0):O(0);return}B.key==="ArrowUp"&&(B.preventDefault(),S()?P(-1):O(-1))},ce=B=>{let H=[...y.values()],L=H.indexOf(B.target?.closest?.(".persona-composer-model-option"));switch(B.key){case"ArrowDown":B.preventDefault(),P(L+1);return;case"ArrowUp":B.preventDefault(),P(L-1);return;case"Home":B.preventDefault(),P(0);return;case"End":B.preventDefault(),P(H.length-1);return;case"Escape":B.preventDefault(),B.stopPropagation(),x(!0);return;case"Tab":x(!0);return;default:}};d.addEventListener("click",N),d.addEventListener("keydown",Y),m.addEventListener("keydown",ce);let{wrapper:Q,chevron:E}=DC();return Q.append(d,E),{element:Q,destroy:()=>{o===A&&(o=null),d.removeEventListener("click",N),d.removeEventListener("keydown",Y),m.removeEventListener("keydown",ce);for(let B of y.values())B.removeEventListener("click",T);y.clear(),C?.destroy(),C=null,m.remove()}}};return{action:{id:uk,kind:"custom",placement:"end",order:gk,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}var Tm="[data-persona-composer-chip-row]";function Qd(e){e.style.display=e.childElementCount>0?"flex":"none"}function km(e){let t=e.querySelector(Tm);if(t)return t;let n=X("div",{className:"persona-composer-chip-row",attrs:{"data-persona-composer-chip-row":""}});n.style.display="none";let o=e.querySelector("[data-persona-composer-quote], [data-persona-composer-pending]");return o?.parentElement===e?e.insertBefore(n,o):e.appendChild(n),n}var fk=":scope > [data-persona-composer-mode]";function FC(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let u=X("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let C=M("span","persona-mention-chip-icon"),S=ge(p.iconName,12,"currentColor",1.5);S&&C.appendChild(S),u.appendChild(C)}let m=M("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let y=X("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=ge("x",12,"currentColor",2);return h?y.appendChild(h):y.textContent="\xD7",y.addEventListener("click",C=>{C.preventDefault(),C.stopPropagation(),e.onRemove(p.id)}),u.appendChild(y),u},a=()=>Array.from(t.querySelectorAll(fk)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),Qd(t)},m=t.ownerDocument.defaultView,y=typeof m?.getComputedStyle=="function"?m.getComputedStyle(p).animationName:"";if(!y||y==="none"){u();return}p.addEventListener("animationend",u,{once:!0}),p.addEventListener("animationcancel",u,{once:!0})},d=()=>{for(let p of a())p.remove()};return{element:t,render:(p,u)=>{if(o)return;let m=u.filter(S=>p.includes(S.id)),y=m.map(S=>`${S.id}:${S.shortLabel??S.label}`).join("|");if(y===n)return;n=y;let h=new Map;for(let S of a()){let x=S.getAttribute("data-persona-composer-mode");x&&m.some(O=>O.id===x)&&!S.hasAttribute("data-persona-chip-exit")?h.set(x,S):S.hasAttribute("data-persona-chip-exit")||l(S)}let C=t.firstChild;for(let S of m){let x=h.get(S.id);x||(x=s(S),r.has(S.id)||(x.setAttribute("data-persona-chip-enter",""),x.addEventListener("animationend",()=>x?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(S.id),x!==C&&t.insertBefore(x,C),C=x.nextSibling}Qd(t)},destroy:()=>{o=!0,d(),Qd(t)}}}var $C=e=>`core:mode:${e}`;var Pm=e=>Math.min(300+e,499),UC=e=>`core:mode-group:${e}`;function Xd(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function hk(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function jC(e,t){return e?.length?e.filter(n=>!Xd(n.groupId,t)&&!hk(n.groupId,t)):[]}var yk=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function qC(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(yk(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 Jd(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function zC(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function VC(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var bk=16;function KC(e){let t=null;return{action:{id:UC(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=X("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=X("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let y=ge(p.iconName,bk,"currentColor",1.5);y&&u.appendChild(y)}let m=M("span","persona-composer-segmented-label");return m.textContent=p.shortLabel??p.label,u.appendChild(m),u.addEventListener("click",a),u},d=()=>{let p=e.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=e.getModes(),m=u.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(m!==s){s=m;for(let C of r.values())C.removeEventListener("click",a);r.clear();let h=u.map(C=>{let S=l(C);return r.set(C.id,S),S});o.replaceChildren(...h)}let y=e.getActiveIds();for(let[h,C]of r)C.setAttribute("aria-pressed",String(y.includes(h)))};return d(),t=d,{element:o,destroy:()=>{t===d&&(t=null);for(let p of r.values())p.removeEventListener("click",a);r.clear()}}}},repaint:()=>t?.()}}function GC(e){let t=X("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let a=M("span","persona-composer-quote-bar"),l=M("div","persona-composer-quote-content");if(s.sourceLabel){let m=M("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let d=X("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=Hd(s.text),l.appendChild(d);let p=X("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=ge("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 YC(e){let t=X("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=X("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[d]:""}}),m=ge(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=Hd(a.text??"",90);if(l)return l;let d=a.contentParts?.length??0;return d>0?d===1?"1 attachment":`${d} attachments`:(a.mentionRefs?.length??0)>0?a.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:t,render:a=>{if(o||a===n)return;if(n=a,!a){t.replaceChildren(),t.style.display="none";return}let l=M("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let d=X("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 QC(e){let t=X("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=X("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=e.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=M("div","persona-message-edit-actions"),s=(l,d,p,u)=>{let m=X("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 XC(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 JC(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 ZC(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 ew(e){return e.wrapped||e.text.includes(`
|
|
23
|
-
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function
|
|
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??X("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,p=null,u=e.textarea,m=null,y=null,h=null,C=null,S=()=>{if(d)return Promise.resolve(d);if(p)return p;let T=Im().then(R=>(R.setMentionIconRenderer(ge),d=R.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:l,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:$,emit:s}),d)).catch(R=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",R),p===T&&(p=null),null));return p=T,T},x=()=>{uw().then(T=>{let R=T.mountInlineComposer({textarea:e.textarea,renderToken:N=>Cl(N,{render:t.renderMentionToken}),onMentionRemoved:N=>d?.untrackMention(N)});m=R.input,y=R.destroy;let A=u;A.replaceWith(R.element),u=R.element,C={next:R.element,prev:A},h?.(R.element,A),d?d.rebindComposer(R.input):p&&p.then(N=>N?.rebindComposer(R.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};t.display==="inline"&&x();let P=[],O=new Map;for(let T of n){if(!T.showButton)continue;let R=pw({config:{...t,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},onOpen:()=>{S().then(A=>A?.openMenu(T.trigger))}});P.push(R),O.set(T.trigger,R.button)}let $=(T,R,A)=>{let N=O.get(R);N&&(N.setAttribute("aria-expanded",T?"true":"false"),T?N.setAttribute("aria-controls",A):N.removeAttribute("aria-controls"))};return{affordanceButtons:P.map(T=>T.wrapper),contextRow:l,handleInput:T=>{if(d){d.handleInput();return}if(!cw(T))return;let R=u,A=R.selectionStart??0;lw(R.value,A,n)&&S().then(N=>N?.handleInput())},handleKeydown:T=>{if(d?.isMenuOpen())return d.handleKeydown(T);if(T.key==="Backspace"&&d?.hasMentions()&&!C){let R=u,A=R.selectionStart===0&&R.selectionEnd===0;if((R.value.length===0||A)&&d.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async T=>r(T)?(d??await S())?.dispatchInlineCommand(T)??null:null,clear:()=>d?.clear(),prefetch:()=>{Im().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 Zd="16px",ep="transparent",Ak=(()=>{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})(),Hm={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:Ak,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"}},Wm={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"}},Om={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:Vn,maxWidth:Nd,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Zd,canvasBackground:ep},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 vn(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."))?vn(e,o):o}function tp(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=vn(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 Bm(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 fw(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]=fw(s,r):n[o]=r}return n}function Mk(e,t){return t?fw(e,t):e}function wl(e,t={}){let n={palette:Hm,semantic:Wm,components:Om},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:Mk(n.components,e?.components)};if(t.validate!==!1){let r=Bm(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 Rm=e=>e.trim()==="0"?"0px":e,mw="--persona-",Ek=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},Tk=.179,rn=(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[mw+s],r!==void 0)break;r!==void 0&&(e[mw+n]=r)}};function np(e){let t=tp(e),n={};for(let[j,Ne]of Object.entries(t)){let Ue=j.replace(/\./g,"-");n[`--persona-${Ue}`]=Ne.value}rn(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"],rn(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"]]),rn(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"]}`,rn(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"]??Zd,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ep,rn(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"]]),rn(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"],rn(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"],rn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=e.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[j,Ne]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Ue=n[`--persona-components-history-overlay-${j}`];Ue&&(n[`--persona-history-overlay-${Ne}`]=Ue)}for(let[j,Ne]of[["background","bg"],["borderRadius","radius"]]){let Ue=n[`--persona-components-history-menu-${j}`];Ue&&(n[`--persona-history-menu-${Ne}`]=Ue)}let m=e.components?.history?.motion;if(m){let j=ht=>{if(ht===void 0)return;let xe=String(ht).trim();return/^\d+(\.\d+)?$/.test(xe)?`${xe}ms`:xe},Ne=j(m.enterDurationMs);Ne!==void 0&&(n["--persona-history-enter-ms"]=Ne);let Ue=j(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 j of["scrim","shadow"]){let Ne=n[`--persona-components-history-confirm-${j}`];Ne&&(n[`--persona-history-confirm-${j}`]=Ne)}for(let[j,Ne]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-${j}`];Ue&&(n[`--persona-tooltip-${Ne}`]=Ue)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[j,Ne]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Ue=n[`--persona-components-messageActions-${j}`];Ue&&(n[`--persona-message-action-${Ne}`]=Ue)}rn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],C=n["--persona-components-introCard-shadow"],S=(!h||h==="transparent"||h==="none")&&(!C||C==="none"),x=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=S&&x==="1.5rem"?"1.5rem 0":x,rn(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"]]),rn(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let P=n["--persona-components-markdown-heading-h1-fontSize"];P&&(n["--persona-md-h1-size"]=P);let O=n["--persona-components-markdown-heading-h1-fontWeight"];O&&(n["--persona-md-h1-weight"]=O);let $=n["--persona-components-markdown-heading-h2-fontSize"];$&&(n["--persona-md-h2-size"]=$);let T=n["--persona-components-markdown-heading-h2-fontWeight"];T&&(n["--persona-md-h2-weight"]=T);let R=n["--persona-components-markdown-prose-fontFamily"];R&&R!=="inherit"&&(n["--persona-md-prose-font-family"]=R),rn(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"]]),rn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),rn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),rn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),rn(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"],rn(n,[["message-border","components-message-border","border"]]),rn(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let A=e.components,N=A?.iconButton;N&&(N.background&&(n["--persona-icon-btn-bg"]=N.background),N.border&&(n["--persona-icon-btn-border"]=N.border),N.color&&(n["--persona-icon-btn-color"]=N.color),N.padding&&(n["--persona-icon-btn-padding"]=N.padding),N.borderRadius&&(n["--persona-icon-btn-radius"]=N.borderRadius),N.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=N.hoverBackground),N.hoverColor&&(n["--persona-icon-btn-hover-color"]=N.hoverColor),N.activeBackground&&(n["--persona-icon-btn-active-bg"]=N.activeBackground),N.activeBorder&&(n["--persona-icon-btn-active-border"]=N.activeBorder));let Y=A?.labelButton;Y&&(Y.background&&(n["--persona-label-btn-bg"]=Y.background),Y.border&&(n["--persona-label-btn-border"]=Y.border),Y.color&&(n["--persona-label-btn-color"]=Y.color),Y.padding&&(n["--persona-label-btn-padding"]=Y.padding),Y.borderRadius&&(n["--persona-label-btn-radius"]=Y.borderRadius),Y.hoverBackground&&(n["--persona-label-btn-hover-bg"]=Y.hoverBackground),Y.fontSize&&(n["--persona-label-btn-font-size"]=Y.fontSize),Y.gap&&(n["--persona-label-btn-gap"]=Y.gap));let ce=A?.toggleGroup;ce&&(ce.gap&&(n["--persona-toggle-group-gap"]=ce.gap),ce.borderRadius&&(n["--persona-toggle-group-radius"]=ce.borderRadius));let Q=A?.artifact;if(Q?.toolbar){let j=Q.toolbar;j.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=j.iconHoverColor),j.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=j.iconHoverBackground),j.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=j.iconPadding),j.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=j.iconBorderRadius),j.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=j.iconBorder),j.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Rm(j.toggleGroupGap)),j.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=j.toggleBorderRadius),j.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Rm(j.toggleGroupPadding)),j.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=j.toggleGroupBorder),j.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=j.toggleGroupBorderRadius),j.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=vn(e,j.toggleGroupBackground)??j.toggleGroupBackground),j.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=j.copyBackground),j.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=j.copyBorder),j.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=j.copyColor),j.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Rm(j.copyBorderRadius)),j.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=j.copyPadding),j.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=j.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??j.copyMenuBackground),j.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=j.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??j.copyMenuBorder),j.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=j.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??j.copyMenuShadow),j.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=j.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??j.copyMenuBorderRadius),j.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=j.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??j.copyMenuItemHoverBackground),j.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=j.iconBackground),j.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=j.toolbarBorder)}if(Q?.tab){let j=Q.tab;j.background&&(n["--persona-artifact-tab-bg"]=j.background),j.activeBackground&&(n["--persona-artifact-tab-active-bg"]=j.activeBackground),j.activeBorder&&(n["--persona-artifact-tab-active-border"]=j.activeBorder),j.borderRadius&&(n["--persona-artifact-tab-radius"]=j.borderRadius),j.textColor&&(n["--persona-artifact-tab-color"]=j.textColor),j.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=j.hoverBackground),j.listBackground&&(n["--persona-artifact-tab-list-bg"]=j.listBackground),j.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=j.listBorderColor),j.listPadding&&(n["--persona-artifact-tab-list-padding"]=j.listPadding)}if(Q?.pane){let j=Q.pane;if(j.toolbarBackground){let Ne=vn(e,j.toolbarBackground)??j.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Ne}}if(Q?.card){let j=Q.card;j.background&&(n["--persona-artifact-card-bg"]=j.background),j.border&&(n["--persona-artifact-card-border"]=j.border),j.borderRadius&&(n["--persona-artifact-card-radius"]=j.borderRadius),j.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=j.hoverBackground),j.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=j.hoverBorderColor)}if(Q?.inline){let j=Q.inline;j.background&&(n["--persona-artifact-inline-bg"]=vn(e,j.background)??j.background),j.border&&(n["--persona-artifact-inline-border"]=j.border),j.borderRadius&&(n["--persona-artifact-inline-radius"]=j.borderRadius),j.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=vn(e,j.chromeBackground)??j.chromeBackground),j.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=vn(e,j.chromeBorder)??j.chromeBorder),j.titleColor&&(n["--persona-artifact-inline-title-color"]=vn(e,j.titleColor)??j.titleColor),j.mutedColor&&(n["--persona-artifact-inline-muted-color"]=vn(e,j.mutedColor)??j.mutedColor),j.frameHeight&&(n["--persona-artifact-inline-frame-height"]=j.frameHeight)}let E=A?.code;E&&(E.keywordColor&&(n["--persona-code-keyword-color"]=E.keywordColor),E.stringColor&&(n["--persona-code-string-color"]=E.stringColor),E.commentColor&&(n["--persona-code-comment-color"]=E.commentColor),E.numberColor&&(n["--persona-code-number-color"]=E.numberColor),E.tagColor&&(n["--persona-code-tag-color"]=E.tagColor),E.attrColor&&(n["--persona-code-attr-color"]=E.attrColor),E.propertyColor&&(n["--persona-code-property-color"]=E.propertyColor),E.lineNumberColor&&(n["--persona-code-line-number-color"]=E.lineNumberColor),E.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=E.gutterBorderColor),E.background&&(n["--persona-code-bg"]=vn(e,E.background)??E.background));let B=n["--persona-surface"],H=n["--persona-container"],L=n["--persona-palette-colors-gray-100"]??"#f3f4f6",te=n["--persona-palette-colors-gray-200"]??"#e5e7eb",K=n["--persona-palette-colors-gray-300"]??"#d1d5db",me=!H||H===B,de=Ek(B??n["--persona-background"]),he=me&&de!==void 0&&de<Tk,We=he?"rgba(255, 255, 255, 0.08)":L,Oe=he?"rgba(255, 255, 255, 0.12)":te,we=he?"rgba(255, 255, 255, 0.16)":K,Qe=me?We:H,Ce=me?Oe:H;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Qe,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Ce,me&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??we),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Qe,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Qe,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Qe,n}var hw={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 kk={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"}}},Pk={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)"}}}},yw=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},xl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Lk=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":xl()},op=e=>Lk(e),Ik=e=>wl(e),Rk=e=>{let t=Zi(Pk,e??{})??{};return wl({...t,palette:{...t.palette,colors:{...kk.colors,...t.palette?.colors}}},{validate:!1})},ns=e=>{let t=op(e),n=yw(e?.theme),o=yw(e?.darkTheme);return t==="dark"?Rk(Zi(n??{},o??{})):Ik(n)},Hk=e=>np(e),Gs=(e,t)=>{let n=ns(t),o=Hk(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",op(t))},na=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(xl())});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(xl());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())}};var Ar=require("lucide");var os=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var rp="24px",_m=(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},bw=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var vw=null;var Dm=()=>{if(vw!==null)return vw;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},Wk="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",sp=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},ip=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 sp("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(sp("unsupported",e),null):(n==="space"&&(o.key=" "),o)},Ok=e=>Wk.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),Cw=(e,t)=>{let n=ip(e);if(!n)return"";let o=Dm(),r=Ok(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("+")},ap=e=>Cw(e,!1),Al=e=>Cw(e,!0),Bk=(e,t)=>t.key?.toLowerCase()===e.key&&(Dm()?t.metaKey:t.ctrlKey)===e.mod&&!(Dm()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,_k=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},ww=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(Bk(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&_k(a))){s.preventDefault();try{l.run(s)}catch(d){sp(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=ip(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=t.get(l);return d?(sp(`${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)}}};var xw=require("idiomorph"),lp=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;xw.Idiomorph.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 Sw=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Nm={index:-1,draft:""};function Aw(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 Mw(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 Ew(){return new Map}function Tw(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function kw(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Pw(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Lw(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 Iw(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Vo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ys(e,t){return Vo(e)-e.scrollTop<=t}function Rw(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 Hw(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 Ww(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Fm(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 Ow(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"},Dk=["pre","code","a","script","style"],cp=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}),_w=[{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 _w)El.set(e.name,e);var Dw=["wipe","glyph-cycle"],Tl=e=>{El.set(e.name,e)},Nw=e=>{_w.some(t=>t.name===e)||El.delete(e)},Fw=()=>Array.from(El.keys()),kl=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:El.get(e)??null,dp=(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},Nk=(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},Fk=(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},$m=/\s/,$k=(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},Uk=(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($m.test(s[l])){let d=l;for(;d<s.length&&$m.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&&!$m.test(s[p]);)d.appendChild(Nk(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,e)},jk=(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(Fk(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??Dk).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)$k(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=t==="char"?Uk:jk;for(let m of l)u(m,n,p);return r.innerHTML},pp=(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},Ll=(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},Bw=new WeakMap,qk=(e,t)=>{if(!e.styles)return;let n=Bw.get(t);if(n||(n=new Set,Bw.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)},Um=new WeakMap,zk=(e,t)=>{if(!e.onAttach)return;let n=Um.get(t);if(n||(n=new Map,Um.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},$w=e=>{let t=Um.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Il=(e,t)=>{qk(e,t),zk(e,t)};var{setLoader:DW,load:Vk}=wt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var Uw=Vk;function jm(e,t=ln){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 Rl=0,rs=null;function qm(e=document){if(Rl++,Rl===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;rs={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,Rl=Math.max(0,Rl-1),Rl===0&&rs)){let n=e.body,o=e.defaultView??window;n.style.overflow=rs.originalOverflow,n.style.position=rs.originalPosition,n.style.top=rs.originalTop,n.style.width=rs.originalWidth,o.scrollTo(0,rs.scrollY),rs=null}}}var Hl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Et=e=>(e?.launcher?.mountMode??"floating")==="docked",ss=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Hn=e=>{let t=e?.launcher?.dock;return{side:t?.side??Hl.side,width:t?.width??Hl.width,animate:t?.animate??Hl.animate,reveal:t?.reveal??Hl.reveal,maxHeight:t?.maxHeight??Hl.maxHeight}};var qw=require("lucide");var zm=e=>e==="followUp"?"follow-up":e,Vm=(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"}},Kk=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'}},jw=new WeakSet,Gk=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Yk=e=>{Gk()||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"})})},Km=e=>{var $,T,R;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:d,chipsConfig:p,session:u,getTextarea:m,eventTarget:y,submitPrompt:h}=e,C=o==="followUp",S=t.behavior,x=()=>{if(u.isStreaming())return;let A={suggestion:{...t},surface:o,source:r,behavior:S},N=y.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:A,bubbles:!0,composed:!0,cancelable:!0}));if(C&&y.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!N)return;for(let ce of d)if(ce.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let Y=m();if(S==="fill"){Y.value=t.prompt,Y.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),Y.focus();return}if(h){h(t.prompt);return}Y.value="",u.sendMessage(t.prompt)},P=()=>{let A=M("button",`persona-suggestion persona-suggestion--${s}`);if(A.type="button",A.disabled=a,A.dataset.suggestionId=t.id,A.dataset.emphasis=t.emphasis,A.dataset.behavior=S,s==="chip"&&(p?.fontFamily&&(A.style.fontFamily=Kk(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 Y=ge(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);Y&&(Y.classList.add("persona-suggestion__icon"),t.iconColor&&(Y.style.color=t.iconColor),A.appendChild(Y))}let N=M("span","persona-suggestion__copy");if(N.appendChild(X("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&N.appendChild(X("span",{className:"persona-suggestion__description",text:t.description})),A.appendChild(N),s!=="chip"){let Y=Bt(qw.ArrowRight,16,"currentColor",1.8);Y&&(Y.classList.add("persona-suggestion__arrow"),A.appendChild(Y))}return A.addEventListener("click",x),A},O=null;for(let A of d)if(A.renderSuggestion&&(O=A.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:P,select:x}),O))break;return O??(O=P()),($=O.dataset).suggestionId||($.suggestionId=t.id),(T=O.dataset).behavior||(T.behavior=S),(R=O.dataset).emphasis||(R.emphasis=t.emphasis),O instanceof HTMLButtonElement||O.setAttribute("aria-disabled",a?"true":"false"),O},Wl=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,e.scrollWidth-e.clientWidth);if(u<=1){s();return}let m=getComputedStyle(e).direction==="rtl",y=Math.min(u,Math.max(0,Math.abs(e.scrollLeft))),h=4,C=y<=h,S=y>=u-h,x=m?!S:!C,P=m?!C:!S;e.toggleAttribute("data-scroll-left",x),e.toggleAttribute("data-scroll-right",P)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,m,y,h,C,S)=>{e.replaceChildren(),t.length=0,n.length=0;let x=S?.source??"config",P=S?.surface??(x==="config"?"starter":"followUp"),O=P==="followUp",$=S?.variant??"chip",T=S?.behavior??"send",R=S?.overflow??"wrap",A=S?.config??{},N=S?.plugins??[],Y=typeof S?.maxItems=="number"?Math.max(0,Math.floor(S.maxItems)):void 0,ce=O?"followUps":"starters";!jw.has(A)&&A.debug===!0&&$!=="chip"&&A.suggestions?.[ce]?.overflow!==void 0&&(jw.add(A),console.info(`[persona] suggestions.${ce}.overflow applies to the "chip" variant only; the "${$}" variant manages its own stacking.`));let Q=K=>K.map(Vm).filter(me=>me!==null).map(me=>({...me,behavior:me.behavior??T})),E=Q(u??[]);N.forEach(K=>{K.transformSuggestions&&(E=Q(K.transformSuggestions({suggestions:E.map(me=>({...me})),surface:P,source:x,config:A})))});let B=Y===void 0?E:E.slice(0,Y);if(!B.length){e.hidden=!0,o=null,s();return}if(!O&&(h??m.getMessages()).some(me=>me.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=zm(P),e.dataset.variant=$,e.dataset.overflow=R;let H=document.createDocumentFragment(),L=m.isStreaming();B.forEach((K,me)=>{let de=Km({item:K,index:me,surface:P,source:x,variant:$,streaming:L,config:A,plugins:N,chipsConfig:C,session:m,getTextarea:()=>y,eventTarget:e,submitPrompt:S?.submitPrompt});H.appendChild(de),n.push(de),[...de instanceof HTMLButtonElement?[de]:[],...Array.from(de.querySelectorAll("button"))].forEach(We=>{t.includes(We)||(We.disabled=L,t.push(We))})}),e.appendChild(H),a(),l();let te=JSON.stringify({normalized:B,surface:P,variant:$,source:x});te!==o&&(o=te,Yk(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:B.map(K=>({...K})),surface:P,source:x,variant:$},bubbles:!0,composed:!0})),O&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:B.map(K=>K.prompt)},bubbles:!0,composed:!0})))}}};var Gn={"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 Qk="persona-header-control",Xk="persona-header-control--glyph",Jk="persona-header-control--sparse",Zk=20,eP={x:[1.4,1.05]},zw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",tP="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",up=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=eP[t]??[1,1.5],l=!o;e.classList.toggle(Xk,l),e.classList.toggle(Jk,l&&s!==1);let d=parseFloat(o??"")||Zk,p=ge(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)},Qs=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=zw,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:y,borderRadius:h,paddingX:C,paddingY:S,hidden:x,extraClassName:P,attrs:O}=e,$=M("div",a),T=!!(m||y),R=X("button",{className:yn(Qk,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!T&&"persona-border-none",!h&&"persona-rounded-full",P),attrs:{type:"button","aria-label":t,...O},style:{width:l,height:l,minWidth:l,minHeight:l,display:x?"none":void 0,color:p||Cn.actionIconColor,backgroundColor:u,border:T?`${m||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:h,paddingLeft:C,paddingRight:C,paddingTop:S,paddingBottom:S}});return r?up(R,r,{iconSize:d,iconText:s}):s&&(R.textContent=s),$.appendChild(R),on({anchor:R,trigger:$,text:()=>R.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:R,wrapper:$}},oa=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=zw,buttonSize:r,iconSize:s}=t,a=e?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=Qs({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}},ra=(e,t={})=>{let{wrapperClassName:n=tP,buttonSize:o,iconSize:r}=t,a=(e?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=Qs({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 Cn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))",minHeight:"var(--persona-header-min-height, auto)"},Gm={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},nP={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)"},Cr=e=>{let{config:t,showClose:n=!0}=e,o=X("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:Cn.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=X("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=ge(d,R*.6,"currentColor",1);A?p.replaceChildren(A):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let R=M("img");R.src=t.launcher.iconUrl,R.alt="",R.className="persona-rounded-xl persona-object-cover",R.style.height=s,R.style.width=s,p.replaceChildren(R)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let u=M("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=X("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Cn.titleColor,...Gm}}),y=X("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Cn.subtitleColor,...nP}});u.append(m,y),l?o.append(u):o.append(p,u);let h=r.clearChat??{},C=h.enabled??!0,S=h.placement??"inline",x=null,P=null;if(C){let A=ra(t,{wrapperClassName:S==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});x=A.button,P=A.wrapper,S==="top-right"&&(P.style.right="48px"),S==="inline"&&o.appendChild(P)}let O=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":C&&S==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:$,wrapper:T}=oa(t,{showClose:n,wrapperClassName:O});return a!=="top-right"&&o.appendChild(T),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:y,closeButton:$,closeButtonWrapper:T,clearChatButton:x,clearChatButtonWrapper:P}},Xs=(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 Js(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=e,l=M("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(Ji)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let C of t){if(C.dividerBefore){let P=document.createElement("hr");l.appendChild(P)}let S=document.createElement("button");if(S.type="button",S.setAttribute("role","menuitem"),S.setAttribute("data-dropdown-item-id",C.id),C.destructive&&S.setAttribute("data-destructive",""),C.icon){let P=ge(C.icon,16,"currentColor",1.5);P&&S.appendChild(P)}let x=document.createElement("span");x.textContent=C.label,S.appendChild(x),S.addEventListener("click",P=>{P.stopPropagation(),m(),n(C.id)}),l.appendChild(S)}let d=null;function p(){if(!s)return;let C=o.getBoundingClientRect();l.style.top=`${C.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-C.right}px`,l.style.left="auto"):(l.style.left=`${C.left}px`,l.style.right="auto")}function u(){let C=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),C&&a?.(!0),requestAnimationFrame(()=>{let S=x=>{!l.contains(x.target)&&!o.contains(x.target)&&m()};document.addEventListener("click",S,!0),d=()=>document.removeEventListener("click",S,!0)})}function m(){let C=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,C&&a?.(!1)}function y(){l.classList.contains("persona-hidden")?u():m()}function h(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:m,toggle:y,destroy:h}}function Wn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=e,p=M("button",yn(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=ge(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 Ym(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:d}=e,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let u=M("button",p);if(u.type="button",u.setAttribute("aria-label",n),t){let y=ge(t,s??14,"currentColor",2);y&&u.appendChild(y)}let m=M("span");if(m.textContent=n,u.appendChild(m),l&&u.addEventListener("click",l),d)for(let[y,h]of Object.entries(d))u.setAttribute(y,h);return u}function Ol(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=M("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function d(){for(let u of l)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of t){let m;u.icon?m=Wn({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,d(),o(u.id)}}):(m=M("button","persona-icon-btn"+(u.className?" "+u.className:"")),m.type="button",m.setAttribute("aria-label",u.label),m.title=u.label,m.textContent=u.label,m.addEventListener("click",()=>{a=u.id,d(),o(u.id)})),m.setAttribute("aria-pressed",u.id===a?"true":"false"),l.push({id:u.id,btn:m}),s.appendChild(m)}function p(u){a=u,d()}return{element:s,setSelected:p}}function Vw(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:d="bottom-left",portal:p,chevronLabel:u="More options",chevronIconSize:m,className:y,primaryClassName:h,chevronClassName:C}=e,S=M("div","persona-split-btn"+(y?" "+y:"")),x={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},P=r&&n?Wn({...x,icon:n,size:o??14}):Ym({...x,icon:n,iconSize:o??14}),O=Wn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(C?" "+C:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});S.append(P,O);let $=null,T=()=>{if($)return $;let R=(typeof p=="function"?p():p)??void 0;return $=Js({items:s,onSelect:a,anchor:S,position:d,portal:R,onOpenChange:A=>{O.setAttribute("aria-expanded",A?"true":"false")}}),R||S.appendChild($.element),$};return S.isConnected?T():requestAnimationFrame(()=>{$||T()}),O.addEventListener("click",R=>{R.stopPropagation(),T().toggle()}),{element:S,primaryButton:P,chevronButton:O,openMenu:()=>T().show(),closeMenu:()=>$?.hide(),toggleMenu:()=>T().toggle(),destroy:()=>{$?.destroy(),S.remove()}}}function gp(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:d}=e,p=M("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",t);let u=M("span","persona-combo-btn-label");u.textContent=t,p.appendChild(u);let m=ge(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=Js({items:o,onSelect:C=>{p.setAttribute("aria-expanded","false"),r(C)},anchor:p,position:s,portal:a});a||p.appendChild(y.element);let h=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",C=>{if(C.stopPropagation(),h())return;let S=!y.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",S?"false":"true"),y.toggle()}),p.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),p.click())}),{element:p,setLabel:C=>{u.textContent=C,p.setAttribute("aria-label",C)},open:()=>{p.setAttribute("aria-expanded","true"),y.show()},close:()=>{p.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let C=!y.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",C?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),p.remove()}}}var Qm=e=>{let t=Cr({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 oP(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=Qs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?ap(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=Js({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 Xm=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=M("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=Cn.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=gp({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:R=>{let A=Y=>{Y===!1&&T.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:R}}))},N=d.onSelect(R);N instanceof Promise?N.then(A,()=>{}):A(N)},hover:d.hover,className:""});p=T.element,p.style.color=Cn.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=M("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=M("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Cn.titleColor,Object.assign(u.style,Gm),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let R=r.onTitleClick;p.addEventListener("click",A=>{A.target.closest("button")||R()}),p.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),R())})}let T=r?.titleRowHover;T&&(p.style.borderRadius=T.borderRadius??"10px",p.style.padding=T.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=T.background??"",p.style.borderColor=T.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:y,wrapper:h}=oa(t,{showClose:n,wrapperClassName:m});o&&y.addEventListener("click",o);let C=M("div","persona-flex persona-items-center persona-gap-1");d||oP(C,r?.trailingActions,r?.onAction??s);let S=a.clearChat??{},x=null,P=null;if(S.enabled??!0){let T=S.placement??"inline",R=ra(t,{wrapperClassName:T==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});x=R.button,P=R.wrapper,T==="top-right"?P.style.right="48px":C.appendChild(P)}C.appendChild(h),l.appendChild(C);let O=M("div");O.style.display="none";let $=M("span");return $.style.display="none",{header:l,iconHolder:O,headerTitle:u,headerSubtitle:$,closeButton:y,closeButtonWrapper:h,clearChatButton:x,clearChatButtonWrapper:P}},mp={default:Qm,minimal:Xm},Jm=e=>mp[e]??mp.default,sa=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=M("div");l.style.display="none";let d=M("span"),p=M("span"),u=M("button");u.style.display="none";let m=M("div");return m.style.display="none",{header:a,iconHolder:l,headerTitle:d,headerSubtitle:p,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Jm(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 Zs=e=>{let{config:t}=e,n=X("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=Gd(),r=X("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}=qd(t);a();let l=zd(t),d=ta(t),p=Vd(t),u=Kd(t),m=X("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=X("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=X("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),C=X("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&h.append(p.wrapper),d&&C.append(d.wrapper),C.append(l.wrapper),y.append(h,C),r.append(y),r.addEventListener("click",S=>{S.target!==l.button&&S.target!==l.wrapper&&S.target!==d?.button&&S.target!==d?.wrapper&&S.target!==p?.button&&S.target!==p?.wrapper&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,header:m,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:u,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:y,leftActions:h,rightActions:C,setSendButtonMode:l.setMode}};var fp=require("lucide");var Kw=()=>{let e=X("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=M("span","persona-pill-peek__icon"),n=Bt(fp.MessageSquare,16,"currentColor",1.5);n&&t.appendChild(n);let o=M("span","persona-pill-peek__text"),r=M("span","persona-pill-peek__caret"),s=Bt(fp.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},hp=e=>{let{config:t}=e,n=X("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Gd(),r=Kd(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=qd(t,{defaultMaxLines:5});a();let l=zd(t),d=ta(t),p=Vd(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=X("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=X("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let y=X("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&y.append(d.wrapper),y.append(l.wrapper),u.addEventListener("click",S=>{S.target!==l.button&&S.target!==l.wrapper&&S.target!==d?.button&&S.target!==d?.wrapper&&S.target!==p?.button&&S.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,y);let h=X("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 rP=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}},sP=(e,t)=>{if(!e)return null;let n=rP(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},iP=(e,t)=>{let n=M("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},aP=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},ef=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(":"))},tf=320,Jw=320,lP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),cP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),dP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),pP=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),uP=e=>{if(!e||e.length===0)return null;let t=X("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=X("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=M("span","persona-mention-chip-icon"),s=ge(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(X("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},gP=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Cl(o.ref,{readonly:!0,render:t}))}return n},Gw="\uE000",Yw="\uE001",mP=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${Gw}${r}:${y}${Yw}`,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(gP(t,o));return}e.innerHTML=l;let p=new RegExp(`${Gw}${r}:(\\d+)${Yw}`),u=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let y=u.nextNode();y;y=u.nextNode())m.push(y);for(let y of m){let h=y;for(let C=p.exec(h.data);C;C=p.exec(h.data)){let S=t[Number(C[1])],x=h.splitText(C.index);x.data=x.data.slice(C[0].length),S?.kind==="mention"&&x.parentNode?.insertBefore(Cl(S.ref,{readonly:!0,render:o}),x),h=x}}},fP=(e,t,n)=>{if(e.length===0)return null;try{let o=M("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,d)=>{let p=M("img");p.alt=l.alt?.trim()||`Attached image ${d+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${tf}px`,p.style.maxHeight=`${Jw}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}),aP(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}},hP=e=>{if(e.length===0)return null;try{let t=M("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!ef(o.audio))return;let r=M("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${tf}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},yP=e=>{if(e.length===0)return null;try{let t=M("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!ef(o.video))return;let r=M("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${tf}px`,r.style.maxHeight=`${Jw}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}},bP=e=>{if(e.length===0)return null;try{let t=M("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!ef(o.data))return;let r=M("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ei=()=>{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},nf=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:ei};if(t){let r=t(o);if(r!==null)return r}return ei()},vP=(e,t)=>{let n=M("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=M("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Qw=(e,t,n="div")=>{let o=M(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Bl=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},Xw={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"}},CP=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=Xw[n??"bubble"]??Xw.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)`)},yp="custom:",wP=e=>`${yp}${e}`,Zw=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),of=(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=Zw(t,e.role);if(!r&&!s&&!a&&!l&&!d&&!p&&!u&&m.length===0){let $=M("div");return $.style.display="none",$.id=`actions-${e.id}`,$.setAttribute("data-actions-for",e.id),$}let y=t.visibility??"hover",h=t.align??"right",C=t.layout??"pill-inside",S={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],x={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[C],P=M("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${S} ${x} ${y==="hover"?"persona-message-actions-hover":""}`);P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id);let O=($,T,R)=>{let A=Wn({icon:$,label:T,size:14,className:"persona-message-action-btn",chromeless:!0});return A.setAttribute("data-action",R),A};r&&P.appendChild(O("copy","Copy message","copy")),l&&P.appendChild(O("volume-2","Read aloud","read-aloud")),s&&P.appendChild(O("thumbs-up","Upvote","upvote")),a&&P.appendChild(O("thumbs-down","Downvote","downvote")),d&&P.appendChild(O("refresh-cw","Regenerate response","regenerate")),p&&P.appendChild(O("pencil","Edit message","edit")),u&&P.appendChild(O("quote","Quote message","quote"));for(let $ of m)P.appendChild(O($.iconName??"ellipsis",$.label,wP($.id)));return P},ia=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",d=a.avatar,p=a.timestamp,u=d?.show??!1,m=p?.show??!1,y=d?.position??"left",h=p?.position??"below",C=Bl(e.role,l),S=M("div",C.join(" "));S.id=`bubble-${e.id}`,S.setAttribute("data-message-id",e.id),S.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let x=s?.widgetConfig?.theme?.components?.message;CP(S,e.role,l,e.role==="user"?x?.user:x?.assistant),l==="flat"?(S.style.backgroundColor="transparent",S.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(S.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",S.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(S.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",S.style.color="var(--persona-message-assistant-text, var(--persona-text))");let P=lP(e),O=e.content?.trim()??"",T=P.length>0&&O===Ki,R=cp(s?.widgetConfig?.features?.streamAnimation),A=s?.widgetConfig?.features?.streamAnimation?.plugins,N=e.role==="assistant"&&R.type!=="none"?kl(R.type,A):null,Y=e.role==="assistant"&&N?.isAnimating?.(e)===!0,ce=e.role==="assistant"&&N!==null&&(!!e.streaming||Y);ce&&N?.bubbleClass&&S.classList.add(N.bubbleClass);let Q=document.createElement("div");Q.classList.add("persona-message-content"),e.streaming&&Q.classList.add("persona-content-streaming"),ce&&N&&(N.containerClass&&Q.classList.add(N.containerClass),Q.style.setProperty("--persona-stream-step",`${R.speed}ms`),Q.style.setProperty("--persona-stream-duration",`${R.duration}ms`));let E=ce?dp(e.content??"",R.buffer,N,e,!!e.streaming):e.content??"",B=()=>{let Ce=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent});return ce&&N?.wrap==="char"?Pl(Ce,"char",e.id,{skipTags:N.skipTags}):ce&&N?.wrap==="word"?Pl(Ce,"word",e.id,{skipTags:N.skipTags}):Ce},H=null;if(T?(H=document.createElement("div"),H.innerHTML=B(),H.style.display="none",Q.appendChild(H)):e.contentSegments?.length?mP(Q,e.contentSegments,Ce=>t({text:Ce,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):Q.innerHTML=B(),ce&&N?.useCaret&&!T&&O){let Ce=pp(),j=Q.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ne=j[j.length-1];if(Ne?.parentNode)Ne.parentNode.insertBefore(Ce,Ne.nextSibling);else{let Ue=Q.lastElementChild;Ue?Ue.appendChild(Ce):Q.appendChild(Ce)}}if(m&&h==="inline"&&e.createdAt){let Ce=Qw(e,p,"span");Ce.classList.add("persona-timestamp-inline");let j=Q.lastElementChild;j?j.appendChild(Ce):Q.appendChild(Ce)}if(P.length>0){let Ce=fP(P,!T&&!!O,()=>{T&&H&&(H.style.display="")});Ce?S.appendChild(Ce):T&&H&&(H.style.display="")}let L=cP(e);if(L.length>0){let Ce=hP(L);Ce&&S.appendChild(Ce)}let te=dP(e);if(te.length>0){let Ce=yP(te);Ce&&S.appendChild(Ce)}let K=pP(e);if(K.length>0){let Ce=bP(K);Ce&&S.appendChild(Ce)}let me=e.contentSegments?.length?null:uP(e.contextMentions);if(me&&S.appendChild(me),S.appendChild(Q),m&&h==="below"&&e.createdAt){let Ce=Qw(e,p);Ce.classList.add("persona-mt-1"),S.appendChild(Ce)}let de=e.role==="assistant"?sP(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Ce=!!(E&&E.trim()),j=R.placeholder==="skeleton",Ne=j&&R.buffer==="line"&&Ce;if(Ce)Ne&&S.appendChild(Ll());else if(j)S.appendChild(Ll());else{let Ue=nf("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);Ue&&S.appendChild(Ue)}}de&&e.stopReason&&!e.streaming&&(O||(Q.style.display="none"),S.appendChild(iP(e.stopReason,de)));let he=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1,We=s?.actionEligibility,Oe=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&We?.canEdit===!0||o?.showQuote===!0&&We?.canQuote===!0||Zw(o,"user").length>0);if((he||Oe)&&o){let Ce=of(e,Oe?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,We);S.appendChild(Ce)}if(!u||e.role==="system")return S;let we=M("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Qe=vP(d,e.role);return y==="right"||y==="left"&&e.role==="user"?we.append(S,Qe):we.append(Qe,S),we},ex=(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}):ia(e,t,n,o,r,s)};var xP=40,SP=(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=ge(t.name,xP);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(X("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(X("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},tx=(e,t,n={})=>{let o=X("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=M("p","persona-welcome-kicker");r.hidden=!0;let s=M("h2","persona-welcome-title"),a=M("p","persona-welcome-subtitle"),l=X("div",{className:"persona-welcome-head-text"},r,s),d=X("div",{className:"persona-welcome-title-row"},o,l);return{host:X("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}},aa=(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)},vp=(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==="",SP(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")},AP="data-persona-welcome-plugin",nx="data-persona-welcome-overlay",bp="persona-welcome-overlay-active",rf=new WeakMap,sf=(e,t,n)=>{n.setAttribute(AP,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(nx,""),e.classList.contains(bp)||(rf.set(e,e.scrollTop),e.classList.add(bp),e.scrollTop=0)},af=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(nx),e.classList.contains(bp)&&(e.classList.remove(bp),e.scrollTop=rf.get(e)??e.scrollTop,rf.delete(e))},ox=()=>{let e=X("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Cp=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=X("div",{className:Bl("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(X("div",{className:"persona-flex"},r)),e.hidden=!1},rx=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,sx=(e,t)=>{if(rx()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,a=0;if(o){let C=getComputedStyle(o);r=parseFloat(C.rowGap)||0;let S=e.previousElementSibling,x=e.nextElementSibling,O=o.getBoundingClientRect().top+(parseFloat(C.borderTopWidth)||0)+(parseFloat(C.paddingTop)||0)-o.scrollTop;s=Math.max(0,S?n.top-S.getBoundingClientRect().bottom-r:n.top-O),a=Math.max(0,x?x.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let d=getComputedStyle(e),p=parseFloat(d.paddingTop)||0,u=parseFloat(d.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${u}px`,marginTop:`${s}px`,marginBottom:`${a}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),y=!1,h=()=>{y||(y=!0,e.style.overflow=l,t(m))};return m.finished.then(h).catch(h),m},ix=(e,t,n)=>{if(t<=1||rx()||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 MP="Hello \u{1F44B}",EP="I can answer questions and help you get things done here.",ax=new WeakSet,wn=(e,t)=>!!e&&e[t]!==void 0,TP=(e,t)=>{!e||e.debug!==!0||!t.length||ax.has(e)||(ax.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},So=e=>{let t=e?.welcome,n=e?.copy,o=wn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":wn(t,"dismiss")?t.dismiss:"never",s=[];wn(t,"title")&&wn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),wn(t,"subtitle")&&wn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),wn(t,"variant")&&wn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&wn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&wn(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=Sl(t?.anchorComposerTop)!==null;return wn(t,"anchorComposerTop")&&!l&&s.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),a!=="center"&&(wn(t,"anchorComposerTop")||wn(t,"composerGap"))&&s.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),TP(e,s),{title:wn(t,"title")?t.title:n?.welcomeTitle??MP,kicker:t?.kicker??"",subtitle:wn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??EP,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()||rp}},lx=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 cx="16px",cf="10px",df="14px",dx=e=>{let t=e?.launcher?.enabled??!0,n=Et(e);if(ss(e)){let u=e?.launcher?.composerBar??{},m=M("div","persona-widget-wrapper persona-fixed persona-transition");m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=u.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??ln);let y=M("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",m.appendChild(y);let h=M("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=u.expandedSize??"anchored",h.style.zIndex=String(e?.launcher?.zIndex??ln),{wrapper:m,panel:y,pillRoot:h}}if(n){let u=M("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),m=M("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return u.appendChild(m),{wrapper:u,panel:m}}if(!t){let u=M("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),m=M("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=e?.launcher?.width??"100%";return u.style.width=y,m.style.width="100%",u.appendChild(m),{wrapper:u,panel:m}}let r=e?.launcher??{},s=r.position&&Gn[r.position]?Gn[r.position]:Gn["bottom-right"],a=M("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??ln);let l=M("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=e?.launcher?.width??e?.launcherWidth??Vn;return l.style.width=p,l.style.maxWidth=p,a.appendChild(l),{wrapper:a,panel:l}},pf=e=>{let t=X("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":zm(e)}});return t.hidden=!0,t},px=(e,t)=>{let n=pf("starter"),o=tx(e,n,{flatShadow:Et(e)}),r=So(e);vp(o,r),aa(t,o.host,is(r,e?.initialMessages));let s=ox();return Cp(s,r.message,e),{welcome:o,greetingHost:s}},kP=(e,t)=>{let n=M("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=oa(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:cx,iconSize:cf});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let N=ra(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:cx,iconSize:df});a=N.button,l=N.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=X("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=X("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}=px(e,p),{host:y,title:h,subtitle:C}=u,S=u.starterSuggestions,x=M("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),P=pf("followUp"),O=os(e,!0);O&&(x.style.maxWidth=O,x.style.marginLeft="auto",x.style.marginRight="auto",x.style.width="100%"),p.append(y,m,x,P);let $=X("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=hp({config:e}),{root:R,textNode:A}=Kw();return n.append(d,r,p,$),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:x,starterSuggestions:S,transcriptSuggestions:P,composerOverlay:$,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:y,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:h,introSubtitle:C,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:M("span"),headerTitle:M("span"),headerSubtitle:M("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:R,peekTextNode:A}},ux=(e,t=!0)=>{if(ss(e))return kP(e,t);let n=X("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?sa(e,o,{showClose:t}):Cr({config:e,showClose:t}),a=X("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}=px(e,a),{host:p,title:u,subtitle:m}=l,y=l.starterSuggestions,h=M("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),C=pf("followUp"),S=os(e,!1);S&&(h.style.maxWidth=S,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),a.append(p,d,h,C);let x=Zs({config:e}),P=e?.layout?.showFooter!==!1;r?Xs(n,s,e):(s.header.style.display="none",Xs(n,s,e)),n.append(a);let O=X("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return P||(x.footer.style.display="none"),n.append(x.footer),n.append(O),{container:n,body:a,messagesWrapper:h,starterSuggestions:y,transcriptSuggestions:C,composerOverlay:O,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:d,introKicker:l.kicker,introTitle:u,introSubtitle:m,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions,setSendButtonMode:x.setSendButtonMode}};var uf=(e,t)=>{let n=M("button");n.type="button",n.innerHTML=`
|
|
22
|
+
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,d=r.contentParts.length>0;if(l){let p=[];s&&p.push(io(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(d){let p=[];a&&p.push(io(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=Bi(),a=jr();this.activeAssistantMessageId=null;let l=n?.contentParts&&Ui(n.contentParts)?$i:"",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=iC({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=um(m,this.config.errorMessage);if(h){let v={id:a,role:"assistant",createdAt:new Date().toISOString(),content:h,sequence:this.nextSequence()};this.appendMessage(v)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,y||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(t,n){let o=aC(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=jr();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=um(r,this.config.errorMessage);if(a){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(u=>u.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,p=d&&typeof d=="object"?d.onDecision:void 0;try{let u;if(p?u=await p({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):u=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let y=await u.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(u=>u.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let u=t.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let y=typeof m[0]?.question=="string"?m[0].question:"";y&&(a={[y]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,d=t.toolCall?.args,p=Array.isArray(d?.questions)?d.questions:[];if(p.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=a??{};p.forEach((m,y)=>{let h=typeof m?.question=="string"?m.question:"";if(!h)return;let v=u[h],x=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${y}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${y}`,role:"user",content:x||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Fo?!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===Fo)return{dedupeKey:m,resumeKey:h,output:Hv(),toolMessage:d,startedAt:y,completedAt:Date.now()};let v=this.client.executeWebMcpToolCall(p,d.toolCall?.args,r.signal),x;if(!v)x={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{x=await v}catch(w){let k=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));return k||this.callbacks.onError?.(w instanceof Error?w:new Error(String(w))),this.markWebMcpToolComplete(d,gm(k?"Aborted by cancel()":_T(w)),y),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,gm("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:h,output:x,toolMessage:d,startedAt:y,completedAt:Date.now()}},a;if(this.config.webmcp?.execution==="sequential"){a=[];for(let d of n)a.push(await s(d))}else a=await Promise.all(n.map(s));let l=[];try{if(l=a.filter(u=>u!==null),l.length===0)return;let d={};for(let u of l)d[u.resumeKey]=u.output;let p=await this.client.resumeFlow(t,d,{signal:r.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!p.ok){let u=await p.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${p.status}`)}for(let u of l)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt,u.toolMessage.toolCall?.name===Fo?{suggestRepliesResolved:!0}:void 0);p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,gm("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=No(this.config.features?.artifacts,t),r=rl(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=No(this.config.features?.artifacts,n),s=rl(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=hC().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=>um(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=jr(),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=cm(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ji(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=cm(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let u=r.approval,m=n.approval;a.approval={...u,...m,executionId:m.executionId||u.executionId,toolName:m.toolName||u.toolName,description:m.description||u.description,toolType:m.toolType??u.toolType,reason:m.reason??u.reason,parameters:m.parameters??u.parameters}}let l=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(l&&yC(l)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let u=`${d}:${p}`,m=this.webMcpInflightKeys.has(u),y=this.webMcpResolvedKeys.has(u),h=r.toolCall?.name,v=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&h!==void 0&&yC(h)&&r.toolCall?.status==="complete";(m||y||v)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var lo=require("lucide");var DT={add:e=>zv(e)},NT=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Hd={allowedTypes:fr,maxFileSize:10*1024*1024,maxFiles:4};function FT(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $T(e){return e==="application/pdf"?lo.FileText:e.startsWith("text/")?lo.FileText:e.includes("word")?lo.FileText:e.includes("excel")||e.includes("spreadsheet")?lo.FileSpreadsheet:e==="application/json"?lo.FileCode:lo.File}var Fs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??Hd.allowedTypes,maxFileSize:t.maxFileSize??Hd.maxFileSize,maxFiles:t.maxFiles??Hd.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:DT}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:Hd.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=Vv(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:FT(),file:o,previewUrl:Pd(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=NT(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=Pd(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=$T(t.file.type),y=Ht(m,20,"var(--persona-muted, #6b7280)",1.5);y&&u.appendChild(y);let h=E("span");h.textContent=Kv(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=Y("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=Y("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=de("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=Ht(lo.X,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 bC=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),UT=(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 vC(){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=>{UT(e.attachments,u)||(e.attachments=[...u],p())},setMentionRefs:u=>{bC(e.mentionRefs,u)||(e.mentionRefs=[...u],p())},setSelectedModelId:u=>{e.selectedModelId!==u&&(e.selectedModelId=u,p())},setActiveModeIds:u=>{bC(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 Bn=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},CC=(e,t)=>{let n=E("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function wC(e,t={}){let n=Bn(e,"[data-persona-composer-form]"),o=Bn(e,"[data-persona-composer-input]");if(!n||!o){let k=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||o))throw new Error(k);return typeof console<"u"&&console.warn(k),null}let r={header:Bn(e,"[data-persona-composer-header]"),body:Bn(e,"[data-persona-composer-body]"),actionsStart:Bn(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Bn(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Bn(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Bn(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Bn(e,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=CC("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(a,n):e.appendChild(a));let l=r.body??o.parentElement??n,d=(w,k,O,D,T)=>{if(k)return k;s.add(w);let I=CC(O,D);return T.appendChild(I),I},p=d("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=d("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),y=d("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),h=[],v=(w,k)=>w.target===k.target&&w.type===k.type&&w.handler===k.handler,x=Bn(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:a,body:l,actionsStart:p,actionsEnd:u,suggestions:m,status:y,attachmentInput:x,attachmentPreviews:Bn(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Bn(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Bn(e,"[data-persona-composer-submit]")??void 0,micButton:Bn(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(w,k,O,D)=>{w.addEventListener(k,O,D),h.push({target:w,type:k,handler:O,options:D})},removeListener:(w,k,O,D)=>{w.removeEventListener(k,O,D),h=h.filter(T=>!v(T,{target:w,type:k,handler:O}))},destroy:()=>{for(let w of h)w.target.removeEventListener(w.type,w.handler,w.options);h=[]}}}var Vt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},an=1e5,Vi=an+1;var jT=8,qT=8,mm=10,xC=200,SC=300,AC=0,Od=e=>Math.max(0,e);function MC(e){e.delayMs!==void 0&&(xC=Od(e.delayMs)),e.skipDelayMs!==void 0&&(SC=Od(e.skipDelayMs))}var zT=()=>Date.now()<AC,VT=e=>{AC=e>0?Date.now()+e:0},Wd=new WeakMap,hm="data-persona-tooltip-suppressed",KT=e=>typeof e.closest=="function"&&e.closest(`[${hm}]`)!==null;function EC(e){Wd.get(e)?.hide()}var TC=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,GT=e=>{let t=e.getRootNode?.();return TC(t)?t:e.ownerDocument.body},fm=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),YT=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function tn(e){Wd.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:a=jT,viewportPadding:l=qT}=e,d=()=>t.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,y=null,h=null,v,x=!1,w=!1,k=!1,O=()=>(typeof o=="function"?o():o).trim(),D=()=>(typeof r=="function"?r():r??"").trim(),T=()=>Od(e.delayMs??xC),I=()=>Od(e.skipDelayMs??SC),A=()=>{v!==void 0&&(p().clearTimeout(v),v=void 0)},_=()=>{A();let fe=u!==null;h?.(),h=null,u?.remove(),u=null,m=null,y=null,fe&&VT(I())},G=()=>{if(!u)return;let fe=d(),He=p(),ve=t.getBoundingClientRect(),pe=u.getBoundingClientRect(),et=fe.documentElement.clientWidth||He.innerWidth,ye=fe.documentElement.clientHeight||He.innerHeight,F=et-l-pe.width,_e=ve.left+ve.width/2-pe.width/2,qe=fm(_e,l,F),Dt=ve.top-l,Ce=ye-l-ve.bottom,De=pe.height+a,we=Dt>=De||Dt>=Ce?"top":"bottom",Ae=we==="top"?ve.top-a-pe.height:ve.bottom+a,Ct=ye-l-pe.height,Wt=fm(Ae,l,Ct),mt=ve.left+ve.width/2,xn=Math.max(mm,pe.width-mm),q=fm(mt-qe,mm,xn);u.dataset.placement=we,u.style.left=`${qe}px`,u.style.top=`${Wt}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${q}px`)},le=()=>{if(k||!s||u||!t.isConnected||KT(t))return;let fe=O(),He=GT(t);if(!fe||!He)return;let ve=d(),pe=p();u=ve.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Vi);let et=pe.getComputedStyle?.(t);if(et){for(let De of YT){let we=et.getPropertyValue(De).trim();we&&u.style.setProperty(De,we)}et.fontFamily&&(u.style.fontFamily=et.fontFamily)}m=ve.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=fe,u.appendChild(m);let ye=D();ye&&(y=ve.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=ye,u.appendChild(y));let F=ve.createElement("span");F.className="persona-control-tooltip__arrow",u.appendChild(F),He.appendChild(u),G(),u.dataset.state="open";let _e=()=>{if(!t.isConnected){_();return}m&&(m.textContent=O()),y&&(y.textContent=D()),G()};pe.addEventListener("scroll",_e,!0),pe.addEventListener("resize",_e);let qe=t.getRootNode(),Dt=TC(qe)?qe:ve.documentElement,Ce=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||_()});Ce?.observe(Dt,{childList:!0,subtree:!0}),h=()=>{pe.removeEventListener("scroll",_e,!0),pe.removeEventListener("resize",_e),Ce?.disconnect()}},ee=fe=>{if(!(k||u)){if(A(),fe||T()<=0||zT()){le();return}v=p().setTimeout(()=>{v=void 0,le()},T())}},M=()=>{x||w?ee(w):_()},B=()=>{let fe=p();(!fe.matchMedia||!fe.matchMedia("(hover: none)").matches)&&(x=!0,M())},H=()=>{x=!1,M()},R=()=>{try{w=t.matches(":focus-visible")}catch{w=!0}M()},Z=()=>{w=!1,M()},V=()=>{x=!1,w=!1,_()},ge=fe=>{fe.key==="Escape"&&V()};n.addEventListener("mouseenter",B),n.addEventListener("mouseleave",H),t.addEventListener("focus",R),t.addEventListener("blur",Z),t.addEventListener("keydown",ge),t.addEventListener("click",V);let ae={get isOpen(){return u!==null},show:le,hide:_,reposition:G,destroy:()=>{k||(k=!0,_(),n.removeEventListener("mouseenter",B),n.removeEventListener("mouseleave",H),t.removeEventListener("focus",R),t.removeEventListener("blur",Z),t.removeEventListener("keydown",ge),t.removeEventListener("click",V),Wd.delete(t))}};return Wd.set(t,ae),ae}var PC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ki(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];PC(s)&&PC(r)?n[o]=Ki(s,r):n[o]=r}return n}var Gn="min(440px, calc(100vw - 24px))",Bd="440px",ym="How can I help...",QT={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Gn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",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)"},it={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:QT,copy:{inputPlaceholder:ym,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 kC(e,t){if(!(!e&&!t))return e?t?Ki(e,t):e:t}function Gi(e){return e?{...it,...e,theme:kC(it.theme,e.theme),darkTheme:kC(it.darkTheme,e.darkTheme),launcher:{...it.launcher,...e.launcher,dock:{...it.launcher?.dock,...e.launcher?.dock},clearChat:{...it.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...it.tooltip,...e.tooltip},copy:{...it.copy,...e.copy},sendButton:{...it.sendButton,...e.sendButton},statusIndicator:{...it.statusIndicator,...e.statusIndicator},voiceRecognition:{...it.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=it.features?.artifacts,n=e.features?.artifacts,o=it.features?.scrollToBottom,r=e.features?.scrollToBottom,s=it.features?.scrollBehavior,a=e.features?.scrollBehavior,l=it.features?.streamAnimation,d=e.features?.streamAnimation,p=it.features?.askUserQuestion,u=e.features?.askUserQuestion,m=it.features?.history,y=e.features?.history,h=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},v=o===void 0&&r===void 0?void 0:{...o,...r},x=s===void 0&&a===void 0?void 0:{...s,...a},w=l===void 0&&d===void 0?void 0:{...l,...d},k=p===void 0&&u===void 0?void 0:{...p,...u,styles:{...p?.styles,...u?.styles}},O=m===void 0&&y===void 0?void 0:{...m,...y,copy:{...m?.copy,...y?.copy}};return{...it.features,...e.features,...v!==void 0?{scrollToBottom:v}:{},...x!==void 0?{scrollBehavior:x}:{},...h!==void 0?{artifacts:h}:{},...w!==void 0?{streamAnimation:w}:{},...k!==void 0?{askUserQuestion:k}:{},...O!==void 0?{history:O}:{}}})(),suggestionChips:e.suggestionChips??it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...it.layout,...e.layout,header:{...it.layout?.header,...e.layout?.header},messages:{...it.layout?.messages,...e.layout?.messages,avatar:{...it.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...it.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...it.layout?.slots,...e.layout?.slots}},markdown:{...it.markdown,...e.markdown,options:{...it.markdown?.options,...e.markdown?.options}},messageActions:{...it.messageActions,...e.messageActions}}:it}function bm(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 _d(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function LC(e,t){e.style.maxHeight=`${t*bm(e)}px`,e.style.overflowY="auto"}function hl(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 IC(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function RC(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||!IC(t)}function XT(e){return(e.submitKey??"enter")!=="enter"||IC(e)?"enter":"send"}function Dd(e,t){e.setAttribute("enterkeyhint",XT(t))}function Nd(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 vm(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 Yn="persona-composer-control",wo="persona-composer-control--glyph",wm=40,yn=24,Fd=(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)}},$d=(e,t)=>{let n=E("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??ym,n.dir="auto",Dd(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:hl(n)}),Nd(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=_d(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*bm(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}},ZT="[data-persona-glyph-stack]",xm=(e,t,n="send")=>{let o=Y("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??"")||wm,h=t.backgroundColor,v=t.textColor,x=E("div","persona-send-button-wrapper"),w=Y("button",{className:hn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Yn}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!h&&"persona-bg-persona-primary",!n&&!v&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?v||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":v||void 0,backgroundColor:n&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),k=null,O=null,D=null;if(n){let A=parseFloat(t.iconSize??"")||Math.round(y*.5),_=t.iconStrokeWidth??2,G=v?.trim()||"currentColor";r&&(k=de(r,A,G,_)),O=de(s,A,G,_),k&&O?(D=xm(k,O),w.appendChild(D)):k?w.appendChild(k):(w.textContent=o,O=null)}else w.textContent=d;w.setAttribute("aria-label",a),x.appendChild(w),tn({anchor:w,trigger:x,text:()=>w.getAttribute("aria-label")??"",enabled:u});let T="send";return{button:w,wrapper:x,setMode:A=>{if(A===T)return;T=A;let _=A==="stop"?l:a;w.setAttribute("aria-label",_),w.setAttribute("data-persona-send-mode",A),n?(w.querySelector(ZT)??D)?.setAttribute("data-mode",A):w.textContent=A==="stop"?p:d},glyphStack:D}},Yi=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype",s=t.provider?.type==="custom";if(!(o||r||s))return null;let l=t.iconName??"mic",d=t.iconSize,p=parseFloat(d??"")||yn,u=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,y=E("div","persona-send-button-wrapper"),h=Y("button",{className:hn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Yn,!d&&wo),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),x=de(l,p,m||"currentColor",1.5);x?h.appendChild(x):h.textContent="\u{1F3A4}",y.appendChild(h);let w=t.tooltipText??"Start voice recognition",k=t.showTooltip??!1;return tn({anchor:h,trigger:y,text:()=>h.getAttribute("aria-label")??w,enabled:k}),{button:h,wrapper:y}},jd=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??fr).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=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Yn} ${wo}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=de(r,yn,"currentColor",1.5);l?a.appendChild(l):a.textContent="\u{1F4CE}",a.addEventListener("click",p=>{p.preventDefault(),o.click()}),s.appendChild(a);let d=t.buttonTooltipText??"Attach file";return tn({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},qd=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},zd=()=>Y("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function eP(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Vd(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:d=2147483e3,onOpen:p,onDismiss:u}=e,m=e.container??eP(t),y=!1,h=null,v=()=>{if(!y)return;let k=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${k.width}px`),a&&(n.style.maxWidth=`${k.width}px`);let O=n.getBoundingClientRect(),D=l?.()??null,T=D!=null?k.top+D:k.top,I=o==="top-start"||o==="top-end"?T-r-O.height:k.bottom+r,_=o==="bottom-end"||o==="top-end"?k.right-O.width:k.left,G=a?.()??null;if(G!=null){let le=Math.max(k.left,k.right-O.width);_=Math.min(Math.max(k.left+G,k.left),le)}n.style.top=`${I}px`,n.style.left=`${_}px`},x=()=>{y&&(y=!1,h&&(h(),h=null),n.remove())},w=()=>{if(y)return;y=!0,d!=null&&(n.style.zIndex=String(d)),m.appendChild(n),v();let k=(t.ownerDocument??document).defaultView??window,O=t.ownerDocument??document,D=()=>{if(!t.isConnected){x(),u?.("anchor-removed");return}v()},T=A=>{let _=typeof A.composedPath=="function"?A.composedPath():[];_.includes(n)||_.includes(t)||(x(),u?.("outside"))},I=k.setTimeout(()=>{O.addEventListener("pointerdown",T,!0)},0);k.addEventListener("scroll",D,!0),k.addEventListener("resize",D),h=()=>{k.clearTimeout(I),O.removeEventListener("pointerdown",T,!0),k.removeEventListener("scroll",D,!0),k.removeEventListener("resize",D)},p?.()};return{get isOpen(){return y},open:w,close:x,toggle:()=>y?x():w(),reposition:v,destroy:x}}var tP='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',nP=["--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"],Sm="data-persona-menu-focus",oP=new Set(["ArrowDown","ArrowUp","Home","End"]);function HC(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(tP)??e}var rP=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function WC(e){let t=e.label,n=!1,o=E("div","persona-send-button-wrapper"),r=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Yn} ${wo}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=Y("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),a=()=>{let R=e.getButtonSize?.()??"";r.style.width=R,r.style.height=R,r.style.minWidth=R,r.style.minHeight=R,r.style.lineHeight="1",r.replaceChildren();let Z=de("plus",yn,"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},y=()=>{let R=m();for(let Z of d){let V=!!R&&HC(Z)===R;Z.toggleAttribute(Sm,V&&u)}},h=()=>d.filter(R=>R.isConnected||s.contains(R)).map(HC).filter(R=>!rP(R)),v=(R,Z)=>{R.forEach((V,ge)=>{V.setAttribute("tabindex",ge===Z?"0":"-1")})},x=R=>{let Z=h();if(Z.length===0)return;let V=(R%Z.length+Z.length)%Z.length;p=V,v(Z,V),Z[V].focus(),y()},w=()=>o.ownerDocument??document,k=null,O=null,D=null,T=()=>{k&&(w().removeEventListener("focusin",k,!0),k=null)},I=()=>{O&&(s.removeEventListener("focusin",O),O=null),D&&(s.removeEventListener("pointerdown",D,!0),D=null)},A=null,_=()=>(A||(A=Vd({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),T()}})),A),G=()=>A?.isOpen===!0,le=(R=!1)=>{if(G()){A?.close(),r.setAttribute("aria-expanded","false"),T(),I(),p=-1,u=!1;for(let Z of d)Z.removeAttribute(Sm);R&&r.focus()}},ee=(R=0,Z=!1)=>{if(n||G())return;u=Z,Fd(r,s,nP),_().open(),r.setAttribute("aria-expanded","true");let V=h();v(V,-1),x(R<0?V.length-1:R),k=ge=>{let ae=typeof ge.composedPath=="function"?ge.composedPath():[];ae.includes(s)||ae.includes(o)||le()},w().addEventListener("focusin",k,!0),O=()=>y(),s.addEventListener("focusin",O),D=()=>{u=!1},s.addEventListener("pointerdown",D,!0)},M=R=>{R.preventDefault(),R.stopPropagation(),G()?le(!0):ee(0)},B=R=>{if(R.key==="ArrowDown"||R.key==="Enter"||R.key===" "){R.preventDefault(),u=!0,G()?x(0):ee(0,!0);return}R.key==="ArrowUp"&&(R.preventDefault(),u=!0,G()?x(-1):ee(-1,!0))},H=R=>{switch(oP.has(R.key)&&(u=!0),R.key){case"ArrowDown":R.preventDefault(),x(p+1);return;case"ArrowUp":R.preventDefault(),x(p-1);return;case"Home":R.preventDefault(),x(0);return;case"End":R.preventDefault(),x(h().length-1);return;case"Escape":R.preventDefault(),R.stopPropagation(),le(!0);return;case"Tab":le(!0);return;default:}};return r.addEventListener("click",M),r.addEventListener("keydown",B),s.addEventListener("keydown",H),{trigger:o,triggerButton:r,panel:s,setItems:R=>{for(let V of d)R.includes(V)||V.removeAttribute(Sm);if(d=[...R],!G())return;let Z=h();v(Z,Math.min(p,Z.length-1)),y()},isOpen:G,open:()=>ee(0),close:le,setLabel:R=>{R!==t&&(t=R,l())},applyButtonSize:a,destroy:()=>{n=!0,T(),I(),r.removeEventListener("click",M),r.removeEventListener("keydown",B),s.removeEventListener("keydown",H),A?.destroy(),A=null,o.remove(),s.remove(),d=[]}}}var Uo={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},OC="data-persona-composer-action",Am="data-persona-composer-disable-when-streaming",sP="core:overflow",iP=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function aP(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 Mm(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 BC=(e,t)=>{!e||typeof console>"u"||console.warn(t)},lP=(e,t)=>t.includes(":")?t:`${e}:${t}`;function cP(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){BC(t,`[Persona] composer action "${l.id}" is already contributed by ${_C(d)}; the ${_C(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?lP(p,l.id):l.id,m=l.order??Uo.custom;l.placement==="end"&&m>=Uo.send&&(BC(t,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${Uo.send-1}.`),m=Uo.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 _C=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",DC=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,dP=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function pP(e,t){if(!e||e==="always")return!0;let n=dP(t);return e==="when-text"?n:!n}var Qr=e=>e.kind==="custom",Em=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,uP=e=>{let t=Em(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},gP='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function mP(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(gP)||o.childNodes.forEach(n)};return n(e),t.trim()}var fP=e=>mP(e).length===0;function NC(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(M,B)=>{let H=M.button;if(!H)return;H.setAttribute("role","menuitem"),H.setAttribute("tabindex","-1"),H.className="persona-composer-overflow-menu__item";for(let V of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])H.style[V]="";H.style.lineHeight="1",B.tooltipText?H.setAttribute("title",B.tooltipText):H.removeAttribute("title"),H.replaceChildren();let R=E("span","persona-composer-overflow-menu__icon");if(B.iconName){let V=de(B.iconName,16,"currentColor",1.5);V&&R.appendChild(V)}let Z=E("span","persona-composer-overflow-menu__label");Z.textContent=B.shortLabel??B.label,H.append(R,Z)},a=(M,B)=>{let H=M.button;if(!H)return;if(H.setAttribute("aria-label",B.label),B.pressed===void 0?H.removeAttribute("aria-pressed"):H.setAttribute("aria-pressed",B.pressed?"true":"false"),H.toggleAttribute(Am,B.disableWhenStreaming===!0),M.mode==="menu"){M.tooltip?.destroy(),M.tooltip=void 0,s(M,B);return}H.removeAttribute("role"),H.removeAttribute("tabindex"),H.removeAttribute("title");let R=r(),Z=!!B.shortLabel;if(H.className=hn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Yn,wo,Z&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),H.style.width=R&&!Z?R:"",H.style.height=R??"",H.style.minWidth=R&&!Z?R:"",H.style.minHeight=R??"",H.style.fontSize=Z?"":"18px",H.style.lineHeight="1",H.style.color=B.iconColor??"",H.style.backgroundColor=B.backgroundColor??"",H.replaceChildren(),B.iconName){let V=de(B.iconName,yn,"currentColor",1.5);V&&H.appendChild(V)}if(Z){let V=E("span","persona-composer-action-button__label");V.textContent=B.shortLabel,H.appendChild(V)}else H.firstChild||(H.textContent=B.label);M.tooltip?.destroy(),M.tooltip=tn({anchor:H,trigger:M.element,text:()=>B.tooltipText??B.label,enabled:!!B.tooltipText})},l=(M,B)=>{let H=M.action,R=Y("button",{attrs:{type:"button"}}),Z=R;if(B==="bar"){let ae=E("div","persona-send-button-wrapper");ae.appendChild(R),Z=ae}Z.setAttribute(OC,M.id);let V={resolved:M,element:Z,button:R,owned:!0,managed:!0,busy:!1,visible:!0,mode:B},ge=ae=>{if(ae.preventDefault(),ae.stopPropagation(),V.busy||R.disabled)return;let fe=V.resolved.action;V.mode==="menu"&&h?.close(!0);let He;try{He=fe.onSelect(e.actionContext,ae)}catch(ve){e.reportError(ve,{actionId:V.resolved.id});return}!He||typeof He.then!="function"||(V.busy=!0,R.setAttribute("aria-busy","true"),He.catch(ve=>{e.reportError(ve,{actionId:V.resolved.id})}).finally(()=>{V.busy=!1,R.removeAttribute("aria-busy")}))};return R.addEventListener("click",ge),V.detach=()=>R.removeEventListener("click",ge),a(V,H),V},d=M=>{let B=M.action,H;try{H=B.render({...e.actionContext,id:M.id,action:B})}catch(R){return e.reportError(R,{actionId:M.id}),null}return H?.element?(H.element.setAttribute(OC,M.id),H.element.toggleAttribute(Am,B.disableWhenStreaming===!0),{resolved:M,element:H.element,owned:!0,managed:!0,destroy:H.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(M,B)=>{if(M.builtIn){let R=M.builtIn.element;return R?{resolved:M,element:R,owned:!1,managed:M.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let H=M.action;return H?Qr(H)?d(M):l(M,B):null},u=M=>{if(M.detach?.(),M.tooltip?.destroy(),M.detachMenuSlot?.(),M.detachMenuSlot=void 0,M.menuLabel?.remove(),M.menuLabel=void 0,M.menuSlot?.remove(),M.menuSlot=void 0,M.owned){try{M.destroy?.()}catch(B){e.reportError(B,{actionId:M.resolved.id})}M.element.remove()}},m=(M,B)=>{for(let H=0;H<B.length;H++){let R=B[H];if(!R.managed)continue;let Z=null;for(let V=H+1;V<B.length;V++){let ge=B[V];if(!ge.managed&&ge.element.parentElement===M){Z=ge.element;break}}Z?(R.element.parentElement!==M||R.element.nextSibling!==Z)&&M.insertBefore(R.element,Z):M.lastChild!==R.element&&M.appendChild(R.element)}},y=(M,B)=>{if(M.button){M.button.disabled=B;return}if(!M.owned)return;let H=M.element;H.toggleAttribute("data-disabled",B),H.setAttribute("aria-disabled",B?"true":"false");let R=H instanceof HTMLButtonElement||H instanceof HTMLSelectElement||H instanceof HTMLInputElement||H instanceof HTMLTextAreaElement?H:H.querySelector("button, select, input, textarea");R&&(R.disabled=B)},h=null,v=null,x=null,w=0,k=()=>{let M=e.getOverflow?.();return M?.enabled===!0?M:void 0},O=()=>(h?h.setLabel(e.getOverflowLabel?.()??"More actions"):h=WC({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),h),D=M=>{v!==M&&(x?.disconnect(),v=M,w=Mm(M),!(typeof ResizeObserver>"u")&&(x=new ResizeObserver(B=>{let R=B[B.length-1]?.contentRect?.width??Mm(M);R!==w&&(w=R,le())}),x.observe(M)))},T=(M,B)=>{let H=aP(M.collapseAutoActionsBelow,B);if(H===null)return!1;let R=w||Mm(B);return R>0&&R<H},I=(M,B,H)=>{if(!B)return"bar";if(M.resolved.builtIn){let Z=iP(M.resolved.id);return Z&&B.includeBuiltIns?.includes(Z)?"menu":"bar"}let R=M.resolved.presentation;return R==="overflow"||R==="auto"&&H?"menu":"bar"},A=M=>{let B=M.menuSlot;if(!B)return;if(!fP(M.element)){M.menuLabel?.remove(),M.menuLabel=void 0;return}let H=uP(M.element);if(!H){M.menuLabel?.remove(),M.menuLabel=void 0;return}M.menuLabel||(M.menuLabel=E("span","persona-composer-overflow-menu__label")),M.menuLabel.textContent!==H&&(M.menuLabel.textContent=H),M.menuLabel.parentElement!==B&&B.appendChild(M.menuLabel)},_=(M,B)=>{if(M.mode===B)return M;let H=M.resolved.action;if(H&&!Qr(H)){u(M),t.delete(M.resolved.id);let R=l(M.resolved,B);return t.set(M.resolved.id,R),R}if(B==="menu"){let R=Y("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[hm]:""}});R.appendChild(M.element),EC(Em(M.element)),M.menuSlot=R;let Z=V=>{let ge=Em(M.element);if(ge.disabled)return;let ae=V.target===ge||ge.contains(V.target);h?.close(!0),ae||ge.click()};R.addEventListener("click",Z,!0),M.detachMenuSlot=()=>R.removeEventListener("click",Z,!0),M.managed=!0,A(M)}else M.detachMenuSlot?.(),M.detachMenuSlot=void 0,M.menuLabel?.remove(),M.menuLabel=void 0,M.menuSlot?.remove(),M.menuSlot=void 0;return M.mode=B,M},G=(M,B)=>{let H=B.map(R=>R.menuSlot??R.element);for(H.forEach((R,Z)=>{let V=M.children[Z];V!==R&&(V?M.insertBefore(R,V):M.appendChild(R))});M.children.length>H.length;)M.lastElementChild?.remove()},le=()=>{if(o)return;let M=e.getBindings();if(!M)return;let B=e.getState(),H=B.phase==="streaming",R=k();R&&D(M.footer);let Z=R?T(R,M.footer):!1,V={start:[],end:[]},ge=[];for(let ae of n){let fe=t.get(ae.id);if(!fe)continue;let He=ae.action,ve=He?DC(He.visible,B,!0)&&pP(He.visibility,B):!0;if(fe.visible!==ve&&(fe.visible=ve,!ve&&fe.managed&&(fe.menuSlot??fe.element).remove()),!!ve){if(fe=_(fe,I(fe,R,Z)),He){let pe=DC(He.disabled,B,!1)||He.disableWhenStreaming===!0&&H;y(fe,pe),!Qr(He)&&He.pressed!==void 0&&fe.button?.setAttribute("aria-pressed",He.pressed?"true":"false")}fe.mode==="menu"?(A(fe),ge.push(fe)):V[ae.placement].push(fe)}}if(ge.length>0){let ae=O();G(ae.panel,ge),ae.setItems(ge.map(pe=>pe.menuSlot??pe.element)),ae.applyButtonSize();let fe=Number.isFinite(R?.order)?R?.order:Uo.overflow,He=V.start.findIndex(pe=>pe.resolved.order>fe),ve={resolved:{id:sP,placement:"start",presentation:"bar",order:fe,sequence:-1,source:"core"},element:ae.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};V.start.splice(He<0?V.start.length:He,0,ve)}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=cP(e.collect()),B=new Set(M.map(H=>H.id));for(let[H,R]of t)B.has(H)||(u(R),t.delete(H));for(let H of M){let R=t.get(H.id);if(!R){let ae=p(H,"bar");ae&&t.set(H.id,ae);continue}let Z=R.resolved.action,V=H.action;if(!!Z!=!!V||Z&&V&&Qr(Z)!==Qr(V)||Z&&V&&Qr(Z)&&Qr(V)&&Z.render!==V.render){u(R),t.delete(H.id);let ae=p(H,R.mode);ae&&t.set(H.id,ae);continue}R.resolved=H,H.builtIn?(R.managed=H.builtIn.managed===!0||R.mode==="menu",H.builtIn.element&&R.mode==="bar"&&(R.element=H.builtIn.element)):V&&!Qr(V)?a(R,V):V&&R.element.toggleAttribute(Am,V.disableWhenStreaming===!0)}n=M,le()},sync:le,getResolved:()=>n,getOverflowMenu:()=>h,destroy:()=>{if(!o){o=!0,x?.disconnect(),x=null,v=null;for(let M of t.values())u(M);t.clear(),h?.destroy(),h=null,n=[]}}}}var hP="core:model",yP=700,FC=16,bP=["--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"],$C=()=>{let e=Y("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=Y("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function UC(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=Y("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),p="",u=()=>{let x=e.getModels(),w=x.map(k=>`${k.id}:${k.label}`).join("|");w!==p&&(p=w,d.replaceChildren(...x.map(k=>{let O=Y("option",{attrs:{value:k.id}});return O.textContent=k.label,O}))),d.value=r(x)?.id??""};u(),o=u;let m=()=>{d.value&&e.onSelect(d.value)};d.addEventListener("change",m);let y=x=>x.stopPropagation();d.addEventListener("click",y);let{wrapper:h,chevron:v}=$C();return h.append(d,v),{element:h,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",y)}}},a=()=>{let d=Y("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=Y("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),y=new Map,h="",v=null,x=()=>v?.isOpen===!0,w=(B=!1)=>{x()&&(v?.close(),d.setAttribute("aria-expanded","false"),B&&d.focus())},k=B=>{let H=[...y.values()];if(H.length===0)return;let R=(B%H.length+H.length)%H.length;H[R].focus()},O=B=>{if(x())return;v||(v=Vd({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),Fd(d,m,bP),v.open(),d.setAttribute("aria-expanded","true");let R=[...y.keys()].indexOf(r(e.getModels())?.id??"");k(B??(R>=0?R:0))},D=B=>{w(!0),e.onSelect(B)},T=B=>{B.preventDefault(),B.stopPropagation();let H=B.currentTarget.getAttribute("data-persona-model-option");H&&D(H)},I=B=>{let H=Y("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":B.id}});if(B.icon){let ae=de(B.icon,FC,"currentColor",1.5);if(ae){let fe=E("span","persona-composer-model-option-icon");fe.appendChild(ae),H.appendChild(fe)}}let R=E("span","persona-composer-model-option-body"),Z=E("span","persona-composer-model-option-label");if(Z.textContent=B.label,R.appendChild(Z),B.description){let ae=E("span","persona-composer-model-option-description");ae.textContent=B.description,R.appendChild(ae)}H.appendChild(R);let V=E("span","persona-composer-model-option-check");V.setAttribute("aria-hidden","true");let ge=de("check",FC,"currentColor",2);return ge&&V.appendChild(ge),H.appendChild(V),H.addEventListener("click",T),H},A=()=>{let B=e.getModels(),H=B.map(V=>`${V.id}:${V.label}:${V.icon??""}:${V.description??""}`).join("|");if(H!==h){h=H;for(let V of y.values())V.removeEventListener("click",T);y.clear(),m.replaceChildren(...B.map(V=>{let ge=I(V);return y.set(V.id,ge),ge}))}let R=r(B);for(let[V,ge]of y)ge.setAttribute("aria-selected",String(V===R?.id));p.textContent=R?.label??"";let Z=e.getSuffix?.()??"";u.textContent=Z,d.setAttribute("aria-label",[t,[R?.label,Z].filter(Boolean).join(" ")].filter(Boolean).join(": "))};A(),o=A;let _=B=>{B.preventDefault(),B.stopPropagation(),x()?w(!0):O()},G=B=>{if(B.key==="ArrowDown"){B.preventDefault(),x()?k(0):O(0);return}B.key==="ArrowUp"&&(B.preventDefault(),x()?k(-1):O(-1))},le=B=>{let H=[...y.values()],R=H.indexOf(B.target?.closest?.(".persona-composer-model-option"));switch(B.key){case"ArrowDown":B.preventDefault(),k(R+1);return;case"ArrowUp":B.preventDefault(),k(R-1);return;case"Home":B.preventDefault(),k(0);return;case"End":B.preventDefault(),k(H.length-1);return;case"Escape":B.preventDefault(),B.stopPropagation(),w(!0);return;case"Tab":w(!0);return;default:}};d.addEventListener("click",_),d.addEventListener("keydown",G),m.addEventListener("keydown",le);let{wrapper:ee,chevron:M}=$C();return ee.append(d,M),{element:ee,destroy:()=>{o===A&&(o=null),d.removeEventListener("click",_),d.removeEventListener("keydown",G),m.removeEventListener("keydown",le);for(let B of y.values())B.removeEventListener("click",T);y.clear(),v?.destroy(),v=null,m.remove()}}};return{action:{id:hP,kind:"custom",placement:"end",order:yP,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}var Tm="[data-persona-composer-chip-row]";function Kd(e){e.style.display=e.childElementCount>0?"flex":"none"}function Pm(e){let t=e.querySelector(Tm);if(t)return t;let n=Y("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 vP=":scope > [data-persona-composer-mode]";function jC(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=p=>{let u=Y("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":p.id}});if(p.iconName){let v=E("span","persona-mention-chip-icon"),x=de(p.iconName,12,"currentColor",1.5);x&&v.appendChild(x),u.appendChild(v)}let m=E("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let y=Y("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),h=de("x",12,"currentColor",2);return h?y.appendChild(h):y.textContent="\xD7",y.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),e.onRemove(p.id)}),u.appendChild(y),u},a=()=>Array.from(t.querySelectorAll(vP)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),Kd(t)},m=t.ownerDocument.defaultView,y=typeof m?.getComputedStyle=="function"?m.getComputedStyle(p).animationName:"";if(!y||y==="none"){u();return}p.addEventListener("animationend",u,{once:!0}),p.addEventListener("animationcancel",u,{once:!0})},d=()=>{for(let p of a())p.remove()};return{element:t,render:(p,u)=>{if(o)return;let m=u.filter(x=>p.includes(x.id)),y=m.map(x=>`${x.id}:${x.shortLabel??x.label}`).join("|");if(y===n)return;n=y;let h=new Map;for(let x of a()){let w=x.getAttribute("data-persona-composer-mode");w&&m.some(O=>O.id===w)&&!x.hasAttribute("data-persona-chip-exit")?h.set(w,x):x.hasAttribute("data-persona-chip-exit")||l(x)}let v=t.firstChild;for(let x of m){let w=h.get(x.id);w||(w=s(x),r.has(x.id)||(w.setAttribute("data-persona-chip-enter",""),w.addEventListener("animationend",()=>w?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(x.id),w!==v&&t.insertBefore(w,v),v=w.nextSibling}Kd(t)},destroy:()=>{o=!0,d(),Kd(t)}}}var qC=e=>`core:mode:${e}`;var km=e=>Math.min(300+e,499),zC=e=>`core:mode-group:${e}`;function Gd(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function CP(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function VC(e,t){return e?.length?e.filter(n=>!Gd(n.groupId,t)&&!CP(n.groupId,t)):[]}var wP=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function KC(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(wP(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 Yd(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function GC(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function YC(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var xP=16;function QC(e){let t=null;return{action:{id:zC(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=Y("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=Y("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":p.id,"aria-label":p.label}});if(p.iconName){let y=de(p.iconName,xP,"currentColor",1.5);y&&u.appendChild(y)}let m=E("span","persona-composer-segmented-label");return m.textContent=p.shortLabel??p.label,u.appendChild(m),u.addEventListener("click",a),u},d=()=>{let p=e.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=e.getModes(),m=u.map(h=>`${h.id}:${h.shortLabel??h.label}:${h.iconName??""}`).join("|");if(m!==s){s=m;for(let v of r.values())v.removeEventListener("click",a);r.clear();let h=u.map(v=>{let x=l(v);return r.set(v.id,x),x});o.replaceChildren(...h)}let y=e.getActiveIds();for(let[h,v]of r)v.setAttribute("aria-pressed",String(y.includes(h)))};return d(),t=d,{element:o,destroy:()=>{t===d&&(t=null);for(let p of r.values())p.removeEventListener("click",a);r.clear()}}}},repaint:()=>t?.()}}function XC(e){let t=Y("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=Y("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=Ld(s.text),l.appendChild(d);let p=Y("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),u=de("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 JC(e){let t=Y("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=Y("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[d]:""}}),m=de(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=Ld(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=Y("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 ZC(e){let t=Y("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=Y("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=Y("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 ew(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 tw(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 nw(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 ow(e){return e.wrapped||e.text.includes(`
|
|
23
|
+
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission||e.dictationActive)}function rw(){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 iw(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Lm(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 lw(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var SP=e=>typeof e?.then=="function";function aw(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 cw(e,t,n){let o;try{o=e(Lm(t),{signal:n})}catch(r){return{status:"error",error:r}}return SP(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:aw(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):aw(t,o)}var dw=/\s/;function AP(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===""||dw.test(o)}function MP(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 AP(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
|
|
25
|
+
`||a==="\uFFFC"||!r&&dw.test(a))return null;s--}return null}function pw(e,t,n){for(let o of n){let r=MP(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function uw(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function gw(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 mw(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=E("div","persona-send-button-wrapper"),a=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Yn} ${wo}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=de(o,yn,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),s.appendChild(a),tn({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}var{setLoader:uW,load:EP}=yt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var Im=EP;var{setLoader:fW,load:TP}=yt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var fw=TP;function yl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Y("span",{className:hn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=de(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=E("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Y("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function hw(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=gw(t).filter(T=>T.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(T=>T.sources.some(I=>typeof I.matchCommand=="function")),r=T=>o.some(I=>I.trigger?I.position==="line-start"?T.split(`
|
|
26
|
+
`).some(_=>_.startsWith(I.trigger)):(I.position==="anywhere"?T:T.split(`
|
|
27
|
+
`)[0]).startsWith(I.trigger):!1),s=(T,I)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:I}))}catch{}},a=!e.chipRow,l=e.chipRow??Y("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,p=null,u=e.textarea,m=null,y=null,h=null,v=null,x=()=>{if(d)return Promise.resolve(d);if(p)return p;let T=Im().then(I=>(I.setMentionIconRenderer(de),d=I.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:l,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:D,emit:s}),d)).catch(I=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",I),p===T&&(p=null),null));return p=T,T},w=()=>{fw().then(T=>{let I=T.mountInlineComposer({textarea:e.textarea,renderToken:_=>yl(_,{render:t.renderMentionToken}),onMentionRemoved:_=>d?.untrackMention(_)});m=I.input,y=I.destroy;let A=u;A.replaceWith(I.element),u=I.element,v={next:I.element,prev:A},h?.(I.element,A),d?d.rebindComposer(I.input):p&&p.then(_=>_?.rebindComposer(I.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};t.display==="inline"&&w();let k=[],O=new Map;for(let T of n){if(!T.showButton)continue;let I=mw({config:{...t,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},onOpen:()=>{x().then(A=>A?.openMenu(T.trigger))}});k.push(I),O.set(T.trigger,I.button)}let D=(T,I,A)=>{let _=O.get(I);_&&(_.setAttribute("aria-expanded",T?"true":"false"),T?_.setAttribute("aria-controls",A):_.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(T=>T.wrapper),contextRow:l,handleInput:T=>{if(d){d.handleInput();return}if(!uw(T))return;let I=u,A=I.selectionStart??0;pw(I.value,A,n)&&x().then(_=>_?.handleInput())},handleKeydown:T=>{if(d?.isMenuOpen())return d.handleKeydown(T);if(T.key==="Backspace"&&d?.hasMentions()&&!v){let I=u,A=I.selectionStart===0&&I.selectionEnd===0;if((I.value.length===0||A)&&d.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async T=>r(T)?(d??await x())?.dispatchInlineCommand(T)??null:null,clear:()=>d?.clear(),prefetch:()=>{Im().catch(()=>{})},onComposerSwap:T=>{h=T,v&&T(v.next,v.prev)},destroy:()=>{d?.destroy(),y?.();for(let T of k)T.wrapper.remove();a&&l.remove()}}}var Qd="16px",Xd="transparent",PP=(()=>{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})(),Hm={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:PP,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"}},Wm={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"}},Om={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:Gn,maxWidth:Bd,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Qd,canvasBackground:Xd},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},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 bn(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?bn(e,o):o}function Jd(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let d=bn(e,a);d!==void 0&&(t[l]={path:l,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Bm(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 bw(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]=bw(s,r):n[o]=r}return n}function kP(e,t){return t?bw(e,t):e}function bl(e,t={}){let n={palette:Hm,semantic:Wm,components:Om},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:kP(n.components,e?.components)};if(t.validate!==!1){let r=Bm(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 Rm=e=>e.trim()==="0"?"0px":e,yw="--persona-",LP=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},IP=.179,nn=(e,t)=>{for(let[n,...o]of t){let r;for(let s of o)if(r=s.charCodeAt(0)===61?s.slice(1):e[yw+s],r!==void 0)break;r!==void 0&&(e[yw+n]=r)}};function Zd(e){let t=Jd(e),n={};for(let[F,_e]of Object.entries(t)){let qe=F.replace(/\./g,"-");n[`--persona-${qe}`]=_e.value}nn(n,[["primary","semantic-colors-primary","palette-colors-primary-500"],["secondary","semantic-colors-secondary","palette-colors-secondary-500"],["accent","semantic-colors-accent","palette-colors-accent-500"],["surface","semantic-colors-surface","palette-colors-gray-50"],["background","semantic-colors-background","palette-colors-gray-50"],["container","semantic-colors-container","palette-colors-gray-100"],["text","semantic-colors-text","palette-colors-gray-900"],["text-muted","semantic-colors-text-muted","palette-colors-gray-500"],["text-inverse","semantic-colors-text-inverse","palette-colors-gray-50"],["border","semantic-colors-border","palette-colors-gray-200"],["divider","semantic-colors-divider","palette-colors-gray-200"],["muted","text-muted"],["voice-recording-indicator","components-voice-recording-indicator","palette-colors-error-500"],["voice-recording-bg","components-voice-recording-background","palette-colors-error-50"],["voice-processing-icon","components-voice-processing-icon","palette-colors-primary-500"],["voice-speaking-icon","components-voice-speaking-icon","palette-colors-success-500"],["approval-bg","components-approval-requested-background","surface"],["approval-border","components-approval-requested-border","border"],["approval-text","components-approval-requested-text","palette-colors-gray-900"],["approval-shadow","components-approval-requested-shadow","=0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"],["approval-approve-bg","components-approval-approve-background","button-primary-bg"],["approval-deny-bg","components-approval-deny-background","container"],["attachment-image-bg","components-attachment-image-background","palette-colors-gray-100"],["attachment-image-border","components-attachment-image-border","palette-colors-gray-200"],["font-family","semantic-typography-fontFamily","palette-typography-fontFamily-sans"],["font-size","semantic-typography-fontSize","palette-typography-fontSize-base"],["font-weight","semantic-typography-fontWeight","palette-typography-fontWeight-normal"],["line-height","semantic-typography-lineHeight","palette-typography-lineHeight-normal"],["input-font-family","font-family"],["input-font-weight","font-weight"],["radius-sm","palette-radius-sm","=0.125rem"],["radius-md","palette-radius-md","=0.375rem"],["radius-lg","palette-radius-lg","=0.5rem"],["radius-xl","palette-radius-xl","=0.75rem"],["radius-full","palette-radius-full","=9999px"],["launcher-radius","components-launcher-borderRadius","palette-radius-full","=9999px"],["launcher-bg","components-launcher-background","surface"],["launcher-fg","components-launcher-foreground","primary"]]);let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],nn(n,[["launcher-border","components-launcher-border","border"],["button-primary-bg","components-button-primary-background","primary"],["button-primary-fg","components-button-primary-foreground","text-inverse"],["button-radius","components-button-primary-borderRadius","palette-radius-full","=9999px"],["button-stop-bg","components-button-stop-background"],["button-stop-fg","components-button-stop-foreground"]]),nn(n,[["button-ghost-bg","components-button-ghost-background","=transparent"],["button-ghost-fg","components-button-ghost-foreground","text"],["button-ghost-radius","components-button-ghost-borderRadius","radius-md","=0.375rem"],["button-ghost-hover-bg","components-button-ghost-hoverBackground","=rgba(0, 0, 0, 0.05)"],["panel-radius","components-panel-borderRadius","radius-xl","=0.75rem"]]),n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,nn(n,[["panel-shadow","components-panel-shadow","palette-shadows-xl","=0 25px 50px -12px rgba(0, 0, 0, 0.25)"]]),n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Qd,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Xd,nn(n,[["launcher-shadow","components-launcher-shadow","=0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"],["input-radius","components-input-borderRadius","radius-lg","=0.5rem"],["message-user-radius","components-message-user-borderRadius","radius-lg","=0.5rem"],["message-assistant-radius","components-message-assistant-borderRadius","radius-lg","=0.5rem"]]),nn(n,[["header-bg","components-header-background","surface"]]);let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],a=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],nn(n,[["header-icon-bg","components-header-iconBackground","primary"],["header-icon-fg","components-header-iconForeground","text-inverse"]]),n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??a??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??a??n["--persona-muted"],nn(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=e.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[F,_e]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let qe=n[`--persona-components-history-overlay-${F}`];qe&&(n[`--persona-history-overlay-${_e}`]=qe)}for(let[F,_e]of[["background","bg"],["borderRadius","radius"]]){let qe=n[`--persona-components-history-menu-${F}`];qe&&(n[`--persona-history-menu-${_e}`]=qe)}let m=e.components?.history?.motion;if(m){let F=Dt=>{if(Dt===void 0)return;let Ce=String(Dt).trim();return/^\d+(\.\d+)?$/.test(Ce)?`${Ce}ms`:Ce},_e=F(m.enterDurationMs);_e!==void 0&&(n["--persona-history-enter-ms"]=_e);let qe=F(m.exitDurationMs);qe!==void 0&&(n["--persona-history-exit-ms"]=qe),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 _e=n[`--persona-components-history-confirm-${F}`];_e&&(n[`--persona-history-confirm-${F}`]=_e)}for(let[F,_e]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let qe=n[`--persona-components-tooltip-${F}`];qe&&(n[`--persona-tooltip-${_e}`]=qe)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[F,_e]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let qe=n[`--persona-components-messageActions-${F}`];qe&&(n[`--persona-message-action-${_e}`]=qe)}nn(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let h=n["--persona-components-introCard-background"],v=n["--persona-components-introCard-shadow"],x=(!h||h==="transparent"||h==="none")&&(!v||v==="none"),w=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=x&&w==="1.5rem"?"1.5rem 0":w,nn(n,[["intro-card-shadow","components-introCard-shadow","=none"],["intro-card-border","components-introCard-border","=none"],["input-background","components-input-background","surface"],["input-placeholder","components-input-placeholder","text-muted"],["input-backdrop-filter","components-input-backdropFilter","=none"],["message-user-bg","components-message-user-background","accent"],["message-user-text","components-message-user-text","text-inverse"],["message-user-shadow","components-message-user-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["message-assistant-bg","components-message-assistant-background","surface"],["message-assistant-text","components-message-assistant-text","text"],["message-assistant-border","components-message-assistant-border","border"],["message-assistant-shadow","components-message-assistant-shadow","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-bg","components-scrollToBottom-background","button-primary-bg","accent"],["scroll-to-bottom-fg","components-scrollToBottom-foreground","button-primary-fg","text-inverse"],["scroll-to-bottom-border","components-scrollToBottom-border","primary"],["scroll-to-bottom-size","components-scrollToBottom-size","=40px"],["scroll-to-bottom-radius","components-scrollToBottom-borderRadius","button-radius","radius-full","=9999px"],["scroll-to-bottom-shadow","components-scrollToBottom-shadow","palette-shadows-sm","=0 1px 2px 0 rgb(0 0 0 / 0.05)"],["scroll-to-bottom-padding","components-scrollToBottom-padding","=0.5rem 0.875rem"],["scroll-to-bottom-gap","components-scrollToBottom-gap","=0.5rem"],["scroll-to-bottom-font-size","components-scrollToBottom-fontSize","palette-typography-fontSize-sm","=0.875rem"],["scroll-to-bottom-icon-size","components-scrollToBottom-iconSize","=14px"],["event-badge-flow-bg","components-eventStream-badge-flow-background","=#dcfce7"],["event-badge-flow-fg","components-eventStream-badge-flow-foreground","=#15803d"],["event-badge-step-bg","components-eventStream-badge-step-background","=#f5f5f5"],["event-badge-step-fg","components-eventStream-badge-step-foreground","=#0a0a0a"],["event-badge-reasoning-bg","components-eventStream-badge-reasoning-background","=#fef9c3"],["event-badge-reasoning-fg","components-eventStream-badge-reasoning-foreground","=#a16207"],["event-badge-tool-bg","components-eventStream-badge-tool-background","=#f3e8ff"],["event-badge-tool-fg","components-eventStream-badge-tool-foreground","=#6b21a8"],["event-badge-agent-bg","components-eventStream-badge-agent-background","=#ccfbf1"],["event-badge-agent-fg","components-eventStream-badge-agent-foreground","=#115e59"],["event-badge-error-bg","components-eventStream-badge-error-background","=#fee2e2"],["event-badge-error-fg","components-eventStream-badge-error-foreground","=#b91c1c"],["event-badge-default-bg","components-eventStream-badge-default-background","=#f3f4f6"],["event-badge-default-fg","components-eventStream-badge-default-foreground","=#4b5563"],["tool-bubble-shadow","components-toolBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["reasoning-bubble-shadow","components-reasoningBubble-shadow","=0 5px 15px rgba(15, 23, 42, 0.08)"],["composer-shadow","components-composer-shadow","=none"]]),nn(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let k=n["--persona-components-markdown-heading-h1-fontSize"];k&&(n["--persona-md-h1-size"]=k);let O=n["--persona-components-markdown-heading-h1-fontWeight"];O&&(n["--persona-md-h1-weight"]=O);let D=n["--persona-components-markdown-heading-h2-fontSize"];D&&(n["--persona-md-h2-size"]=D);let T=n["--persona-components-markdown-heading-h2-fontWeight"];T&&(n["--persona-md-h2-weight"]=T);let I=n["--persona-components-markdown-prose-fontFamily"];I&&I!=="inherit"&&(n["--persona-md-prose-font-family"]=I),nn(n,[["md-code-block-bg","components-markdown-codeBlock-background","container"],["md-code-block-border-color","components-markdown-codeBlock-borderColor","border"],["md-code-block-text-color","components-markdown-codeBlock-textColor","=inherit"]]),nn(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),nn(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),nn(n,[["md-hr-color","components-markdown-hr-color","divider"]]),nn(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]),n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],nn(n,[["message-border","components-message-border","border"]]),nn(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let A=e.components,_=A?.iconButton;_&&(_.background&&(n["--persona-icon-btn-bg"]=_.background),_.border&&(n["--persona-icon-btn-border"]=_.border),_.color&&(n["--persona-icon-btn-color"]=_.color),_.padding&&(n["--persona-icon-btn-padding"]=_.padding),_.borderRadius&&(n["--persona-icon-btn-radius"]=_.borderRadius),_.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=_.hoverBackground),_.hoverColor&&(n["--persona-icon-btn-hover-color"]=_.hoverColor),_.activeBackground&&(n["--persona-icon-btn-active-bg"]=_.activeBackground),_.activeBorder&&(n["--persona-icon-btn-active-border"]=_.activeBorder));let G=A?.labelButton;G&&(G.background&&(n["--persona-label-btn-bg"]=G.background),G.border&&(n["--persona-label-btn-border"]=G.border),G.color&&(n["--persona-label-btn-color"]=G.color),G.padding&&(n["--persona-label-btn-padding"]=G.padding),G.borderRadius&&(n["--persona-label-btn-radius"]=G.borderRadius),G.hoverBackground&&(n["--persona-label-btn-hover-bg"]=G.hoverBackground),G.fontSize&&(n["--persona-label-btn-font-size"]=G.fontSize),G.gap&&(n["--persona-label-btn-gap"]=G.gap));let le=A?.toggleGroup;le&&(le.gap&&(n["--persona-toggle-group-gap"]=le.gap),le.borderRadius&&(n["--persona-toggle-group-radius"]=le.borderRadius));let ee=A?.artifact;if(ee?.toolbar){let F=ee.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"]=Rm(F.toggleGroupGap)),F.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=F.toggleBorderRadius),F.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Rm(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"]=bn(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"]=Rm(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(ee?.tab){let F=ee.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(ee?.pane){let F=ee.pane;if(F.toolbarBackground){let _e=bn(e,F.toolbarBackground)??F.toolbarBackground;n["--persona-artifact-toolbar-bg"]=_e}}if(ee?.card){let F=ee.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(ee?.inline){let F=ee.inline;F.background&&(n["--persona-artifact-inline-bg"]=bn(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"]=bn(e,F.chromeBackground)??F.chromeBackground),F.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=bn(e,F.chromeBorder)??F.chromeBorder),F.titleColor&&(n["--persona-artifact-inline-title-color"]=bn(e,F.titleColor)??F.titleColor),F.mutedColor&&(n["--persona-artifact-inline-muted-color"]=bn(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"]=bn(e,M.background)??M.background));let B=n["--persona-surface"],H=n["--persona-container"],R=n["--persona-palette-colors-gray-100"]??"#f3f4f6",Z=n["--persona-palette-colors-gray-200"]??"#e5e7eb",V=n["--persona-palette-colors-gray-300"]??"#d1d5db",ge=!H||H===B,ae=LP(B??n["--persona-background"]),fe=ge&&ae!==void 0&&ae<IP,He=fe?"rgba(255, 255, 255, 0.08)":R,ve=fe?"rgba(255, 255, 255, 0.12)":Z,pe=fe?"rgba(255, 255, 255, 0.16)":V,et=ge?He:H,ye=ge?ve:H;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??et,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??ye,ge&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??pe),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??et,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??et,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??et,n}var vw={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 RP={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"}}},HP={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)"}}}},Cw=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},vl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",WP=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":vl()},ep=e=>WP(e),OP=e=>bl(e),BP=e=>{let t=Ki(HP,e??{})??{};return bl({...t,palette:{...t.palette,colors:{...RP.colors,...t.palette?.colors}}},{validate:!1})},Xr=e=>{let t=ep(e),n=Cw(e?.theme),o=Cw(e?.darkTheme);return t==="dark"?BP(Ki(n??{},o??{})):OP(n)},_P=e=>Zd(e),$s=(e,t)=>{let n=Xr(t),o=_P(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",ep(t))},Qi=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(vl())});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(vl());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())}};var Cr=require("lucide");var Jr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var tp="24px",_m=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",Cl=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},ww=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var xw=null;var Dm=()=>{if(xw!==null)return xw;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},DP="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",np=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},op=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 np("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(np("unsupported",e),null):(n==="space"&&(o.key=" "),o)},NP=e=>DP.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),Sw=(e,t)=>{let n=op(e);if(!n)return"";let o=Dm(),r=NP(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("+")},rp=e=>Sw(e,!1),wl=e=>Sw(e,!0),FP=(e,t)=>t.key?.toLowerCase()===e.key&&(Dm()?t.metaKey:t.ctrlKey)===e.mod&&!(Dm()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,$P=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},Aw=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(FP(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&$P(a))){s.preventDefault();try{l.run(s)}catch(d){np(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=op(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=t.get(l);return d?(np(`${d.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",wl(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}};var Mw=require("idiomorph"),sp=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Mw.Idiomorph.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 Ew=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Nm={index:-1,draft:""};function Tw(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 Pw(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 kw(){return new Map}function Lw(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Iw(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Rw(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Hw(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 Ww(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function jo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Us(e,t){return jo(e)-e.scrollTop<=t}function Ow(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 Bw(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 _w(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Fm(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 Dw(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var xl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},UP=["pre","code","a","script","style"],ip=e=>({type:e?.type??xl.type,placeholder:e?.placeholder??xl.placeholder,speed:e?.speed??xl.speed,duration:e?.duration??xl.duration,buffer:e?.buffer??xl.buffer}),Fw=[{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"}],Sl=new Map;for(let e of Fw)Sl.set(e.name,e);var $w=["wipe","glyph-cycle"],Al=e=>{Sl.set(e.name,e)},Uw=e=>{Fw.some(t=>t.name===e)||Sl.delete(e)},jw=()=>Array.from(Sl.keys()),Ml=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Sl.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},jP=(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},qP=(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},$m=/\s/,zP=(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},VP=(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($m.test(s[l])){let d=l;for(;d<s.length&&$m.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&&!$m.test(s[p]);)d.appendChild(jP(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,e)},KP=(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(qP(o,d,t,n.value)),n.value+=1));r.replaceChild(a,e)},El=(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??UP).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)zP(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=t==="char"?VP:KP;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},Tl=(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},Nw=new WeakMap,GP=(e,t)=>{if(!e.styles)return;let n=Nw.get(t);if(n||(n=new Set,Nw.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)},Um=new WeakMap,YP=(e,t)=>{if(!e.onAttach)return;let n=Um.get(t);if(n||(n=new Map,Um.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},qw=e=>{let t=Um.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Pl=(e,t)=>{GP(e,t),YP(e,t)};var{setLoader:qW,load:QP}=yt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var zw=QP;function jm(e,t=an){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 kl=0,Zr=null;function qm(e=document){if(kl++,kl===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Zr={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,kl=Math.max(0,kl-1),kl===0&&Zr)){let n=e.body,o=e.defaultView??window;n.style.overflow=Zr.originalOverflow,n.style.position=Zr.originalPosition,n.style.top=Zr.originalTop,n.style.width=Zr.originalWidth,o.scrollTo(0,Zr.scrollY),Zr=null}}}var Ll={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},At=e=>(e?.launcher?.mountMode??"floating")==="docked",es=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",_n=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ll.side,width:t?.width??Ll.width,animate:t?.animate??Ll.animate,reveal:t?.reveal??Ll.reveal,maxHeight:t?.maxHeight??Ll.maxHeight}};var Kw=require("lucide");var zm=e=>e==="followUp"?"follow-up":e,Vm=(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"}},XP=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'}},Vw=new WeakSet,JP=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,ZP=e=>{JP()||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"})})},Km=e=>{var D,T,I;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:d,chipsConfig:p,session:u,getTextarea:m,eventTarget:y,submitPrompt:h}=e,v=o==="followUp",x=t.behavior,w=()=>{if(u.isStreaming())return;let A={suggestion:{...t},surface:o,source:r,behavior:x},_=y.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:A,bubbles:!0,composed:!0,cancelable:!0}));if(v&&y.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!_)return;for(let le of d)if(le.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let G=m();if(x==="fill"){G.value=t.prompt,G.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),G.focus();return}if(h){h(t.prompt);return}G.value="",u.sendMessage(t.prompt)},k=()=>{let A=E("button",`persona-suggestion persona-suggestion--${s}`);if(A.type="button",A.disabled=a,A.dataset.suggestionId=t.id,A.dataset.emphasis=t.emphasis,A.dataset.behavior=x,s==="chip"&&(p?.fontFamily&&(A.style.fontFamily=XP(p.fontFamily)),p?.fontWeight&&(A.style.fontWeight=p.fontWeight),p?.paddingX&&(A.style.paddingLeft=p.paddingX,A.style.paddingRight=p.paddingX),p?.paddingY&&(A.style.paddingTop=p.paddingY,A.style.paddingBottom=p.paddingY)),t.icon){let G=de(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);G&&(G.classList.add("persona-suggestion__icon"),t.iconColor&&(G.style.color=t.iconColor),A.appendChild(G))}let _=E("span","persona-suggestion__copy");if(_.appendChild(Y("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&_.appendChild(Y("span",{className:"persona-suggestion__description",text:t.description})),A.appendChild(_),s!=="chip"){let G=Ht(Kw.ArrowRight,16,"currentColor",1.8);G&&(G.classList.add("persona-suggestion__arrow"),A.appendChild(G))}return A.addEventListener("click",w),A},O=null;for(let A of d)if(A.renderSuggestion&&(O=A.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:k,select:w}),O))break;return O??(O=k()),(D=O.dataset).suggestionId||(D.suggestionId=t.id),(T=O.dataset).behavior||(T.behavior=x),(I=O.dataset).emphasis||(I.emphasis=t.emphasis),O instanceof HTMLButtonElement||O.setAttribute("aria-disabled",a?"true":"false"),O},Il=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,e.scrollWidth-e.clientWidth);if(u<=1){s();return}let m=getComputedStyle(e).direction==="rtl",y=Math.min(u,Math.max(0,Math.abs(e.scrollLeft))),h=4,v=y<=h,x=y>=u-h,w=m?!x:!v,k=m?!v:!x;e.toggleAttribute("data-scroll-left",w),e.toggleAttribute("data-scroll-right",k)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,m,y,h,v,x)=>{e.replaceChildren(),t.length=0,n.length=0;let w=x?.source??"config",k=x?.surface??(w==="config"?"starter":"followUp"),O=k==="followUp",D=x?.variant??"chip",T=x?.behavior??"send",I=x?.overflow??"wrap",A=x?.config??{},_=x?.plugins??[],G=typeof x?.maxItems=="number"?Math.max(0,Math.floor(x.maxItems)):void 0,le=O?"followUps":"starters";!Vw.has(A)&&A.debug===!0&&D!=="chip"&&A.suggestions?.[le]?.overflow!==void 0&&(Vw.add(A),console.info(`[persona] suggestions.${le}.overflow applies to the "chip" variant only; the "${D}" variant manages its own stacking.`));let ee=V=>V.map(Vm).filter(ge=>ge!==null).map(ge=>({...ge,behavior:ge.behavior??T})),M=ee(u??[]);_.forEach(V=>{V.transformSuggestions&&(M=ee(V.transformSuggestions({suggestions:M.map(ge=>({...ge})),surface:k,source:w,config:A})))});let B=G===void 0?M:M.slice(0,G);if(!B.length){e.hidden=!0,o=null,s();return}if(!O&&(h??m.getMessages()).some(ge=>ge.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=zm(k),e.dataset.variant=D,e.dataset.overflow=I;let H=document.createDocumentFragment(),R=m.isStreaming();B.forEach((V,ge)=>{let ae=Km({item:V,index:ge,surface:k,source:w,variant:D,streaming:R,config:A,plugins:_,chipsConfig:v,session:m,getTextarea:()=>y,eventTarget:e,submitPrompt:x?.submitPrompt});H.appendChild(ae),n.push(ae),[...ae instanceof HTMLButtonElement?[ae]:[],...Array.from(ae.querySelectorAll("button"))].forEach(He=>{t.includes(He)||(He.disabled=R,t.push(He))})}),e.appendChild(H),a(),l();let Z=JSON.stringify({normalized:B,surface:k,variant:D,source:w});Z!==o&&(o=Z,ZP(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:B.map(V=>({...V})),surface:k,source:w,variant:D},bubbles:!0,composed:!0})),O&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:B.map(V=>V.prompt)},bubbles:!0,composed:!0})))}}};var 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 ek="persona-header-control",tk="persona-header-control--glyph",nk="persona-header-control--sparse",ok=20,rk={x:[1.4,1.05]},Gw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",sk="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",cp=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=rk[t]??[1,1.5],l=!o;e.classList.toggle(tk,l),e.classList.toggle(nk,l&&s!==1);let d=parseFloat(o??"")||ok,p=de(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)},js=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=Gw,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:y,borderRadius:h,paddingX:v,paddingY:x,hidden:w,extraClassName:k,attrs:O}=e,D=E("div",a),T=!!(m||y),I=Y("button",{className:hn(ek,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!T&&"persona-border-none",!h&&"persona-rounded-full",k),attrs:{type:"button","aria-label":t,...O},style:{width:l,height:l,minWidth:l,minHeight:l,display:w?"none":void 0,color:p||vn.actionIconColor,backgroundColor:u,border:T?`${m||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:h,paddingLeft:v,paddingRight:v,paddingTop:x,paddingBottom:x}});return r?cp(I,r,{iconSize:d,iconText:s}):s&&(I.textContent=s),D.appendChild(I),tn({anchor:I,trigger:D,text:()=>I.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:I,wrapper:D}},Xi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Gw,buttonSize:r,iconSize:s}=t,a=e?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=js({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=sk,buttonSize:o,iconSize:r}=t,a=(e?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=js({ariaLabel:l,tooltip:d,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:p,wrapper:u}};var vn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))",minHeight:"var(--persona-header-min-height, auto)"},Gm={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},ik={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)"},hr=e=>{let{config:t,showClose:n=!0}=e,o=Y("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{minHeight:vn.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,p=Y("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(d){let I=parseFloat(s)||24,A=de(d,I*.6,"currentColor",1);A?p.replaceChildren(A):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let I=E("img");I.src=t.launcher.iconUrl,I.alt="",I.className="persona-rounded-xl persona-object-cover",I.style.height=s,I.style.width=s,p.replaceChildren(I)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let u=E("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Y("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:vn.titleColor,...Gm}}),y=Y("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:vn.subtitleColor,...ik}});u.append(m,y),l?o.append(u):o.append(p,u);let h=r.clearChat??{},v=h.enabled??!0,x=h.placement??"inline",w=null,k=null;if(v){let A=Ji(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});w=A.button,k=A.wrapper,x==="top-right"&&(k.style.right="48px"),x==="inline"&&o.appendChild(k)}let O=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:D,wrapper:T}=Xi(t,{showClose:n,wrapperClassName:O});return a!=="top-right"&&o.appendChild(T),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:y,closeButton:D,closeButtonWrapper:T,clearChatButton:w,clearChatButtonWrapper:k}},qs=(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 zs(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(Vi)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let v of t){if(v.dividerBefore){let k=document.createElement("hr");l.appendChild(k)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",v.id),v.destructive&&x.setAttribute("data-destructive",""),v.icon){let k=de(v.icon,16,"currentColor",1.5);k&&x.appendChild(k)}let w=document.createElement("span");w.textContent=v.label,x.appendChild(w),x.addEventListener("click",k=>{k.stopPropagation(),m(),n(v.id)}),l.appendChild(x)}let d=null;function p(){if(!s)return;let v=o.getBoundingClientRect();l.style.top=`${v.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-v.right}px`,l.style.left="auto"):(l.style.left=`${v.left}px`,l.style.right="auto")}function u(){let v=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),v&&a?.(!0),requestAnimationFrame(()=>{let x=w=>{!l.contains(w.target)&&!o.contains(w.target)&&m()};document.addEventListener("click",x,!0),d=()=>document.removeEventListener("click",x,!0)})}function m(){let v=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,v&&a?.(!1)}function y(){l.classList.contains("persona-hidden")?u():m()}function h(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:m,toggle:y,destroy:h}}function Dn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=e,p=E("button",hn(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=de(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 Ym(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=de(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 Rl(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=Dn({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 Yw(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:d="bottom-left",portal:p,chevronLabel:u="More options",chevronIconSize:m,className:y,primaryClassName:h,chevronClassName:v}=e,x=E("div","persona-split-btn"+(y?" "+y:"")),w={label:t,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},k=r&&n?Dn({...w,icon:n,size:o??14}):Ym({...w,icon:n,iconSize:o??14}),O=Dn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(v?" "+v:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});x.append(k,O);let D=null,T=()=>{if(D)return D;let I=(typeof p=="function"?p():p)??void 0;return D=zs({items:s,onSelect:a,anchor:x,position:d,portal:I,onOpenChange:A=>{O.setAttribute("aria-expanded",A?"true":"false")}}),I||x.appendChild(D.element),D};return x.isConnected?T():requestAnimationFrame(()=>{D||T()}),O.addEventListener("click",I=>{I.stopPropagation(),T().toggle()}),{element:x,primaryButton:k,chevronButton:O,openMenu:()=>T().show(),closeMenu:()=>D?.hide(),toggleMenu:()=>T().toggle(),destroy:()=>{D?.destroy(),x.remove()}}}function dp(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=de(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=zs({items:o,onSelect:v=>{p.setAttribute("aria-expanded","false"),r(v)},anchor:p,position:s,portal:a});a||p.appendChild(y.element);let h=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",v=>{if(v.stopPropagation(),h())return;let x=!y.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",x?"false":"true"),y.toggle()}),p.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),p.click())}),{element:p,setLabel:v=>{u.textContent=v,p.setAttribute("aria-label",v)},open:()=>{p.setAttribute("aria-expanded","true"),y.show()},close:()=>{p.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let v=!y.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",v?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),p.remove()}}}var Qm=e=>{let t=hr({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 ak(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=js({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?rp(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=wl(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=zs({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 Xm=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=vn.minHeight,l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r?.titleMenu,p,u;if(d){let T=dp({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:I=>{let A=G=>{G===!1&&T.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:I}}))},_=d.onSelect(I);_ instanceof Promise?_.then(A,()=>{}):A(_)},hover:d.hover,className:""});p=T.element,p.style.color=vn.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=vn.titleColor,Object.assign(u.style,Gm),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let I=r.onTitleClick;p.addEventListener("click",A=>{A.target.closest("button")||I()}),p.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),I())})}let T=r?.titleRowHover;T&&(p.style.borderRadius=T.borderRadius??"10px",p.style.padding=T.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=T.background??"",p.style.borderColor=T.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:y,wrapper:h}=Xi(t,{showClose:n,wrapperClassName:m});o&&y.addEventListener("click",o);let v=E("div","persona-flex persona-items-center persona-gap-1");d||ak(v,r?.trailingActions,r?.onAction??s);let x=a.clearChat??{},w=null,k=null;if(x.enabled??!0){let T=x.placement??"inline",I=Ji(t,{wrapperClassName:T==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});w=I.button,k=I.wrapper,T==="top-right"?k.style.right="48px":v.appendChild(k)}v.appendChild(h),l.appendChild(v);let O=E("div");O.style.display="none";let D=E("span");return D.style.display="none",{header:l,iconHolder:O,headerTitle:u,headerSubtitle:D,closeButton:y,closeButtonWrapper:h,clearChatButton:w,clearChatButtonWrapper:k}},pp={default:Qm,minimal:Xm},Jm=e=>pp[e]??pp.default,Zi=(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=Jm(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 Vs=e=>{let{config:t}=e,n=Y("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=zd(),r=Y("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}=$d(t);a();let l=Ud(t),d=Yi(t),p=jd(t),u=qd(t),m=Y("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=Y("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=Y("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),v=Y("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return p&&h.append(p.wrapper),d&&v.append(d.wrapper),v.append(l.wrapper),y.append(h,v),r.append(y),r.addEventListener("click",x=>{x.target!==l.button&&x.target!==l.wrapper&&x.target!==d?.button&&x.target!==d?.wrapper&&x.target!==p?.button&&x.target!==p?.wrapper&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,header:m,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:u,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:y,leftActions:h,rightActions:v,setSendButtonMode:l.setMode}};var up=require("lucide");var Qw=()=>{let e=Y("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=Ht(up.MessageSquare,16,"currentColor",1.5);n&&t.appendChild(n);let o=E("span","persona-pill-peek__text"),r=E("span","persona-pill-peek__caret"),s=Ht(up.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},gp=e=>{let{config:t}=e,n=Y("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=zd(),r=qd(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=$d(t,{defaultMaxLines:5});a();let l=Ud(t),d=Yi(t),p=jd(t);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=Y("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=Y("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});p&&m.append(p.wrapper);let y=Y("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&y.append(d.wrapper),y.append(l.wrapper),u.addEventListener("click",x=>{x.target!==l.button&&x.target!==l.wrapper&&x.target!==d?.button&&x.target!==d?.wrapper&&x.target!==p?.button&&x.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,y);let h=Y("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(h),p&&h.append(p.previewsContainer),n.append(o,u,r);let v=u;return{footer:n,suggestions:o,composerForm:u,header:h,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:v,leftActions:m,rightActions:y,setSendButtonMode:l.setMode}};var lk=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}},ck=(e,t)=>{if(!e)return null;let n=lk(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},dk=(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},pk=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},ef=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(":"))},tf=320,tx=320,uk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),gk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),mk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),fk=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),hk=e=>{if(!e||e.length===0)return null;let t=Y("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Y("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=E("span","persona-mention-chip-icon"),s=de(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Y("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},yk=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(yl(o.ref,{readonly:!0,render:t}))}return n},Xw="\uE000",Jw="\uE001",bk=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${Xw}${r}:${y}${Jw}`,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(yk(t,o));return}e.innerHTML=l;let p=new RegExp(`${Xw}${r}:(\\d+)${Jw}`),u=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let y=u.nextNode();y;y=u.nextNode())m.push(y);for(let y of m){let h=y;for(let v=p.exec(h.data);v;v=p.exec(h.data)){let x=t[Number(v[1])],w=h.splitText(v.index);w.data=w.data.slice(v[0].length),x?.kind==="mention"&&w.parentNode?.insertBefore(yl(x.ref,{readonly:!0,render:o}),w),h=w}}},vk=(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=`${tf}px`,p.style.maxHeight=`${tx}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}),pk(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}},Ck=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(!ef(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=`${tf}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},wk=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(!ef(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=`${tf}px`,r.style.maxHeight=`${tx}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}},xk=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(!ef(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}},Ks=()=>{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},nf=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Ks};if(t){let r=t(o);if(r!==null)return r}return Ks()},Sk=(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},Zw=(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},Hl=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},ex={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"}},Ak=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=ex[n??"bubble"]??ex.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)`)},mp="custom:",Mk=e=>`${mp}${e}`,nx=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),of=(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=nx(t,e.role);if(!r&&!s&&!a&&!l&&!d&&!p&&!u&&m.length===0){let D=E("div");return D.style.display="none",D.id=`actions-${e.id}`,D.setAttribute("data-actions-for",e.id),D}let y=t.visibility??"hover",h=t.align??"right",v=t.layout??"pill-inside",x={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[h],w={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[v],k=E("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${x} ${w} ${y==="hover"?"persona-message-actions-hover":""}`);k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id);let O=(D,T,I)=>{let A=Dn({icon:D,label:T,size:14,className:"persona-message-action-btn",chromeless:!0});return A.setAttribute("data-action",I),A};r&&k.appendChild(O("copy","Copy message","copy")),l&&k.appendChild(O("volume-2","Read aloud","read-aloud")),s&&k.appendChild(O("thumbs-up","Upvote","upvote")),a&&k.appendChild(O("thumbs-down","Downvote","downvote")),d&&k.appendChild(O("refresh-cw","Regenerate response","regenerate")),p&&k.appendChild(O("pencil","Edit message","edit")),u&&k.appendChild(O("quote","Quote message","quote"));for(let D of m)k.appendChild(O(D.iconName??"ellipsis",D.label,Mk(D.id)));return k},ea=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",d=a.avatar,p=a.timestamp,u=d?.show??!1,m=p?.show??!1,y=d?.position??"left",h=p?.position??"below",v=Hl(e.role,l),x=E("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let w=s?.widgetConfig?.theme?.components?.message;Ak(x,e.role,l,e.role==="user"?w?.user:w?.assistant),l==="flat"?(x.style.backgroundColor="transparent",x.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=uk(e),O=e.content?.trim()??"",T=k.length>0&&O===$i,I=ip(s?.widgetConfig?.features?.streamAnimation),A=s?.widgetConfig?.features?.streamAnimation?.plugins,_=e.role==="assistant"&&I.type!=="none"?Ml(I.type,A):null,G=e.role==="assistant"&&_?.isAnimating?.(e)===!0,le=e.role==="assistant"&&_!==null&&(!!e.streaming||G);le&&_?.bubbleClass&&x.classList.add(_.bubbleClass);let ee=document.createElement("div");ee.classList.add("persona-message-content"),e.streaming&&ee.classList.add("persona-content-streaming"),le&&_&&(_.containerClass&&ee.classList.add(_.containerClass),ee.style.setProperty("--persona-stream-step",`${I.speed}ms`),ee.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let M=le?ap(e.content??"",I.buffer,_,e,!!e.streaming):e.content??"",B=()=>{let ye=t({text:M,message:e,streaming:!!e.streaming,raw:e.rawContent});return le&&_?.wrap==="char"?El(ye,"char",e.id,{skipTags:_.skipTags}):le&&_?.wrap==="word"?El(ye,"word",e.id,{skipTags:_.skipTags}):ye},H=null;if(T?(H=document.createElement("div"),H.innerHTML=B(),H.style.display="none",ee.appendChild(H)):e.contentSegments?.length?bk(ee,e.contentSegments,ye=>t({text:ye,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):ee.innerHTML=B(),le&&_?.useCaret&&!T&&O){let ye=lp(),F=ee.querySelectorAll(".persona-stream-char, .persona-stream-word"),_e=F[F.length-1];if(_e?.parentNode)_e.parentNode.insertBefore(ye,_e.nextSibling);else{let qe=ee.lastElementChild;qe?qe.appendChild(ye):ee.appendChild(ye)}}if(m&&h==="inline"&&e.createdAt){let ye=Zw(e,p,"span");ye.classList.add("persona-timestamp-inline");let F=ee.lastElementChild;F?F.appendChild(ye):ee.appendChild(ye)}if(k.length>0){let ye=vk(k,!T&&!!O,()=>{T&&H&&(H.style.display="")});ye?x.appendChild(ye):T&&H&&(H.style.display="")}let R=gk(e);if(R.length>0){let ye=Ck(R);ye&&x.appendChild(ye)}let Z=mk(e);if(Z.length>0){let ye=wk(Z);ye&&x.appendChild(ye)}let V=fk(e);if(V.length>0){let ye=xk(V);ye&&x.appendChild(ye)}let ge=e.contentSegments?.length?null:hk(e.contextMentions);if(ge&&x.appendChild(ge),x.appendChild(ee),m&&h==="below"&&e.createdAt){let ye=Zw(e,p);ye.classList.add("persona-mt-1"),x.appendChild(ye)}let ae=e.role==="assistant"?ck(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ye=!!(M&&M.trim()),F=I.placeholder==="skeleton",_e=F&&I.buffer==="line"&&ye;if(ye)_e&&x.appendChild(Tl());else if(F)x.appendChild(Tl());else{let qe=nf("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);qe&&x.appendChild(qe)}}ae&&e.stopReason&&!e.streaming&&(O||(ee.style.display="none"),x.appendChild(dk(e.stopReason,ae)));let fe=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1,He=s?.actionEligibility,ve=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&He?.canEdit===!0||o?.showQuote===!0&&He?.canQuote===!0||nx(o,"user").length>0);if((fe||ve)&&o){let ye=of(e,ve?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,He);x.appendChild(ye)}if(!u||e.role==="system")return x;let pe=E("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),et=Sk(d,e.role);return y==="right"||y==="left"&&e.role==="user"?pe.append(x,et):pe.append(et,x),pe},ox=(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}):ea(e,t,n,o,r,s)};var Ek=40,Tk=(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=de(t.name,Ek);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(Y("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Y("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},rx=(e,t,n={})=>{let o=Y("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=Y("div",{className:"persona-welcome-head-text"},r,s),d=Y("div",{className:"persona-welcome-title-row"},o,l);return{host:Y("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}},ta=(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)},hp=(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==="",Tk(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")},Pk="data-persona-welcome-plugin",sx="data-persona-welcome-overlay",fp="persona-welcome-overlay-active",rf=new WeakMap,sf=(e,t,n)=>{n.setAttribute(Pk,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(sx,""),e.classList.contains(fp)||(rf.set(e,e.scrollTop),e.classList.add(fp),e.scrollTop=0)},af=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(sx),e.classList.contains(fp)&&(e.classList.remove(fp),e.scrollTop=rf.get(e)??e.scrollTop,rf.delete(e))},ix=()=>{let e=Y("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},yp=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Y("div",{className:Hl("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(Y("div",{className:"persona-flex"},r)),e.hidden=!1},ax=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,lx=(e,t)=>{if(ax()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,a=0;if(o){let v=getComputedStyle(o);r=parseFloat(v.rowGap)||0;let x=e.previousElementSibling,w=e.nextElementSibling,O=o.getBoundingClientRect().top+(parseFloat(v.borderTopWidth)||0)+(parseFloat(v.paddingTop)||0)-o.scrollTop;s=Math.max(0,x?n.top-x.getBoundingClientRect().bottom-r:n.top-O),a=Math.max(0,w?w.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let d=getComputedStyle(e),p=parseFloat(d.paddingTop)||0,u=parseFloat(d.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${u}px`,marginTop:`${s}px`,marginBottom:`${a}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),y=!1,h=()=>{y||(y=!0,e.style.overflow=l,t(m))};return m.finished.then(h).catch(h),m},cx=(e,t,n)=>{if(t<=1||ax()||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 kk="Hello \u{1F44B}",Lk="I can answer questions and help you get things done here.",dx=new WeakSet,Cn=(e,t)=>!!e&&e[t]!==void 0,Ik=(e,t)=>{!e||e.debug!==!0||!t.length||dx.has(e)||(dx.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},xo=e=>{let t=e?.welcome,n=e?.copy,o=Cn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":Cn(t,"dismiss")?t.dismiss:"never",s=[];Cn(t,"title")&&Cn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Cn(t,"subtitle")&&Cn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Cn(t,"variant")&&Cn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&Cn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&Cn(t,"dismiss")&&t.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let a=t?.anchor==="center"?"center":"bottom",l=Cl(t?.anchorComposerTop)!==null;return Cn(t,"anchorComposerTop")&&!l&&s.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),a!=="center"&&(Cn(t,"anchorComposerTop")||Cn(t,"composerGap"))&&s.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),Ik(e,s),{title:Cn(t,"title")?t.title:n?.welcomeTitle??kk,kicker:t?.kicker??"",subtitle:Cn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??Lk,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()||tp}},px=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",ts=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var ux="16px",cf="10px",df="14px",gx=e=>{let t=e?.launcher?.enabled??!0,n=At(e);if(es(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??an);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??an),{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&&Qn[r.position]?Qn[r.position]:Qn["bottom-right"],a=E("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??an);let l=E("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=e?.launcher?.width??e?.launcherWidth??Gn;return l.style.width=p,l.style.maxWidth=p,a.appendChild(l),{wrapper:a,panel:l}},pf=e=>{let t=Y("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":zm(e)}});return t.hidden=!0,t},mx=(e,t)=>{let n=pf("starter"),o=rx(e,n,{flatShadow:At(e)}),r=xo(e);hp(o,r),ta(t,o.host,ts(r,e?.initialMessages));let s=ix();return yp(s,r.message,e),{welcome:o,greetingHost:s}},Rk=(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}=Xi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:ux,iconSize:cf});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:ux,iconSize:df});a=_.button,l=_.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=Y("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=Y("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}=mx(e,p),{host:y,title:h,subtitle:v}=u,x=u.starterSuggestions,w=E("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),k=pf("followUp"),O=Jr(e,!0);O&&(w.style.maxWidth=O,w.style.marginLeft="auto",w.style.marginRight="auto",w.style.width="100%"),p.append(y,m,w,k);let D=Y("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=gp({config:e}),{root:I,textNode:A}=Qw();return n.append(d,r,p,D),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:w,starterSuggestions:x,transcriptSuggestions:k,composerOverlay:D,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:y,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:h,introSubtitle:v,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:E("span"),headerTitle:E("span"),headerSubtitle:E("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:I,peekTextNode:A}},fx=(e,t=!0)=>{if(es(e))return Rk(e,t);let n=Y("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?Zi(e,o,{showClose:t}):hr({config:e,showClose:t}),a=Y("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}=mx(e,a),{host:p,title:u,subtitle:m}=l,y=l.starterSuggestions,h=E("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),v=pf("followUp"),x=Jr(e,!1);x&&(h.style.maxWidth=x,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),a.append(p,d,h,v);let w=Vs({config:e}),k=e?.layout?.showFooter!==!1;r?qs(n,s,e):(s.header.style.display="none",qs(n,s,e)),n.append(a);let O=Y("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return k||(w.footer.style.display="none"),n.append(w.footer),n.append(O),{container:n,body:a,messagesWrapper:h,starterSuggestions:y,transcriptSuggestions:v,composerOverlay:O,suggestions:w.suggestions,textarea:w.textarea,sendButton:w.sendButton,sendButtonWrapper:w.sendButtonWrapper,micButton:w.micButton,micButtonWrapper:w.micButtonWrapper,composerForm:w.composerForm,statusText:w.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:d,introKicker:l.kicker,introTitle:u,introSubtitle:m,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:w.footer,attachmentButton:w.attachmentButton,attachmentButtonWrapper:w.attachmentButtonWrapper,attachmentInput:w.attachmentInput,attachmentPreviewsContainer:w.attachmentPreviewsContainer,actionsRow:w.actionsRow,leftActions:w.leftActions,rightActions:w.rightActions,setSendButtonMode:w.setSendButtonMode}};var uf=(e,t)=>{let n=E("button");n.type="button",n.innerHTML=`
|
|
29
29
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
30
30
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
31
31
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -33,14 +33,14 @@ _Details: ${n.message}_`:o}var gm=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
33
33
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
|
|
34
34
|
</span>
|
|
35
35
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
36
|
-
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=Et(s),d=n.querySelector("[data-role='launcher-title']");if(d){let $=a.title??"Chat Assistant";d.textContent=$,d.setAttribute("title",$)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let $=a.subtitle??"Here to help you get answers fast";p.textContent=$,p.setAttribute("title",$)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||l?u.style.display="none":u.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let $=a.agentIconSize??"40px";if(m.style.height=$,m.style.width=$,a.agentIconBackgroundColor?(m.style.backgroundColor=a.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",a.agentIconName){let T=parseFloat($)||24,R=ge(a.agentIconName,T*.6,"var(--persona-text-inverse, #ffffff)",1.5);R?(m.appendChild(R),m.style.display=""):(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let $=a.agentIconSize??"40px";y.style.height=$,y.style.width=$,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let h=n.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let $=a.callToActionIconSize??"32px";h.style.height=$,h.style.width=$,a.callToActionIconBackgroundColor?(h.style.backgroundColor=a.callToActionIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(h.style.color=a.callToActionIconColor,h.classList.remove("persona-text-persona-call-to-action")):(h.style.color="",h.classList.add("persona-text-persona-call-to-action"));let T=0;if(a.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=a.callToActionIconPadding,T=(parseFloat(a.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),a.callToActionIconHidden)h.style.display="none";else if(h.style.display=l?"none":"",h.innerHTML="",a.callToActionIconName){let R=parseFloat($)||24,A=Math.max(R-T,8),N=ge(a.callToActionIconName,A,"currentColor",1.5);N?h.appendChild(N):h.textContent=a.callToActionIconText??"\u2197"}else h.textContent=a.callToActionIconText??"\u2197"}let C=a.position&&Gn[a.position]?Gn[a.position]:Gn["bottom-right"],S="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",x="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?x:`${S} ${C}`,l||(n.style.zIndex=String(a.zIndex??ln));let P="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",O="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??P,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:O,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},PP="teaser-dismissed",mx=new Set,gx=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${PP}`},LP=(e,t)=>{if(mx.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},IP=(e,t)=>{if(mx.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},RP=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,HP=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Et(e??{})?null:t},fx=(e,t)=>{let n=M("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,a=null,l=null,d=null,p=!1,u=!1,m=!1,y=!1,h=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,C=()=>{d!==null&&(clearTimeout(d),d=null)},S=()=>{!s||!p||(p=!1,s.hidden=!0)},x=te=>{C(),m=!0,S(),IP(gx(o),te&&h())},P=te=>{!r||m||x(te==="user"&&p)},O=()=>{d=null,!(!s||m||y)&&(u=!0,p=!0,s.hidden=!1,!(RP()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},$=()=>{!r||!s||m||u||y||LP(gx(o),h())||(C(),d=setTimeout(O,Math.max(0,r.delayMs??0)))},T=()=>{x(h()),t()},R=te=>{te.stopPropagation(),x(h())},N=uf(e,()=>{P("user"),t()}),Y=()=>{C(),l?.removeEventListener("click",T),a?.removeEventListener("click",R),s?.remove(),s=null,l=null,a=null,p=!1},ce=()=>{l=X("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",T),a=X("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",R),s=X("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,N.element)},Q=()=>{let te=o.launcher?.position??"bottom-right",K=Gn[te]??Gn["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",N.element.style.position="";return}n.className=yn("persona-launcher-surface",K),n.setAttribute("data-teaser",te),n.style.zIndex=String(o.launcher?.zIndex??ln),N.element.style.position="static"},E=te=>{let K=HP(te);if(r=K,!K){Y();return}s||ce(),l.textContent=K.text,a.hidden=K.dismissible===!1,a.setAttribute("aria-label",K.dismissLabel??"Dismiss message"),$()},B=te=>{o=te,N.update(te),E(te),Q()},H=(te,K="user")=>{y=te,te&&P(K)},L=()=>{Y(),N.destroy(),n.remove()};return n.appendChild(N.element),e&&(E(e),Q()),{element:n,launcher:N,get teaser(){return s?{element:s,show:O,dismiss:x}:null},setPanelOpen:H,update:B,destroy:L}};var hx=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=dx(e),s=ux(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}}},gf=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>uf(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=fx(e,n);return{instance:r,element:r.element}};var WP=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},OP=(e,t,n)=>`${WP(e)}plugin:${t}:${n}`,yx=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=>OP(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 la=(e,t,n)=>{let o=n;for(let r of t){let s=M("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};var wp=require("lucide");var BP=["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"],_P="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",DP="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",NP=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),xp=(e,t)=>{let n=M("div",["persona-message-bubble",e,...BP].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},Sp=e=>{let t=M("button",e.expandable?_P:DP);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},mf=(e,t,n)=>{e.innerHTML="";let o=Bt(t?wp.ChevronUp:wp.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},Ap=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=M("div","persona-flex persona-items-center");mf(o,n.expanded,n.iconColor);let r=M("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),e.append(t,r),o},Mp=e=>{let t=M("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();NP(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Ep=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&mf(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"},Tp=(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&&mf(d,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};var ca=new Set,FP=(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
|
-
`);let r=
|
|
39
|
-
`):""},hf=(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)"},UP=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=$P(e,o?.previewMaxLines??3),a=n?Rv(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=nm(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=nm(n,d.completeTextTemplate,p)),{summary:p,previewText:s,isActive:l}},Cx=(e,t,n)=>{Tp(e,t,{stateSet:da,previewKind:"tool",iconColor:vx(n?.toolCall??{})})},yf=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=xp("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&&da.has(e.id),{summary:d,previewText:p,isActive:u}=UP(e,t),m=Sp({expandable:a,expanded:l,bubbleType:"tool"});o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let y=M("div","persona-flex persona-flex-col persona-text-left"),h=M("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(h.style.color=o.headerTextColor);let C=String(n.startedAt??Date.now()),S=()=>{let E=M("span","");return E.setAttribute("data-tool-elapsed",C),E.textContent=gl(n),E},x=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:t??{},elapsed:gl(n),createElapsedElement:S});typeof x=="string"&&x.trim()?(h.textContent=x,y.appendChild(h)):x instanceof HTMLElement?y.appendChild(x):(h.textContent=d,y.appendChild(h));let P=s.loadingAnimation??"none",O=o.activeTextTemplate,$=o.completeTextTemplate,T=u?O:$,R=x instanceof HTMLElement,A=(E,B)=>{h.textContent="";let H=n.name?.trim()||"tool",L=Ad(E,H),te=0;for(let K of L){let me=K.styles.length>0?(()=>{let de=M("span",K.styles.map(he=>`persona-tool-text-${he}`).join(" "));return h.appendChild(de),de})():h;if(K.isDuration&&u)me.appendChild(S());else{let de=K.isDuration?gl(n):K.text;B?te=la(me,de,te):me.appendChild(document.createTextNode(de))}}};if(!R)if(u&&P!=="none"){let E=o.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),P==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${E}ms`),T&&A(T,!1);else if(h.classList.add(`persona-tool-loading-${P}`),h.style.setProperty("--persona-tool-anim-duration",`${E}ms`),P==="shimmer-color"&&(o.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),T)A(T,!0);else{let B=h.textContent||d;h.textContent="",la(h,B,0)}}else T&&A(T,!1);let N=vx(o),Y=Ap(m,y,{expandable:a,expanded:l,iconColor:N,metaGap:!0}),ce=Mp({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,ce),r;let Q=M("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(Q.style.display=l?"":"none",o.contentBackgroundColor&&(Q.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(Q.style.color=o.contentTextColor),o.contentPaddingX&&(Q.style.paddingLeft=o.contentPaddingX,Q.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(Q.style.paddingTop=o.contentPaddingY,Q.style.paddingBottom=o.contentPaddingY),n.name){let E=M("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?E.style.color=o.contentTextColor:o.headerTextColor&&(E.style.color=o.headerTextColor),E.textContent=n.name,Q.appendChild(E)}if(n.args!==void 0){let E=M("div","persona-space-y-1"),B=M("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Arguments";let H=M("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",hf(H,o),H.textContent=wd(n.args),E.append(B,H),Q.appendChild(E)}if(n.chunks&&n.chunks.length){let E=M("div","persona-space-y-1"),B=M("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Activity";let H=M("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",hf(H,o),H.textContent=n.chunks.join(""),E.append(B,H),Q.appendChild(E)}if(n.status==="complete"&&n.result!==void 0){let E=M("div","persona-space-y-1"),B=M("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Result";let H=M("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",hf(H,o),H.textContent=wd(n.result),E.append(B,H),Q.appendChild(E)}if(n.status==="complete"&&typeof n.duration=="number"){let E=M("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(E.style.color=o.contentTextColor),E.textContent=`Duration: ${n.duration}ms`,Q.appendChild(E)}return Ep({expanded:l,header:m,toggleIcon:Y,content:Q,collapsedPreview:ce,iconColor:N}),r.append(m,ce,Q),r};var{setLoader:OB,load:jP,provide:BB,getSync:qP}=wt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var wx=jP;var xx=qP;var{setLoader:NB,load:zP}=wt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var bf=zP;var vf=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)})}},Ao=new vf;var Cf=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:VB,load:VP,provide:KB,getSync:KP}=wt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),pa=null,kp=new Set,Sx=e=>{if(pa)return pa;pa=e,e.initArtifactsUi({componentRegistry:Ao});for(let o of Cf)Ao.has(o)||Ao.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=$o();t?e.__provideMarkdownParsers(t):Di(()=>{let o=$o();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>dd());let n=[...kp];kp.clear();for(let o of n)try{o()}catch{}return e};var Pp=()=>VP().then(Sx);var wr=()=>{if(pa)return pa;let e=KP();return e?Sx(e):null},wf=e=>pa?()=>{}:(kp.add(e),()=>{kp.delete(e)});function xn(e){return e?.features?.artifacts?.enabled===!0}function Ax(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"),!xn(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 GP(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 Mx=["panel","seamless","detached"];function xf(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Mx.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Sf(e){return!e||!xn(e)?!1:xf(e)==="detached"}function _l(e,t){if(!xn(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"),GP(e),Ax(e,t);return}let n=t.features?.artifacts?.layout,o=xf(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)}Ax(e,t)}function Dl(e,t){for(let l of Mx)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"),!xn(t))return;let n=t.features?.artifacts?.layout,o=xf(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 Ex(e,t){return!t||!xn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var YP=new Set(["__proto__","prototype","constructor"]),QP=new Set(["collapsed","card","panel","inline"]),Tx=new Set(["markdown","component"]),XP=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,ti=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ip=e=>!YP.has(e),Af=e=>typeof e=="string"&&QP.has(e),ni=e=>Object.keys(e).length>0;function Ko(e,t,n,o){e.push({path:t,code:n,message:o})}var JP="Ignored because this key is not part of the persisted preference schema.",Lp="Ignored an unsupported value.",ZP="Expected collapsed, panel, or inline.",e0='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',kx={kind:"mode",message:Lp},ua={kind:"string",message:"Expected a CSS length string."},xr={kind:"boolean"},t0={paneWidth:ua,paneMaxWidth:ua,paneMinWidth:ua,expandedPanelWidth:ua,resizableMinWidth:ua,resizableMaxWidth:ua,expandLauncherPanelWhenOpen:xr,resizable:xr},n0={kind:"object",message:"Expected a preference object.",children:{showToolCalls:xr,showReasoning:xr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Lp},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Lp},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Lp},expandable:xr,grouped:xr}},reasoningDisplay:{kind:"object",children:{expandable:xr,activePreview:xr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:kx,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:kx,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Tx,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Tx}}},filePreview:{kind:"object",children:{enabled:xr}},layout:{kind:"object",children:t0}}}}};function Px(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Ko(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Ko(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Ko(o,n,"invalid_value",t.message);case"mode":return Af(e)?In(e):Ko(o,n,"invalid_value",t.message);case"modeMap":{if(!ti(e))return Ko(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:Kr(a);Ip(a)&&(r?r.has(a):XP.test(d))?Af(l)?s[d]=In(l):Ko(o,`${n}.${a}`,"invalid_value",ZP):Ko(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":e0)}return ni(s)?s:void 0}case"object":{if(t.bareMode&&Af(e))return In(e);if(!ti(e))return Ko(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))(!Ip(l)||!r.includes(l))&&Ko(o,s(l),"unknown_key",JP);let a={};for(let l of r){let d=t.children[l],p=Px(e[l],d,s(l),o);if(d.deprecated&&e[l]!==void 0&&Ko(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=ti(m)&&ti(p)?{...m,...p}:p}return ni(a)?a:void 0}}}function Mf(e){let t=[];return{preferences:(e===null?void 0:Px(e,n0,"",t))??{},issues:t}}function ga(e){if(Array.isArray(e))return e.map(ga);if(!ti(e))return e;let t={};for(let[n,o]of Object.entries(e))Ip(n)&&o!==void 0&&(t[n]=ga(o));return t}function Lx(e,t){let n=ga(e);for(let[o,r]of Object.entries(t)){if(!Ip(o)||r===void 0)continue;let s=n[o];n[o]=ti(s)&&ti(r)?Lx(s,r):ga(r)}return n}function o0(e){let t={},n;for(let r of e){let s=Mf(r).preferences;n=Ix(n,s.artifacts?.display),t=Lx(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function r0(e,t){if(t===void 0)return e===void 0?void 0:ga(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}:{},...ni(r)?{byMediaType:r}:{}};return ni(s)?s:void 0}function Ix(e,t){if(t===void 0)return e===void 0?void 0:ga(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=r0(n.files,t.files),a={...o?{default:o}:{},...ni(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return ni(a)?a:void 0}function Ef(e={},t){let n=o0(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=Ix(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 Nl(e){let t=e.preferences;return!t||!ni(t)?e:{...e,features:Ef(e.features??{},[t])}}function s0(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 i0(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 a0(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function l0(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Tf(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 Rx(e,t,n,o,r,s,a=200){let l=s0(r,200),d=l0(t,n,o,a);d=Math.max(l,d);let p=i0(s);return p!==null&&(d=Math.min(d,p)),a0(e,l,d)}var{setLoader:e_,load:c0,provide:t_,getSync:d0}=wt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var Hx=c0;var Wx=d0;var kf=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()}},Fl=new kf;var Ox=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),p0=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Bx=(e,t,n)=>{if(!Ox(e)||!Ox(t)||p0.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]=Bx(e[r],t[r],s)}return o};function Rp(e,t){let n=Bx(e,t,"");return ea(n)}var _x=()=>{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 u0=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},g0=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},$l=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=u0(e),n=g0(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Pf=e=>typeof e=="string"?e:e==null?"":String(e),oi={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Pf(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Pf(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:Pf(n.text)}}},Dx=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ul=e=>{let t=new Set(Dx(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Dx(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 m0=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}},f0=e=>e.map(t=>({...t,streaming:!1})),h0=e=>e.map(t=>({...t,status:"complete"})),Hp=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?m0(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?f0(n.messages):void 0,artifacts:n.artifacts?h0(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 y0=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")},Nx=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 y0(e)},b0=async(e,t)=>{let n=await Nx(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await Nx(`${e}\0${t}`)}`}};var Fx=(e,t,n)=>{let o="",r="",s="",a=!1,l=!1,d=0,p=null,u=null,m=new Set,y=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},h=()=>{let A=y();if(!A)return p;try{return A.getItem(o)}catch{return a=!0,p}},C=(A,N)=>{if(l||A===p)return;let Y=p;p=A,d+=1;let ce={previousToken:Y,token:A,source:N,revision:d};for(let Q of m)Q(ce)},S=A=>{l||A.key!==null&&A.key!==o||C(A.key===null?null:A.newValue??null,"external")},x=(async()=>{let A=await b0(e,t);o=A.storageKey,r=A.leaseKey,s=A.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",S)})(),P=A=>new Promise(N=>setTimeout(N,A)),O=()=>{let A=y();if(!A)return null;try{let N=A.getItem(r);if(!N)return null;let Y=JSON.parse(N);return typeof Y?.expiresAt=="number"&&typeof Y?.ownerNonce=="string"?Y:null}catch{return null}},$=A=>{let N=y();if(N)try{O()?.ownerNonce===A&&N.removeItem(r)}catch{}},T=A=>new Promise(N=>{let Y=setTimeout(ce,A);function ce(){clearTimeout(Y),window.removeEventListener("storage",Q),N()}function Q(E){(E.key===null||E.key===r)&&ce()}window.addEventListener("storage",Q)}),R=async A=>{let N=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,Y=Date.now()+15e3;for(;Date.now()<Y;){let ce=y();if(!ce)break;let Q=Date.now(),E=O();if(E&&E.expiresAt>Q&&E.ownerNonce!==N){await T(Math.min(E.expiresAt-Q,500));continue}try{ce.setItem(r,JSON.stringify({ownerNonce:N,expiresAt:Q+1e4}))}catch{a=!0;break}if(await P(20+Math.random()*40),O()?.ownerNonce!==N){await T(500);continue}u=N;try{return await A()}finally{u=null,$(N)}}return A()};return{ready:x,async get(){return await x,C(h(),"external"),p},async set(A){await x;let N=y();if(N)try{N.setItem(o,A)}catch{a=!0}C(A,"local")},async clear(){await x;let A=y();if(A)try{A.removeItem(o)}catch{a=!0}C(null,"local")},revision(){return d},subscribe(A){return m.add(A),()=>{m.delete(A)}},async withFirstInitLock(A){await x;let N=globalThis.navigator?.locks;return N?.request?N.request(s,()=>A()):y()?R(A):A()},matches(A,N,Y){return A===e&&N===t&&Y===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",S),u&&$(u)}}};var{setLoader:p_,load:v0}=wt({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var Lf=v0;var If=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Sr=e=>Object.freeze({...e}),$x=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),Ux=e=>e?Sr(e):null;function jx(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){If("renderHistoryView cleanup",R)}},u=(T,R)=>{for(let A of t){let N=A[T];if(N)try{let Y=N(R);if(Y)return Y}catch(Y){If(T,Y)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),y={header:T=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:Sr(T.identityStatus),pendingAction:Ux(T.pendingAction),copy:Sr(T.copy),actions:Object.freeze({close:S.close,startNewConversation:S.startNewConversation}),defaultRenderer:T.defaultRenderer})):null,conversation:T=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:$x(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:Sr(T.state),identityStatus:Sr(T.identityStatus),copy:Sr(T.copy),...T.retry?{retry:T.retry}:{},...T.startNewConversation?{startNewConversation:T.startNewConversation}:{},defaultRenderer:T.defaultRenderer})):null},h=t.flatMap(T=>(T.railSections??[]).map(R=>({...R,placement:R.placement??"above-conversations",items:[],render:A=>R.render(Object.freeze({collapsed:A,presentation:e.getPresentation(),actions:S}))}))),C=e.createView({slots:y,renderDom:!1,onModelChange:()=>$(),railSections:h}),S=Object.freeze({...C.operations,close:e.close}),x=()=>(a=!0,C.setDomRenderEnabled(!0),C.element),P=T=>Object.freeze({conversations:Object.freeze(T.conversations.map($x)),activeConversationId:T.activeConversationId,state:Sr(T.state),pendingAction:Ux(T.pendingAction),identityStatus:Sr(T.identityStatus),nextCursor:T.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Sr(C.copy),actions:S,defaultRenderer:x,requestRender:()=>$(),onCleanup:R=>{d.push(R)}}),O=()=>{a=!1;let T=null;for(let A of t)if(A.renderHistoryView){try{T=A.renderHistoryView(P(C.getModel()))}catch(N){If("renderHistoryView",N),T=null}if(T)break}let R=!T||T.contains(C.element);return a=R,C.setDomRenderEnabled(R),T??C.element};function $(){if(!(!s||o||r)){r=!0;try{p();let T=O();if(T===l)return;let R=l;l=T,e.onElementChanged(T,R)}finally{r=!1}}}return s=!0,$(),{view:C,get element(){return l??C.element},requestRender:$,dispose:()=>{o=!0,p()}}}var C0=null;function qx(){return C0}var w0=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"]]),x0=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."]]),Rf=e=>x0.get(e)??"Conversation history is unavailable right now.";function S0(e){if(e instanceof co)return e;if(e instanceof je){let t=w0.get(e.code)??"unavailable";return new co(t,Rf(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new co("unavailable",Rf("unavailable"))}function zx(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 co("unsupported_scope",Rf("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw S0(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=zv(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:hl([],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 A0=["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"],Vx={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 Hf(e){if(!e)return Vx;let t={...Vx};for(let n of A0){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var M0="button:not([disabled])";function Wp(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=X("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),a=X("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=X("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"}},X("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),X("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),X("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=X("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(M0));if(C.length===0)return;let S=C[0],x=C[C.length-1],P=document.activeElement;h.shiftKey&&(P===S||!l.contains(P))?(h.preventDefault(),x.focus()):!h.shiftKey&&P===x&&(h.preventDefault(),S.focus())}d.addEventListener("keydown",y,!0),d.addEventListener("pointerdown",h=>{h.target===d&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),e.host.appendChild(d),s.focus()})}var ma=require("partial-json");function E0(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function T0(e,t){if(!E0(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 Op(){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=(0,ma.parse)(n,ma.STR|ma.OBJ),s=T0(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Kx(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Bp(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Ao.get(e.component);if(!s){if(Cf.includes(e.component)){Pp().catch(()=>{});let l=M("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function Gx(){let e=Op();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Yx(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 jl(e){let t=Yx(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 _p(e){let t=Yx(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 k0=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Dp(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=k0}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,y=document.createElement("div");y.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,h.appendChild(C);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,h.appendChild(S),y.appendChild(h);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-csat",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Satisfaction rating from 1 to 5");let P=[];for(let A=1;A<=5;A++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-star-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${p[A-1]}`),N.title=p[A-1],N.dataset.rating=String(A),N.innerHTML=`
|
|
36
|
+
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=At(s),d=n.querySelector("[data-role='launcher-title']");if(d){let D=a.title??"Chat Assistant";d.textContent=D,d.setAttribute("title",D)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let D=a.subtitle??"Here to help you get answers fast";p.textContent=D,p.setAttribute("title",D)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||l?u.style.display="none":u.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let D=a.agentIconSize??"40px";if(m.style.height=D,m.style.width=D,a.agentIconBackgroundColor?(m.style.backgroundColor=a.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",a.agentIconName){let T=parseFloat(D)||24,I=de(a.agentIconName,T*.6,"var(--persona-text-inverse, #ffffff)",1.5);I?(m.appendChild(I),m.style.display=""):(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=a.agentIconText??"\u{1F4AC}",m.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let D=a.agentIconSize??"40px";y.style.height=D,y.style.width=D,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let h=n.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let D=a.callToActionIconSize??"32px";h.style.height=D,h.style.width=D,a.callToActionIconBackgroundColor?(h.style.backgroundColor=a.callToActionIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(h.style.color=a.callToActionIconColor,h.classList.remove("persona-text-persona-call-to-action")):(h.style.color="",h.classList.add("persona-text-persona-call-to-action"));let T=0;if(a.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=a.callToActionIconPadding,T=(parseFloat(a.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),a.callToActionIconHidden)h.style.display="none";else if(h.style.display=l?"none":"",h.innerHTML="",a.callToActionIconName){let I=parseFloat(D)||24,A=Math.max(I-T,8),_=de(a.callToActionIconName,A,"currentColor",1.5);_?h.appendChild(_):h.textContent=a.callToActionIconText??"\u2197"}else h.textContent=a.callToActionIconText??"\u2197"}let v=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",w="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?w:`${x} ${v}`,l||(n.style.zIndex=String(a.zIndex??an));let k="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",O="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??k,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:O,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},Hk="teaser-dismissed",yx=new Set,hx=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${Hk}`},Wk=(e,t)=>{if(yx.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},Ok=(e,t)=>{if(yx.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},Bk=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,_k=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||At(e??{})?null:t},bx=(e,t)=>{let n=E("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,a=null,l=null,d=null,p=!1,u=!1,m=!1,y=!1,h=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,v=()=>{d!==null&&(clearTimeout(d),d=null)},x=()=>{!s||!p||(p=!1,s.hidden=!0)},w=Z=>{v(),m=!0,x(),Ok(hx(o),Z&&h())},k=Z=>{!r||m||w(Z==="user"&&p)},O=()=>{d=null,!(!s||m||y)&&(u=!0,p=!0,s.hidden=!1,!(Bk()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},D=()=>{!r||!s||m||u||y||Wk(hx(o),h())||(v(),d=setTimeout(O,Math.max(0,r.delayMs??0)))},T=()=>{w(h()),t()},I=Z=>{Z.stopPropagation(),w(h())},_=uf(e,()=>{k("user"),t()}),G=()=>{v(),l?.removeEventListener("click",T),a?.removeEventListener("click",I),s?.remove(),s=null,l=null,a=null,p=!1},le=()=>{l=Y("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",T),a=Y("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",I),s=Y("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,_.element)},ee=()=>{let Z=o.launcher?.position??"bottom-right",V=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=hn("persona-launcher-surface",V),n.setAttribute("data-teaser",Z),n.style.zIndex=String(o.launcher?.zIndex??an),_.element.style.position="static"},M=Z=>{let V=_k(Z);if(r=V,!V){G();return}s||le(),l.textContent=V.text,a.hidden=V.dismissible===!1,a.setAttribute("aria-label",V.dismissLabel??"Dismiss message"),D()},B=Z=>{o=Z,_.update(Z),M(Z),ee()},H=(Z,V="user")=>{y=Z,Z&&k(V)},R=()=>{G(),_.destroy(),n.remove()};return n.appendChild(_.element),e&&(M(e),ee()),{element:n,launcher:_,get teaser(){return s?{element:s,show:O,dismiss:w}:null},setPanelOpen:H,update:B,destroy:R}};var vx=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=gx(e),s=fx(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}}},gf=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>uf(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=bx(e,n);return{instance:r,element:r.element}};var Dk=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},Nk=(e,t,n)=>`${Dk(e)}plugin:${t}:${n}`,Cx=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=>Nk(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 na=(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};var bp=require("lucide");var Fk=["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"],$k="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",Uk="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",jk=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),vp=(e,t)=>{let n=E("div",["persona-message-bubble",e,...Fk].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},Cp=e=>{let t=E("button",e.expandable?$k:Uk);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},mf=(e,t,n)=>{e.innerHTML="";let o=Ht(t?bp.ChevronUp:bp.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},wp=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=E("div","persona-flex persona-items-center");mf(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},xp=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?.();jk(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Sp=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&mf(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"},Ap=(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&&mf(d,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};var oa=new Set,qk=(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
|
+
`):""},wx=(e,t)=>{Ap(e,t,{stateSet:oa,previewKind:"reasoning",iconColor:"currentColor"})},ff=(e,t)=>{let n=e.reasoning,o=vp("persona-reasoning-bubble",e.id);if(!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&oa.has(e.id),l=n.status!=="complete",d=qk(e,r.previewMaxLines??3),p=Cp({expandable:s,expanded:a,bubbleType:"reasoning"}),u=E("div","persona-flex persona-flex-col persona-text-left"),m=E("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",h=t?.reasoning??{},v=String(n.startedAt??Date.now()),x=()=>{let R=E("span","");return R.setAttribute("data-tool-elapsed",v),R.textContent=Cd(n),R},w=h.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:y,previewText:d,isActive:l,config:t??{},elapsed:Cd(n),createElapsedElement:x});typeof w=="string"&&w.trim()?(m.textContent=w,u.appendChild(m)):w instanceof HTMLElement?u.appendChild(w):(m.textContent=y,u.appendChild(m));let k=E("span","persona-text-xs persona-text-persona-primary");k.textContent=Wv(n),u.appendChild(k);let O=r.loadingAnimation??"none",D=h.activeTextTemplate,T=h.completeTextTemplate,I=l?D:T,A=w instanceof HTMLElement,_=(R,Z)=>{m.textContent="";let V=wd(R,""),ge=0;for(let ae of V){let fe=ae.styles.length>0?(()=>{let He=E("span",ae.styles.map(ve=>`persona-tool-text-${ve}`).join(" "));return m.appendChild(He),He})():m;if(ae.isDuration&&l)fe.appendChild(x());else{let He=ae.isDuration?Cd(n):ae.text;Z?ge=na(fe,He,ge):fe.appendChild(document.createTextNode(He))}}};if(!A&&I)if(k.style.display="none",m.style.display="",l&&O!=="none"){let R=h.loadingAnimationDuration??2e3;m.setAttribute("data-preserve-animation","true"),O==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${R}ms`),_(I,!1)):(m.classList.add(`persona-tool-loading-${O}`),m.style.setProperty("--persona-tool-anim-duration",`${R}ms`),O==="shimmer-color"&&(h.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor)),_(I,!0))}else _(I,!1);else if(!A&&l&&O!=="none"){m.style.display="";let R=h.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),O==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${R}ms`);else{m.classList.add(`persona-tool-loading-${O}`),m.style.setProperty("--persona-tool-anim-duration",`${R}ms`),O==="shimmer-color"&&(h.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor));let Z=m.textContent||y;m.textContent="",na(m,Z,0)}n.status==="complete"&&(m.style.display="none")}else A||(n.status==="complete"?m.style.display="none":m.style.display="");if(r.iconName&&!A){let R=E("span","persona-reasoning-header-icon"),Z=de(r.iconName,16,"currentColor",2);Z&&(R.appendChild(Z),p.appendChild(R))}let G="currentColor",le=wp(p,u,{expandable:s,expanded:a,iconColor:G,metaGap:!1}),ee=xp({bubble:o,previewKind:"reasoning",expanded:a,isActive:l,previewText:d,activePreview:r.activePreview,activeMinHeight:r.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:d,isActive:l,config:t??{}})});if(!s)return o.append(p,ee),o;let M=E("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");M.style.display=a?"":"none";let B=n.chunks.join(""),H=E("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return H.textContent=B||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),M.appendChild(H),Sp({expanded:a,header:p,toggleIcon:le,content:M,collapsedPreview:ee,iconColor:G}),o.append(p,ee,M),o};var ra=new Set,xx=e=>e.toggleTextColor||e.headerTextColor||"var(--persona-primary, #171717)",zk=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
|
|
38
|
+
`);let r=bd(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
39
|
+
`):""},hf=(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)"},Vk=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=n?.success===!1?n.error||"Tool failed":zk(e,o?.previewMaxLines??3),a=n?Bv(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=nm(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=nm(n,d.completeTextTemplate,p)),n.success===!1&&(p+=" \xB7 Failed"),{summary:p,previewText:s,isActive:l}},Sx=(e,t,n)=>{Ap(e,t,{stateSet:ra,previewKind:"tool",iconColor:xx(n?.toolCall??{})})},yf=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=vp("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&&ra.has(e.id),{summary:d,previewText:p,isActive:u}=Vk(e,t),m=Cp({expandable:a,expanded:l,bubbleType:"tool"});o.headerBackgroundColor&&(m.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(m.style.paddingLeft=o.headerPaddingX,m.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(m.style.paddingTop=o.headerPaddingY,m.style.paddingBottom=o.headerPaddingY);let y=E("div","persona-flex persona-flex-col persona-text-left"),h=E("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(h.style.color=o.headerTextColor);let v=String(n.startedAt??Date.now()),x=()=>{let M=E("span","");return M.setAttribute("data-tool-elapsed",v),M.textContent=cl(n),M},w=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:t??{},elapsed:cl(n),createElapsedElement:x});typeof w=="string"&&w.trim()?(h.textContent=w,y.appendChild(h)):w instanceof HTMLElement?y.appendChild(w):(h.textContent=d,y.appendChild(h));let k=s.loadingAnimation??"none",O=o.activeTextTemplate,D=o.completeTextTemplate,T=u?O:D,I=w instanceof HTMLElement,A=(M,B)=>{h.textContent="";let H=n.name?.trim()||"tool",R=wd(M,H),Z=0;for(let V of R){let ge=V.styles.length>0?(()=>{let ae=E("span",V.styles.map(fe=>`persona-tool-text-${fe}`).join(" "));return h.appendChild(ae),ae})():h;if(V.isDuration&&u)ge.appendChild(x());else{let ae=V.isDuration?cl(n):V.text;B?Z=na(ge,ae,Z):ge.appendChild(document.createTextNode(ae))}}};if(!I)if(u&&k!=="none"){let M=o.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),k==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${M}ms`),T&&A(T,!1);else if(h.classList.add(`persona-tool-loading-${k}`),h.style.setProperty("--persona-tool-anim-duration",`${M}ms`),k==="shimmer-color"&&(o.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),T)A(T,!0);else{let B=h.textContent||d;h.textContent="",na(h,B,0)}}else T&&A(T,!1);let _=xx(o),G=wp(m,y,{expandable:a,expanded:l,iconColor:_,metaGap:!0}),le=xp({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,le),r;let ee=E("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(ee.style.display=l?"":"none",o.contentBackgroundColor&&(ee.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(ee.style.color=o.contentTextColor),o.contentPaddingX&&(ee.style.paddingLeft=o.contentPaddingX,ee.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(ee.style.paddingTop=o.contentPaddingY,ee.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,ee.appendChild(M)}if(n.args!==void 0){let M=E("div","persona-space-y-1"),B=E("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Arguments";let H=E("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",hf(H,o),H.textContent=bd(n.args),M.append(B,H),ee.appendChild(M)}if(n.chunks&&n.chunks.length){let M=E("div","persona-space-y-1"),B=E("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Activity";let H=E("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",hf(H,o),H.textContent=n.chunks.join(""),M.append(B,H),ee.appendChild(M)}if(n.success===!1&&ee.appendChild(Y("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:n.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),n.status==="complete"&&n.result!==void 0){let M=E("div","persona-space-y-1"),B=E("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(B.style.color=o.labelTextColor),B.textContent="Result";let H=E("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",hf(H,o),H.textContent=bd(n.result),M.append(B,H),ee.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`,ee.appendChild(M)}return Sp({expanded:l,header:m,toggleIcon:G,content:ee,collapsedPreview:le,iconColor:_}),r.append(m,le,ee),r};var{setLoader:$B,load:Kk,provide:UB,getSync:Gk}=yt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var Ax=Kk;var Mx=Gk;var{setLoader:zB,load:Yk}=yt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var bf=Yk;var vf=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)})}},So=new vf;var Cf=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:JB,load:Qk,provide:ZB,getSync:Xk}=yt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),sa=null,Mp=new Set,Ex=e=>{if(sa)return sa;sa=e,e.initArtifactsUi({componentRegistry:So});for(let o of Cf)So.has(o)||So.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=Do();t?e.__provideMarkdownParsers(t):Ri(()=>{let o=Do();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>ad());let n=[...Mp];Mp.clear();for(let o of n)try{o()}catch{}return e};var Ep=()=>Qk().then(Ex);var yr=()=>{if(sa)return sa;let e=Xk();return e?Ex(e):null},wf=e=>sa?()=>{}:(Mp.add(e),()=>{Mp.delete(e)});function wn(e){return e?.features?.artifacts?.enabled===!0}function Tx(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!wn(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Jk(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 Px=["panel","seamless","detached"];function xf(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Px.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Sf(e){return!e||!wn(e)?!1:xf(e)==="detached"}function Wl(e,t){if(!wn(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Jk(e),Tx(e,t);return}let n=t.features?.artifacts?.layout,o=xf(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)}Tx(e,t)}function Ol(e,t){for(let l of Px)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!wn(t))return;let n=t.features?.artifacts?.layout,o=xf(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 kx(e,t){return!t||!wn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var Zk=new Set(["__proto__","prototype","constructor"]),e0=new Set(["collapsed","card","panel","inline"]),Lx=new Set(["markdown","component"]),t0=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Gs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pp=e=>!Zk.has(e),Af=e=>typeof e=="string"&&e0.has(e),Ys=e=>Object.keys(e).length>0;function qo(e,t,n,o){e.push({path:t,code:n,message:o})}var n0="Ignored because this key is not part of the persisted preference schema.",Tp="Ignored an unsupported value.",o0="Expected collapsed, panel, or inline.",r0='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Ix={kind:"mode",message:Tp},ia={kind:"string",message:"Expected a CSS length string."},br={kind:"boolean"},s0={paneWidth:ia,paneMaxWidth:ia,paneMinWidth:ia,expandedPanelWidth:ia,resizableMinWidth:ia,resizableMaxWidth:ia,expandLauncherPanelWhenOpen:br,resizable:br},i0={kind:"object",message:"Expected a preference object.",children:{showToolCalls:br,showReasoning:br,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Tp},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Tp},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Tp},expandable:br,grouped:br}},reasoningDisplay:{kind:"object",children:{expandable:br,activePreview:br}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Ix,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Ix,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Lx,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Lx}}},filePreview:{kind:"object",children:{enabled:br}},layout:{kind:"object",children:s0}}}}};function Rx(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:qo(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:qo(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:qo(o,n,"invalid_value",t.message);case"mode":return Af(e)?On(e):qo(o,n,"invalid_value",t.message);case"modeMap":{if(!Gs(e))return qo(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:Ur(a);Pp(a)&&(r?r.has(a):t0.test(d))?Af(l)?s[d]=On(l):qo(o,`${n}.${a}`,"invalid_value",o0):qo(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":r0)}return Ys(s)?s:void 0}case"object":{if(t.bareMode&&Af(e))return On(e);if(!Gs(e))return qo(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))(!Pp(l)||!r.includes(l))&&qo(o,s(l),"unknown_key",n0);let a={};for(let l of r){let d=t.children[l],p=Rx(e[l],d,s(l),o);if(d.deprecated&&e[l]!==void 0&&qo(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=Gs(m)&&Gs(p)?{...m,...p}:p}return Ys(a)?a:void 0}}}function Mf(e){let t=[];return{preferences:(e===null?void 0:Rx(e,i0,"",t))??{},issues:t}}function aa(e){if(Array.isArray(e))return e.map(aa);if(!Gs(e))return e;let t={};for(let[n,o]of Object.entries(e))Pp(n)&&o!==void 0&&(t[n]=aa(o));return t}function Hx(e,t){let n=aa(e);for(let[o,r]of Object.entries(t)){if(!Pp(o)||r===void 0)continue;let s=n[o];n[o]=Gs(s)&&Gs(r)?Hx(s,r):aa(r)}return n}function a0(e){let t={},n;for(let r of e){let s=Mf(r).preferences;n=Wx(n,s.artifacts?.display),t=Hx(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function l0(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}:{},...Ys(r)?{byMediaType:r}:{}};return Ys(s)?s:void 0}function Wx(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=l0(n.files,t.files),a={...o?{default:o}:{},...Ys(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Ys(a)?a:void 0}function Ef(e={},t){let n=a0(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=Wx(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 Bl(e){let t=e.preferences;return!t||!Ys(t)?e:{...e,features:Ef(e.features??{},[t])}}function c0(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 d0(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 p0(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function u0(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Tf(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 Ox(e,t,n,o,r,s,a=200){let l=c0(r,200),d=u0(t,n,o,a);d=Math.max(l,d);let p=d0(s);return p!==null&&(d=Math.min(d,p)),p0(e,l,d)}var{setLoader:i_,load:g0,provide:a_,getSync:m0}=yt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var Bx=g0;var _x=m0;var Pf=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()}},_l=new Pf;var Dx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),f0=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Nx=(e,t,n)=>{if(!Dx(e)||!Dx(t)||f0.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]=Nx(e[r],t[r],s)}return o};function kp(e,t){let n=Nx(e,t,"");return Gi(n)}var Fx=()=>{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 h0=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},y0=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},Dl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=h0(e),n=y0(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}},kf=e=>typeof e=="string"?e:e==null?"":String(e),Qs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:kf(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=kf(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:kf(n.text)}}},$x=e=>Array.isArray(e)?e.map(t=>String(t)):[],Nl=e=>{let t=new Set($x(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set($x(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 b0=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}},v0=e=>e.map(t=>({...t,streaming:!1})),C0=e=>e.map(t=>({...t,status:"complete"})),Lp=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?b0(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?v0(n.messages):void 0,artifacts:n.artifacts?C0(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 w0=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")},Ux=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 w0(e)},x0=async(e,t)=>{let n=await Ux(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await Ux(`${e}\0${t}`)}`}};var jx=(e,t,n)=>{let o="",r="",s="",a=!1,l=!1,d=0,p=null,u=null,m=new Set,y=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},h=()=>{let A=y();if(!A)return p;try{return A.getItem(o)}catch{return a=!0,p}},v=(A,_)=>{if(l||A===p)return;let G=p;p=A,d+=1;let le={previousToken:G,token:A,source:_,revision:d};for(let ee of m)ee(le)},x=A=>{l||A.key!==null&&A.key!==o||v(A.key===null?null:A.newValue??null,"external")},w=(async()=>{let A=await x0(e,t);o=A.storageKey,r=A.leaseKey,s=A.lockName,p=h(),!n&&typeof window<"u"&&window.addEventListener("storage",x)})(),k=A=>new Promise(_=>setTimeout(_,A)),O=()=>{let A=y();if(!A)return null;try{let _=A.getItem(r);if(!_)return null;let G=JSON.parse(_);return typeof G?.expiresAt=="number"&&typeof G?.ownerNonce=="string"?G:null}catch{return null}},D=A=>{let _=y();if(_)try{O()?.ownerNonce===A&&_.removeItem(r)}catch{}},T=A=>new Promise(_=>{let G=setTimeout(le,A);function le(){clearTimeout(G),window.removeEventListener("storage",ee),_()}function ee(M){(M.key===null||M.key===r)&&le()}window.addEventListener("storage",ee)}),I=async A=>{let _=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;Date.now()<G;){let le=y();if(!le)break;let ee=Date.now(),M=O();if(M&&M.expiresAt>ee&&M.ownerNonce!==_){await T(Math.min(M.expiresAt-ee,500));continue}try{le.setItem(r,JSON.stringify({ownerNonce:_,expiresAt:ee+1e4}))}catch{a=!0;break}if(await k(20+Math.random()*40),O()?.ownerNonce!==_){await T(500);continue}u=_;try{return await A()}finally{u=null,D(_)}}return A()};return{ready:w,async get(){return await w,v(h(),"external"),p},async set(A){await w;let _=y();if(_)try{_.setItem(o,A)}catch{a=!0}v(A,"local")},async clear(){await w;let A=y();if(A)try{A.removeItem(o)}catch{a=!0}v(null,"local")},revision(){return d},subscribe(A){return m.add(A),()=>{m.delete(A)}},async withFirstInitLock(A){await w;let _=globalThis.navigator?.locks;return _?.request?_.request(s,()=>A()):y()?I(A):A()},matches(A,_,G){return A===e&&_===t&&G===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",x),u&&D(u)}}};var{setLoader:y_,load:S0}=yt({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var Lf=S0;var If=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},vr=e=>Object.freeze({...e}),qx=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),zx=e=>e?vr(e):null;function Vx(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,a=!1,l=null,d=[],p=()=>{for(let T of d.splice(0))try{T()}catch(I){If("renderHistoryView cleanup",I)}},u=(T,I)=>{for(let A of t){let _=A[T];if(_)try{let G=_(I);if(G)return G}catch(G){If(T,G)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),y={header:T=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:vr(T.identityStatus),pendingAction:zx(T.pendingAction),copy:vr(T.copy),actions:Object.freeze({close:x.close,startNewConversation:x.startNewConversation}),defaultRenderer:T.defaultRenderer})):null,conversation:T=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:qx(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:vr(T.state),identityStatus:vr(T.identityStatus),copy:vr(T.copy),...T.retry?{retry:T.retry}:{},...T.startNewConversation?{startNewConversation:T.startNewConversation}:{},defaultRenderer:T.defaultRenderer})):null},h=t.flatMap(T=>(T.railSections??[]).map(I=>({...I,placement:I.placement??"above-conversations",items:[],render:A=>I.render(Object.freeze({collapsed:A,presentation:e.getPresentation(),actions:x}))}))),v=e.createView({slots:y,renderDom:!1,onModelChange:()=>D(),railSections:h}),x=Object.freeze({...v.operations,close:e.close}),w=()=>(a=!0,v.setDomRenderEnabled(!0),v.element),k=T=>Object.freeze({conversations:Object.freeze(T.conversations.map(qx)),activeConversationId:T.activeConversationId,state:vr(T.state),pendingAction:zx(T.pendingAction),identityStatus:vr(T.identityStatus),nextCursor:T.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:vr(v.copy),actions:x,defaultRenderer:w,requestRender:()=>D(),onCleanup:I=>{d.push(I)}}),O=()=>{a=!1;let T=null;for(let A of t)if(A.renderHistoryView){try{T=A.renderHistoryView(k(v.getModel()))}catch(_){If("renderHistoryView",_),T=null}if(T)break}let I=!T||T.contains(v.element);return a=I,v.setDomRenderEnabled(I),T??v.element};function D(){if(!(!s||o||r)){r=!0;try{p();let T=O();if(T===l)return;let I=l;l=T,e.onElementChanged(T,I)}finally{r=!1}}}return s=!0,D(),{view:v,get element(){return l??v.element},requestRender:D,dispose:()=>{o=!0,p()}}}var A0=null;function Kx(){return A0}var M0=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"]]),E0=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."]]),Rf=e=>E0.get(e)??"Conversation history is unavailable right now.";function T0(e){if(e instanceof ao)return e;if(e instanceof $e){let t=M0.get(e.code)??"unavailable";return new ao(t,Rf(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new ao("unavailable",Rf("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 ao("unsupported_scope",Rf("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw T0(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=Yv(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:ul([],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 P0=["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"],Yx={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 Hf(e){if(!e)return Yx;let t={...Yx};for(let n of P0){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var k0="button:not([disabled])";function Ip(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=Y("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),a=Y("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=Y("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"}},Y("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),Y("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),Y("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=Y("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(p=>{let u=!1,m=h=>{u||(u=!0,d.removeEventListener("keydown",y,!0),d.remove(),t?.focus(),p(h))};function y(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),m(!1);return}if(h.key!=="Tab")return;let v=Array.from(l.querySelectorAll(k0));if(v.length===0)return;let x=v[0],w=v[v.length-1],k=document.activeElement;h.shiftKey&&(k===x||!l.contains(k))?(h.preventDefault(),w.focus()):!h.shiftKey&&k===w&&(h.preventDefault(),x.focus())}d.addEventListener("keydown",y,!0),d.addEventListener("pointerdown",h=>{h.target===d&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),e.host.appendChild(d),s.focus()})}var la=require("partial-json");function L0(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function I0(e,t){if(!L0(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 Rp(){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=(0,la.parse)(n,la.STR|la.OBJ),s=I0(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Qx(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Hp(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=So.get(e.component);if(!s){if(Cf.includes(e.component)){Ep().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 Xx(){let e=Rp();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Jx(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 Fl(e){let t=Jx(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 Wp(e){let t=Jx(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 R0=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Op(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=R0}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,y=document.createElement("div");y.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,h.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,h.appendChild(x),y.appendChild(h);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-csat",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let A=1;A<=5;A++){let _=document.createElement("button");_.type="button",_.className="persona-feedback-rating-btn persona-feedback-star-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${p[A-1]}`),_.title=p[A-1],_.dataset.rating=String(A),_.innerHTML=`
|
|
40
40
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
41
41
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
42
42
|
</svg>
|
|
43
|
-
`,N.addEventListener("click",()=>{m=A,P.forEach((Y,ce)=>{let Q=ce<A;Y.classList.toggle("selected",Q),Y.setAttribute("aria-checked",ce===A-1?"true":"false")})}),P.push(N),x.appendChild(N)}y.appendChild(x);let O=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",O=document.createElement("textarea"),O.className="persona-feedback-comment",O.placeholder=s,O.rows=3,O.setAttribute("aria-label","Additional comments"),A.appendChild(O),y.appendChild(A)}let $=document.createElement("div");$.className="persona-feedback-actions";let T=document.createElement("button");T.type="button",T.className="persona-feedback-btn persona-feedback-btn-skip",T.textContent=l,T.addEventListener("click",()=>{n?.(),u.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(m===null){x.classList.add("persona-feedback-shake"),setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let A=O?.value.trim()||void 0;await t(m,A),u.remove()}catch(A){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),$.appendChild(T),$.appendChild(R),y.appendChild($),u.appendChild(y),u}function Np(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:p="Not likely",highLabel:u="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let y=null,h=document.createElement("div");h.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let S=document.createElement("h3");S.className="persona-feedback-title",S.textContent=o,C.appendChild(S);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,C.appendChild(x),h.appendChild(C);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-nps",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Likelihood rating from 0 to 10");let O=document.createElement("div");O.className="persona-feedback-labels";let $=document.createElement("span");$.className="persona-feedback-label-low",$.textContent=p;let T=document.createElement("span");T.className="persona-feedback-label-high",T.textContent=u,O.appendChild($),O.appendChild(T);let R=document.createElement("div");R.className="persona-feedback-numbers";let A=[];for(let E=0;E<=10;E++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-number-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`Rating ${E} out of 10`),B.textContent=String(E),B.dataset.rating=String(E),E<=6?B.classList.add("persona-feedback-detractor"):E<=8?B.classList.add("persona-feedback-passive"):B.classList.add("persona-feedback-promoter"),B.addEventListener("click",()=>{y=E,A.forEach((H,L)=>{H.classList.toggle("selected",L===E),H.setAttribute("aria-checked",L===E?"true":"false")})}),A.push(B),R.appendChild(B)}P.appendChild(O),P.appendChild(R),h.appendChild(P);let N=null;if(d){let E=document.createElement("div");E.className="persona-feedback-comment-container",N=document.createElement("textarea"),N.className="persona-feedback-comment",N.placeholder=s,N.rows=3,N.setAttribute("aria-label","Additional comments"),E.appendChild(N),h.appendChild(E)}let Y=document.createElement("div");Y.className="persona-feedback-actions";let ce=document.createElement("button");ce.type="button",ce.className="persona-feedback-btn persona-feedback-btn-skip",ce.textContent=l,ce.addEventListener("click",()=>{n?.(),m.remove()});let Q=document.createElement("button");return Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-submit",Q.textContent=a,Q.addEventListener("click",async()=>{if(y===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}Q.disabled=!0,Q.textContent="Submitting...";try{let E=N?.value.trim()||void 0;await t(y,E),m.remove()}catch(E){Q.disabled=!1,Q.textContent=a,console.error("[NPS Feedback] Failed to submit:",E)}}),Y.appendChild(ce),Y.appendChild(Q),h.appendChild(Y),m.appendChild(h),m}var fa="persona-chat-history",I0=30*1e3,R0=641,ha="data-persona-composer-reason",H0={"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 W0(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=H0[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 Fp(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 O0(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 B0(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Wf=e=>!e||typeof e!="object"?{}:{...e},Qx=e=>e.map(t=>({...t,streaming:!1})),Xx=(e,t,n)=>{let o=e?.markdown?il(e.markdown):null,r=ud(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=$o()!==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?nv(d):d,h=o(y);m=r&&u?r(h):h}else m=fr(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)),fr(l.text??"")}}};function Jx(e){let t=M("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=ge(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=M("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var _0=(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},D0=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:_0(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),$p=(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=ea(t),r=()=>{xC({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=Nl(o);let a=Fl.getForInstance(o.plugins),l=ww(e),d=[],p=!1,u=yx(()=>o),m=null,y=null,h=null,C=!1,S=null,x=i=>{m=i,i.initApprovalUi({webMcpToolTitle:$i});let c=i.createBuiltInApprovalPlugin();y=c.plugin,h=c.teardown},P=()=>{if(m)return m;let i=xx();return i?(x(i),i):(wx().then(c=>{C||m||(x(c),S?.())}).catch(()=>{}),null)},O=!1,$=!1,T=null,R=(i,c,g,f)=>{if(!i.querySelector("[data-tv-form]"))return;let b=Wx();if(b){b.enhanceWithForms(i,c,g,f);return}Hx().then(()=>{O||$||!T||($=!0,T())}).catch(()=>{})};o.components&&Ao.registerAll(o.components);let A=_x(),Y=o.persistState===!1?null:o.storageAdapter??Hp(),ce=!!o.clientToken&&typeof o.reconnectStream!="function",Q={},E=null,B,H=new Promise(i=>{B=i}),L,te=!1,K=i=>{if(o.onStateLoaded)try{let c=o.onStateLoaded(i);if(c&&typeof c=="object"&&"state"in c){let{state:g,open:f}=c;return f&&(te=!0),g}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(Y?.load)try{let i=Y.load();if(i&&typeof i.then=="function")E=i.then(c=>K(c??{messages:[],metadata:{}}));else{let g=K(i??{messages:[],metadata:{}});g.metadata&&(Q=Wf(g.metadata)),g.messages?.length&&(o={...o,initialMessages:g.messages}),g.artifacts?.length&&(o={...o,initialArtifacts:g.artifacts,initialSelectedArtifactId:g.selectedArtifactId??null}),L=g.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=K({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}E||B();let me=()=>Q,de=i=>{Q=i({...Q})??{},bi()},he=o.actionParsers&&o.actionParsers.length?o.actionParsers:[$l],We=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[oi.message,oi.messageAndClick],Oe=Ul({parsers:he,handlers:We,getSessionMetadata:me,updateSessionMetadata:de,emit:A.emit,documentRef:typeof document<"u"?document:null});Oe.syncFromMetadata();let we=o.launcher?.enabled??!0,Qe=o.launcher?.autoExpand??!1,Ce=o.autoFocusInput??!1,j=Qe,Ne=we,Ue=o.layout?.header?.layout,ht=!1,xe=()=>ss(o),ke=()=>we||xe(),be=xe()?!1:we?Qe:!0,Ie=!1,Tt=null,Xt=()=>{Ie=!0,Tt&&clearTimeout(Tt),Tt=setTimeout(()=>{Ie&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Ie=!1)},1e4)},yt=Xx(o,Oe,Xt),gn=o.features?.showReasoning??!0,Yn=o.features?.showToolCalls??!0,cn=o.features?.showEventStreamToggle??!1,Eo=o.features?.scrollToBottom??{},Qn=o.features?.scrollBehavior??{},uo=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",To=`${uo()}event-stream`,Yo=null,ls=o.features?.eventStream?.maxEvents??2e3,nt=null,On=null,go=null,D=!1,J=null,v=!1,_=null,F=0,U=(i,c)=>{nt?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},oe=(i,c)=>{On?.processEvent(i,c),nt?U(i,c):go&&(go.length>=ls&&go.shift(),go.push({type:i,payload:c}))},ie=()=>{nt||!cn||(go??(go=[]),bf().then(i=>{if(D||nt||!cn)return;Yo=new i.EventStreamStore(To),nt=new i.EventStreamBuffer(ls,Yo),On=On??new i.ThroughputTracker,Yo.open().then(()=>nt?.restore()).catch(g=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",g)});let c=go??[];go=null;for(let g of c)On?.processEvent(g.type,g.payload),U(g.type,g.payload)}).catch(()=>{}))};cn&&ie();let le=!1,pe=null,qt=()=>{},_e=()=>{},_t=()=>{},Lt=()=>{},Qo=()=>{},Er=()=>v||le&&pe==="panel",zt={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)}},Vt=o.statusIndicator??{},Sn=i=>i==="idle"?Vt.idleText??jt.idle:i==="connecting"?Vt.connectingText??jt.connecting:i==="connected"?Vt.connectedText??jt.connected:i==="error"?Vt.errorText??jt.error:i==="paused"?Vt.pausedText??jt.paused:i==="resuming"?Vt.resumingText??jt.resuming:jt[i];function Kl(i,c,g,f){if(!i.hasAttribute(ha))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 Bn=hx({config:o,showClose:ke()}),{wrapper:Ye,panel:Me,pillRoot:Jt}=Bn.shell,Fe=Bn.panelElements,{container:fe,body:re,messagesWrapper:Pe,starterSuggestions:ou,transcriptSuggestions:ba,suggestions:Tr,textarea:ue,sendButton:Ee,composerForm:mo,statusText:lt,welcomeHost:An,welcomeIconHolder:VS,greetingHost:_n,introKicker:KS,introTitle:GS,introSubtitle:YS,closeButton:qe,iconHolder:It,headerTitle:kr,headerSubtitle:cs,header:Te,footer:He,actionsRow:QS}=Fe,ru=Fe.leftActions,Gl=Fe.rightActions,ko=Fe.sendButtonWrapper,Zf=Fe.setSendButtonMode,se=Fe.micButton,Dn=Fe.micButtonWrapper,kt=Fe.attachmentButton,Mn=Fe.attachmentButtonWrapper,xt=Fe.attachmentInput,En=Fe.attachmentPreviewsContainer;fe.classList.add("persona-relative"),re.classList.add("persona-relative");let XS=12,va=()=>Eo.label??"",JS=()=>Eo.iconName??"arrow-down",ZS=()=>Eo.enabled!==!1,Nn=()=>Qn.mode??"anchor-top",Pr=()=>Nn()==="follow"||Nn()==="anchor-top"&&Pa,Ca=()=>Qn.anchorTopOffset??16,eA=()=>Qn.restorePosition??"bottom",eh=()=>Qn.pauseOnInteraction===!0,th=()=>Qn.showActivityWhilePinned!==!1,nh=()=>Qn.announce===!0,su=()=>Qn.scrollbar??"on-scroll",Nt=M("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Nt.type="button",Nt.style.display="none",Nt.setAttribute("data-persona-scroll-to-bottom","true");let wa=M("span","persona-flex persona-items-center"),iu=M("span",""),ds=M("span","");ds.setAttribute("data-persona-scroll-to-bottom-count",""),ds.style.display="none",Nt.append(wa,iu,ds),fe.appendChild(Nt);let Xn=M("div","persona-stream-anchor-spacer");Xn.setAttribute("aria-hidden","true"),Xn.setAttribute("data-persona-anchor-spacer",""),Xn.style.flexShrink="0",Xn.style.pointerEvents="none",Xn.style.height="0px",Xn.style.display="none",re.appendChild(Xn);let Xo=M("div","persona-sr-only");Xo.setAttribute("aria-live","polite"),Xo.setAttribute("aria-atomic","true"),Xo.setAttribute("role","status"),Xo.setAttribute("data-persona-live-region",""),Object.assign(Xo.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"}),fe.appendChild(Xo);let xa=null,Yl=null,Ql=i=>{!nh()||!i||(Yl=i,xa===null&&(xa=setTimeout(()=>{xa=null,Yl&&nh()&&(Xo.textContent=Yl),Yl=null},400)))},Xl="empty",Jl=0,au=()=>Jl||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,ps=()=>{let c=He.style.display==="none"?0:He.offsetHeight;Nt.style.bottom=`${c+au()+XS}px`};ps();let lu=()=>{di||(He.style.marginBottom=Jl>0?`${Jl}px`:"")},Zl=()=>{let i=_m(o,xe()),c=So(o),f=He.style.display==="none"?0:He.offsetHeight,b=c.anchor==="center"&&Xl==="empty"?Sl(c.anchorComposerTop)??Sl("44%"):null,w=b===null||xe()?0:bw({columnHeight:fe.clientHeight,footerHeight:f,fraction:b});e.style.setProperty("--persona-composer-overlay-height",`${f}px`),e.style.setProperty("--persona-composer-lift",`${i==="overlay"?w:0}px`),Jl=i==="block"?w:0,lu(),ps()},oh=()=>{let i=!!va();Nt.setAttribute("aria-label",va()||"Jump to latest"),Nt.title=va(),Nt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),wa.innerHTML="";let c=ge(JS(),"14px","currentColor",2);c?(wa.appendChild(c),wa.style.display=""):wa.style.display="none",iu.textContent=va(),iu.style.display=i?"":"none"};oh();let et=null,Dt=null,Se=hC(),tA=i=>{try{fe.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};Se.subscribe(tA);let Po=()=>{Se.setText(ue?.value??"")},us=()=>{Se.setMentionRefs(Dt?.getMentionRefs()??[])},nA=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}),rh=i=>{let c=Object.freeze(i.map(nA));Se.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(g){console.error("[AgentWidget] attachments.onChange failed:",g)}Wu()};Se.setSelectedModelId(o.composer?.selectedModelId);let Sa=()=>o.composer?.modes??[],ii=()=>jC(Sa(),o.composer?.modeGroups);{let i=Jd(o.composer?.defaultActiveModeIds??[],Sa());i.length&&Se.setActiveModeIds(i)}function sh(i){if(Se.getState().selectedModelId!==i){Se.setSelectedModelId(i),Lr?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function ec(i){Se.setActiveModeIds(i),Jo?.render(i,ii()),ai.forEach(c=>c.repaint()),Io?.resolve(),Mc(),fo()}function cu(i){ec(qC(Se.getState().activeModeIds,i,Sa(),o.composer?.modeGroups))}let Lr=null,du=null,Jo=null,ai=new Map,Ir=null;function Lo(i){Se.setQuote(i),Ir?.render(Se.getState().quote),fo(),Xh()}let ih=!1;function pu(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!ih&&o.debug===!0&&(ih=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Rr=null;function li(i){Se.setPendingSubmission(i),Rr?.render(Se.getState().pendingSubmission),fo()}let oA=i=>{let c=ai.get(i);if(c)return c;let g=KC({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===i),getModes:()=>Sa().filter(f=>f.groupId===i),getActiveIds:()=>Se.getState().activeModeIds,onSelect:f=>cu(f)});return ai.set(i,g),g},rA=()=>{let i=[],c=Se.getState().activeModeIds,g=new Set;if(Sa().forEach((f,b)=>{if(Xd(f.groupId,o.composer?.modeGroups)){let w=f.groupId;if(g.has(w))return;g.add(w);let W=oA(w);W.action.order=Pm(b),W.action.label=o.composer?.modeGroups?.find(z=>z.id===w)?.label??w,i.push(W.action);return}i.push({id:$C(f.id),kind:"button",placement:"start",order:Pm(b),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:c.includes(f.id),onSelect:()=>cu(f.id)})}),o.composer?.models?.length&&!a.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!Lr||du!==f)&&(du=f,Lr=NC({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>Se.getState().selectedModelId,onSelect:b=>sh(b),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Lr.action)}return i},uu=null,ah=a.find(i=>i.renderHeader);if(ah?.renderHeader){let i=ah.renderHeader({config:o,defaultRenderer:()=>{let c=Cr({config:o,showClose:ke()});return Xs(fe,c,o),c.header},onClose:()=>mt(!1,"user")});if(i){let c=Te;c&&(c.replaceWith(i),Te=i,Bn.header.element=i)}}let lh=()=>{J&&(re.style.display="none",He.parentNode?.insertBefore(J.element,He),J.update())},gu=()=>{if(!nt){ie();return}if(v=!0,J?lh():bf().then(c=>{J||!v||!nt||(J=c.createEventStreamView({buffer:nt,getFullHistory:()=>nt.getAllFromStore(),onClose:()=>ci(),config:o,plugins:a,getThroughput:()=>On?.getMetric()??{status:"idle"},renderIconByName:ge}),lh())}).catch(()=>{ci()}),ot){ot.style.boxShadow=`inset 0 0 0 1.5px ${Cn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(g=>g&&ot.classList.add(g))}let i=()=>{if(!v)return;let c=Date.now();c-F>=200&&(J?.update(),F=c),_=requestAnimationFrame(i)};F=0,_=requestAnimationFrame(i),Gt(),A.emit("eventStream:opened",{timestamp:Date.now()})},ci=()=>{if(v){if(v=!1,J&&J.element.remove(),re.style.display="",ot){ot.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&ot.classList.remove(c))}_!==null&&(cancelAnimationFrame(_),_=null),Gt(),A.emit("eventStream:closed",{timestamp:Date.now()})}},ot=null;if(cn){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:"");ot=M("button",c),ot.style.width="28px",ot.style.height="28px",ot.style.color=Cn.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let g=Bt(Ar.Activity,"18px","currentColor",1.5);g&&ot.appendChild(g);let f=Fe.clearChatButtonWrapper,b=Fe.closeButtonWrapper,w=f||b;w&&w.parentNode===Te?Te.insertBefore(ot,w):Te.appendChild(ot),ot.addEventListener("click",()=>{v?ci():gu()})}let ch=i=>{let c=o.attachments;if(!c?.enabled)return;let g=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!g){g=M("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),g.setAttribute("data-persona-composer-attachment-previews",""),g.style.display="none";let b=i.querySelector("[data-persona-composer-form]");b?.parentNode?b.parentNode.insertBefore(g,b):i.insertBefore(g,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let b=M("input");b.type="file",b.setAttribute("data-persona-composer-attachment-input",""),b.accept=(c.allowedTypes??vr).join(","),b.multiple=(c.maxFiles??4)>1,b.style.display="none",b.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(b)}},di=!1,dh=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:()=>Sb(),storage:u(c.id),onSubmit:b=>{!k||k.isStreaming()||Jc(b.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{Nr()||xt?.click()},models:g?.models,selectedModelId:Se.getState().selectedModelId??g?.selectedModelId,onModelChange:b=>sh(b),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{uu?.()}:void 0})},ph=dh(()=>Zs({config:o}).footer);ph&&(Bn.replaceComposer(ph),He=Bn.composer.footer,di=!0);let rt=null,sA=i=>{mo=i.form,ue=i.input,ko=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Ee=i.sendButton),i.micButton&&(se=i.micButton,Dn=i.micButton.parentElement),i.found.status&&(lt=i.found.status),i.found.suggestions&&(Tr=i.found.suggestions),i.attachmentButton&&(kt=i.attachmentButton,Mn=i.attachmentButton.parentElement),xt=i.attachmentInput??null,En=i.attachmentPreviews??null,i.found.actionsRow&&(QS=i.found.actionsRow),ru=i.found.actionsStart,Gl=i.found.actionsEnd};function mu(){let i=ue;if(!i)return;let c=o.composer?.inputAttributes,g=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;Ud(i,c),g&&i.setAttribute("aria-label",g),$d(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:vl(i)}),TC(i,Fd(o.composer?.maxLines,xe()?5:3))}let uh=i=>{rt=bC(i,{debug:o.debug===!0}),rt&&sA(rt),mu()};ch(He),uh(He),Po();let Aa=os(o,xe());Aa&&(Pe.style.maxWidth=Aa,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%",_n.style.maxWidth=Aa,_n.style.marginLeft="auto",_n.style.marginRight="auto",_n.style.width="100%",ou.style.maxWidth=Aa,ba.style.maxWidth=Aa,ba.style.marginLeft="auto",ba.style.marginRight="auto",ba.style.width="100%");let gh=()=>{let i=os(o,xe());if(!(!i||xe()))for(let c of[mo,Tr,En,lt])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};gh();let mh=()=>{!o.attachments?.enabled||!xt||!En||(et?et.remountPreviews(En):(et=Ks.fromConfig(o.attachments,rh),et.setPreviewsContainer(En)),rt?.addListener(xt,"change",i=>{let c=i.target;et?.handleFileSelect(c.files),c.value=""}),fe.querySelector(".persona-attachment-drop-overlay")||fe.appendChild(Jx(o.attachments.dropOverlay)))};mh();let iA=()=>Dt?.prefetch(),fh=()=>{if(!o.contextMentions?.enabled||!ue)return;let i=rt?.header??null,c=i?km(i):void 0;if(Dt=gw({config:o,textarea:ue,anchor:mo??ue,getMessages:()=>k.getMessages(),liveRegionHost:fe,chipRow:c}),Dt&&!c){let g=ue;g.parentElement?.insertBefore(Dt.contextRow,g)}};fh();let Io=null,aA={getState:()=>Se.getState(),getValue:()=>ue?.value??"",setValue:i=>{ue&&(ue.value=i,ue.dispatchEvent(new Event("input",{bubbles:!0})),Po())},submit:()=>{ow(rt?.form??null)},openAttachmentPicker:()=>{Nr()||xt?.click()},toggleVoice:()=>{uu?.()},requestRender:()=>Io?.resolve()},lA=()=>{let i=[];return(Dt?.affordanceButtons??[]).forEach((g,f)=>{i.push({id:`core:mention-${f}`,placement:"start",order:zo.mention+f,element:g,managed:!0})}),Mn&&i.push({id:"core:attachment",placement:"start",order:zo.attachment,element:Mn}),Dn&&i.push({id:"core:mic",placement:"end",order:zo.mic,element:Dn}),ko&&i.push({id:"core:send",placement:"end",order:zo.send,element:ko}),i},hh=()=>{Io?.destroy(),Io=BC({getBindings:()=>rt,collect:()=>({builtIns:lA(),configActions:[...rA(),...o.composer?.actions??[]],plugins:a,contributionContext:{config:o,getState:()=>Se.getState(),requestRender:()=>Io?.resolve()},debug:o.debug===!0}),actionContext:aA,getState:()=>Se.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),Io.resolve()};hh();let fu=()=>{if(Jo?.destroy(),Jo=null,!ii().length)return;let i=rt?.header;i&&(Jo=FC({row:km(i),onRemove:c=>cu(c),initialIds:Se.getState().activeModeIds}),Jo.render(Se.getState().activeModeIds,ii()))};fu();let yh=()=>{Ir?.destroy(),Ir=null,Rr?.destroy(),Rr=null;let i=rt?.header;i&&(Ir=GC({onDismiss:()=>Lo(void 0)}),i.appendChild(Ir.element),Ir.render(Se.getState().quote),pu()==="defer-one"&&(Rr=YC({onEdit:()=>BM(),onRemove:()=>li(void 0)}),i.appendChild(Rr.element),Rr.render(Se.getState().pendingSubmission)))};yh();let hu=tw(),cA=()=>{let i=rt?.header?.querySelector(Tm);if(i)return i.childElementCount>0;let c=Se.getState();return c.mentionRefs.length>0||Jd(c.activeModeIds,ii()).length>0},bh=()=>!1;function fo(){let i=Se.getState(),c=hu.observe(nw(ue),i.text);He.toggleAttribute("data-persona-composer-compact",ew({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:cA(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0,dictationActive:bh()}))}function vh(){o.composer?.layout==="single-row"&&!xe()?He.setAttribute("data-persona-composer-layout","single-row"):He.removeAttribute("data-persona-composer-layout")}vh(),Se.subscribe(()=>{Io?.sync(),Wu(),Sc(),fo(),Xh()}),Sc();let Ch=!1,dA=i=>{if(Ch||o.debug!==!0)return;let c=["messages","composer"].filter(g=>i[g]);c.length&&(Ch=!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??{};dA(i);let c=f=>{switch(f){case"body-top":return re.querySelector("[data-persona-intro-card]");case"messages":return Pe;case"footer-top":return Tr;case"composer":return mo;case"footer-bottom":return lt;default:return null}},g=(f,b)=>{switch(f){case"header-left":case"header-center":case"header-right":if(f==="header-left")Te.insertBefore(b,Te.firstChild);else if(f==="header-right")Te.appendChild(b);else{let w=Te.querySelector(".persona-flex-col");w?w.parentNode?.insertBefore(b,w.nextSibling):Te.appendChild(b)}break;case"body-top":{let w=re.querySelector("[data-persona-intro-card]");w?w.replaceWith(b):re.insertBefore(b,re.firstChild);break}case"body-bottom":re.appendChild(b);break;case"footer-top":Tr.replaceWith(b);break;case"footer-bottom":lt.replaceWith(b);break;default:break}};for(let[f,b]of Object.entries(i))if(b)try{let w=b({config:o,defaultContent:()=>c(f)});w&&g(f,w)}catch(w){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${f}":`,w)}})();let wh=i=>{let g=i.target.closest('button[data-expand-header="true"]');if(!g)return;let f=g.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!f)return;let b=f.getAttribute("data-message-id");if(!b)return;let w=g.getAttribute("data-bubble-type");if(w==="reasoning")ca.has(b)?ca.delete(b):ca.add(b),bx(b,f);else if(w==="tool")da.has(b)?da.delete(b):da.add(b),Cx(b,f,o);else if(w==="approval"&&m){let z=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",q=m.approvalDetailsExpansionState.get(b)??z;m.approvalDetailsExpansionState.set(b,!q),m.updateApprovalDetailsUI(b,f,o)}Ft.delete(b)};Pe.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),wh(i))}),Pe.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),wh(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(),w=Sw(b);!w||w===b||(c.setData("text/plain",w),i.preventDefault())});let yu=new Map,xh=null,Sh="idle",pA={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},uA=(i,c)=>{let{icon:g,label:f}=pA[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=ge(g,14,"currentColor",2);b&&(i.innerHTML="",i.appendChild(b))},Ah=()=>{Pe.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let f=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;uA(c,f&&f===xh?Sh:"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 w=g.getAttribute("data-action");if(w==="copy"){let z=k.getMessages().find(q=>q.id===b);if(z&&zt.onCopy){let q=z.content||"";navigator.clipboard.writeText(q).then(()=>{g.classList.add("persona-message-action-success");let V=Bt(Ar.Check,14,"currentColor",2);V&&(g.innerHTML="",g.appendChild(V)),setTimeout(()=>{g.classList.remove("persona-message-action-success");let Z=Bt(Ar.Copy,14,"currentColor",2);Z&&(g.innerHTML="",g.appendChild(Z))},2e3)}).catch(V=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",V)}),zt.onCopy(z)}}else if(w==="read-aloud")k.toggleReadAloud(b);else if(w==="upvote"||w==="downvote"){let z=(yu.get(b)??null)===w,q=w==="upvote"?"thumbs-up":"thumbs-down";if(z){yu.delete(b),g.classList.remove("persona-message-action-active");let V=ge(q,14,"currentColor",2);V&&(g.innerHTML="",g.appendChild(V))}else{let V=w==="upvote"?"downvote":"upvote",Z=f.querySelector(`[data-action="${V}"]`);if(Z){Z.classList.remove("persona-message-action-active");let ft=ge(V==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ft&&(Z.innerHTML="",Z.appendChild(ft))}yu.set(b,w),g.classList.add("persona-message-action-active");let ae=ge(q,14,"currentColor",2);ae&&(ae.setAttribute("fill","currentColor"),g.innerHTML="",g.appendChild(ae)),g.classList.remove("persona-message-action-pop"),g.offsetWidth,g.classList.add("persona-message-action-pop");let Ze=k.getMessages().find(ut=>ut.id===b);Ze&&zt.onFeedback&&zt.onFeedback({type:w,messageId:Ze.id,message:Ze})}}else if(w==="regenerate")tc?.regenerate(b);else if(w==="edit")tc?.edit(b);else if(w==="quote")tc?.quote(b);else if(w?.startsWith(yp)){let W=w.slice(yp.length),z=o.messageActions?.custom?.find(V=>V.id===W),q=k.getMessages().find(V=>V.id===b);if(!z||!q)return;try{z.onSelect(q)}catch(V){console.error(`[AgentWidget] messageActions.custom "${W}" onSelect failed:`,V)}}});let tc=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 w=g.getAttribute("data-approval-action");if(!w)return;let W=w==="approve"?"approved":"denied",q=k.getMessages().find(Z=>Z.id===b);if(!q?.approval)return;let V=f.querySelector("[data-approval-buttons]");V&&V.querySelectorAll("button").forEach(ae=>{ae.disabled=!0,ae.style.opacity="0.5",ae.style.cursor="not-allowed"}),q.approval.toolType==="webmcp"?k.resolveWebMcpApproval(b,W):k.resolveApproval(q.approval,W)});let Ve=null,Mh=!1,Ma=null,gs=()=>{},Ea="none",nc=null,Jn={artifacts:[],selectedId:null},Zo=!1,ho=!1,Ta=!1,pi=!1,Eh=()=>pi||Jn.artifacts.some(i=>Uo(o.features?.artifacts,i)==="panel"),oc=()=>Jn.artifacts.length>0&&!Zo&&Eh(),pt={current:null},bu=(i,c)=>{let g=k.getArtifactById(c),f=g?.markdown,b=g?.title||"artifact",w=g?.file,W=g?.artifactType??"markdown";if(!f){let V=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(V){let ae=k.getMessages().find(ye=>ye.id===V);if(ae?.rawContent)try{let ye=JSON.parse(ae.rawContent);f=ye?.props?.markdown,b=ye?.props?.title||b,ye?.props?.file&&typeof ye.props.file=="object"&&(w=ye.props.file),!g&&typeof ye?.props?.artifactType=="string"&&(W=ye.props.artifactType)}catch{}}}return{markdown:f,title:b,file:w,artifactType:W}};Pe.addEventListener("click",i=>{let g=i.target.closest("[data-download-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-download-artifact");if(!f||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:f})===!0)return;let{markdown:w,title:W,file:z}=bu(g,f);if(!w)return;let q=wr();q&&q.triggerArtifactDownload(q.downloadInfoFor({title:W,markdown:w,file:z}))}),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]"),w=b?null:g.closest("[data-open-artifact]"),W=b?b.getAttribute("data-artifact-inline"):w?.getAttribute("data-open-artifact")??null,q=(b?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ut=>ut.id===f);if(!q)return;let{markdown:V,title:Z,file:ae,artifactType:ye}=bu(g,W??""),Ze={artifactId:W,title:Z,artifactType:ye,markdown:V,file:ae};try{Promise.resolve(q.onClick(Ze)).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),w=wr();if(!w)return;let W="";if(b)W=w.artifactCopyText(b);else{let{markdown:z,file:q,artifactType:V}=bu(g,f);V==="markdown"&&(W=w.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:z??"",...q?{file:q}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let z=Bt(Ar.Check,16,"currentColor",2);z&&(g.replaceChildren(z),setTimeout(()=>{let q=Bt(Ar.Copy,16,"currentColor",2);q&&g.replaceChildren(q)},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||(Zo=!1,pi=!0,ho=!0,Ta=!0,k.selectArtifact(f),yo())}),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(),Zo=!1,pi=!0,k.selectArtifact(f),yo())}),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 ui=Fe.composerOverlay,gi=(i,c,g)=>{let f=c.trim();if(!f||!pt.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})),Xr(ui,b);let W=pt.current.getMessages().find(z=>z.toolCall?.id===b);W?.agentMetadata?.awaitingLocalTool?pt.current.resolveAskUserQuestion(W,g.structured??f):pt.current.sendMessage(f)},ms=i=>{let c=pt.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:hd(i,f),currentIndex:io(i)})},Th=i=>Object.entries(i).map(([c,g])=>`${c}: ${Array.isArray(g)?g.join(", "):g}`).join(" | "),vu=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=io(i),g=qi(i);if(c>=g-1)return;let f=pt.current?.getMessages().find(b=>b.toolCall?.id===i.getAttribute("data-tool-call-id"));f&&(yd(i,f,o,c+1),ms(i))};ui.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})),Xr(ui,w);let W=pt.current?.getMessages().find(z=>z.toolCall?.id===w);W?.agentMetadata?.awaitingLocalTool&&(pt.current?.markAskUserQuestionResolved(W),pt.current?.resolveAskUserQuestion(W,"(dismissed)"));return}if(b==="pick"){let w=g.getAttribute("data-option-label");if(!w)return;let W=f.getAttribute("data-multi-select")==="true",z=Qr(f);if(z&&W){let q=js(f)[io(f)],V=new Set(Array.isArray(q)?q:[]);V.has(w)?V.delete(w):V.add(w),Jr(f,Array.from(V)),ms(f);return}if(z){Jr(f,w),ms(f),vu(f);return}if(W){let q=g.getAttribute("aria-pressed")==="true";g.setAttribute("aria-pressed",q?"false":"true"),g.classList.toggle("persona-ask-pill-selected",!q);let V=f.querySelector('[data-ask-user-action="submit-multi"]');V&&(V.disabled=Xg(f).length===0);return}gi(f,w,{source:"pick",values:[w]});return}if(b==="submit-multi"){let w=Xg(f);if(w.length===0)return;gi(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(Qr(f)){Jr(f,W.trim()),ms(f),vu(f);return}gi(f,W,{source:"free-text"});return}if(b==="next"||b==="back"){if(!pt.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=pt.current.getMessages().find(ae=>ae.toolCall?.id===w);if(!W)return;let q=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(q){let ae=js(f)[io(f)];(typeof ae!="string"||ae!==q)&&Jr(f,q)}let V=b==="next"?1:-1,Z=io(f)+V;yd(f,W,o,Z),ms(f);return}if(b==="submit-all"){if(!pt.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=pt.current.getMessages().find(ae=>ae.toolCall?.id===w);if(!W)return;let q=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";q&&Jr(f,q);let V=hd(f,W);pt.current.persistAskUserQuestionProgress(W,{answers:V,currentIndex:io(f)});let Z=Th(V);gi(f,Z||"(submitted)",{source:"submit-all",structured:V});return}if(b==="skip"){if(!pt.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=pt.current.getMessages().find(ye=>ye.toolCall?.id===w);if(!W)return;let z=Qr(f),q=io(f),V=qi(f),Z=q>=V-1;if(!z){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:w},bubbles:!0,composed:!0})),Xr(ui,w),W.agentMetadata?.awaitingLocalTool&&(pt.current.markAskUserQuestionResolved(W),pt.current.resolveAskUserQuestion(W,"(dismissed)"));return}Jr(f,"");let ae=f.querySelector('[data-ask-free-text-input="true"]');if(ae&&(ae.value=""),Z){let ye=hd(f,W),Ze=Th(ye);gi(f,Ze||"(skipped)",{source:"submit-all",structured:ye});return}yd(f,W,o,q+1),ms(f);return}}),ui.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(Qr(f)){Jr(f,b.trim()),ms(f),vu(f);return}gi(f,b,{source:"free-text"})}});let kh=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=ui.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",kh);let Ro=null,St=null,ka=null,rc=null,sc=()=>{},Ph=!1,ic="",ac="";function Cu(){rc?.(),rc=null}let gA=()=>{let i=Ei&&Ws?.isConnected?Ws:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},Lh=()=>{if(!Ro||!St)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){St.style.removeProperty("position"),St.style.removeProperty("left"),St.style.removeProperty("top"),St.style.removeProperty("bottom"),St.style.removeProperty("width"),St.style.removeProperty("z-index");return}let f=Ro.firstElementChild;if(!f||f===St)return;let b=10;St.style.position="absolute",St.style.top="0",St.style.bottom="0",St.style.width=`${b}px`,St.style.zIndex="5";let w=Tf(Ro,c),W=f.offsetWidth+w/2-b/2;St.style.left=`${Math.max(0,W)}px`},lc=()=>{},mA=()=>{let i=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,g=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>g?!1:we||Et(o)},cc=()=>!xn(o)||!oc()||e.classList.contains("persona-artifact-narrow-host")||mA()||(e.ownerDocument.defaultView??window).innerWidth<R0?"none":Sf(o)?"detached":"welded",yo=()=>{if(!Ve||!xn(o))return;_l(e,o),Dl(e,o),lc();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=Me.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let g=oc();Ve.setVisible(g),Ve.update(Jn),Zo?(Ve.setMobileOpen(!1),Ve.element.classList.add("persona-hidden"),Ve.backdrop?.classList.add("persona-hidden"),ho=!1,Ta=!1):Jn.artifacts.length>0&&Eh()?(Ve.element.classList.remove("persona-hidden"),Ve.setMobileOpen(!0)):(Ve.setMobileOpen(!1),Ve.element.classList.add("persona-hidden"),Ve.backdrop?.classList.add("persona-hidden"),ho=!1,Ta=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ve.setExpandToggleVisible(f),Ve.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ve.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Ve.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ve.setTabFade(o.features?.artifacts?.layout?.tabFade),Ve.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!Ta&&(ho=!1),ho!==Ph){let w=Ve.element;ho?(ic=w.style.width,ac=w.style.maxWidth,w.style.removeProperty("width"),w.style.removeProperty("max-width")):(ic&&(w.style.width=ic),ac&&(w.style.maxWidth=ac),ic="",ac=""),Ph=ho}e.classList.toggle("persona-artifact-expanded",ho),Ve.setExpanded(ho);let b=cc();b!==Ea&&(Ea=b,gs()),sc()};if(xn(o)){Me.style.position="relative";let i=M("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=M("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(fe),Ro=c,c.appendChild(i),Me.appendChild(c);let g=b=>{Mh||Ve||(Ve=b.createArtifactPane(o,{onSelect:w=>pt.current?.selectArtifact(w),onDismiss:()=>{Zo=!0,yo()},onToggleExpand:()=>{let w=!ho,W=Jn.selectedId??Jn.artifacts[Jn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:W,expanded:w})!==!0&&(ho=w,w||(Ta=!1),yo())}}),Ve.element.classList.add("persona-hidden"),c.appendChild(Ve.element),Ve.backdrop&&Me.appendChild(Ve.backdrop),sc(),yo())},f=wr();f?g(f):(wf(()=>{let b=wr();b&&g(b)}),Pp().catch(()=>{})),sc=()=>{if(!Ro||!Ve)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){ka?.(),ka=null,Cu(),St&&(St.remove(),St=null),Ve.element.style.removeProperty("width"),Ve.element.style.removeProperty("maxWidth");return}if(!St){let w=M("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");w.setAttribute("role","separator"),w.setAttribute("aria-orientation","vertical"),w.setAttribute("aria-label","Resize artifacts panel"),w.tabIndex=0;let W=e.ownerDocument,z=W.defaultView??window,q=V=>{if(!Ve||V.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||z.innerWidth<=640)return;V.preventDefault(),Cu();let Z=V.clientX,ae=Ve.element.getBoundingClientRect().width,ye=o.features?.artifacts?.layout,Ze=ft=>{let Zt=Ro.getBoundingClientRect().width,Ut=e.classList.contains("persona-artifact-welded-split"),Wt=Tf(Ro,z),dn=Ut?0:w.getBoundingClientRect().width||6,tt=ae-(ft.clientX-Z),pn=Rx(tt,Zt,Wt,dn,ye?.resizableMinWidth,ye?.resizableMaxWidth,gA());Ve.element.style.width=`${pn}px`,Ve.element.style.maxWidth="none",Lh()},ut=()=>{W.removeEventListener("pointermove",Ze),W.removeEventListener("pointerup",ut),W.removeEventListener("pointercancel",ut),rc=null;try{w.releasePointerCapture(V.pointerId)}catch{}};rc=ut,W.addEventListener("pointermove",Ze),W.addEventListener("pointerup",ut),W.addEventListener("pointercancel",ut);try{w.setPointerCapture(V.pointerId)}catch{}};w.addEventListener("pointerdown",q),St=w,Ro.insertBefore(w,Ve.element),ka=()=>{w.removeEventListener("pointerdown",q)}}if(St){let w=oc();St.classList.toggle("persona-hidden",!w),Lh()}},lc=()=>{if(!we||!Ve||(o.launcher?.sidebarMode??!1)||Et(o)&&Hn(o).reveal==="emerge")return;let w=e.ownerDocument.defaultView??window,W=o.launcher?.mobileFullscreen??!0,z=o.launcher?.mobileBreakpoint??640;if(W&&w.innerWidth<=z||!Ex(o,we))return;let q=o.launcher?.width??o.launcherWidth??Vn,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";oc()?(Me.style.width=V,Me.style.maxWidth=V):(Me.style.width=q,Me.style.maxWidth=q)},typeof ResizeObserver<"u"&&(Ma=new ResizeObserver(()=>{yo()}),Ma.observe(Me))}else Me.appendChild(fe);xe()&&Jt&&(Fe.peekBanner&&Jt.appendChild(Fe.peekBanner),Jt.appendChild(He)),e.appendChild(Ye),Jt&&e.appendChild(Jt);let wu=()=>{if(xe()){Me.style.width="100%",Me.style.maxWidth="100%";let $e=o.launcher?.composerBar??{},bt=Ye.dataset.state==="expanded",st=$e.expandedSize??"anchored";if(!(bt&&st!=="fullscreen")){fe.style.background="",fe.style.border="",fe.style.borderRadius="",fe.style.overflow="",fe.style.boxShadow="";return}let vt=o.theme?.components?.panel,mr=ns(o),en=($s,rd)=>$s==null||$s===""?rd:vn(mr,$s)??$s,so="1px solid var(--persona-border)",Ct="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Og="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";fe.style.background="var(--persona-surface, #ffffff)",fe.style.border=en(vt?.border,so),fe.style.borderRadius=en(vt?.borderRadius,Og),fe.style.boxShadow=en(vt?.shadow,Ct),fe.style.overflow="hidden";return}let i=Et(o),c=o.launcher?.sidebarMode??!1,g=i||c||(o.launcher?.fullHeight??!1),f=o.launcher?.enabled===!1,b=o.launcher?.detachedPanel===!0,w=o.theme?.components?.panel,W=ns(o),z=($e,bt)=>$e==null||$e===""?bt:vn(W,$e)??$e,q=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,Z=o.launcher?.mobileBreakpoint??640,ae=q.innerWidth<=Z,ye=V&&ae&&we,Ze=i&&V&&ae,ut=o.launcher?.position??"bottom-left",ft=ut==="bottom-left"||ut==="top-left",Zt=o.launcher?.zIndex??ln,Ut="var(--persona-panel-border, 1px solid var(--persona-border))",Wt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",dn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",tt=b&&!ye&&!Ze;tt?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let pn=tt?Ut:c||ye?"none":Ut,Do=tt?Wt:ye?"none":c?ft?"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":Wt;i&&!ye&&!tt&&(Do="none",pn="none");let gr=tt?dn:c||ye?"0":dn,No=z(w?.border,pn),_i=z(w?.shadow,Do),Fs=z(w?.borderRadius,gr),I=cc(),Le=I==="detached",Be=I==="welded";e.classList.toggle("persona-artifact-detached-split",Le),e.classList.toggle("persona-artifact-welded-split",Be);let Ae="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)))))",dt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&xn(o)&&Sf(o)&&f&&!i;e.classList.toggle("persona-artifact-chat-flush",dt);let Re=Le||dt?"none":_i,Co=Le?Ut:Be?"none":No,Pt=Le?dn:Fs;dt&&(Co="none",Pt="0");let sn=w?.borderRadius!=null&&w.borderRadius!=="",Qt=dt&&!sn?"0":Fs,Ot=re.scrollTop;e.style.cssText="",Ye.style.cssText="",Me.style.cssText="",fe.style.cssText="",re.style.cssText="",di||(He.style.cssText=""),v&&(re.style.display="none"),(g||f)&&(e.style.minWidth="0");let De=()=>{if(Ot<=0)return;(re.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(re.scrollTop===Ot)return;let bt=re.scrollHeight-re.clientHeight;bt<=0||(re.scrollTop=Math.min(Ot,bt))})};if(ye){Ye.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"),Ye.style.cssText=`
|
|
43
|
+
`,_.addEventListener("click",()=>{m=A,k.forEach((G,le)=>{let ee=le<A;G.classList.toggle("selected",ee),G.setAttribute("aria-checked",le===A-1?"true":"false")})}),k.push(_),w.appendChild(_)}y.appendChild(w);let O=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",O=document.createElement("textarea"),O.className="persona-feedback-comment",O.placeholder=s,O.rows=3,O.setAttribute("aria-label","Additional comments"),A.appendChild(O),y.appendChild(A)}let D=document.createElement("div");D.className="persona-feedback-actions";let T=document.createElement("button");T.type="button",T.className="persona-feedback-btn persona-feedback-btn-skip",T.textContent=l,T.addEventListener("click",()=>{n?.(),u.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=a,I.addEventListener("click",async()=>{if(m===null){w.classList.add("persona-feedback-shake"),setTimeout(()=>w.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let A=O?.value.trim()||void 0;await t(m,A),u.remove()}catch(A){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),D.appendChild(T),D.appendChild(I),y.appendChild(D),u.appendChild(y),u}function Bp(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:p="Not likely",highLabel:u="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let y=null,h=document.createElement("div");h.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,v.appendChild(x);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=r,v.appendChild(w),h.appendChild(v);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let O=document.createElement("div");O.className="persona-feedback-labels";let D=document.createElement("span");D.className="persona-feedback-label-low",D.textContent=p;let T=document.createElement("span");T.className="persona-feedback-label-high",T.textContent=u,O.appendChild(D),O.appendChild(T);let I=document.createElement("div");I.className="persona-feedback-numbers";let A=[];for(let M=0;M<=10;M++){let B=document.createElement("button");B.type="button",B.className="persona-feedback-rating-btn persona-feedback-number-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`Rating ${M} out of 10`),B.textContent=String(M),B.dataset.rating=String(M),M<=6?B.classList.add("persona-feedback-detractor"):M<=8?B.classList.add("persona-feedback-passive"):B.classList.add("persona-feedback-promoter"),B.addEventListener("click",()=>{y=M,A.forEach((H,R)=>{H.classList.toggle("selected",R===M),H.setAttribute("aria-checked",R===M?"true":"false")})}),A.push(B),I.appendChild(B)}k.appendChild(O),k.appendChild(I),h.appendChild(k);let _=null;if(d){let M=document.createElement("div");M.className="persona-feedback-comment-container",_=document.createElement("textarea"),_.className="persona-feedback-comment",_.placeholder=s,_.rows=3,_.setAttribute("aria-label","Additional comments"),M.appendChild(_),h.appendChild(M)}let G=document.createElement("div");G.className="persona-feedback-actions";let le=document.createElement("button");le.type="button",le.className="persona-feedback-btn persona-feedback-btn-skip",le.textContent=l,le.addEventListener("click",()=>{n?.(),m.remove()});let ee=document.createElement("button");return ee.type="button",ee.className="persona-feedback-btn persona-feedback-btn-submit",ee.textContent=a,ee.addEventListener("click",async()=>{if(y===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}ee.disabled=!0,ee.textContent="Submitting...";try{let M=_?.value.trim()||void 0;await t(y,M),m.remove()}catch(M){ee.disabled=!1,ee.textContent=a,console.error("[NPS Feedback] Failed to submit:",M)}}),G.appendChild(le),G.appendChild(ee),h.appendChild(G),m.appendChild(h),m}var ca="persona-chat-history",O0=30*1e3,B0=641,da="data-persona-composer-reason",_0={"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 D0(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=_0[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 _p(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 N0(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 F0(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Wf=e=>!e||typeof e!="object"?{}:{...e},Zx=e=>e.map(t=>({...t,streaming:!1})),eS=(e,t,n)=>{let o=e?.markdown?nl(e.markdown):null,r=cd(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=Do()!==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?iv(d):d,h=o(y);m=r&&u?r(h):h}else m=pr(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)),pr(l.text??"")}}};function tS(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=de(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 $0=(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},U0=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:$0(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Dp=(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=Gi(t),r=()=>{MC({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=Bl(o);let a=_l.getForInstance(o.plugins),l=Aw(e),d=[],p=!1,u=Cx(()=>o),m=null,y=null,h=null,v=!1,x=null,w=i=>{m=i,i.initApprovalUi({webMcpToolTitle:Oi});let c=i.createBuiltInApprovalPlugin();y=c.plugin,h=c.teardown},k=()=>{if(m)return m;let i=Mx();return i?(w(i),i):(Ax().then(c=>{v||m||(w(c),x?.())}).catch(()=>{}),null)},O=!1,D=!1,T=null,I=(i,c,g,f)=>{if(!i.querySelector("[data-tv-form]"))return;let b=_x();if(b){b.enhanceWithForms(i,c,g,f);return}Bx().then(()=>{O||D||!T||(D=!0,T())}).catch(()=>{})};o.components&&So.registerAll(o.components);let A=Fx(),G=o.persistState===!1?null:o.storageAdapter??Lp(),le=!!o.clientToken&&typeof o.reconnectStream!="function",ee={},M=null,B,H=new Promise(i=>{B=i}),R,Z=!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&&(Z=!0),g}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(G?.load)try{let i=G.load();if(i&&typeof i.then=="function")M=i.then(c=>V(c??{messages:[],metadata:{}}));else{let g=V(i??{messages:[],metadata:{}});g.metadata&&(ee=Wf(g.metadata)),g.messages?.length&&(o={...o,initialMessages:g.messages}),g.artifacts?.length&&(o={...o,initialArtifacts:g.artifacts,initialSelectedArtifactId:g.selectedArtifactId??null}),R=g.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=V({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}M||B();let ge=()=>ee,ae=i=>{ee=i({...ee})??{},ui()},fe=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dl],He=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Qs.message,Qs.messageAndClick],ve=Nl({parsers:fe,handlers:He,getSessionMetadata:ge,updateSessionMetadata:ae,emit:A.emit,documentRef:typeof document<"u"?document:null});ve.syncFromMetadata();let pe=o.launcher?.enabled??!0,et=o.launcher?.autoExpand??!1,ye=o.autoFocusInput??!1,F=et,_e=pe,qe=o.layout?.header?.layout,Dt=!1,Ce=()=>es(o),De=()=>pe||Ce(),we=Ce()?!1:pe?et:!0,Ae=!1,Ct=null,Wt=()=>{Ae=!0,Ct&&clearTimeout(Ct),Ct=setTimeout(()=>{Ae&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Ae=!1)},1e4)},mt=eS(o,ve,Wt),xn=o.features?.showReasoning??!0,q=o.features?.showToolCalls??!0,S=o.features?.showEventStreamToggle??!1,N=o.features?.scrollToBottom??{},z=o.features?.scrollBehavior??{},Q=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",be=`${Q()}event-stream`,ke=null,Ie=o.features?.eventStream?.maxEvents??2e3,Oe=null,at=null,Ye=null,ze=!1,bt=null,Qt=!1,Ot=null,ln=0,Sn=(i,c)=>{Oe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},eu=(i,c)=>{at?.processEvent(i,c),Oe?Sn(i,c):Ye&&(Ye.length>=Ie&&Ye.shift(),Ye.push({type:i,payload:c}))},ql=()=>{Oe||!S||(Ye??(Ye=[]),bf().then(i=>{if(ze||Oe||!S)return;ke=new i.EventStreamStore(be),Oe=new i.EventStreamBuffer(Ie,ke),at=at??new i.ThroughputTracker,ke.open().then(()=>Oe?.restore()).catch(g=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",g)});let c=Ye??[];Ye=null;for(let g of c)at?.processEvent(g.type,g.payload),Sn(g.type,g.payload)}).catch(()=>{}))};S&&ql();let Et=!1,Nt=null,tu=()=>{},Vo=()=>{},Zf=()=>{},eh=()=>{},nu=()=>{},YS=()=>Qt||Et&&Nt==="panel",Js={onCopy:i=>{A.emit("message:copy",i),P?.isClientTokenMode()&&P.submitMessageFeedback(i.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{A.emit("message:feedback",i),P?.isClientTokenMode()&&P.submitMessageFeedback(i.messageId,i.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(i)}},Zs=o.statusIndicator??{},th=i=>i==="idle"?Zs.idleText??Vt.idle:i==="connecting"?Zs.connectingText??Vt.connecting:i==="connected"?Zs.connectedText??Vt.connected:i==="error"?Zs.errorText??Vt.error:i==="paused"?Zs.pausedText??Vt.paused:i==="resuming"?Zs.resumingText??Vt.resuming:Vt[i];function zl(i,c,g,f){if(!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 Nn=vx({config:o,showClose:De()}),{wrapper:Qe,panel:Me,pillRoot:Xt}=Nn.shell,Ne=Nn.panelElements,{container:ue,body:oe,messagesWrapper:Le,starterSuggestions:ou,transcriptSuggestions:ua,suggestions:xr,textarea:ce,sendButton:Te,composerForm:co,statusText:lt,welcomeHost:An,welcomeIconHolder:QS,greetingHost:Fn,introKicker:XS,introTitle:JS,introSubtitle:ZS,closeButton:Ue,iconHolder:Tt,headerTitle:Sr,headerSubtitle:os,header:Pe,footer:Re,actionsRow:eA}=Ne,ru=Ne.leftActions,Vl=Ne.rightActions,Mo=Ne.sendButtonWrapper,nh=Ne.setSendButtonMode,re=Ne.micButton,$n=Ne.micButtonWrapper,Mt=Ne.attachmentButton,Mn=Ne.attachmentButtonWrapper,vt=Ne.attachmentInput,En=Ne.attachmentPreviewsContainer;ue.classList.add("persona-relative"),oe.classList.add("persona-relative");let tA=12,ga=()=>N.label??"",nA=()=>N.iconName??"arrow-down",oA=()=>N.enabled!==!1,Un=()=>z.mode??"anchor-top",Ar=()=>Un()==="follow"||Un()==="anchor-top"&&Sa,ma=()=>z.anchorTopOffset??16,rA=()=>z.restorePosition??"bottom",oh=()=>z.pauseOnInteraction===!0,rh=()=>z.showActivityWhilePinned!==!1,sh=()=>z.announce===!0,su=()=>z.scrollbar??"on-scroll",Ft=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");Ft.type="button",Ft.style.display="none",Ft.setAttribute("data-persona-scroll-to-bottom","true");let fa=E("span","persona-flex persona-items-center"),iu=E("span",""),rs=E("span","");rs.setAttribute("data-persona-scroll-to-bottom-count",""),rs.style.display="none",Ft.append(fa,iu,rs),ue.appendChild(Ft);let Xn=E("div","persona-stream-anchor-spacer");Xn.setAttribute("aria-hidden","true"),Xn.setAttribute("data-persona-anchor-spacer",""),Xn.style.flexShrink="0",Xn.style.pointerEvents="none",Xn.style.height="0px",Xn.style.display="none",oe.appendChild(Xn);let Ko=E("div","persona-sr-only");Ko.setAttribute("aria-live","polite"),Ko.setAttribute("aria-atomic","true"),Ko.setAttribute("role","status"),Ko.setAttribute("data-persona-live-region",""),Object.assign(Ko.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),ue.appendChild(Ko);let ha=null,Kl=null,Gl=i=>{!sh()||!i||(Kl=i,ha===null&&(ha=setTimeout(()=>{ha=null,Kl&&sh()&&(Ko.textContent=Kl),Kl=null},400)))},Yl="empty",Ql=0,au=()=>Ql||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,ss=()=>{let c=Re.style.display==="none"?0:Re.offsetHeight;Ft.style.bottom=`${c+au()+tA}px`};ss();let lu=()=>{ri||(Re.style.marginBottom=Ql>0?`${Ql}px`:"")},Xl=()=>{let i=_m(o,Ce()),c=xo(o),f=Re.style.display==="none"?0:Re.offsetHeight,b=c.anchor==="center"&&Yl==="empty"?Cl(c.anchorComposerTop)??Cl("44%"):null,C=b===null||Ce()?0:ww({columnHeight:ue.clientHeight,footerHeight:f,fraction:b});e.style.setProperty("--persona-composer-overlay-height",`${f}px`),e.style.setProperty("--persona-composer-lift",`${i==="overlay"?C:0}px`),Ql=i==="block"?C:0,lu(),ss()},ih=()=>{let i=!!ga();Ft.setAttribute("aria-label",ga()||"Jump to latest"),Ft.title=ga(),Ft.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),fa.innerHTML="";let c=de(nA(),"14px","currentColor",2);c?(fa.appendChild(c),fa.style.display=""):fa.style.display="none",iu.textContent=ga(),iu.style.display=i?"":"none"};ih();let tt=null,Bt=null,xe=vC(),sA=i=>{try{ue.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};xe.subscribe(sA);let Eo=()=>{xe.setText(ce?.value??"")},is=()=>{xe.setMentionRefs(Bt?.getMentionRefs()??[])},iA=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}),ah=i=>{let c=Object.freeze(i.map(iA));xe.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(g){console.error("[AgentWidget] attachments.onChange failed:",g)}Ou()};xe.setSelectedModelId(o.composer?.selectedModelId);let ya=()=>o.composer?.modes??[],ei=()=>VC(ya(),o.composer?.modeGroups);{let i=Yd(o.composer?.defaultActiveModeIds??[],ya());i.length&&xe.setActiveModeIds(i)}function lh(i){if(xe.getState().selectedModelId!==i){xe.setSelectedModelId(i),Mr?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function Jl(i){xe.setActiveModeIds(i),Go?.render(i,ei()),ti.forEach(c=>c.repaint()),Po?.resolve(),Sc(),po()}function cu(i){Jl(KC(xe.getState().activeModeIds,i,ya(),o.composer?.modeGroups))}let Mr=null,du=null,Go=null,ti=new Map,Er=null;function To(i){xe.setQuote(i),Er?.render(xe.getState().quote),po(),ey()}let ch=!1;function pu(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!ch&&o.debug===!0&&(ch=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Tr=null;function ni(i){xe.setPendingSubmission(i),Tr?.render(xe.getState().pendingSubmission),po()}let aA=i=>{let c=ti.get(i);if(c)return c;let g=QC({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===i),getModes:()=>ya().filter(f=>f.groupId===i),getActiveIds:()=>xe.getState().activeModeIds,onSelect:f=>cu(f)});return ti.set(i,g),g},lA=()=>{let i=[],c=xe.getState().activeModeIds,g=new Set;if(ya().forEach((f,b)=>{if(Gd(f.groupId,o.composer?.modeGroups)){let C=f.groupId;if(g.has(C))return;g.add(C);let W=aA(C);W.action.order=km(b),W.action.label=o.composer?.modeGroups?.find(U=>U.id===C)?.label??C,i.push(W.action);return}i.push({id:qC(f.id),kind:"button",placement:"start",order:km(b),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:c.includes(f.id),onSelect:()=>cu(f.id)})}),o.composer?.models?.length&&!a.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!Mr||du!==f)&&(du=f,Mr=UC({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>xe.getState().selectedModelId,onSelect:b=>lh(b),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Mr.action)}return i},uu=null,dh=a.find(i=>i.renderHeader);if(dh?.renderHeader){let i=dh.renderHeader({config:o,defaultRenderer:()=>{let c=hr({config:o,showClose:De()});return qs(ue,c,o),c.header},onClose:()=>ft(!1,"user")});if(i){let c=Pe;c&&(c.replaceWith(i),Pe=i,Nn.header.element=i)}}let ph=()=>{bt&&(oe.style.display="none",Re.parentNode?.insertBefore(bt.element,Re),bt.update())},gu=()=>{if(!Oe){ql();return}if(Qt=!0,bt?ph():bf().then(c=>{bt||!Qt||!Oe||(bt=c.createEventStreamView({buffer:Oe,getFullHistory:()=>Oe.getAllFromStore(),onClose:()=>oi(),config:o,plugins:a,getThroughput:()=>at?.getMetric()??{status:"idle"},renderIconByName:de}),ph())}).catch(()=>{oi()}),ot){ot.style.boxShadow=`inset 0 0 0 1.5px ${vn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(g=>g&&ot.classList.add(g))}let i=()=>{if(!Qt)return;let c=Date.now();c-ln>=200&&(bt?.update(),ln=c),Ot=requestAnimationFrame(i)};ln=0,Ot=requestAnimationFrame(i),Gt(),A.emit("eventStream:opened",{timestamp:Date.now()})},oi=()=>{if(Qt){if(Qt=!1,bt&&bt.element.remove(),oe.style.display="",ot){ot.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&ot.classList.remove(c))}Ot!==null&&(cancelAnimationFrame(Ot),Ot=null),Gt(),A.emit("eventStream:closed",{timestamp:Date.now()})}},ot=null;if(S){let i=o.features?.eventStream?.classNames,c="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");ot=E("button",c),ot.style.width="28px",ot.style.height="28px",ot.style.color=vn.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let g=Ht(Cr.Activity,"18px","currentColor",1.5);g&&ot.appendChild(g);let f=Ne.clearChatButtonWrapper,b=Ne.closeButtonWrapper,C=f||b;C&&C.parentNode===Pe?Pe.insertBefore(ot,C):Pe.appendChild(ot),ot.addEventListener("click",()=>{Qt?oi():gu()})}let uh=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??fr).join(","),b.multiple=(c.maxFiles??4)>1,b.style.display="none",b.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(b)}},ri=!1,gh=i=>{let c=a.find(b=>b.renderComposer);if(!c?.renderComposer)return null;let g=o.composer,f=p?P.isStreaming():!1;return c.renderComposer({config:o,defaultRenderer:i,requestRender:()=>Eb(),storage:u(c.id),onSubmit:b=>{!P||P.isStreaming()||Qc(b.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{Ro()||vt?.click()},models:g?.models,selectedModelId:xe.getState().selectedModelId??g?.selectedModelId,onModelChange:b=>lh(b),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{uu?.()}:void 0})},mh=gh(()=>Vs({config:o}).footer);mh&&(Nn.replaceComposer(mh),Re=Nn.composer.footer,ri=!0);let rt=null,cA=i=>{co=i.form,ce=i.input,Mo=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Te=i.sendButton),i.micButton&&(re=i.micButton,$n=i.micButton.parentElement),i.found.status&&(lt=i.found.status),i.found.suggestions&&(xr=i.found.suggestions),i.attachmentButton&&(Mt=i.attachmentButton,Mn=i.attachmentButton.parentElement),vt=i.attachmentInput??null,En=i.attachmentPreviews??null,i.found.actionsRow&&(eA=i.found.actionsRow),ru=i.found.actionsStart,Vl=i.found.actionsEnd};function mu(){let i=ce;if(!i)return;let c=o.composer?.inputAttributes,g=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;Nd(i,c),g&&i.setAttribute("aria-label",g),Dd(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:hl(i)}),LC(i,_d(o.composer?.maxLines,Ce()?5:3))}let fh=i=>{rt=wC(i,{debug:o.debug===!0}),rt&&cA(rt),mu()};uh(Re),fh(Re),Eo();let ba=Jr(o,Ce());ba&&(Le.style.maxWidth=ba,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%",Fn.style.maxWidth=ba,Fn.style.marginLeft="auto",Fn.style.marginRight="auto",Fn.style.width="100%",ou.style.maxWidth=ba,ua.style.maxWidth=ba,ua.style.marginLeft="auto",ua.style.marginRight="auto",ua.style.width="100%");let hh=()=>{let i=Jr(o,Ce());if(!(!i||Ce()))for(let c of[co,xr,En,lt])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};hh();let yh=()=>{!o.attachments?.enabled||!vt||!En||(tt?tt.remountPreviews(En):(tt=Fs.fromConfig(o.attachments,ah),tt.setPreviewsContainer(En)),rt?.addListener(vt,"change",i=>{let c=i.target;tt?.handleFileSelect(c.files),c.value=""}),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(tS(o.attachments.dropOverlay)))};yh();let dA=()=>Bt?.prefetch(),bh=()=>{if(!o.contextMentions?.enabled||!ce)return;let i=rt?.header??null,c=i?Pm(i):void 0;if(Bt=hw({config:o,textarea:ce,anchor:co??ce,getMessages:()=>P.getMessages(),liveRegionHost:ue,chipRow:c}),Bt&&!c){let g=ce;g.parentElement?.insertBefore(Bt.contextRow,g)}};bh();let Po=null,pA={getState:()=>xe.getState(),getValue:()=>ce?.value??"",setValue:i=>{ce&&(ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),Eo())},submit:()=>{iw(rt?.form??null)},openAttachmentPicker:()=>{Ro()||vt?.click()},toggleVoice:()=>{uu?.()},requestRender:()=>Po?.resolve()},uA=()=>{let i=[];return(Bt?.affordanceButtons??[]).forEach((g,f)=>{i.push({id:`core:mention-${f}`,placement:"start",order:Uo.mention+f,element:g,managed:!0})}),Mn&&i.push({id:"core:attachment",placement:"start",order:Uo.attachment,element:Mn}),$n&&i.push({id:"core:mic",placement:"end",order:Uo.mic,element:$n}),Mo&&i.push({id:"core:send",placement:"end",order:Uo.send,element:Mo}),i},vh=()=>{Po?.destroy(),Po=NC({getBindings:()=>rt,collect:()=>({builtIns:uA(),configActions:[...lA(),...o.composer?.actions??[]],plugins:a,contributionContext:{config:o,getState:()=>xe.getState(),requestRender:()=>Po?.resolve()},debug:o.debug===!0}),actionContext:pA,getState:()=>xe.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),Po.resolve()};vh();let fu=()=>{if(Go?.destroy(),Go=null,!ei().length)return;let i=rt?.header;i&&(Go=jC({row:Pm(i),onRemove:c=>cu(c),initialIds:xe.getState().activeModeIds}),Go.render(xe.getState().activeModeIds,ei()))};fu();let Ch=()=>{Er?.destroy(),Er=null,Tr?.destroy(),Tr=null;let i=rt?.header;i&&(Er=XC({onDismiss:()=>To(void 0)}),i.appendChild(Er.element),Er.render(xe.getState().quote),pu()==="defer-one"&&(Tr=JC({onEdit:()=>FM(),onRemove:()=>ni(void 0)}),i.appendChild(Tr.element),Tr.render(xe.getState().pendingSubmission)))};Ch();let hu=rw(),gA=()=>{let i=rt?.header?.querySelector(Tm);if(i)return i.childElementCount>0;let c=xe.getState();return c.mentionRefs.length>0||Yd(c.activeModeIds,ei()).length>0},wh=()=>!1;function po(){let i=xe.getState(),c=hu.observe(sw(ce),i.text);Re.toggleAttribute("data-persona-composer-compact",ow({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:gA(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0,dictationActive:wh()}))}function xh(){o.composer?.layout==="single-row"&&!Ce()?Re.setAttribute("data-persona-composer-layout","single-row"):Re.removeAttribute("data-persona-composer-layout")}xh(),xe.subscribe(()=>{Po?.sync(),Ou(),wc(),po(),ey()}),wc();let Sh=!1,mA=i=>{if(Sh||o.debug!==!0)return;let c=["messages","composer"].filter(g=>i[g]);c.length&&(Sh=!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??{};mA(i);let c=f=>{switch(f){case"body-top":return oe.querySelector("[data-persona-intro-card]");case"messages":return Le;case"footer-top":return xr;case"composer":return co;case"footer-bottom":return lt;default:return null}},g=(f,b)=>{switch(f){case"header-left":case"header-center":case"header-right":if(f==="header-left")Pe.insertBefore(b,Pe.firstChild);else if(f==="header-right")Pe.appendChild(b);else{let C=Pe.querySelector(".persona-flex-col");C?C.parentNode?.insertBefore(b,C.nextSibling):Pe.appendChild(b)}break;case"body-top":{let C=oe.querySelector("[data-persona-intro-card]");C?C.replaceWith(b):oe.insertBefore(b,oe.firstChild);break}case"body-bottom":oe.appendChild(b);break;case"footer-top":xr.replaceWith(b);break;case"footer-bottom":lt.replaceWith(b);break;default:break}};for(let[f,b]of Object.entries(i))if(b)try{let C=b({config:o,defaultContent:()=>c(f)});C&&g(f,C)}catch(C){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${f}":`,C)}})();let Ah=i=>{let g=i.target.closest('button[data-expand-header="true"]');if(!g)return;let f=g.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!f)return;let b=f.getAttribute("data-message-id");if(!b)return;let C=g.getAttribute("data-bubble-type");if(C==="reasoning")oa.has(b)?oa.delete(b):oa.add(b),wx(b,f);else if(C==="tool")ra.has(b)?ra.delete(b):ra.add(b),Sx(b,f,o);else if(C==="approval"&&m){let U=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",$=m.approvalDetailsExpansionState.get(b)??U;m.approvalDetailsExpansionState.set(b,!$),m.updateApprovalDetailsUI(b,f,o)}$t.delete(b)};Le.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Ah(i))}),Le.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Ah(i))}),Le.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let g=Le.getRootNode(),f=typeof g.getSelection=="function"?g.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let b=f.toString(),C=Ew(b);!C||C===b||(c.setData("text/plain",C),i.preventDefault())});let yu=new Map,Mh=null,Eh="idle",fA={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}=fA[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=de(g,14,"currentColor",2);b&&(i.innerHTML="",i.appendChild(b))},Th=()=>{Le.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let f=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;hA(c,f&&f===Mh?Eh:"idle")})};Le.addEventListener("click",i=>{let g=i.target.closest(".persona-message-action-btn[data-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest("[data-actions-for]");if(!f)return;let b=f.getAttribute("data-actions-for");if(!b)return;let C=g.getAttribute("data-action");if(C==="copy"){let U=P.getMessages().find($=>$.id===b);if(U&&Js.onCopy){let $=U.content||"";navigator.clipboard.writeText($).then(()=>{g.classList.add("persona-message-action-success");let j=Ht(Cr.Check,14,"currentColor",2);j&&(g.innerHTML="",g.appendChild(j)),setTimeout(()=>{g.classList.remove("persona-message-action-success");let X=Ht(Cr.Copy,14,"currentColor",2);X&&(g.innerHTML="",g.appendChild(X))},2e3)}).catch(j=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",j)}),Js.onCopy(U)}}else if(C==="read-aloud")P.toggleReadAloud(b);else if(C==="upvote"||C==="downvote"){let U=(yu.get(b)??null)===C,$=C==="upvote"?"thumbs-up":"thumbs-down";if(U){yu.delete(b),g.classList.remove("persona-message-action-active");let j=de($,14,"currentColor",2);j&&(g.innerHTML="",g.appendChild(j))}else{let j=C==="upvote"?"downvote":"upvote",X=f.querySelector(`[data-action="${j}"]`);if(X){X.classList.remove("persona-message-action-active");let ht=de(j==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ht&&(X.innerHTML="",X.appendChild(ht))}yu.set(b,C),g.classList.add("persona-message-action-active");let se=de($,14,"currentColor",2);se&&(se.setAttribute("fill","currentColor"),g.innerHTML="",g.appendChild(se)),g.classList.remove("persona-message-action-pop"),g.offsetWidth,g.classList.add("persona-message-action-pop");let Ze=P.getMessages().find(ut=>ut.id===b);Ze&&Js.onFeedback&&Js.onFeedback({type:C,messageId:Ze.id,message:Ze})}}else if(C==="regenerate")Zl?.regenerate(b);else if(C==="edit")Zl?.edit(b);else if(C==="quote")Zl?.quote(b);else if(C?.startsWith(mp)){let W=C.slice(mp.length),U=o.messageActions?.custom?.find(j=>j.id===W),$=P.getMessages().find(j=>j.id===b);if(!U||!$)return;try{U.onSelect($)}catch(j){console.error(`[AgentWidget] messageActions.custom "${W}" onSelect failed:`,j)}}});let Zl=null;Le.addEventListener("click",i=>{let g=i.target.closest("button[data-approval-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest(".persona-approval-bubble");if(!f)return;let b=f.getAttribute("data-message-id");if(!b)return;let C=g.getAttribute("data-approval-action");if(!C)return;let W=C==="approve"?"approved":"denied",$=P.getMessages().find(X=>X.id===b);if(!$?.approval)return;let j=f.querySelector("[data-approval-buttons]");j&&j.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),$.approval.toolType==="webmcp"?P.resolveWebMcpApproval(b,W):P.resolveApproval($.approval,W)});let Ve=null,Ph=!1,va=null,as=()=>{},Ca="none",ec=null,Jn={artifacts:[],selectedId:null},Yo=!1,uo=!1,wa=!1,si=!1,kh=()=>si||Jn.artifacts.some(i=>No(o.features?.artifacts,i)==="panel"),tc=()=>Jn.artifacts.length>0&&!Yo&&kh(),pt={current:null},bu=(i,c)=>{let g=P.getArtifactById(c),f=g?.markdown,b=g?.title||"artifact",C=g?.file,W=g?.artifactType??"markdown";if(!f){let j=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(j){let se=P.getMessages().find(me=>me.id===j);if(se?.rawContent)try{let me=JSON.parse(se.rawContent);f=me?.props?.markdown,b=me?.props?.title||b,me?.props?.file&&typeof me.props.file=="object"&&(C=me.props.file),!g&&typeof me?.props?.artifactType=="string"&&(W=me.props.artifactType)}catch{}}}return{markdown:f,title:b,file:C,artifactType:W}};Le.addEventListener("click",i=>{let g=i.target.closest("[data-download-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-download-artifact");if(!f||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:f})===!0)return;let{markdown:C,title:W,file:U}=bu(g,f);if(!C)return;let $=yr();$&&$.triggerArtifactDownload($.downloadInfoFor({title:W,markdown:C,file:U}))}),Le.addEventListener("click",i=>{let g=i.target.closest("[data-artifact-custom-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-artifact-custom-action");if(!f)return;let b=g.closest("[data-artifact-inline]"),C=b?null:g.closest("[data-open-artifact]"),W=b?b.getAttribute("data-artifact-inline"):C?.getAttribute("data-open-artifact")??null,$=(b?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ut=>ut.id===f);if(!$)return;let{markdown:j,title:X,file:se,artifactType:me}=bu(g,W??""),Ze={artifactId:W,title:X,artifactType:me,markdown:j,file:se};try{Promise.resolve($.onClick(Ze)).catch(()=>{})}catch{}}),Le.addEventListener("click",i=>{let g=i.target.closest("[data-copy-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-copy-artifact");if(!f)return;let b=P.getArtifactById(f),C=yr();if(!C)return;let W="";if(b)W=C.artifactCopyText(b);else{let{markdown:U,file:$,artifactType:j}=bu(g,f);j==="markdown"&&(W=C.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:U??"",...$?{file:$}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let U=Ht(Cr.Check,16,"currentColor",2);U&&(g.replaceChildren(U),setTimeout(()=>{let $=Ht(Cr.Copy,16,"currentColor",2);$&&g.replaceChildren($)},1500))}).catch(()=>{})}),Le.addEventListener("click",i=>{let g=i.target.closest("[data-expand-artifact-inline]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-expand-artifact-inline");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(Yo=!1,si=!0,uo=!0,wa=!0,P.selectArtifact(f),go())}),Le.addEventListener("click",i=>{let c=i.target;if(c.closest("[data-download-artifact]")||c.closest("[data-artifact-custom-action]"))return;let g=c.closest("[data-open-artifact]");if(!g)return;let f=g.getAttribute("data-open-artifact");!f||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:f})===!0||(i.preventDefault(),i.stopPropagation(),Yo=!1,si=!0,P.selectArtifact(f),go())}),Le.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let c=i.target;!c.hasAttribute("data-open-artifact")&&!c.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),c.click())});let ii=Ne.composerOverlay,ai=(i,c,g)=>{let f=c.trim();if(!f||!pt.current)return;let b=i.getAttribute("data-tool-call-id")??"",C=g.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:b,answer:f,answers:g.structured,values:g.values??(g.source==="multi"?f.split(", "):[f]),isFreeText:C,source:g.source},bubbles:!0,composed:!0})),Vr(ii,b);let W=pt.current.getMessages().find(U=>U.toolCall?.id===b);W?.agentMetadata?.awaitingLocalTool?pt.current.resolveAskUserQuestion(W,g.structured??f):pt.current.sendMessage(f)},ls=i=>{let c=pt.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:gd(i,f),currentIndex:so(i)})},Lh=i=>Object.entries(i).map(([c,g])=>`${c}: ${Array.isArray(g)?g.join(", "):g}`).join(" | "),vu=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=so(i),g=Di(i);if(c>=g-1)return;let f=pt.current?.getMessages().find(b=>b.toolCall?.id===i.getAttribute("data-tool-call-id"));f&&(md(i,f,o,c+1),ls(i))};ii.addEventListener("click",i=>{let g=i.target.closest("[data-ask-user-action]");if(!g)return;let f=g.closest("[data-persona-ask-sheet-for]");if(!f)return;let b=g.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),b==="dismiss"){let C=f.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:C},bubbles:!0,composed:!0})),Vr(ii,C);let W=pt.current?.getMessages().find(U=>U.toolCall?.id===C);W?.agentMetadata?.awaitingLocalTool&&(pt.current?.markAskUserQuestionResolved(W),pt.current?.resolveAskUserQuestion(W,"(dismissed)"));return}if(b==="pick"){let C=g.getAttribute("data-option-label");if(!C)return;let W=f.getAttribute("data-multi-select")==="true",U=zr(f);if(U&&W){let $=Bs(f)[so(f)],j=new Set(Array.isArray($)?$:[]);j.has(C)?j.delete(C):j.add(C),Kr(f,Array.from(j)),ls(f);return}if(U){Kr(f,C),ls(f),vu(f);return}if(W){let $=g.getAttribute("aria-pressed")==="true";g.setAttribute("aria-pressed",$?"false":"true"),g.classList.toggle("persona-ask-pill-selected",!$);let j=f.querySelector('[data-ask-user-action="submit-multi"]');j&&(j.disabled=Xg(f).length===0);return}ai(f,C,{source:"pick",values:[C]});return}if(b==="submit-multi"){let C=Xg(f);if(C.length===0)return;ai(f,C.join(", "),{source:"multi",values:C});return}if(b==="open-free-text"){let C=f.querySelector('[data-ask-free-text-row="true"]');C&&(C.classList.remove("persona-hidden"),C.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(b==="focus-free-text"){f.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(b==="submit-free-text"){let W=f.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!W.trim())return;if(zr(f)){Kr(f,W.trim()),ls(f),vu(f);return}ai(f,W,{source:"free-text"});return}if(b==="next"||b==="back"){if(!pt.current)return;let C=f.getAttribute("data-tool-call-id")??"",W=pt.current.getMessages().find(se=>se.toolCall?.id===C);if(!W)return;let $=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if($){let se=Bs(f)[so(f)];(typeof se!="string"||se!==$)&&Kr(f,$)}let j=b==="next"?1:-1,X=so(f)+j;md(f,W,o,X),ls(f);return}if(b==="submit-all"){if(!pt.current)return;let C=f.getAttribute("data-tool-call-id")??"",W=pt.current.getMessages().find(se=>se.toolCall?.id===C);if(!W)return;let $=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";$&&Kr(f,$);let j=gd(f,W);pt.current.persistAskUserQuestionProgress(W,{answers:j,currentIndex:so(f)});let X=Lh(j);ai(f,X||"(submitted)",{source:"submit-all",structured:j});return}if(b==="skip"){if(!pt.current)return;let C=f.getAttribute("data-tool-call-id")??"",W=pt.current.getMessages().find(me=>me.toolCall?.id===C);if(!W)return;let U=zr(f),$=so(f),j=Di(f),X=$>=j-1;if(!U){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:C},bubbles:!0,composed:!0})),Vr(ii,C),W.agentMetadata?.awaitingLocalTool&&(pt.current.markAskUserQuestionResolved(W),pt.current.resolveAskUserQuestion(W,"(dismissed)"));return}Kr(f,"");let se=f.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),X){let me=gd(f,W),Ze=Lh(me);ai(f,Ze||"(skipped)",{source:"submit-all",structured:me});return}md(f,W,o,$+1),ls(f);return}}),ii.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(zr(f)){Kr(f,b.trim()),ls(f),vu(f);return}ai(f,b,{source:"free-text"})}});let Ih=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=ii.querySelector("[data-persona-ask-sheet-for]");if(!g||g.getAttribute("data-ask-layout")!=="rows"||g.getAttribute("data-multi-select")==="true")return;let f=Number(i.key),C=g.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[f-1];C&&(i.preventDefault(),C.click())};document.addEventListener("keydown",Ih);let ko=null,wt=null,xa=null,nc=null,oc=()=>{},Rh=!1,rc="",sc="";function Cu(){nc?.(),nc=null}let yA=()=>{let i=Ci&&Ps?.isConnected?Ps:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},Hh=()=>{if(!ko||!wt)return;let i=e.classList.contains("persona-artifact-welded-split"),c=e.ownerDocument.defaultView??window,g=c.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||g){wt.style.removeProperty("position"),wt.style.removeProperty("left"),wt.style.removeProperty("top"),wt.style.removeProperty("bottom"),wt.style.removeProperty("width"),wt.style.removeProperty("z-index");return}let f=ko.firstElementChild;if(!f||f===wt)return;let b=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${b}px`,wt.style.zIndex="5";let C=Tf(ko,c),W=f.offsetWidth+C/2-b/2;wt.style.left=`${Math.max(0,W)}px`},ic=()=>{},bA=()=>{let i=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,g=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>g?!1:pe||At(o)},ac=()=>!wn(o)||!tc()||e.classList.contains("persona-artifact-narrow-host")||bA()||(e.ownerDocument.defaultView??window).innerWidth<B0?"none":Sf(o)?"detached":"welded",go=()=>{if(!Ve||!wn(o))return;Wl(e,o),Ol(e,o),ic();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=Me.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let g=tc();Ve.setVisible(g),Ve.update(Jn),Yo?(Ve.setMobileOpen(!1),Ve.element.classList.add("persona-hidden"),Ve.backdrop?.classList.add("persona-hidden"),uo=!1,wa=!1):Jn.artifacts.length>0&&kh()?(Ve.element.classList.remove("persona-hidden"),Ve.setMobileOpen(!0)):(Ve.setMobileOpen(!1),Ve.element.classList.add("persona-hidden"),Ve.backdrop?.classList.add("persona-hidden"),uo=!1,wa=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ve.setExpandToggleVisible(f),Ve.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ve.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Ve.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ve.setTabFade(o.features?.artifacts?.layout?.tabFade),Ve.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!wa&&(uo=!1),uo!==Rh){let C=Ve.element;uo?(rc=C.style.width,sc=C.style.maxWidth,C.style.removeProperty("width"),C.style.removeProperty("max-width")):(rc&&(C.style.width=rc),sc&&(C.style.maxWidth=sc),rc="",sc=""),Rh=uo}e.classList.toggle("persona-artifact-expanded",uo),Ve.setExpanded(uo);let b=ac();b!==Ca&&(Ca=b,as()),oc()};if(wn(o)){Me.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(ue),ko=c,c.appendChild(i),Me.appendChild(c);let g=b=>{Ph||Ve||(Ve=b.createArtifactPane(o,{onSelect:C=>pt.current?.selectArtifact(C),onDismiss:()=>{Yo=!0,go()},onToggleExpand:()=>{let C=!uo,W=Jn.selectedId??Jn.artifacts[Jn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:W,expanded:C})!==!0&&(uo=C,C||(wa=!1),go())}}),Ve.element.classList.add("persona-hidden"),c.appendChild(Ve.element),Ve.backdrop&&Me.appendChild(Ve.backdrop),oc(),go())},f=yr();f?g(f):(wf(()=>{let b=yr();b&&g(b)}),Ep().catch(()=>{})),oc=()=>{if(!ko||!Ve)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){xa?.(),xa=null,Cu(),wt&&(wt.remove(),wt=null),Ve.element.style.removeProperty("width"),Ve.element.style.removeProperty("maxWidth");return}if(!wt){let C=E("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");C.setAttribute("role","separator"),C.setAttribute("aria-orientation","vertical"),C.setAttribute("aria-label","Resize artifacts panel"),C.tabIndex=0;let W=e.ownerDocument,U=W.defaultView??window,$=j=>{if(!Ve||j.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||U.innerWidth<=640)return;j.preventDefault(),Cu();let X=j.clientX,se=Ve.element.getBoundingClientRect().width,me=o.features?.artifacts?.layout,Ze=ht=>{let Jt=ko.getBoundingClientRect().width,jt=e.classList.contains("persona-artifact-welded-split"),Lt=Tf(ko,U),cn=jt?0:C.getBoundingClientRect().width||6,nt=se-(ht.clientX-X),dn=Ox(nt,Jt,Lt,cn,me?.resizableMinWidth,me?.resizableMaxWidth,yA());Ve.element.style.width=`${dn}px`,Ve.element.style.maxWidth="none",Hh()},ut=()=>{W.removeEventListener("pointermove",Ze),W.removeEventListener("pointerup",ut),W.removeEventListener("pointercancel",ut),nc=null;try{C.releasePointerCapture(j.pointerId)}catch{}};nc=ut,W.addEventListener("pointermove",Ze),W.addEventListener("pointerup",ut),W.addEventListener("pointercancel",ut);try{C.setPointerCapture(j.pointerId)}catch{}};C.addEventListener("pointerdown",$),wt=C,ko.insertBefore(C,Ve.element),xa=()=>{C.removeEventListener("pointerdown",$)}}if(wt){let C=tc();wt.classList.toggle("persona-hidden",!C),Hh()}},ic=()=>{if(!pe||!Ve||(o.launcher?.sidebarMode??!1)||At(o)&&_n(o).reveal==="emerge")return;let C=e.ownerDocument.defaultView??window,W=o.launcher?.mobileFullscreen??!0,U=o.launcher?.mobileBreakpoint??640;if(W&&C.innerWidth<=U||!kx(o,pe))return;let $=o.launcher?.width??o.launcherWidth??Gn,j=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";tc()?(Me.style.width=j,Me.style.maxWidth=j):(Me.style.width=$,Me.style.maxWidth=$)},typeof ResizeObserver<"u"&&(va=new ResizeObserver(()=>{go()}),va.observe(Me))}else Me.appendChild(ue);Ce()&&Xt&&(Ne.peekBanner&&Xt.appendChild(Ne.peekBanner),Xt.appendChild(Re)),e.appendChild(Qe),Xt&&e.appendChild(Xt);let wu=()=>{if(Ce()){Me.style.width="100%",Me.style.maxWidth="100%";let Fe=o.launcher?.composerBar??{},Se=Qe.dataset.state==="expanded",un=Fe.expandedSize??"anchored";if(!(Se&&un!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let In=o.theme?.components?.panel,Rn=Xr(o),dt=(_t,Hn)=>_t==null||_t===""?Hn:bn(Rn,_t)??_t,gt="1px solid var(--persona-border)",Be="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",dr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=dt(In?.border,gt),ue.style.borderRadius=dt(In?.borderRadius,dr),ue.style.boxShadow=dt(In?.shadow,Be),ue.style.overflow="hidden";return}let i=At(o),c=o.launcher?.sidebarMode??!1,g=i||c||(o.launcher?.fullHeight??!1),f=o.launcher?.enabled===!1,b=o.launcher?.detachedPanel===!0,C=o.theme?.components?.panel,W=Xr(o),U=(Fe,Se)=>Fe==null||Fe===""?Se:bn(W,Fe)??Fe,$=e.ownerDocument.defaultView??window,j=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,se=$.innerWidth<=X,me=j&&se&&pe,Ze=i&&j&&se,ut=o.launcher?.position??"bottom-left",ht=ut==="bottom-left"||ut==="top-left",Jt=o.launcher?.zIndex??an,jt="var(--persona-panel-border, 1px solid var(--persona-border))",Lt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",cn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",nt=b&&!me&&!Ze;nt?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let dn=nt?jt:c||me?"none":jt,Bo=nt?Lt:me?"none":c?ht?"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":Lt;i&&!me&&!nt&&(Bo="none",dn="none");let cr=nt?cn:c||me?"0":cn,ho=U(C?.border,dn),Qa=U(C?.shadow,Bo),Ws=U(C?.borderRadius,cr),yo=ac(),on=yo==="detached",bo=yo==="welded";e.classList.toggle("persona-artifact-detached-split",on),e.classList.toggle("persona-artifact-welded-split",bo);let Ii="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)))))",Ee=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&wn(o)&&Sf(o)&&f&&!i;e.classList.toggle("persona-artifact-chat-flush",Ee);let ie=on||Ee?"none":Qa,It=on?jt:bo?"none":ho,qt=on?cn:Ws;Ee&&(It="none",qt="0");let rn=C?.borderRadius!=null&&C.borderRadius!=="",zt=Ee&&!rn?"0":Ws,Yt=oe.scrollTop;e.style.cssText="",Qe.style.cssText="",Me.style.cssText="",ue.style.cssText="",oe.style.cssText="",ri||(Re.style.cssText=""),Qt&&(oe.style.display="none"),(g||f)&&(e.style.minWidth="0");let Rt=()=>{if(Yt<=0)return;(oe.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(oe.scrollTop===Yt)return;let Se=oe.scrollHeight-oe.clientHeight;Se<=0||(oe.scrollTop=Math.min(Yt,Se))})};if(me){Qe.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"),Qe.style.cssText=`
|
|
44
44
|
position: fixed !important;
|
|
45
45
|
inset: 0 !important;
|
|
46
46
|
width: 100% !important;
|
|
@@ -50,7 +50,7 @@ _Details: ${n.message}_`:o}var gm=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
50
50
|
padding: 0 !important;
|
|
51
51
|
display: flex !important;
|
|
52
52
|
flex-direction: column !important;
|
|
53
|
-
z-index: ${
|
|
53
|
+
z-index: ${Jt} !important;
|
|
54
54
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
55
55
|
`,Me.style.cssText=`
|
|
56
56
|
position: relative !important;
|
|
@@ -65,7 +65,7 @@ _Details: ${n.message}_`:o}var gm=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
65
65
|
padding: 0 !important;
|
|
66
66
|
box-shadow: none !important;
|
|
67
67
|
border-radius: 0 !important;
|
|
68
|
-
`,
|
|
68
|
+
`,ue.style.cssText=`
|
|
69
69
|
display: flex !important;
|
|
70
70
|
flex-direction: column !important;
|
|
71
71
|
flex: 1 1 0% !important;
|
|
@@ -76,32 +76,32 @@ _Details: ${n.message}_`:o}var gm=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
76
76
|
overflow: hidden !important;
|
|
77
77
|
border-radius: 0 !important;
|
|
78
78
|
border: none !important;
|
|
79
|
-
`,
|
|
79
|
+
`,oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",Re.style.flexShrink="0",lu(),Dt=!0,Rt();return}let We=o?.launcher?.width??o?.launcherWidth??Gn;if(!c&&!i)f&&g?(Me.style.width="100%",Me.style.maxWidth="100%"):(Me.style.width=We,Me.style.maxWidth=We);else if(i)if(_n(o).reveal==="emerge"&&!b){let Se=_n(o).width;Me.style.width=Se,Me.style.maxWidth=Se}else Me.style.width="100%",Me.style.maxWidth="100%";if(ic(),Me.style.boxShadow=ie,Me.style.borderRadius=zt,on?Me.style.border="none":bo&&(Me.style.border=ho),ue.style.border=It,ue.style.borderRadius=qt,ue.style.boxShadow=on&&!Ee?Ii:"",Ee&&(ue.style.background="transparent",oe.style.background="transparent",Re.style.background="transparent",Re.style.borderTop="none"),bo){let Fe=o.features?.artifacts?.layout;ec=Fe?.unifiedSplitOuterRadius?.trim()||Fe?.paneBorderRadius?.trim()||Ws}else ec=null;if(i&&!me&&!nt&&!on&&!bo&&C?.border===void 0&&(ue.style.border="none",_n(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),i&&!me&&bo&&C?.border===void 0&&(_n(o).side==="right"?Me.style.borderLeft="1px solid var(--persona-border)":Me.style.borderRight="1px solid var(--persona-border)"),g&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",f&&(e.style.width="100%"),Qe.style.display="flex",Qe.style.flexDirection="column",Qe.style.flex="1 1 0%",Qe.style.minHeight="0",Qe.style.maxHeight="100%",Qe.style.height="100%",f&&(Qe.style.overflow="hidden"),Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.maxHeight="100%",Me.style.height="100%",on||(Me.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",Re.style.flexShrink="0"),f&&(nt||on||Ee)&&!i&&(Ee||(Qe.style.padding="var(--persona-panel-inset)"),Qe.style.background="var(--persona-panel-canvas-bg)"),Qe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!c&&!f&&!i&&(Qn[ut]??Qn["bottom-right"]).split(" ").forEach(Se=>Qe.classList.add(Se)),c){let Fe=o.launcher?.sidebarWidth??"420px";b?Qe.style.cssText=`
|
|
80
80
|
position: fixed !important;
|
|
81
81
|
top: var(--persona-panel-inset) !important;
|
|
82
82
|
bottom: var(--persona-panel-inset) !important;
|
|
83
|
-
width: ${
|
|
83
|
+
width: ${Fe} !important;
|
|
84
84
|
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
85
85
|
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
86
86
|
margin: 0 !important;
|
|
87
87
|
padding: 0 !important;
|
|
88
88
|
display: flex !important;
|
|
89
89
|
flex-direction: column !important;
|
|
90
|
-
z-index: ${
|
|
91
|
-
${
|
|
92
|
-
`:
|
|
90
|
+
z-index: ${Jt} !important;
|
|
91
|
+
${ht?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
92
|
+
`:Qe.style.cssText=`
|
|
93
93
|
position: fixed !important;
|
|
94
94
|
top: 0 !important;
|
|
95
95
|
bottom: 0 !important;
|
|
96
|
-
width: ${
|
|
96
|
+
width: ${Fe} !important;
|
|
97
97
|
height: 100vh !important;
|
|
98
98
|
max-height: 100vh !important;
|
|
99
99
|
margin: 0 !important;
|
|
100
100
|
padding: 0 !important;
|
|
101
101
|
display: flex !important;
|
|
102
102
|
flex-direction: column !important;
|
|
103
|
-
z-index: ${
|
|
104
|
-
${
|
|
103
|
+
z-index: ${Jt} !important;
|
|
104
|
+
${ht?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
105
105
|
`,Me.style.cssText=`
|
|
106
106
|
position: relative !important;
|
|
107
107
|
display: flex !important;
|
|
@@ -113,10 +113,10 @@ _Details: ${n.message}_`:o}var gm=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
113
113
|
min-height: 0 !important;
|
|
114
114
|
margin: 0 !important;
|
|
115
115
|
padding: 0 !important;
|
|
116
|
-
box-shadow: ${
|
|
117
|
-
border-radius: ${
|
|
118
|
-
${
|
|
119
|
-
`,Me.style.setProperty("width","100%","important"),Me.style.setProperty("max-width","100%","important"),
|
|
116
|
+
box-shadow: ${ie} !important;
|
|
117
|
+
border-radius: ${zt} !important;
|
|
118
|
+
${on?"border: none !important;":bo?`border: ${ho} !important;`:""}
|
|
119
|
+
`,Me.style.setProperty("width","100%","important"),Me.style.setProperty("max-width","100%","important"),ue.style.cssText=`
|
|
120
120
|
display: flex !important;
|
|
121
121
|
flex-direction: column !important;
|
|
122
122
|
flex: 1 1 0% !important;
|
|
@@ -125,32 +125,32 @@ _Details: ${n.message}_`:o}var gm=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
125
125
|
min-height: 0 !important;
|
|
126
126
|
max-height: 100% !important;
|
|
127
127
|
overflow: hidden !important;
|
|
128
|
-
border-radius: ${
|
|
129
|
-
border: ${
|
|
130
|
-
${
|
|
131
|
-
${
|
|
132
|
-
`,
|
|
128
|
+
border-radius: ${qt} !important;
|
|
129
|
+
border: ${It} !important;
|
|
130
|
+
${on&&!Ee?`box-shadow: ${Ii} !important;`:""}
|
|
131
|
+
${Ee?"background: transparent !important;":""}
|
|
132
|
+
`,ri||(Re.style.cssText=`
|
|
133
133
|
flex-shrink: 0 !important;
|
|
134
134
|
border-top: none !important;
|
|
135
135
|
padding: 8px 16px 12px 16px !important;
|
|
136
|
-
${
|
|
137
|
-
`)}if(!f&&!i){let $e="max-height: -moz-available !important; max-height: stretch !important;",bt=c?"":"padding-top: 1.25em !important;",st=c?"":`z-index: ${o.launcher?.zIndex??ln} !important;`;Ye.style.cssText+=$e+bt+st}lu(),De()},xu=()=>{e.style.setProperty("--persona-content-max-width",os(o,xe()))},Ih=!1,Rh=()=>{let i=_m(o,xe());xe()&&o.composer?.placement&&o.debug===!0&&!Ih&&(Ih=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=So(o);e.setAttribute("data-persona-composer-placement",i),e.setAttribute("data-persona-conversation-state",Xl),e.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",c.composerGap??rp),Zl()},Hh=()=>{if(xe())return;let i=Et(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!we)return;let f=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640;if(b&&f.innerWidth<=w)return;let W=f.innerHeight,z=64,q=o.launcher?.heightOffset??0,V=Math.max(200,W-z),Z=Math.min(640,V);Me.style.height=`${Math.max(200,Z-q)}px`};wu(),Gs(e,o),_l(e,o),Dl(e,o),xu(),Rh(),gs=()=>{wu(),Hh(),Gs(e,o),_l(e,o),Dl(e,o),xu(),Rh(),nc?e.style.setProperty("--persona-artifact-welded-outer-radius",nc):e.style.removeProperty("--persona-artifact-welded-outer-radius"),_e(),qt()};let ve=[];ve.push(()=>{Mh=!0}),ve.push(()=>{d.forEach(i=>i()),l.destroy()}),ve.push(()=>{document.removeEventListener("keydown",kh)}),ve.push(()=>{xa!==null&&clearTimeout(xa)});let Ho=null,Wo=null;ve.push(()=>{Ho?.(),Ho=null,Wo?.(),Wo=null}),Ma&&ve.push(()=>{Ma?.disconnect(),Ma=null}),ve.push(()=>{ka?.(),ka=null,Cu(),St&&(St.remove(),St=null),Ve?.element.style.removeProperty("width"),Ve?.element.style.removeProperty("maxWidth"),Ve?.destroy()}),cn&&ve.push(()=>{D=!0,go=null,_!==null&&(cancelAnimationFrame(_),_=null),J?.destroy(),J=null,nt?.destroy(),nt=null,Yo=null});let fs=null,Wh=()=>{fs&&(fs(),fs=null),o.colorScheme==="auto"&&(fs=na(()=>{Gs(e,o)}))};Wh(),ve.push(()=>{fs&&(fs(),fs=null)}),ve.push(()=>{C=!0,h?.()}),ve.push(()=>{O=!0});let Oh=!1;ve.push(()=>{Oh=!0});let Su=(i,c)=>{let g=kl(i,c);return g||!Dw.includes(i)?g:(Uw().then(f=>{if(Oh)return;Tl(f.wipe),Tl(f.glyphCycle);let b=kl(i,c);b&&Il(b,e)}).catch(()=>{}),null)},dc=o.features?.streamAnimation;if(dc?.type&&dc.type!=="none"){let i=Su(dc.type,dc.plugins);i&&Il(i,e),ve.push(()=>$w(e))}let er=Wl(Tr),Bh=Wl(ou),_h=Wl(ba),hs=[er,Bh,_h];ve.push(()=>{hs.forEach(i=>i.destroy())});let ys=null,k,bs=null,Dh=!1,Nh=0,Fh=null,$h=i=>i.reduce((c,g)=>g.role==="user"?c+1:c,0),Uh=i=>{for(let c=i.length-1;c>=0;c--)if(qs(i[c]))return i[c].id??null;return null},jh=!1,fA=()=>{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".'))},qh=!1,zh=!1,Vh=(i,c)=>{qh||o.debug!==!0||!c.enabled||c.expose||Dh||zh&&(k.isStreaming()||i.some(qs)||(qh=!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.")))},mi=i=>{if(!k)return;let c=i??k.getMessages(),g=V=>{V.render([],k,ue,c)},f=V=>{hs.forEach(Z=>{Z!==V&&g(Z)})};bs&&($h(c)>Nh||Uh(c)!==Fh)&&(bs=null);let b=Zr(o);Vh(c,b);let w=b.enabled?vd(c):null,W=bs??w,z=bs?"host":"agent";if(W){let V=o.suggestions?.followUps,Z=V?.placement??(V?"auto":"composer"),ye=(Z==="auto"?xe()?"composer":"after-message":Z)==="after-message"?_h:er;f(ye),ye.render(W,k,ue,c,o.suggestionChipsConfig,{source:z,surface:"followUp",variant:V?.variant??"chip",behavior:V?.behavior??"send",overflow:V?.overflow??"wrap",maxItems:V?.maxItems??4,config:o,plugins:a,submitPrompt:Xc});return}if(c.some(V=>V.role==="user")){hs.forEach(g);return}let q=o.suggestions?.starters;if(q){let V=is(So(o),c),Z=q.placement??"auto",ae=Z==="auto"?V?"welcome":"composer":Z;if(ae==="welcome"&&!V){fA(),hs.forEach(g);return}let ye=ae==="welcome"?Bh:er;f(ye),ye.render(q.items??o.suggestionChips,k,ue,c,o.suggestionChipsConfig,{surface:"starter",variant:q.variant??"card",behavior:q.behavior??"send",overflow:q.overflow??"wrap",maxItems:q.maxItems??4,config:o,plugins:a,submitPrompt:Xc});return}f(er),er.render(o.suggestionChips,k,ue,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a,submitPrompt:Xc})},Kh=()=>{bs&&(bs=null,mi())},hA=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){Kh();return}let g=k?k.getMessages():[];bs=c,Dh=!0,Nh=$h(g),Fh=Uh(g),mi(g)},Fn=!1,Ft=Ew(),fi=new Map,vs=new Map,Hr=new Map,Cs=null,Wr=null;function ws(){if(!Cs)return;let i=Cs;Cs=null,Wr?.destroy(),Wr=null,Ft.delete(i),fe.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),k&&Zn(Pe,k.getMessages(),yt)}let xs=0,yA=$o()!==null,$n=Iw(),Un=0,Or=null,Tn=!1,pc=!1,Br=0,Kt=null,Ss=null,Au=!1,hi=!1,As=null,Pa=!0,uc=!1,yi=null,gc=!1,Ms=()=>{gc=!0,wA()},Mu=null,bA=4,tr=24,vA=80,CA=1e3,nr=null,Gh=()=>{e.setAttribute("data-persona-scrollbar",su()),su()!=="on-scroll"&&(nr!==null&&clearTimeout(nr),nr=null,re.removeAttribute("data-persona-scrollbar-visible"))},wA=()=>{su()==="on-scroll"&&(re.setAttribute("data-persona-scrollbar-visible",""),nr!==null&&clearTimeout(nr),nr=setTimeout(()=>{nr=null,Ys(re,tr)&&re.removeAttribute("data-persona-scrollbar-visible")},CA))};Gh(),ve.push(()=>{nr!==null&&clearTimeout(nr)});let Eu=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};bh=()=>Ke.active,fo();let Yh=o.voiceRecognition?.autoResume??!1,or=i=>{A.emit("voice:state",{active:Ke.active,source:i,timestamp:Date.now()})},bo=()=>{de(i=>({...i,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},xA=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Wf(Q.voiceState),c=!!i.active,g=Number(i.timestamp??0);Ke.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-g<I0&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?k.toggleVoice().then(()=>{Ke.active=k.isVoiceActive(),or("restore"),k.isVoiceActive()&&Oi()}):ed("restore"))},1e3)},SA=()=>k?Qx(k.getMessages()).filter(i=>!i.__skipPersist):[],mc=null,Qh=(i,c)=>{typeof console<"u"&&console.error(i,c)},fc=(i,c)=>{let g=()=>{try{let W=i();return!W||typeof W.then!="function"?null:Promise.resolve(W).catch(z=>{Qh(c,z)})}catch(W){return Qh(c,W),null}},f=mc,b=f?f.then(()=>g()??void 0):g();if(!b)return;let w=b.finally(()=>{mc===w&&(mc=null)});mc=w};function bi(i){if(!Y?.save)return;let c=i?Qx(i):k?SA():[],g=ce&&k?.getResumableHandle();g&&(Q={...Q,durableResume:{executionId:g.executionId,after:g.lastEventId}});let f={messages:c,metadata:Q,artifacts:Jn.artifacts,selectedArtifactId:Jn.selectedId,...Es?{draft:Es}:{}};fc(()=>Y.save(f),"[AgentWidget] Failed to persist state:")}let Es,hc=()=>!Y?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,La=ZC({write:()=>{if(!hc())return;let i=Se.getState(),c=XC({text:i.text,mentionRefs:i.mentionRefs,contentSegments:wg(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(Es)&&(Es=c,bi())}});function Xh(){hc()&&La.schedule()}function Tu(){La.flush()}function Jh(i){if(!hc())return;let c=JC(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(g=>g.id),modelIds:(o.composer?.models??[]).map(g=>g.id),modes:o.composer?.modes??[]});c&&(Es=i,ue&&!ue.value&&(ue.value=c.text,ue.dispatchEvent(new Event("input",{bubbles:!0})),Po()),c.selectedModelId&&(Se.setSelectedModelId(c.selectedModelId),Lr?.repaint()),ec(c.activeModeIds??[]),c.quote&&Lo(c.quote),La.cancel())}function yc(){La.cancel(),Es&&(Es=void 0,hc()&&bi())}let vi=null,Zh=()=>Ye.querySelector("#persona-scroll-container")||re,Ci=()=>{vi!==null&&(cancelAnimationFrame(vi),vi=null),Tn=!1},ey=()=>{Or!==null&&(cancelAnimationFrame(Or),Or=null),pc=!1,Ci()},AA=()=>Fn&&Pu()&&(Nn()!=="anchor-top"||th()),ku=()=>{let i=va()||"Jump to latest",c=AA();Nt.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Br>0?(ds.textContent=String(Br),ds.style.display="",Nt.setAttribute("aria-label",`${i} (${Br} new)`)):(ds.textContent="",ds.style.display="none",Nt.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},ty=()=>{Br!==0&&(Br=0,ku())},MA=()=>{let i=Kt?.spacerHeight??0;return i<=0?Ys(re,tr):wc(i)-re.scrollTop-re.clientHeight<=tr},Pu=()=>Pr()?!$n.isFollowing():!MA(),Lu=()=>!!k&&k.getMessages().length>0,Gt=()=>{if(!ZS()||Er()){Nt.parentNode&&Nt.remove(),Nt.style.display="none";return}Nt.parentNode!==fe&&fe.appendChild(Nt),ps();let c=Vo(re)>0&&Pu()&&Lu();c?ku():ty(),Nt.style.display=c?"":"none"},Ia=()=>{$n.pause()&&(ey(),Gt())},kn=()=>{$n.resume(),ty(),Gt()},_r=(i=!1)=>{Pr()&&Lu()&&$n.isFollowing()&&(!i&&!Fn||(Or!==null&&(cancelAnimationFrame(Or),Or=null),pc=!0,Or=requestAnimationFrame(()=>{Or=null,pc=!1,$n.isFollowing()&&EA(Zh(),i?220:140)})))},ny=(i,c,g,f=()=>!0)=>{let b=i.scrollTop,w=c(),W=w-b;if(Ci(),Math.abs(W)<1){Tn=!0,i.scrollTop=w,Un=i.scrollTop,Tn=!1;return}let z=performance.now();Tn=!0;let q=Z=>1-Math.pow(1-Z,3),V=Z=>{if(!f()){Ci();return}let ae=c();ae!==w&&(w=ae,W=w-b);let ye=Z-z,Ze=Math.min(ye/g,1),ut=q(Ze),ft=b+W*ut;i.scrollTop=ft,Un=i.scrollTop,Ze<1?vi=requestAnimationFrame(V):(i.scrollTop=w,Un=i.scrollTop,vi=null,Tn=!1)};vi=requestAnimationFrame(V)},EA=(i,c=500)=>{let g=Vo(i)-i.scrollTop;if(Math.abs(g)<1){Un=i.scrollTop;return}if(Math.abs(g)>=vA){Ci(),Tn=!0,i.scrollTop=Vo(i),Un=i.scrollTop,Tn=!1;return}ny(i,()=>Vo(i),c,()=>$n.isFollowing())},bc=()=>{if(!Lu()){Gt();return}let i=Zh();Tn=!0,i.scrollTop=Vo(i),Un=i.scrollTop,Tn=!1,Gt()},Ts=i=>{let c=0,g=i;for(;g&&g!==re;)c+=g.offsetTop,g=g.offsetParent;return c},TA=()=>{let i=re.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??re.ownerDocument.getSelection()},vc=()=>Ww(TA(),re),Iu=()=>{if(eA()!=="last-user-turn")return!1;let i=k?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(w=>w.role==="user");if(!c)return!1;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=re.querySelector(`[data-message-id="${g}"]`);if(!f)return!1;let b=Math.min(Math.max(0,Ts(f)-Ca()),Vo(re));return Tn=!0,re.scrollTop=b,Un=re.scrollTop,Tn=!1,Nn()==="follow"&&!Ys(re,tr)&&$n.pause(),Gt(),!0},Cc=i=>{let c=Math.max(0,Math.round(i));Xn.style.height=`${c}px`,Xn.style.display=c>0?"":"none",Kt&&(Kt.spacerHeight=Math.max(0,i))},wc=i=>{let c=parseFloat(getComputedStyle(re).paddingBottom)||0,g=0;for(let b of Array.from(re.children)){if(b===Xn||b.offsetHeight===0)continue;let w=Ts(b)+b.offsetHeight;w>g&&(g=w)}let f=re.scrollHeight-i;return g>0?Math.min(g+c,f):f},kA=()=>{if(!Kt||Kt.spacerHeight<=0)return;let i=wc(Kt.spacerHeight),c=Math.max(0,Math.round(re.scrollTop)+re.clientHeight-i+tr);c<Kt.spacerHeight&&(Cc(c),Gt())},vo=()=>{Ss!==null&&(cancelAnimationFrame(Ss),Ss=null),Ci(),Kt=null,Xn.style.height="0px",Xn.style.display="none"},oy=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Ru=i=>re.querySelector(`[data-message-id="${oy(i)}"]`),ry=i=>{Ss!==null&&cancelAnimationFrame(Ss),Ss=requestAnimationFrame(()=>{Ss=null;let c=oy(i),g=re.querySelector(`[data-message-id="${c}"]`);if(!g)return;let f=Ts(g),b=Kt?.spacerHeight??0,w=wc(b),{targetScrollTop:W,spacerHeight:z}=Fm({anchorOffsetTop:f,topOffset:Ca(),viewportHeight:re.clientHeight,contentHeight:w,slack:tr});Kt={initialSpacerHeight:z,contentHeightAtAnchor:w,spacerHeight:z},Cc(z),ny(re,()=>g.isConnected?Math.max(0,Ts(g)-Ca()):W,220)})},Pn=()=>{if(Nn()!=="anchor-top"||!Kt||!yi)return;let i=Ru(yi);if(!i)return;Ci();let c=Kt.spacerHeight,g=wc(c),{targetScrollTop:f,spacerHeight:b}=Fm({anchorOffsetTop:Ts(i),topOffset:Ca(),viewportHeight:re.clientHeight,contentHeight:g,slack:tr});Kt={initialSpacerHeight:b,contentHeightAtAnchor:g,spacerHeight:b},Cc(b),Tn=!0,re.scrollTop=f,Un=re.scrollTop,Tn=!1,Gt()},PA=()=>{if(Pr()){if(!$n.isFollowing()||Ys(re,1))return;_r(!Fn);return}if(Kt&&Kt.initialSpacerHeight>0){let i=re.scrollHeight-Kt.spacerHeight,c=Ow({initialSpacerHeight:Kt.initialSpacerHeight,contentHeightAtAnchor:Kt.contentHeightAtAnchor,currentContentHeight:i});c!==Kt.spacerHeight&&Cc(c)}Gt()},LA=i=>{let c=Nn();c==="follow"?(kn(),_r(!0)):c==="anchor-top"&&(Pa=!1,uc=!0,gc=!1,yi=i,ry(i))},IA=()=>{if(Nn()==="anchor-top"){if(uc){Pa=!1;return}Pa=!0,vo(),kn(),_r(!0)}},RA=96,HA=i=>{if(As===null)return!0;let c=Ru(As),g=Ru(i);if(!c||!g)return!0;let f=Ts(g)-Ts(c);return Ca()+f>re.clientHeight-RA},WA=i=>{if(Nn()!=="anchor-top"||!uc||gc||vc())return;let c=As===null;for(let g of i){if(!c){g.id===As&&(c=!0);continue}if(Lw(g)){if(g.id===yi||!HA(g.id))return;yi=g.id,ry(g.id);return}}},OA=i=>{let c=new Map;i.forEach(g=>{let f=Eu.get(g.id);c.set(g.id,{streaming:g.streaming,role:g.role}),!f&&g.role==="assistant"&&(A.emit("assistant:message",g),!hi&&(Nn()!=="anchor-top"||th())&&Pu()&&(Br+=1,ku(),Gt(),Ql(Br===1?"1 new message below.":`${Br} 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}))}),Eu.clear(),c.forEach((g,f)=>{Eu.set(f,g)})},Ra=(i,c)=>{let g=c==="user"?"user":"assistant",f=o.layout?.messages?.[g],b=f?.width??"content",w=f?.maxWidth??(b==="full"?"100%":void 0);i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${c}`,`persona-message-width-${b}`),i.classList.toggle("persona-justify-end",c==="user"),i.setAttribute("data-message-role",c),i.setAttribute("data-message-width",b),w?i.style.setProperty("--persona-message-row-max-width",w):i.style.removeProperty("--persona-message-row-max-width")},rr=(i,c)=>{let g=document.createElement("div");return g.className="persona-flex",g.id=`wrapper-${i}`,g.setAttribute("data-wrapper-id",i),Ra(g,c),g},BA=(i,c,g)=>{let f=document.createElement("div"),w=(()=>{let I=a.find(Le=>Le.renderLoadingIndicator);if(I?.renderLoadingIndicator)return I.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),W=(I,Le)=>Le==null?!1:typeof Le=="string"?(I.textContent=Le,!0):(I.appendChild(Le),!0),z=new Set,q=new Map,V=new Set,Z=a.some(I=>I.renderAskUserQuestion),ae=[],ye=[],Ze=o.enableComponentStreaming!==!1,ut=o.approval!==!1,ft=[],Zt=o.messageActions,Ut=Zt?.showRegenerate===!0&&Zt.enabled!==!1&&pt.current?.isStreaming()!==!0?rC(c):null,Wt=Zt?.showEdit===!0&&Zt.enabled!==!1,dn=Zt?.showQuote===!0&&Zt.enabled!==!1,tt=null,pn=o.features?.reasoningDisplay?.completedVisibility,Do=I=>pn==="removed"?!0:pn==="removed-when-short"?Iv(I,o.features?.reasoningDisplay?.shortThinkThreshold):!1,gr=o.features?.toolCallDisplay?.completedVisibility==="removed";if(c.forEach(I=>{if(I.variant==="reasoning"&&I.reasoning?.status==="complete"&&Do(I.reasoning)||gr&&I.variant==="tool"&&I.toolCall?.status==="complete")return;if(z.add(I.id),q.set(I.id,I.role),Cs===I.id&&Wr){let De=rr(I.id,I.role);De.setAttribute("data-persona-message-edit-stub","true"),De.setAttribute("data-preserve-runtime","true"),f.appendChild(De),tt={messageId:I.id,element:Wr.element};return}let Le=Z&&hr(I),Be=ut&&I.variant==="approval"&&!!I.approval,Ae=!Le&&I.role==="assistant"&&!I.variant&&Ze&&jl(I);!Be&&Hr.has(I.id)&&(i.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime"),Hr.delete(I.id)),!Ae&&vs.has(I.id)&&(i.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime"),vs.delete(I.id));let Yt=hr(I)?`:${I.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${I.agentMetadata?.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",un={canRegenerate:Ut===I.id,canEdit:Wt&&am(I),canQuote:dn&&!I.variant&&(I.content?.trim().length??0)>0},dt=`${un.canRegenerate?"r":""}${un.canEdit?"e":""}${un.canQuote?"q":""}`,Re=Mw(I,xs)+Yt+`:${dt}`,Co=Le||Be||Ae?null:Tw(Ft,I.id,Re);if(Co){f.appendChild(Co.cloneNode(!0)),hr(I)&&I.toolCall?.id&&I.agentMetadata?.awaitingLocalTool===!0&&!I.agentMetadata?.askUserQuestionAnswered&&(V.add(I.toolCall.id),zi(I,o,Fe.composerOverlay));return}let Pt=null,sn=a.find(De=>!!(I.variant==="reasoning"&&De.renderReasoning||I.variant==="tool"&&De.renderToolCall||!I.variant&&De.renderMessage)),Qt=o.layout?.messages;if(hr(I)&&I.agentMetadata?.askUserQuestionAnswered===!0){fi.delete(I.id),i.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime");return}if(qs(I)&&Zr(o).enabled)return;if(hr(I)&&o.features?.askUserQuestion?.enabled!==!1){let De=a.find(zn=>typeof zn.renderAskUserQuestion=="function");if(De&&pt.current){let zn=fi.get(I.id),ze=zn!==Re,$e=null;if(ze){let{payload:gt,complete:vt}=yr(I),mr=I.id,en=()=>pt.current?.getMessages().find(so=>so.id===mr);$e=De.renderAskUserQuestion({message:I,payload:gt,complete:vt,resolve:so=>{let Ct=en();Ct&&pt.current?.resolveAskUserQuestion(Ct,so)},dismiss:()=>{let so=en();so?.agentMetadata?.awaitingLocalTool&&(pt.current?.markAskUserQuestionResolved(so),pt.current?.resolveAskUserQuestion(so,"(dismissed)"))},config:o})}let bt=zn!=null;if(ze&&$e===null&&!bt){I.agentMetadata?.awaitingLocalTool===!0&&!I.agentMetadata?.askUserQuestionAnswered&&(V.add(I.toolCall.id),zi(I,o,Fe.composerOverlay));return}let st=rr(I.id,I.role);st.setAttribute("data-ask-plugin-stub","true"),st.setAttribute("data-preserve-runtime","true"),f.appendChild(st),ae.push({messageId:I.id,fingerprint:Re,bubble:$e});return}else{I.agentMetadata?.awaitingLocalTool===!0&&!I.agentMetadata?.askUserQuestionAnswered&&(V.add(I.toolCall.id),zi(I,o,Fe.composerOverlay));return}}else if(Be){let De=P();if(!De){f.appendChild(rr(I.id,I.role));return}let zn=a.find(st=>typeof st.renderApproval=="function")??y,$e=Hr.get(I.id)!==Re,bt=null;if($e&&zn?.renderApproval){let st=I.id,gt=(vt,mr)=>{let en=pt.current?.getMessages().find(so=>so.id===st);en?.approval&&(en.approval.toolType==="webmcp"?pt.current?.resolveWebMcpApproval(en.id,vt):pt.current?.resolveApproval(en.approval,vt,mr))};bt=zn.renderApproval({message:I,defaultRenderer:()=>De.createApprovalBubble(I,o),config:o,approve:vt=>gt("approved",vt),deny:vt=>gt("denied",vt)})}if($e&&bt===null)i.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime"),Hr.delete(I.id),Pt=De.createApprovalBubble(I,o);else{let st=rr(I.id,I.role);st.setAttribute("data-approval-plugin-stub","true"),st.setAttribute("data-preserve-runtime","true"),f.appendChild(st),ft.push({messageId:I.id,fingerprint:Re,bubble:bt});return}}else if(sn)if(I.variant==="reasoning"&&I.reasoning&&sn.renderReasoning){if(!gn)return;Pt=sn.renderReasoning({message:I,defaultRenderer:()=>ff(I,o),config:o})}else if(I.variant==="tool"&&I.toolCall&&sn.renderToolCall){if(!Yn)return;Pt=sn.renderToolCall({message:I,defaultRenderer:()=>yf(I,o),config:o})}else sn.renderMessage&&(Pt=sn.renderMessage({message:I,defaultRenderer:()=>{let De=ia(I,g,Qt,o.messageActions,zt,{loadingIndicatorRenderer:w,widgetConfig:o,actionEligibility:un});return I.role!=="user"&&R(De,I,o,k),De},config:o}));if(!Pt&&Ae){let De=_p(I);if(De){let zn=vs.get(I.id),ze=zn!==Re,$e=o.wrapComponentDirectiveInBubble!==!1&&Ao.getOptions(De.component)?.bubbleChrome!==!1,bt=null;if(ze){let st=Bp(De,{config:o,message:I,transform:g});if(st&&De.component==="PersonaArtifactInline"){let gt=st.hasAttribute("data-artifact-inline")?st:st.querySelector("[data-artifact-inline]"),vt=gt?.getAttribute("data-artifact-inline")??"",mr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(vt):vt,en=vt?i.querySelector(`#wrapper-${I.id}`)?.querySelector(`[data-artifact-inline="${mr}"]`)??null:null;gt&&en&&en!==gt&&wr()?.hasLiveInlineArtifactBlock(en)&&(gt===st?st=en:gt.replaceWith(en))}if(st)if($e){let gt=document.createElement("div");if(gt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),gt.id=`bubble-${I.id}`,gt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let vt=document.createElement("div");vt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",vt.innerHTML=g({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),gt.appendChild(vt)}gt.appendChild(st),bt=gt}else{let gt=document.createElement("div");if(gt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",gt.id=`bubble-${I.id}`,gt.setAttribute("data-message-id",I.id),gt.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let vt=document.createElement("div");vt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",vt.innerHTML=g({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),gt.appendChild(vt)}gt.appendChild(st),bt=gt}}if(bt||zn!=null){let st=rr(I.id,I.role);st.setAttribute("data-component-directive-stub","true"),st.setAttribute("data-preserve-runtime","true"),f.appendChild(st),ye.push({messageId:I.id,fingerprint:Re,bubble:bt});return}}}if(!Pt)if(I.variant==="reasoning"&&I.reasoning){if(!gn)return;Pt=ff(I,o)}else if(I.variant==="tool"&&I.toolCall){if(!Yn)return;Pt=yf(I,o)}else if(I.variant==="approval"&&I.approval){if(o.approval===!1)return;let De=P();if(!De)return;Pt=De.createApprovalBubble(I,o)}else{let De=o.layout?.messages;De?.renderUserMessage&&I.role==="user"?Pt=De.renderUserMessage({message:I,config:o,streaming:!!I.streaming}):De?.renderAssistantMessage&&I.role==="assistant"?Pt=De.renderAssistantMessage({message:I,config:o,streaming:!!I.streaming}):Pt=ia(I,g,De,o.messageActions,zt,{loadingIndicatorRenderer:w,widgetConfig:o,actionEligibility:un}),I.role!=="user"&&Pt&&R(Pt,I,o,k)}let Ot=rr(I.id,I.role);Ot.appendChild(Pt),kw(Ft,I.id,Re,Ot),f.appendChild(Ot)}),Fe.composerOverlay&&Fe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Le=>{let Be=Le.getAttribute("data-persona-ask-sheet-for");Be&&!V.has(Be)&&Xr(Fe.composerOverlay,Be)}),o.features?.toolCallDisplay?.grouped){let I=[],Le=[],Be=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(Ae=>{if(Ae.variant==="tool"&&Ae.toolCall&&Yn){if(gr&&Ae.toolCall.status==="complete")return;Le.push(Ae);return}Ae.variant==="reasoning"&&(!gn||Ae.reasoning?.status==="complete"&&Do(Ae.reasoning))||((Le.length>1||Be&&Le.length>0)&&I.push(Le),Le=[])}),(Le.length>1||Be&&Le.length>0)&&I.push(Le),I.forEach(Ae=>{let Yt=Ae.map(Qt=>Array.from(f.children).find(Ot=>Ot instanceof HTMLElement&&Ot.getAttribute("data-wrapper-id")===Qt.id)).filter(Qt=>!!Qt);if(Yt.length<(Be?1:2))return;let un=rr(`tool-group-${Ae[0].id}`,"assistant");un.setAttribute("data-persona-tool-group-row","true");let dt=document.createElement("div");dt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",dt.setAttribute("data-persona-tool-group","true");let Re=document.createElement("div");Re.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",Re.id=`tool-group-summary-${Ae[0].id}`;let Co=`Called ${Ae.length} ${Ae.length===1?"tool":"tools"}`,Pt=o.toolCall?.renderGroupedSummary?.({messages:Ae,toolCalls:Ae.map(Qt=>Qt.toolCall).filter(Qt=>!!Qt),defaultSummary:Co,config:o});W(Re,Pt)||(Re.textContent=Co);let sn=document.createElement("div");sn.className="persona-tool-group-stack persona-flex persona-flex-col",sn.id=`tool-group-stack-${Ae[0].id}`,sn.setAttribute("data-persona-tool-group-stack","true"),dt.appendChild(Re),Be||dt.appendChild(sn),un.appendChild(dt),Yt[0].before(un),Yt.forEach((Qt,Ot)=>{if(Be){Qt.remove();return}Qt.style.setProperty("--persona-message-row-max-width","100%");let De=document.createElement("div");De.className="persona-tool-group-item persona-relative",De.setAttribute("data-persona-tool-group-item","true"),Ot<Yt.length-1&&De.setAttribute("data-persona-tool-group-connector","true"),De.appendChild(Qt),sn.appendChild(De)})})}Pw(Ft,z);let No=c.some(I=>I.role==="assistant"&&I.streaming),_i=c[c.length-1],Fs=_i?.role==="assistant"&&!_i.streaming&&_i.variant!=="approval";if(Fn&&c.some(I=>I.role==="user")&&!No&&!Fs){let I={config:o,streaming:!0,location:"standalone",defaultRenderer:ei},Le=a.find(Ae=>Ae.renderLoadingIndicator),Be=null;if(Le?.renderLoadingIndicator&&(Be=Le.renderLoadingIndicator(I)),Be===null&&o.loadingIndicator?.render&&(Be=o.loadingIndicator.render(I)),Be===null&&(Be=ei()),Be){let Ae=document.createElement("div"),Yt=o.loadingIndicator?.showBubble!==!1,un=o.layout?.messages?.layout??"bubble";Ae.className=Yt?Bl("assistant",un).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ae.setAttribute("data-typing-indicator","true"),Yt&&(Ae.style.color="var(--persona-message-assistant-text, var(--persona-text))",un!=="flat"&&(Ae.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ae.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ae.appendChild(Be);let dt=rr("typing-indicator","assistant");dt.appendChild(Ae),f.appendChild(dt)}}if(!Fn&&c.length>0){let I=c[c.length-1],Le={config:o,lastMessage:I,messageCount:c.length},Be=a.find(Yt=>Yt.renderIdleIndicator),Ae=null;if(Be?.renderIdleIndicator&&(Ae=Be.renderIdleIndicator(Le)),Ae===null&&o.loadingIndicator?.renderIdle&&(Ae=o.loadingIndicator.renderIdle(Le)),Ae){let Yt=document.createElement("div"),un=o.loadingIndicator?.showBubble!==!1;Yt.className=un?["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(" "),Yt.setAttribute("data-idle-indicator","true"),Yt.appendChild(Ae);let dt=rr("idle-indicator","assistant");dt.appendChild(Yt),f.appendChild(dt)}}if(iv(f),lp(i,f),jg(i),tt){let{messageId:I,element:Le}=tt,Be=i.querySelector(`#wrapper-${I}`);Be&&Le.parentElement!==Be&&(Ra(Be,q.get(I)??"user"),Be.replaceChildren(Le))}if(ae.length>0)for(let{messageId:I,fingerprint:Le,bubble:Be}of ae){let Ae=i.querySelector(`#wrapper-${I}`);Ae&&(Ra(Ae,q.get(I)??"assistant"),Be!==null&&(Ae.replaceChildren(Be),Ae.setAttribute("data-bubble-fp",Le),fi.set(I,Le)))}if(fi.size>0)for(let I of fi.keys())z.has(I)||fi.delete(I);if(ye.length>0)for(let{messageId:I,fingerprint:Le,bubble:Be}of ye){let Ae=i.querySelector(`#wrapper-${I}`);Ae&&(Ra(Ae,q.get(I)??"assistant"),Be!==null&&(Ae.replaceChildren(Be),Ae.setAttribute("data-bubble-fp",Le),vs.set(I,Le)))}if(vs.size>0)for(let I of vs.keys())z.has(I)||vs.delete(I);if(ft.length>0)for(let{messageId:I,fingerprint:Le,bubble:Be}of ft){let Ae=i.querySelector(`#wrapper-${I}`);Ae&&(Ra(Ae,q.get(I)??"assistant"),Be!==null&&(Ae.replaceChildren(Be),Ae.setAttribute("data-bubble-fp",Le),Hr.set(I,Le)))}if(Hr.size>0)for(let I of Hr.keys())z.has(I)||Hr.delete(I)},Hu=!1,xc=()=>{Hu||(Hu=!0,cd().catch(()=>{Hu=!1}))},Zn=(i,c,g)=>{c.length>0&&xc(),BA(i,c,g),Ah()},Ha=null,_A=()=>{if(Ha)return;let i=g=>{let f=g.composedPath();f.includes(Ye)||Jt&&f.includes(Jt)||mt(!1,"user")};Ha=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},sy=()=>{if(!Ha)return;(e.ownerDocument??document).removeEventListener("pointerdown",Ha,!0),Ha=null};ve.push(()=>sy());let Wa=null,DA=()=>{if(Wa)return;let i=g=>{g.key==="Escape"&&(g.isComposing||mt(!1,"user"))};Wa=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},iy=()=>{if(!Wa)return;(e.ownerDocument??document).removeEventListener("keydown",Wa,!0),Wa=null};ve.push(()=>iy());let Oa=!1,ay=new Set,NA=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},wi=()=>{if(!xe())return;let i=Fe.peekBanner,c=Fe.peekTextNode;if(!i||!c)return;if(be){i.classList.remove("persona-pill-peek--visible");return}let g=k?.getMessages()??[],f;for(let Ut=g.length-1;Ut>=0;Ut--){let Wt=g[Ut];if(Wt.role==="assistant"&&Wt.content){f=Wt;break}}if(!f){i.classList.remove("persona-pill-peek--visible");return}let b=f.content,w=!!f.streaming,W=NA(),z=cp(W),q=z.type!=="none"?Su(z.type,W?.plugins):null,V=q?.isAnimating?.(f)===!0,Z=q!==null&&(w||V);Z&&q&&!ay.has(q.name)&&(Il(q,e),ay.add(q.name));let ae=Z&&q?.containerClass?q.containerClass:null,ye=c.dataset.personaPeekStreamClass??null;ye&&ye!==ae&&(c.classList.remove(ye),delete c.dataset.personaPeekStreamClass),ae&&ye!==ae&&(c.classList.add(ae),c.dataset.personaPeekStreamClass=ae),Z?(c.style.setProperty("--persona-stream-step",`${z.speed}ms`),c.style.setProperty("--persona-stream-duration",`${z.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let Ze=Z?dp(b,z.buffer,q,f,w):b;if(Z&&z.placeholder==="skeleton"&&w&&(!Ze||!Ze.trim())){let Ut=document.createElement("div"),Wt=Ll();Wt.classList.add("persona-pill-peek__skeleton"),Ut.appendChild(Wt),lp(c,Ut)}else{let Ut=Math.max(0,Ze.length-100),Wt=Ze.length>100?Ze.slice(-100):Ze,dn=fr(Wt);if(!Z||!q){let tt=Ze.length>100?`\u2026${Wt}`:Wt;c.textContent!==tt&&(c.textContent=tt)}else{let tt=dn;(q.wrap==="char"||q.wrap==="word")&&(tt=Pl(dn,q.wrap,`peek-${f.id}`,{skipTags:q.skipTags,startIndex:Ut}));let pn=document.createElement("div");if(pn.innerHTML=tt,q.useCaret&&Wt.length>0){let Do=pp(),gr=pn.querySelectorAll(".persona-stream-char, .persona-stream-word"),No=gr[gr.length-1];No?.parentNode?No.parentNode.insertBefore(Do,No.nextSibling):pn.appendChild(Do)}lp(c,pn),q.onAfterRender?.({container:c,bubble:i,messageId:f.id,message:f,speed:z.speed,duration:z.duration})}}let Zt=Fn||Oa;i.classList.toggle("persona-pill-peek--visible",Zt)};if(xe()){let i=Fe.peekBanner;if(i){let f=b=>{b.preventDefault(),b.stopPropagation(),mt(!0,"user")};i.addEventListener("pointerdown",f),ve.push(()=>{i.removeEventListener("pointerdown",f)})}let c=()=>{Oa||(Oa=!0,wi())},g=()=>{Oa&&(Oa=!1,wi())};Me.addEventListener("pointerenter",c),Me.addEventListener("pointerleave",g),ve.push(()=>{Me.removeEventListener("pointerenter",c),Me.removeEventListener("pointerleave",g)}),Jt&&(Jt.addEventListener("pointerenter",c),Jt.addEventListener("pointerleave",g),ve.push(()=>{Jt.removeEventListener("pointerenter",c),Jt.removeEventListener("pointerleave",g)}))}let FA=i=>{let c=o.launcher?.composerBar??{},g=c.expandedSize??"anchored",f=c.bottomOffset??"16px",b=c.collapsedMaxWidth,w=c.expandedMaxWidth??"880px",W=c.expandedTopOffset??"5vh",z=c.modalMaxWidth??"880px",q=c.modalMaxHeight??"min(90vh, 800px)",V="calc(100vw - 32px)",Z="var(--persona-pill-area-height, 80px)",ae=Ye.style;if(ae.left="",ae.right="",ae.top="",ae.bottom="",ae.transform="",ae.width="",ae.maxWidth="",ae.height="",ae.maxHeight="",Jt){let ye=Jt.style;ye.bottom=f,ye.width=b??""}if(i&&g!=="fullscreen"){if(g==="modal"){ae.top="50%",ae.left="50%",ae.transform="translate(-50%, -50%)",ae.bottom="auto",ae.right="auto",ae.width=z,ae.maxWidth=V,ae.maxHeight=q,ae.height=q;return}ae.left="50%",ae.transform="translateX(-50%)",ae.bottom=`calc(${f} + ${Z})`,ae.top=W,ae.width=w,ae.maxWidth=V}},Ba=()=>{if(be&&xc(),!ke())return;if(xe()){let V=(o.launcher?.composerBar??{}).expandedSize??"anchored",Z=be?"expanded":"collapsed";Ye.dataset.state=Z,Ye.dataset.expandedSize=V,Jt&&(Jt.dataset.state=Z,Jt.dataset.expandedSize=V),Ye.style.removeProperty("display"),Ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),FA(be),fe.style.display=be?"flex":"none",gs(),be?(_A(),DA()):(sy(),iy()),wi();return}let i=Et(o),c=e.ownerDocument.defaultView??window,g=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,b=c.innerWidth<=g,w=f&&b&&we,W=Hn(o).reveal;be?(Ye.style.removeProperty("display"),Ye.style.display=i?"flex":"",Ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-95","persona-opacity-0"),Me.classList.add("persona-scale-100","persona-opacity-100"),Rt?(Rt.setPanelOpen(!0),Rt.element.style.display="none"):fn&&(fn.style.display="none")):(i?i&&(W==="overlay"||W==="push")&&!w?(Ye.style.removeProperty("display"),Ye.style.display="flex",Ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ye.style.setProperty("display","none","important"),Ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ye.style.display="",Ye.classList.add("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-100","persona-opacity-100"),Me.classList.add("persona-scale-95","persona-opacity-0")),Rt?(Rt.setPanelOpen(!1),Rt.element.style.display=i?"none":""):fn&&(fn.style.display=i?"none":""))},mt=(i,c="user")=>{if(!ke()||be===i)return;let g=be;be=i,Ba();let f=(()=>{let w=o.launcher?.sidebarMode??!1,W=e.ownerDocument.defaultView??window,z=o.launcher?.mobileFullscreen??!0,q=o.launcher?.mobileBreakpoint??640,V=W.innerWidth<=q,Z=Et(o)&&z&&V,ae=xe()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return w||z&&V&&we||Z||ae})();if(be&&f){if(!Ho){let w=e.getRootNode(),W=w instanceof ShadowRoot?w.host:e.closest(".persona-host");W&&(Ho=jm(W,o.launcher?.zIndex??ln))}Wo||(Wo=qm(e.ownerDocument))}else be||(Ho?.(),Ho=null,Wo?.(),Wo=null);be&&(Za(),Iu()||(Nn()==="follow"?_r(!0):bc()));let b={open:be,source:c,timestamp:Date.now()};be&&!g?A.emit("widget:opened",b):!be&&g&&A.emit("widget:closed",b),A.emit("widget:state",{open:be,launcherEnabled:we,voiceActive:Ke.active,streaming:k.isStreaming()})},Dr={inputDisabled:!1,sendDisabled:!1},Nr=()=>Dr.inputDisabled,ks=()=>Dr.inputDisabled||Dr.sendDisabled,$A=()=>(Dr.inputDisabled?Dr.inputReason:void 0)??(Dr.sendDisabled?Dr.sendReason:void 0);function Wu(){if(!Ee)return;if(Se.getState().phase==="streaming"){Ee.disabled=!1;return}let i=et?!et.isReady():!1;Ee.disabled=ks()||i}function Sc(){if(!ko)return;let i=Se.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;ko.toggleAttribute("data-persona-send-hidden",c)}function UA(){let i=$A();if(xe()){let c=mo??He;i?c.setAttribute("title",i):c.removeAttribute("title"),He.toggleAttribute(ha,!!i);return}if(i){lt.setAttribute("role","status"),lt.setAttribute("aria-live","polite"),lt.setAttribute(ha,""),lt.textContent=i;return}if(lt.hasAttribute(ha)&&(lt.removeAttribute("role"),lt.removeAttribute("aria-live"),lt.removeAttribute(ha),p)){let c=k.getStatus();Kl(lt,Sn(c),o.statusIndicator??{},c)}}function Ou(){let i=vm(o.composer?.inputDisabled),c=vm(o.composer?.sendDisabled);Dr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},Se.setInputDisabled(i.disabled),Se.setSendDisabled(c.disabled);let g=Se.getState().phase==="streaming",f=i.disabled,b=g||f;ue&&(ue instanceof HTMLTextAreaElement?ue.disabled=f:ue.setAttribute("contenteditable",f?"false":"true"),ue.setAttribute("aria-disabled",f?"true":"false")),kt&&(kt.disabled=f),xt&&(xt.disabled=f);for(let w of Dt?.affordanceButtons??[])w.querySelectorAll("button").forEach(W=>{W.disabled=f});se&&(se.disabled=b),hs.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})}),Fu.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})}),He.dataset.personaComposerStreaming=g?"true":"false",He.dataset.personaComposerInputDisabled=f?"true":"false",He.dataset.personaComposerSendDisabled=ks()?"true":"false",He.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(w=>{(w instanceof HTMLButtonElement||w instanceof HTMLInputElement||w instanceof HTMLTextAreaElement||w instanceof HTMLSelectElement)&&(w.disabled=g)}),Wu(),UA()}let _a=i=>{Se.setStreaming(i),Zf(i?"stop":"send"),Ou()},Ps=()=>{Ke.active||ue&&ue.focus()};A.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Ps(),200)});let Ls=null,Da=!1,Bu=!An.hidden,Fr=null,_u=!E,Ac=null;ve.push(()=>{Ac?.cancel(),Ac=null});let jA=i=>{let c=lx(i);if(c===Xl)return;Xl=c,e.setAttribute("data-persona-conversation-state",c);let g=au();Zl(),_u&&(Ac?.cancel(),Ac=ix(He,c==="active"?g:au(),c==="active"?"drop":"rise")),Pn()},ly=null,cy,dy=null,xi=null,Du=!1,Na=i=>{let c=So(o),g=`${c.variant}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(g!==ly||c.icon!==cy)&&(ly=g,cy=c.icon,vp({host:An,iconHolder:VS,kicker:KS,title:GS,subtitle:YS,starterSuggestions:ou},c));let f=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;f!==dy&&(dy=f,Cp(_n,c.message,o));let b=i??(k?k.getMessages():o.initialMessages);jA(b);let w=Da,W=!w&&is(c,b),z=W!==Bu;if(Bu=W,xi){Fr?.cancel(),Fr=null,w!==Du&&(Du=w,w?af(re,An,null):sf(re,An,xi)),aa(re,An,!w);return}if(z&&!W&&!w&&c.dismiss==="on-first-message"&&_u){Fr=sx(An,V=>{Fr===V&&(Fr=null),!Bu&&!xi&&(aa(re,An,!1),Pn()),V?.cancel()});return}if(Fr){if(!W&&!w)return;Fr.cancel(),Fr=null}let q=!An.hidden;aa(re,An,W),!W&&q&&Pn()},Nu=[],Fu=[],$u=!1,py=null,uy,gy=()=>{Fu.length=0;let i=Nu.splice(0,Nu.length);for(let c of i)try{c()}catch(g){console.warn("[persona] renderWelcome cleanup threw",g)}};ve.push(gy);let qA=(i,c)=>{let g=Vm(i,c);if(!g)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),M("span");let f=o.suggestions?.starters,b=Km({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:()=>ue,eventTarget:An,submitPrompt:Xc});return Fu.push(b),b},Uu=()=>{if($u)return;$u=!0;let i=So(o);py=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,uy=i.icon;try{gy(),af(re,An,xi),xi=null,Du=!1;let c=k?k.getMessages():o.initialMessages,g=is(i,c),f=0,b=null;for(let w of a)if(w.renderWelcome&&(b=w.renderWelcome({config:i,variant:i.variant,visible:g,defaultRenderer:()=>An,sendMessage:W=>{if(!k||k.isStreaming())return;let z=W.trim();z&&k.sendMessage(z)},requestRender:()=>Uu(),renderStarter:W=>qA(W,f++),storage:u(w.id),onCleanup:W=>{Nu.push(W)}}),b))break;b&&b!==An&&(xi=b,sf(re,An,b))}finally{$u=!1}Na()},zA=()=>{let i=So(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===py&&i.icon===uy||Uu()},Mc=()=>{Na(),di||(ue.placeholder=VC(Se.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!k?.isStreaming()&&(Ee.textContent=o.copy?.sendButtonLabel??"Send")),ue.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ue.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},VA=!!o.setStoredConversationId,Si=i=>de(c=>{let g={...c};return delete g[i],g}),Ec=i=>{let c=Q[i];return typeof c=="string"?c:null},my=()=>{let i=Q.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:()=>Ec("sessionId"),setStoredSessionId:i=>{de(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Si("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Ec("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{de(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Si("conversationId"))});let fy=()=>o.clientToken??null,hy=i=>Fx(i,uo(),o.persistState===!1),yy=fy(),sr=yy?hy(yy):null,ir={...sr?{visitorStore:sr}:{},historyBootstrapReady:H,getStoredMessageCursor:()=>Ec("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){Si("historyMessageCursor");return}de(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=Q.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){Si("pendingDisplayProjections");return}de(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:my,setStoredResumableHandle:i=>{if(!i){Si("durableResume");return}de(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>ce&&my()!==null,...VA?{}:{getStoredConversationRevision:()=>Ec("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){Si("conversationRevision");return}de(c=>({...c,conversationRevision:i}))}}};if(ce){let i=o.onExecutionState,c=e.ownerDocument.defaultView,g=!1,f=()=>g=!0,b=()=>g=!1;c?.addEventListener("pagehide",f),c?.addEventListener("pageshow",b),ve.push(()=>{c?.removeEventListener("pagehide",f),c?.removeEventListener("pageshow",b)}),o={...o,reconnectStream:o.reconnectStream??(w=>k.getClient().reconnectClientTokenStream(w)),onExecutionState:w=>{(w||!g)&&ir.setStoredResumableHandle?.(w?{executionId:w.executionId,after:w.lastEventId}:null),i?.(w)}}}let KA=()=>{let i=fy();if(i&&sr?.matches(i,uo(),o.persistState===!1)||!i&&!sr)return;sr?.destroy(),sr=i?hy(i):null;let c={...ir};sr?c.visitorStore=sr:delete c.visitorStore,ir=c,k.setHistoryInternals(ir)},Is=null,GA=()=>{Is==null&&(Is=setInterval(()=>{let i=Pe.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Is),Is=null;return}let c=Date.now();i.forEach(g=>{let f=Number(g.getAttribute("data-tool-elapsed"));f&&(g.textContent=xd(c-f))})},100))},ju=(i,c)=>{if(Object.is(i,c))return!0;if(i===null||c===null||typeof i!="object"||typeof c!="object")return!1;if(Array.isArray(i)||Array.isArray(c))return!Array.isArray(i)||!Array.isArray(c)||i.length!==c.length?!1:i.every((W,z)=>ju(W,c[z]));let g=i,f=c,b=Object.keys(g),w=Object.keys(f);return b.length===w.length&&b.every(W=>Object.prototype.hasOwnProperty.call(f,W)&&ju(g[W],f[W]))},by=i=>{let{content:c,rawContent:g,llmContent:f,...b}=i;return b},qu=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!jl(i),YA=(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))&&qu(f)&&qu(b)&&ju(by(f),by(b))},zu=null,Ai=null,Rs=null,ar=null,Vu=null,QA=i=>{if(!ce)return bi(i);Vu=i,queueMicrotask(()=>{Vu===i&&(Vu=null,bi(i))})},Tc=i=>{zu=i;let c,g;Ai=null;for(let b=i.length-1;b>=0;b-=1){let w=i[b];if(!c&&w.role==="user"&&(c=w),!g&&w.role==="assistant"&&(g=w),!Ai&&qu(w)&&(Ai={index:b,id:w.id}),c&&g&&Ai)break}Zn(Pe,i,yt),wr()?.updateInlineArtifactBlocks(Pe,Jn.artifacts,{suppressTransition:Fn}),GA(),Na(i),mi(i),_r(!Fn),OA(i),i.length===0&&(vo(),Pa=!0,uc=!1,yi=null,gc=!1),!Au||hi?(Au=!0,As=c?.id??null,Mu=g?.id??null):c&&c.id!==As?(As=c.id,LA(c.id)):g&&g.id!==Mu&&IA(),g&&(Mu=g.id),WA(i);let f=Ke.lastUserMessageId;c&&c.id!==f&&(Ke.lastUserMessageId=c.id,A.emit("user:message",c)),Ke.lastUserMessageWasVoice=!!c?.viaVoice,QA(i),wi()},Ku=()=>{ar!==null&&(cancelAnimationFrame(ar),ar=null);let i=Rs;Rs=null,i&&Tc(i)},vy=()=>{ar!==null&&cancelAnimationFrame(ar),ar=null,Rs=null},XA=i=>{let c=Rs??zu;if(Fn&&c&&Ai&&YA(c,i,Ai)){Rs=i,ar===null&&(ar=requestAnimationFrame(()=>{ar=null;let g=Rs;Rs=null,g&&Tc(g)}));return}if(i.length===0){vy(),Tc(i);return}Ku(),Tc(i)};k=new Xi(o,{onMessagesChanged(i){XA(i)},onStatusChanged(i){let c=o.statusIndicator??{};Kl(lt,(f=>f==="idle"?c.idleText??jt.idle:f==="connecting"?c.connectingText??jt.connecting:f==="connected"?c.connectedText??jt.connected:f==="error"?c.errorText??jt.error:f==="paused"?c.pausedText??jt.paused:f==="resuming"?c.resumingText??jt.resuming:jt[f])(i),c,i),Qo()},onStreamingChanged(i){i||(k?.getMessages().length===0?vy():Ku()),Fn=i,_a(i),Qo(),k&&Zn(Pe,k.getMessages(),yt),i||(_r(!0),kA(),zh=!0,k&&Vh(k.getMessages(),Zr(o))),Gt(),Ql(i?"Responding\u2026":"Response complete."),wi()},onVoiceStatusChanged(i){if(A.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":ur(),Oi();break;case"processing":ur(),ZM();break;case"speaking":ur(),eE();break;default:i==="idle"&&k.isBargeInActive()?(ur(),Oi(),se?.setAttribute("aria-label","End voice session")):(Ke.active=!1,ur(),or("system"),bo());break}},onArtifactsState(i){Jn=i,i.artifacts.length===0&&(pi=!1),wr()?.updateInlineArtifactBlocks(Pe,i.artifacts,{suppressTransition:Fn}),yo(),bi()},onHistoryStateChanged(i){_t(i)},onHistoryNotice(i){Lt(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})}},ir),pt.current=k,ve.push(()=>k.cancel()),ve.push(()=>{k.destroy(),sr?.destroy()});let Gu=null;if(k.onReadAloudChange((i,c)=>{xh=i,Sh=c,Ah();let g=i??Gu;i&&(Gu=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"&&(Gu=null)}),p=!0,Au=!0,o.voiceRecognition?.provider?.type==="runtype")try{k.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let JA=720,ZA=250,Je=Hf(o.features?.history?.copy),jn=null,Yu=!1,ct=null,kc=null,Pc="conversation",Qu=null,mn=null,Oo=null,Lc=k.getHistoryState(),Xu=null,Fa=0,Ju=null,Ic=null,Rc=null,Zu=`persona-history-${Math.random().toString(36).slice(2,8)}`,eg=()=>o.features?.history?.enabled===!0,Bo=()=>eg()&&!!jn&&!Yu,Cy=()=>{let i=k.getStatus();return Fn||i==="paused"||i==="resuming"},tg=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",g=jn?.capabilities.scopes;return!g||g.includes(c)?c:g[0]??c},Mi=()=>kc?.scope??tg(),wy=()=>k.getClientSession()?.targetId??null,xy=i=>`${i.state}:${"reason"in i?i.reason:""}`,eM=i=>{let c=xy(i);c!==Xu&&(Xu=c,A.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},Hc=i=>{i&&(Xo.textContent="",Xo.textContent=i)},Sy=null,Ay=null,tM=()=>{if(!eg())return null;let i=qx();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(Sy!==c&&(Sy=c,Ay=c()),Ay):k.isClientTokenMode()?zx({client:k.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:g=>k.bindActivatedSession(g),getClient:()=>k.getClient()}):null},My=()=>{Ic?.(),Ic=null,Rc?.(),Rc=null,Yu=!1,jn=tM();let i={...ir};jn?i.historyProvider=jn:delete i.historyProvider,ir=i,k.setHistoryInternals(ir),jn&&(Ic=jn.subscribeAvailability?.(c=>{Yu=!c,c||Ln({restoreFocus:!1}),Ur()})??null,Rc=jn.subscribeIdentityStatus(c=>eM(c)),Xu=xy(jn.getIdentityStatus()))},ng=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!we||Et(o)))return"panel";let c=Ro??fe;return(c.getBoundingClientRect().width||c.clientWidth)>=JA?"rail":"panel"},eo=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},Wc="data-persona-history-suppressed",qn=null,$r=null,Hs=null,$a=null,og=null,Ey="",Ty=()=>Te===og?Ey:o.layout?.showHeader===!1?"none":"",nM=()=>pe==="panel"&&!!Hs&&$a===Hs.element&&o.layout?.showHeader!==!1&&Ty()!=="none",oM=()=>{for(let i of Array.from(Te.children))i!==qn&&i.setAttribute(Wc,"")},rM=()=>{for(let i of Array.from(fe.querySelectorAll(`[${Wc}]`)))i.removeAttribute(Wc)},sM=()=>{let i=Hs;if(!i)return;if(Array.from(Te.children).some(f=>f!==qn&&!f.hasAttribute(Wc))){$r&&$r!==Te&&($r.style.removeProperty("min-height"),$r=null);let f=Te.offsetHeight;f>0&&(Te.style.minHeight=`${f}px`,$r=Te)}qn||(qn=M("div","persona-history-header-host")),i.setHeaderPlacement("external");let g=i.getHeaderElement();g.parentNode!==qn&&qn.replaceChildren(g),qn.parentNode!==Te&&Te.appendChild(qn),oM()},ky=()=>{$r&&($r.style.removeProperty("min-height"),$r=null),qn&&(Hs?.setHeaderPlacement("inline"),qn.remove(),qn=null,rM())},Oc=null,rg=()=>{if(Oc){if(re.style.display="none",eo(re,!0),He.hidden=!0,eo(He,!0),nM()){sM(),Te.style.display=Ty(),eo(Te,!1);return}ky(),Te.style.display="none",eo(Te,!0)}};qt=rg;let iM=i=>{let c=re.style.display,g=He.hidden,f=He,b=Te,w=Te.style.display;og=b,Ey=w,Oc=()=>{Oc=null,ky(),og=null,re.style.display=c,eo(re,!1),f.hidden=g,eo(f,!1),He!==f&&(He.hidden=!1,eo(He,!1)),b.style.display=w,eo(b,!1),Te!==b&&(Te.style.display=o.layout?.showHeader===!1?"none":"",eo(Te,!1))},He.parentNode?.insertBefore(i,He),rg()},Ei=null,Ws=null,Ua=null,Ti=null,Py=()=>[Te,Fe.closeButtonWrapper,Fe.clearChatButtonWrapper,re,He],aM=52,Bc=()=>o.features?.history?.rail?.collapsible!==!1,ki=()=>o.features?.history?.rail?.side==="right"?"right":"left",sg=200,ig=400,ag=i=>Math.min(ig,Math.max(sg,Math.round(i))),lM=()=>o.features?.history?.rail?.resizable===!0,ja,cM=()=>{if(ja===void 0&&(ja=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${uo()}rail-width`));i&&(ja=i)}catch{}return ja},qa=()=>ag(cM()??o.features?.history?.rail?.width??260),dM=i=>{if(ja=i,o.persistState!==!1)try{window.localStorage.setItem(`${uo()}rail-width`,String(i))}catch{}},_c=()=>Bc()&&o.features?.history?.rail?.collapsedBehavior==="overlay",$t=!1,Ly=i=>{let c=M("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},pM=()=>{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=Ly(i.iconUrl):g=i.icon?ge(i.icon,20):null),g?g.cloneNode(!0):null}},uM=()=>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=Ly(f.iconUrl):b=f.icon?ge(f.icon,20):null}catch(w){g(w),b=null}return b},onSelect:()=>{try{f.onSelect()}catch(w){g(w)}}}})}})??[],gM=i=>{let c=uM();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},za=null,Iy=()=>`${uo()}rail-collapsed`,lg=()=>{if(za===null&&(za=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(Iy());i&&(za=i==="1")}catch{}return za},cg=i=>{if(za=i,o.persistState!==!1)try{window.localStorage.setItem(Iy(),i?"1":"0")}catch{}},Va=()=>pe==="rail"&&Bc()&&!_c()&&lg(),dg=()=>{},Ry=()=>{if(_c()){dg();return}cg(!lg()),ct?.view.setCollapsed(Va()),_e(),Pn()},pg=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!ip(i)?null:{combo:i,hint:ap(i),aria:Al(i)}},Hy=()=>{d.forEach(c=>c()),d=[];let i=pg();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>le&&pe==="rail"&&Bc()||Li(),run:()=>_c()?dg():Ry()}));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}`}))};Hy();let mM=300,Dc="var(--persona-history-overlay-margin,8px)",to=null,lr=null,Nc=0,cr=null,Pi=null,Os=!1,ug=0,Wy=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Li=()=>Bo()&&_c()&&(pe??ng())==="rail",fM=()=>le&&!$t,Ka=()=>{Pi!==null&&clearTimeout(Pi),Pi=null},hM=()=>{Lf().catch(()=>{})},Oy=()=>{Ka(),$t&&(Pi=setTimeout(()=>{Pi=null,!(Os||!$t)&&(cr?.contains(document.activeElement)||Ln({restoreFocus:!1}))},mM))},yM=(i,c)=>{let g=cr?.getBoundingClientRect();if(!g)return!1;let f=to?.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},gg=i=>{$t&&(Os=yM(i.clientX,i.clientY),Os?Ka():Pi===null&&Oy())},By=i=>{le||!Li()||($t=!0,Ya({invoker:to,keyboard:i?.keyboard===!0}).then(()=>{le?!Os&&document.activeElement!==to&&Ln():$t=!1}))},_y=()=>{let i=$a?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",$t?Je.expandLabel:Je.collapseLabel),i.setAttribute("aria-expanded",$t?"false":"true"))},Dy=()=>{cg(!1);let i=ct;if(!$t||!i){Ya({invoker:to});return}let c=document.activeElement===to;$t=!1,Fc(),i.element.remove(),fg(i.element),_y(),c&&Uc(),Pn(),Ur()},bM=()=>{cg(!0),Ln()};dg=()=>{!le||$t?Dy():bM()};let vM=()=>{let i=pg(),c=Qs({ariaLabel:Je.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",()=>{Os=!0,Ka(),!(Wy()||Date.now()<ug)&&By()}),g.addEventListener("mouseleave",()=>{Os=!1,ug=0,Oy()}),g.addEventListener("focus",()=>{le||hM()}),g.addEventListener("click",f=>{Bo()&&(f.detail!==0&&Wy()&&!le?By():Dy())}),to=g,lr=c.wrapper},Ga=()=>{if(lr&&!lr.isConnected&&(lr=null,to=null),!Li()){lr?.remove(),lr=null,to=null;return}to||vM();let i=lr,c=to;if(!i||!c)return;let g=ki()!=="right"?Te.firstChild:null;(g??Te.lastChild)!==i&&Te.insertBefore(i,g),i.style.display=fM()||Nc>0?"none":"",c.setAttribute("aria-label",Je.expandLabel),c.setAttribute("aria-expanded",le?"true":"false"),cr&&_e()},Ny=i=>{if(!$t)return;let c=i.target;c instanceof Node&&(cr?.contains(c)||lr?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||Ln({restoreFocus:!1}))};document.addEventListener("pointerdown",Ny,!0),ve.push(()=>{document.removeEventListener("pointerdown",Ny,!0),document.removeEventListener("pointermove",gg),Ii?.(),Ka()});let mg=null,Ii=null,Fy=16,$y=i=>{dM(ag(i)),_e(),Pn()},CM=()=>{let i=M("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(sg)),i.setAttribute("aria-valuemax",String(ig)),i.addEventListener("pointerdown",c=>{let g=Ws;if(!g||c.button!==0)return;c.preventDefault(),Ii?.();let f=c.clientX,b=g.getBoundingClientRect().width||qa(),w=ki()==="right"?-1:1,W=b,z=e.ownerDocument;g.style.transition="none";let q=Z=>{W=ag(b+w*(Z.clientX-f)),g.style.flex=`0 0 ${W}px`,i.setAttribute("aria-valuenow",String(W))},V=()=>{Ii=null,z.removeEventListener("pointermove",q),z.removeEventListener("pointerup",V),z.removeEventListener("pointercancel",V),g.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}$y(W)};Ii=V,z.addEventListener("pointermove",q),z.addEventListener("pointerup",V),z.addEventListener("pointercancel",V);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let g=ki()==="right"?-Fy:Fy,f=qa(),b=c.key==="ArrowRight"?f+g:c.key==="ArrowLeft"?f-g:c.key==="Home"?sg:c.key==="End"?ig:null;b!==null&&(c.preventDefault(),$y(b))}),i},wM=(i,c)=>{if(!lM()||Va()){Ii?.(),mg?.remove();return}let g=mg??CM();mg=g,g.setAttribute("aria-label",Je.resizeLabel),g.setAttribute("aria-valuenow",String(qa())),g.nextElementSibling!==c&&i.insertBefore(g,c)};_e=()=>{ct?.view.setRailSide(ki());let i=ki()==="right",c=cr;if(c){let z=to?to.getBoundingClientRect().bottom-fe.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(z))}px + ${Dc})`,c.style.width=`${qa()}px`,c.style.left=i?"":Dc,c.style.right=i?Dc:""}let g=Ws,f=Ei,b=Ua;if(!g||!f||!b)return;g.style.flex=`0 0 ${Va()?aM:qa()}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),wM(f,i?g:b)};let Uy=i=>{if(Ti&&Ws){Ti.replaceWith(i),Ti=null,_e();return}let c=M("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let g=M("div","persona-history-rail-conversation");g.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let f=M("div","persona-history-rail-host");f.style.cssText="display:flex;min-height:0;overflow:hidden",fe.insertBefore(c,Te.parentNode===fe?Te:re);for(let b of Py())b?.parentNode===fe&&g.appendChild(b);c.append(f,g),f.appendChild(i),Ei=c,Ws=f,Ua=g,_e()},xM=()=>{if(Ei)return;let i=M("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",Ti=i,Uy(i),Pn()},jy=()=>{Ti&&(Fc(),Pn())},SM=i=>{let c=M("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${Dc};display:flex;overflow:hidden;z-index:${Ji-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))`,fe.style.position="relative",fe.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",gg),cr=c,_e(),_y()},Fc=()=>{Oc?.(),cr&&(Os&&(ug=Date.now()+150),document.removeEventListener("pointermove",gg),cr.remove(),cr=null);let i=Ei;if(i){Ii?.();for(let c of Py())c&&i.contains(c)&&fe.insertBefore(c,i);i.remove(),Ei=null,Ws=null,Ua=null,Ti=null}},qy=i=>{$a=i,i.id=Zu,i.style.flex="1 1 auto",i.style.minHeight="0"},fg=i=>{qy(i),(pe!=="rail"||$t)&&jy(),pe!=="rail"?iM(i):$t?SM(i):Uy(i)},$c=()=>{if(Ga(),tb(),!le||!ct)return;let i=ng();if(i===pe)return;let c=document.activeElement,g=c instanceof HTMLElement&&(ct.element.contains(c)||qn?.contains(c)===!0)?c:null;Fc(),ct.element.remove(),ct.view.setHeaderPlacement("inline"),pe=i,ct.view.setPresentation(i),ct.view.setCollapsed(Va()),ct.requestRender(),ct.element.isConnected||fg(ct.element),g?.isConnected?g.focus():Uc(),Gt(),Pn(),Ur()},zy=(i,c)=>qn?.querySelector(c)??i.querySelector(c),Uc=()=>{let i=ct?.element??$a;if(!i)return;let c=zy(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let g=zy(i,".persona-history-title")??i;g.tabIndex=-1,g.focus()},Ya=async i=>{if(!Bo()||le)return;let c=jn;if(!c)return;if(!$t&&Li()&&lg()){Ga();return}jc();let g=++Fa;Pc=i?.returnSurface??"conversation",Qu=i?.invoker??mn;let f=Li()&&!$t;f&&(Nc+=1,Ga(),xM());let b;try{b=await Lf()}catch{Hc(Je.openHistoryLabel),f&&(Nc-=1,g===Fa&&(jy(),Ga()));return}if(f&&(Nc-=1),g!==Fa||le)return;kc={scope:tg()},pe=ng(),le=!0;let w=pe==="panel"&&o.layout?.showHeader!==!1&&Te.style.display!=="none"?"external":"inline",W=o.features?.history?.rowAvatar,z=pg(),q=z?{hint:z.hint,aria:z.aria}:null,V={provider:c,context:kc,targetId:wy(),presentation:pe,collapsible:Bc(),collapsed:Va(),railSide:ki(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:pM(),onToggleCollapse:Ry,...q?{collapseShortcut:q}:{},headerPlacement:w,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:W===!1?!1:typeof W=="string"?W:o.launcher?.iconUrl,activeConversationId:k.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:Z=>yg(Z,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Z=>Bs(Z),attachTooltip:on,onStartNew:()=>bg({focusComposer:!0}),onClose:()=>Ln(),onRequestDeleteConversation:Z=>eb(Z),onRequestClearHistory:()=>PM(),...c.resetDevice?{onRequestResetIdentity:()=>LM()}:{}};ct=jx({plugins:a,config:o,getPresentation:()=>pe??"panel",getReturnSurface:()=>Pc,close:()=>Ln(),createView:({slots:Z,renderDom:ae,onModelChange:ye,railSections:Ze})=>(Hs=b.createHistoryView({...V,railSections:gM(Ze),slots:Z,renderDom:ae,onModelChange:ye,onAnnounce:Hc}),Hs),onElementChanged:(Z,ae)=>{if(!ae?.isConnected)return fg(Z);qy(Z),ae.replaceWith(Z),rg()}}),ct.view.setNewConversationRequired(Lc.recovery==="new_conversation_required"),i?.focus!==!1&&(pe!=="rail"||i?.keyboard===!0)&&Uc(),Gt(),Pn(),Ur(),A.emit("history:opened",{presentation:pe,returnSurface:Pc,timestamp:Date.now()})},jc=()=>{},Ln=i=>{if(!le)return;Fa+=1;let c=Pc,g=Qu,f=ct,b=i?.restoreFocus!==!1;le=!1;let w=!1,W=null,z=()=>{if(!w){if(w=!0,jc=()=>{},W!==null&&clearTimeout(W),$t=!1,Ka(),Fc(),f?.dispose(),f?.view.destroy(),f?.element.remove(),ct===f&&(ct=null,Hs=null,$a=null,pe=null,kc=null,Qu=null),Gt(),Pn(),Ur(),b){let V=g??mn;V?.isConnected?V.focus():Ps()}A.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},q=f&&f.element===f.view.element?f.view.playExit():null;if(!q){z();return}jc=z,W=setTimeout(z,ZA),q.then(z)},Vy=i=>{if(!(i.key!=="Escape"||!le||!ct)){if(pe==="rail"){let c=i.target;if(!(c instanceof Node)||!(ct.element.contains(c)||$t&&lr?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Ln()}};fe.addEventListener("keydown",Vy),ve.push(()=>fe.removeEventListener("keydown",Vy));let qc=null,Ky=!1,Qa=()=>{if(!kr)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&qc?.trim()||null;kr.textContent=c??o.launcher?.title??"Chat Assistant";let g=kr.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")},AM=i=>{i!==qc&&(qc=i,Qa())},Bs=i=>{Ky=i?.starred===!0,AM(i&&i.title.trim()||null),Qa()};Qa(),fe.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,g=k.getActiveConversationId();g&&(c==="delete"?eb(g):c==="star"&&k.canUpdateConversations()&&vg(g,{starred:!Ky}).catch(()=>{}))});let zc=0,MM=250,Vc=null,Kc=()=>{Vc&&clearTimeout(Vc),Vc=null};ve.push(Kc);let Gy=()=>{Kc();let i=Ls;i&&(Da=!0,i.hidden=!1,Pe.style.display="none",Na())},Gc=()=>{zc+=1,Kc(),Ls&&(Ls.remove(),Ls=null,Da=!1,Pe.style.removeProperty("display"),eo(He,!1),Na())},EM=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Pe.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},hg=(i,c)=>X("div",{className:yn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),Yy=()=>X("div",{className:"persona-conversation-loading-body"},hg("58%",!1),hg("72%",!0),hg("44%",!1)),Qy=i=>{Ls?.remove(),Ls=i,i.hidden=!Da,re.insertBefore(i,Pe),Kc(),Da||(Vc=setTimeout(Gy,MM)),eo(He,!0)},TM=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Yy},c=null,g=a.find(f=>f.renderLoadingIndicator);g?.renderLoadingIndicator&&(c=g.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),Qy(X("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Je.openConversationLoadingLabel}},c??Yy()))},kM=i=>{let c=()=>{yg(i,{focusComposer:!0}).catch(()=>{})},g=Bo()?()=>{Gc(),Ya()}:void 0,f=(z,q)=>{let V=X("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:z});return V.addEventListener("click",q),V},b=()=>X("div",{className:"persona-conversation-loading-error-body"},X("p",{className:"persona-conversation-loading-error-title",text:Je.openConversationErrorTitle}),X("div",{className:"persona-conversation-loading-error-actions"},f(Je.openConversationRetryLabel,c),g?f(Je.openConversationBackLabel,g):null)),w=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Je.openConversationErrorTitle,retryLabel:Je.openConversationRetryLabel,backLabel:Je.openConversationBackLabel}),retry:c,...g?{back:g}:{},defaultRenderer:b}),W=null;for(let z of a)if(z.renderHistoryOpenError){try{W=z.renderHistoryOpenError(w)}catch(q){console.warn("[persona] renderHistoryOpenError threw",q),W=null}if(W)break}Qy(X("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},W??b())),Gy()};A.on("history:closed",()=>{Ls&&eo(He,!0)});let yg=async(i,{focusComposer:c=!1}={})=>{let g=Mi(),f=!!ct;ct?.view.setActiveConversationId(i),Gc();let b=zc;TM(),le&&(pe==="panel"||$t)&&Ln({restoreFocus:!1}),hi=!0;try{await k.openConversation(i,{scope:g})}catch(w){throw b===zc&&kM(i),w}finally{hi=!1}b===zc&&(Gc(),Ft.clear(),vo(),kn(),Iu()||bc(),EM(),dr(),f||Bs(null),A.emit("history:conversationOpened",{conversationId:i,title:qc,scope:g,timestamp:Date.now()}),c&&Ps())},bg=async({focusComposer:i=!1}={})=>{Gc(),await k.startNewConversation({scope:Mi()}),Bs(null),Ft.clear(),vo(),kn(),bc(),dr();let c=k.getActiveConversationId();ct?.view.setActiveConversationId(c),A.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),le&&(pe==="panel"||$t)&&Ln({restoreFocus:!1}),i&&Ps()},vg=async(i,c)=>{let g=await k.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return ct?.view.applyConversationSummary(g),!ct&&i===k.getActiveConversationId()&&Bs(g),g},Xy=async i=>{let c=Mi(),g=k.getActiveConversationId()===i;await k.deleteConversation(i,{scope:c}),ct?.view.removeConversationSummary(i),g&&(Bs(null),Ft.clear(),vo(),kn(),dr()),A.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:g,timestamp:Date.now()})},Jy=async i=>{let c=i?.scope??Mi(),g=i?.allTargets?null:i?.targetId??wy(),f=await k.clearConversationHistory({...g?{targetId:g}:{},scope:c});return Bs(null),Ft.clear(),vo(),kn(),dr(),A.emit("history:cleared",{deleted:f.deleted,scope:c,targetId:g,timestamp:Date.now()}),f},Zy=async()=>{if(!jn?.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{Bs(null),k.clearArtifacts(),Ft.clear(),zu=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),Q={},Oe.syncFromMetadata(),Y?.clear&&fc(()=>Y.clear(),"[AgentWidget] Failed to clear storage adapter:"),vo(),kn(),dr(),Ln({restoreFocus:!1}),Ps(),be||Rt?.launcher.element.focus()}return Hc(i?Je.identityResetNotice:Je.identityResetUnconfirmedNotice),A.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},Cg=()=>Ro?Me:fe,eb=async i=>await Wp({host:Cg(),title:Je.deleteConversationConfirmTitle,description:Je.deleteConversationConfirm,confirmLabel:Je.deleteConversationConfirmLabel,cancelLabel:Je.confirmCancelLabel})?(await Xy(i),"deleted"):"cancelled",PM=async()=>{let i=Mi()==="verified-user";return await Wp({host:Cg(),title:Je.clearHistoryConfirmTitle,description:i?Je.clearHistoryVerifiedConfirm:Je.clearHistoryConfirm,confirmLabel:Je.clearHistoryConfirmLabel,cancelLabel:Je.confirmCancelLabel})?(await Jy(),"cleared"):"cancelled"},LM=async()=>{if(!await Wp({host:Cg(),title:Je.resetIdentityConfirmTitle,description:Je.resetIdentityConfirm,confirmLabel:Je.resetIdentityConfirmLabel,cancelLabel:Je.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await Zy();return{outcome:"reset",remoteRevocationConfirmed:c}},no=M("button","persona-history-earlier");no.type="button",no.textContent=Je.showEarlierMessagesLabel,no.setAttribute("data-persona-history-earlier",""),Object.assign(no.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 dr=()=>{if(!(Bo()&&!!Lc.nextMessageCursor&&!!k.getActiveConversationId())){no.remove();return}no.textContent=Je.showEarlierMessagesLabel,no.parentNode!==re&&re.insertBefore(no,re.firstChild)};no.addEventListener("click",()=>{let i=k.getActiveConversationId(),c=Lc.nextMessageCursor;if(!i||!c||no.disabled)return;no.disabled=!0;let g=re.scrollHeight,f=re.scrollTop;k.loadOlderMessages(i,c,{scope:Mi()}).then(()=>{re.scrollTop=f+(re.scrollHeight-g),Pn()}).catch(()=>{}).finally(()=>{no.disabled=!1,dr()})});let IM=()=>{let i=Qs({ariaLabel:Je.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(!(!Bo()||Cy())){if(le){Ln();return}Ya({invoker:i.button,keyboard:c.detail===0})}}),i},tb=()=>{if(!Bo()){Oo?.remove(),mn=null,Oo=null;return}if(Oo&&!Oo.isConnected&&(mn=null,Oo=null),!mn&&Te){let f=IM();mn=f.button,Oo=f.wrapper;let b=Fe.clearChatButtonWrapper||Fe.closeButtonWrapper;b?.parentNode&&Te.contains(b)?b.parentNode.insertBefore(Oo,b):Te.appendChild(Oo)}if(!mn||!Oo)return;let i=Li()||le&&pe==="rail";if(Oo.style.display=i?"none":"",i){document.activeElement===mn&&Uc();return}let c=Cy();mn.disabled=c,mn.setAttribute("aria-disabled",c?"true":"false");let g=c?Je.openHistoryBusyLabel:Je.openHistoryLabel;mn.setAttribute("aria-label",g),(o.features?.history?.presentation??"panel")==="panel"?(mn.removeAttribute("aria-expanded"),mn.removeAttribute("aria-controls")):(mn.setAttribute("aria-expanded",le?"true":"false"),mn.setAttribute("aria-controls",Zu))},Yc=!1,RM=()=>{let i=Fe.clearChatButton;if(i){if(Bo()){Yc||(Ju=i.getAttribute("aria-label")??"",Yc=!0),i.setAttribute("aria-label",Je.newConversationLabel),i.removeAttribute("title");return}Yc&&(Yc=!1,Ju&&i.setAttribute("aria-label",Ju))}},Ur=()=>{Je=Hf(o.features?.history?.copy),tb(),Ga(),RM(),dr()};Qo=Ur,_t=i=>{Lc=i,ct?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),_a(i.sendBlocked||Fn),dr()},Lt=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(Ft.clear(),vo(),kn()),Hc(i.message),ct?.view.refresh()},My(),Ur(),ve.push(()=>{Ic?.(),Rc?.(),Fa+=1,jc(),ct?.dispose(),ct?.view.destroy(),ct=null}),o.clientToken&&k.initClientSession().then(()=>{if(Bo())return k.reconcileBootConversation({scope:tg()})}).then(()=>{dr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(cn||o.onSSEEvent)&&k.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),oe(i,c)});let nb=()=>{let i=o.resume??(ce?ir.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&k.resumeFromHandle(i)};E?E.then(i=>{if(i){if(i.metadata&&(Q=Wf(i.metadata),Oe.syncFromMetadata()),i.messages?.length){hi=!0;try{k.hydrateMessages(i.messages)}finally{hi=!1}xc()}i.artifacts?.length&&k.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),Jh(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{_u=!0,B(),nb()}):(Jh(L),nb());let HM=()=>{!xe()||be||!(o.launcher?.composerBar?.expandOnSubmit??!0)||mt(!0,"auto")},WM=(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),D0(b)}}:i:c,wg=()=>{let c=ue.getInlineMessageFields?.();return c&&c.contentSegments.some(f=>f.kind==="mention")?c.contentSegments:void 0},pr=!1,_s=null,Qc=()=>{ue.value="",ue.style.height="auto",Po(),Ja()},xg="data-persona-composer-notice",Ri=null;function OM(i){Ql(i),!(xe()||!lt)&&(lt.hasAttribute(ha)||(lt.setAttribute(xg,""),lt.setAttribute("role","status"),lt.setAttribute("aria-live","polite"),lt.textContent=i,Ri&&clearTimeout(Ri),Ri=setTimeout(()=>{if(Ri=null,!!lt?.hasAttribute(xg)&&(lt.removeAttribute(xg),lt.removeAttribute("role"),lt.removeAttribute("aria-live"),p)){let c=k.getStatus();Kl(lt,Sn(c),o.statusIndicator??{},c)}},4e3)))}function BM(){let i=Se.getState().pendingSubmission;i&&(li(void 0),ue&&(ue.value=i.text,ue.dispatchEvent(new Event("input",{bubbles:!0})),Po()),i.options.selectedModelId&&(Se.setSelectedModelId(i.options.selectedModelId),Lr?.repaint()),i.options.activeModeIds?.length&&ec(i.options.activeModeIds),i.options.quote&&Lo(i.options.quote),ue?.focus())}let _M=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},ob=(i={})=>{let c=(i.overrideText??ue?.value??"").trim();return i.resolveInlineCommand&&c?(Dt?.takeInlineCommand(c)??Promise.resolve(null)).then(g=>rb(i,c,g)):rb(i,c,null)},rb=(i,c,g)=>{if(g?.kind==="action"){Qc(),Dt?.clear(),us();return}let f=g?.kind==="server"?g.mentions:null,b=g?.kind==="prompt"?g.sendText:c,w=i.pending?.contentParts,W=(et?.hasAttachments()??!1)||(w?.length??0)>0;if(!sw({text:b,hasAttachments:W,attachmentsReady:et?.isReady()??!0,hasMentions:Dt?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:Nr(),sendDisabled:ks()}))return;let z=k.isStreaming()?pu():"block";if(z==="defer-one"&&!i.pending){if(Se.getState().pendingSubmission){OM("One message is already queued. Edit or remove it first.");return}DM({intent:i,sendText:b,serverMentions:f});return}let q={text:b,mentionRefs:[...Dt?.getMentionRefs()??[],...f?.refs??[]],contentSegments:g?.kind==="prompt"?void 0:wg(),options:{...Se.getState().selectedModelId&&{selectedModelId:Se.getState().selectedModelId},...Se.getState().activeModeIds.length>0&&{activeModeIds:[...Se.getState().activeModeIds]},...Se.getState().quote&&{quote:{...Se.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(q.options={...i.pending.options},q.contentSegments=i.pending.contentSegments,q.mentionRefs=[...i.pending.mentionRefs],q.viaVoice=i.pending.viaVoice);let V=()=>{if(w?.length)return[...w];if(!et?.hasAttachments())return;let ft=[...et.getContentParts()];return q.text&&ft.push(lo(q.text)),ft};q.contentParts=V();let Z=()=>{ws(),HM();let ft=Dt?.collectForSubmit()??null,Zt=WM(ft,f),Ut=V();i.consumeDraft!==!1&&Qc();let Wt={selectedModelId:q.options.selectedModelId,activeModeIds:q.options.activeModeIds},dn=z==="interrupt";dn&&k.cancel(),k.sendMessage(q.text,{contentParts:Ut,mentions:Zt??void 0,contentSegments:q.contentSegments,viaVoice:q.viaVoice,composerOptions:Wt,...q.options.quote&&{quote:q.options.quote},...dn&&{interrupt:!0}}),et?.hasAttachments()&&et.clearAttachments(),ft&&Dt?.clear(),us();let tt=Se.getState().activeModeIds,pn=zC(tt,o.composer?.modes);pn.length!==tt.length&&ec(pn),Se.getState().quote&&Lo(void 0),yc(),hu.release(),fo()},ae=o.composer?.onBeforeSend;if(!ae){Z();return}let ye=new AbortController;_s=ye;let Ze=ft=>{if(_s=null,ft.status==="error"){_M(ft.error);return}ft.status==="proceed"&&Z()},ut=iw(ae,q,ye.signal);if(!(ut instanceof Promise)){Ze(ut);return}return Se.setPreparing(!0),ut.then(Ze).finally(()=>Se.setPreparing(!1))};function DM(i){let c=Se.getState(),g=et?.hasAttachments()??!1,f=g?[...et.getContentParts()]:[];g&&i.sendText&&f.push(lo(i.sendText));let b=Lm({text:i.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Dt?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:wg(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});li(b),i.intent.consumeDraft!==!1&&Qc(),g&&et.clearAttachments(),Dt?.clear(),us(),c.quote&&Lo(void 0),yc(),hu.release(),fo(),Ql("Message queued. It sends when the response finishes.")}function NM(){let i=Se.getState().pendingSubmission;i&&(li(void 0),Jc(i.text,{consumeDraft:!1,pending:i}))}function FM(i){if(o.messageActions?.showEdit!==!0)return;let c=k.getMessages().find(g=>g.id===i);!c||!am(c)||Cs!==i&&(ws(),Cs=i,Wr=QC({messageId:i,initialText:c.content,onSave:g=>$M(i,g),onCancel:()=>ws()}),Ft.delete(i),Zn(Pe,k.getMessages(),yt),Wr.focus())}function $M(i,c){let g=Wr;if(Cs=null,Wr=null,g?.destroy(),Ft.delete(i),!k.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){Zn(Pe,k.getMessages(),yt);return}Pn()}function UM(i){if(k.isStreaming())return;let c=im(k.getMessages(),i);c&&(ws(),k.resubmitFrom(c,{reason:"retry"})&&Pn())}tc={regenerate:UM,edit:FM,quote:i=>{let g=k.getMessages().find(f=>f.id===i)?.content?.trim();g&&(Lo({text:g,messageId:i}),ue?.focus())}};let Xa=async i=>{if(!pr){pr=!0;try{await ob({resolveInlineCommand:!0,...i})}finally{pr=!1}}};function Xc(i){ks()||(Qc(),Jc(i,{consumeDraft:!1}))}let Jc=(i,c)=>{if(pr)return;pr=!0;let g=()=>{pr=!1};try{let f=ob({...c,overrideText:i});f instanceof Promise?f.finally(g):g()}catch(f){throw g(),f}},jM=i=>{if(i.preventDefault(),k.isStreaming()){k.cancel(),On?.reset(),J?.update();return}pr||Xa()},qM=()=>o.features?.composerHistory!==!1,Sg={...Nm},Ag=!1,Ja=()=>{Sg={...Nm}},zM=()=>k.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),VM=i=>{if(!ue)return;Ag=!0,ue.value=i,ue.dispatchEvent(new Event("input",{bubbles:!0})),Ag=!1;let c=ue.value.length;ue.setSelectionRange(c,c)},KM=i=>{Ag||(i.isComposing||Dt?.handleInput(i.inputType??void 0),Ja())},GM=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:vl(ue)}),YM=i=>{if(ue&&!Nr()&&!(!i.isComposing&&Dt?.handleKeydown(i))){if(qM()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let c=ue.selectionStart===0&&ue.selectionEnd===0,g=Aw({direction:i.key==="ArrowUp"?"up":"down",history:zM(),currentValue:ue.value,atStart:c,state:Sg});if(Sg=g.state,g.handled){i.preventDefault(),g.value!==void 0&&VM(g.value);return}}if(PC(i,GM())){if(k.isStreaming()){if(i.preventDefault(),pu()==="block"||pr||ks())return;Ja(),Xa();return}if(pr){i.preventDefault();return}if(ks()){i.preventDefault();return}Ja(),i.preventDefault(),Ee.click()}}},sb=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(fe)){if(_s){_s.abort(),_s=null,i.preventDefault(),i.stopImmediatePropagation();return}k.isStreaming()&&(k.cancel(),On?.reset(),J?.update(),Ja(),i.preventDefault(),i.stopImmediatePropagation())}},QM=async i=>{if(o.attachments?.enabled!==!0||!et||Nr())return;let c=W0(i.clipboardData);c.length!==0&&(i.preventDefault(),await et.handleFiles(c))},oo=null,_o=!1,Hi=null,At=null,Mg=()=>o.voiceRecognition?.completionBehavior==="review";function Ds(i){se?.setAttribute("data-state",i),i==="recording"?JM():Pg()}let ib="--persona-voice-level",Eg=.5,Wi=null,Tg=-1,Zc=0,ab=()=>{let i=[],c=Dn??se?.parentElement??null;return c&&i.push(c),He&&i.push(He),i},kg=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==Tg){Tg=c;for(let g of ab())g.style.setProperty(ib,String(c))}},XM=()=>{Tg=-1,Zc=0;for(let i of ab())i.style.removeProperty(ib)};function JM(){if(Wi!==null)return;if(typeof requestAnimationFrame!="function"){kg(p?k.getVoiceLevel()??Eg:Eg);return}let i=()=>{Wi=requestAnimationFrame(i);let c=p?k.getVoiceLevel():null;if(c===null){kg(Eg);return}Zc+=(c-Zc)*.3,kg(Zc)};Wi=requestAnimationFrame(i)}function Pg(){Wi!==null&&(cancelAnimationFrame(Wi),Wi=null),XM()}let lb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ed=(i="user")=>{if(_o||k.isStreaming())return;let c=lb();if(!c)return;oo=new c;let g=o.voiceRecognition??{},f=g.pauseDuration??2e3;oo.continuous=g.provider?.browser?.continuous??!0,oo.interimResults=!0,oo.lang=g.provider?.browser?.language??"en-US";let b=ue.value;oo.onresult=w=>{let W="",z="";for(let V=0;V<w.results.length;V++){let Z=w.results[V],ae=Z[0].transcript;Z.isFinal?W+=ae+" ":z=ae}let q=b+W+z;ue.value=q,Po(),Hi&&clearTimeout(Hi),(W||z)&&(Hi=window.setTimeout(()=>{if(ue.value.trim()&&oo&&_o){if(jr(),Mg())return;Xa({viaVoice:!0})}},f))},oo.onerror=w=>{w.error!=="no-speech"&&jr()},oo.onend=()=>{if(_o){let w=ue.value.trim();!Mg()&&w&&w!==b.trim()&&Xa({viaVoice:!0}),jr()}};try{if(oo.start(),_o=!0,Ke.active=!0,i!=="system"&&(Ke.manuallyDeactivated=!1),or(i),bo(),fo(),se){let w=o.voiceRecognition??{};At={backgroundColor:se.style.backgroundColor,color:se.style.color,borderColor:se.style.borderColor,iconName:w.iconName??"mic",iconSize:parseFloat(w.iconSize??"")||bn};let W=w.recordingBackgroundColor,z=w.recordingIconColor,q=w.recordingBorderColor;if(se.classList.add("persona-voice-recording"),Ds("recording"),se.style.backgroundColor=W??"var(--persona-voice-recording-bg, #ef4444)",se.style.color=z??"var(--persona-voice-recording-indicator, #ffffff)",z){let V=se.querySelector("svg");V&&V.setAttribute("stroke",z)}q&&(se.style.borderColor=q),se.setAttribute("aria-label","Stop voice recognition")}}catch{jr("system")}},jr=(i="user")=>{if(_o){if(_o=!1,Hi&&(clearTimeout(Hi),Hi=null),oo){try{oo.stop()}catch{}oo=null}if(Ke.active=!1,or(i),bo(),fo(),se){if(se.classList.remove("persona-voice-recording"),Ds("idle"),At){se.style.backgroundColor=At.backgroundColor,se.style.color=At.color,se.style.borderColor=At.borderColor;let c=se.querySelector("svg");c&&c.setAttribute("stroke",At.color||"currentColor"),At=null}se.setAttribute("aria-label","Start voice recognition")}}},Lg=()=>{if(!se||At)return;let i=o.voiceRecognition??{};At={backgroundColor:se.style.backgroundColor,color:se.style.color,borderColor:se.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||bn}},Ig=(i,c)=>{if(!se)return;let g=se.querySelector("svg");g&&g.remove();let f=At?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||bn),b=ge(i,f,c,1.5);b&&se.appendChild(b)},td=()=>{se&&se.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Oi=()=>{if(!se)return;Lg();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,g=i.recordingIconColor,f=i.recordingBorderColor;if(td(),se.classList.add("persona-voice-recording"),Ds("recording"),se.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",se.style.color=g??"var(--persona-voice-recording-indicator, #ffffff)",g){let b=se.querySelector("svg");b&&b.setAttribute("stroke",g)}f&&(se.style.borderColor=f),se.setAttribute("aria-label","Stop voice recognition")},ZM=()=>{if(!se)return;Lg();let i=o.voiceRecognition??{},c=k.getVoiceInterruptionMode(),g=i.processingIconName??"loader",f=i.processingIconColor??At?.color??"",b=i.processingBackgroundColor??At?.backgroundColor??"",w=i.processingBorderColor??At?.borderColor??"";td(),se.classList.add("persona-voice-processing"),Ds("processing"),se.style.backgroundColor=b,se.style.borderColor=w;let W=f||"currentColor";se.style.color=W,Ig(g,W),se.setAttribute("aria-label","Processing voice input"),c==="none"&&(se.style.cursor="default")},eE=()=>{if(!se)return;Lg();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??At?.color??"":At?.color??""),w=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":At?.backgroundColor??""),W=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":At?.borderColor??"");td(),se.classList.add("persona-voice-speaking"),Ds("speaking"),se.style.backgroundColor=w,se.style.borderColor=W;let z=b||"currentColor";se.style.color=z,Ig(f,z);let q=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";se.setAttribute("aria-label",q),c==="none"&&(se.style.cursor="default"),c==="barge-in"&&se.classList.add("persona-voice-recording")},ur=()=>{se&&(td(),Ds("idle"),At&&(se.style.backgroundColor=At.backgroundColor??"",se.style.color=At.color??"",se.style.borderColor=At.borderColor??"",Ig(At.iconName,At.color||"currentColor"),At=null),se.style.cursor="",se.setAttribute("aria-label","Start voice recognition"))},Rg=()=>{if(!Nr()){if(o.voiceRecognition?.provider?.type==="runtype"){let i=k.getVoiceStatus(),c=k.getVoiceInterruptionMode();if(c==="none"&&(i==="processing"||i==="speaking"))return;if(c==="cancel"&&(i==="processing"||i==="speaking")){k.stopVoicePlayback();return}if(k.isBargeInActive()){k.stopVoicePlayback(),k.deactivateBargeIn().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,bo(),or("user"),ur()});return}k.toggleVoice().then(()=>{Ke.active=k.isVoiceActive(),Ke.manuallyDeactivated=!k.isVoiceActive(),bo(),or("user"),k.isVoiceActive()?Oi():ur()});return}if(_o){let i=ue.value.trim();Ke.manuallyDeactivated=!0,bo(),jr("user"),i&&!Mg()&&Xa()}else Ke.manuallyDeactivated=!1,bo(),ed("user")}};uu=Rg,se&&ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(k.isVoiceActive()&&k.toggleVoice(),ur()):jr("system")});let tE=A.on("assistant:complete",()=>{Se.getState().pendingSubmission&&setTimeout(()=>{k.isStreaming()||NM()},0)});ve.push(tE);let nE=A.on("assistant:complete",()=>{Yh&&(Ke.active||Ke.manuallyDeactivated||Yh==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?k.toggleVoice().then(()=>{Ke.active=k.isVoiceActive(),or("auto"),k.isVoiceActive()&&Oi()}):ed("auto"))},600))});ve.push(nE);let oE=A.on("action:resubmit",()=>{setTimeout(()=>{k&&!k.isStreaming()&&k.continueConversation()},100)});ve.push(oE);let cb=()=>{mt(!be,"user")},Rt=null,fn=null;if(we&&!xe()){let{instance:i,element:c}=gf({config:o,plugins:a,onToggle:cb});Rt=i,i||(fn=c)}Rt?e.appendChild(Rt.element):fn&&e.appendChild(fn),Ba(),mi(),Mc(),Uu(),_a(k.isStreaming()),Iu()||(Nn()==="follow"?_r(!0):bc()),xA(),Ce&&(!we||xe()?setTimeout(()=>Ps(),0):be&&setTimeout(()=>Ps(),200));let Ns=null,db=()=>{Ns&&(Ns.disconnect(),Ns.observe(He),Ns.observe(fe))},Za=()=>{if(xe()){ps(),Ba();return}let i=Et(o),c=o.launcher?.sidebarMode??!1,g=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640,w=g.innerWidth<=b,W=f&&w&&we;try{if(W){gs(),Ea=cc();return}let z=!1;ht&&(ht=!1,gs(),z=!0);let q=cc();if(!z&&q!==Ea&&(gs(),z=!0),Ea=q,z&&sc(),!we&&!i){Me.style.height="",Me.style.width="";return}if(!c&&!i){let Z=o?.launcher?.width??o?.launcherWidth??Vn;Me.style.width=Z,Me.style.maxWidth=Z}lc(),Hh()}finally{if(ps(),Zl(),Ba(),be&&we){let q=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),V=o.launcher?.sidebarMode??!1,Z=o.launcher?.mobileFullscreen??!0,ae=Et(o)&&Z&&q,ye=V||Z&&q&&we||ae;if(ye&&!Wo){let Ze=e.getRootNode(),ut=Ze instanceof ShadowRoot?Ze.host:e.closest(".persona-host");ut&&!Ho&&(Ho=jm(ut,o.launcher?.zIndex??ln)),Wo=qm(e.ownerDocument)}else ye||(Ho?.(),Ho=null,Wo?.(),Wo=null)}}};Za();let nd=e.ownerDocument.defaultView??window;if(nd.addEventListener("resize",Za),ve.push(()=>nd.removeEventListener("resize",Za)),typeof ResizeObserver<"u"){Ns=new ResizeObserver(()=>{Zl()}),db(),ve.push(()=>{Ns?.disconnect(),Ns=null});let i=new ResizeObserver(()=>{$c()});i.observe(fe),ve.push(()=>i.disconnect())}nd.addEventListener("resize",$c),ve.push(()=>nd.removeEventListener("resize",$c)),Un=re.scrollTop;let pb=Vo(re),ub=()=>{let i=re.scrollTop,c=Vo(re),g=c<pb;if(pb=c,!Pr()){Un=i,Gt();return}let{action:f,nextLastScrollTop:b}=Rw({following:$n.isFollowing(),currentScrollTop:i,lastScrollTop:Un,nearBottom:Ys(re,tr),userScrollThreshold:bA,isAutoScrolling:Tn||pc||g,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Un=b,f==="resume"){vc()||kn();return}f==="pause"&&Ia()};if(re.addEventListener("scroll",ub,{passive:!0}),ve.push(()=>re.removeEventListener("scroll",ub)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{PA(),jg(Pe)});i.observe(Pe),i.observe(re),ve.push(()=>i.disconnect())}let gb=()=>{Pr()&&$n.isFollowing()&&vc()&&Ia()},mb=re.ownerDocument;mb.addEventListener("selectionchange",gb),ve.push(()=>{mb.removeEventListener("selectionchange",gb)});let rE=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),fb=i=>{rE.has(i.key)&&(Ms(),eh()&&Pr()&&$n.isFollowing()&&Ia())},hb=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Ms(),eh()&&Pr()&&$n.isFollowing()&&Ia())};re.addEventListener("keydown",fb),re.addEventListener("focusin",hb),ve.push(()=>{re.removeEventListener("keydown",fb),re.removeEventListener("focusin",hb)});let yb=i=>{if(i.deltaY!==0&&Ms(),!Pr())return;let c=Hw({following:$n.isFollowing(),deltaY:i.deltaY,nearBottom:Ys(re,tr),resumeWhenNearBottom:!0});c==="pause"?Ia():c==="resume"&&!vc()&&kn()};re.addEventListener("wheel",yb,{passive:!0}),re.addEventListener("touchmove",Ms,{passive:!0}),re.addEventListener("pointerdown",Ms,{passive:!0}),ve.push(()=>{re.removeEventListener("touchmove",Ms),re.removeEventListener("pointerdown",Ms)}),ve.push(()=>re.removeEventListener("wheel",yb)),Nt.addEventListener("click",()=>{vo(),re.scrollTop=re.scrollHeight,Un=re.scrollTop,kn(),_r(!0),Gt()}),ve.push(()=>Nt.remove()),ve.push(()=>{ey(),vo()});let bb=()=>{qe&&(ys&&(qe.removeEventListener("click",ys),ys=null),ke()?(qe.style.display="",ys=()=>{mt(!1,"user")},qe.addEventListener("click",ys)):qe.style.display="none")};bb(),(()=>{let{clearChatButton:i}=Fe;i&&i.addEventListener("click",()=>{if(Bo()){bg({focusComposer:!0}).catch(g=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",g)});return}k.clearMessages(),Ft.clear(),kn(),Xr(Fe.composerOverlay);try{localStorage.removeItem(fa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${fa}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==fa)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),Y?.clear&&fc(()=>Y.clear(),"[AgentWidget] Failed to clear storage adapter:"),Q={},Oe.syncFromMetadata(),et?.clearAttachments(),yc(),li(void 0),Lo(void 0),ws(),nt?.clear(),On?.reset(),J?.update()})})();let vb=[["keydown",YM],["input",KM],["input",Po],["input",us],["keyup",us],["paste",QM],["focus",iA]],Cb=i=>{if(i)for(let[c,g]of vb)rt?.addListener(i,c,g)},sE=i=>{if(i)for(let[c,g]of vb)rt?.removeListener(i,c,g)},wb=()=>{rt&&(rt.addListener(rt.form,"submit",jM),rt.addListener(rt.footer,"click",us),Cb(ue),se&&rt.addListener(se,"click",Rg))};wb();let xb=()=>{Dt?.onComposerSwap((i,c)=>{sE(c),ue=i,rt&&(rt.input=i),Cb(i),mu(),Ou(),Po()})};xb();let Hg=!1;function Sb(){if(!Hg){Hg=!0;try{let i=ue?.value??"",c=He.ownerDocument??document,g=ue?c.activeElement===ue:!1;Pg(),rt?.destroy(),rt=null,Dt?.destroy(),Dt=null;let f=null,b=()=>(f=xe()?hp({config:o}):Zs({config:o}),f.footer),w=dh(b)??b();Bn.replaceComposer(w),He=Bn.composer.footer;let W=f!==null&&w===f.footer;di=!W,Zf=W?f.setSendButtonMode:()=>{},ch(He),uh(He),gh(),mh(),fh(),xb(),hh(),fu(),yh(),wb();let z=hs.indexOf(er);er.destroy(),er=Wl(Tr),z>=0&&(hs[z]=er),ue&&(ue.value=i),Po(),us(),Mc(),mi(),_a(k.isStreaming()),Ke.active&&Ds("recording"),gs(),db(),ps(),fo(),Sc(),g&&ue?.focus()}finally{Hg=!1}}}let el=e.ownerDocument??document;el.addEventListener("keydown",sb,!0);let Ab=()=>{Tu()},Mb=()=>{el.visibilityState==="hidden"&&Tu()};typeof window<"u"&&(window.addEventListener("pagehide",Ab),el.addEventListener("visibilitychange",Mb),ve.push(()=>{window.removeEventListener("pagehide",Ab),el.removeEventListener("visibilitychange",Mb)}));let Eb="persona-attachment-drop-active",tl=0,Wg=()=>{tl=0,fe.classList.remove(Eb)},Bi=()=>o.attachments?.enabled===!0&&et!==null&&!Nr(),Tb=i=>{!Fp(i.dataTransfer)||!Bi()||(tl++,tl===1&&fe.classList.add(Eb))},kb=i=>{!Fp(i.dataTransfer)||!Bi()||(tl--,tl<=0&&Wg())},Pb=i=>{!Fp(i.dataTransfer)||!Bi()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Lb=i=>{if(!Fp(i.dataTransfer)||!Bi())return;i.preventDefault(),i.stopPropagation(),Wg();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&et.handleFiles(c)},qr=!0;fe.addEventListener("dragenter",Tb,qr),fe.addEventListener("dragleave",kb,qr),e.addEventListener("dragover",Pb,qr),e.addEventListener("drop",Lb,qr);let od=e.ownerDocument,Ib=i=>{Bi()&&i.preventDefault()},Rb=i=>{Bi()&&i.preventDefault()};od.addEventListener("dragover",Ib),od.addEventListener("drop",Rb),ve.push(()=>{rt?.destroy(),rt=null,Pg(),Io?.destroy(),Io=null,Jo?.destroy(),Jo=null,Ir?.destroy(),Ir=null,Rr?.destroy(),Rr=null,Lr=null,du=null,Tu(),La.destroy(),Ri&&clearTimeout(Ri),ws(),_s?.abort(),_s=null,et?.destroy(),et=null,Se.destroy(),el.removeEventListener("keydown",sb,!0),Dt?.destroy()}),ve.push(()=>{fe.removeEventListener("dragenter",Tb,qr),fe.removeEventListener("dragleave",kb,qr),e.removeEventListener("dragover",Pb,qr),e.removeEventListener("drop",Lb,qr),od.removeEventListener("dragover",Ib),od.removeEventListener("drop",Rb),Wg()}),ve.push(()=>{k.cancel()}),Rt?ve.push(()=>{Rt?.destroy()}):fn&&ve.push(()=>{fn?.remove()});let Ht={update(i){let c=o.toolCall,g=o.messageActions,f=o.layout?.messages,b=o.colorScheme,w=o.loadingIndicator,W=o.iterationDisplay,z=o.features?.showReasoning,q=o.features?.showToolCalls,V=o.features?.toolCallDisplay,Z=o.features?.reasoningDisplay,ae=o.features?.streamAnimation?.type,ye=o.features?.history?.enabled===!0,Ze=o.features?.history?.provider,ut=o.getIdentityProof,ft=o.clientToken,Zt=o.contextMentions;o=Rp({...o,features:s},i),s=o.features,o=Nl(o),r(),wu(),Gs(e,o),_l(e,o),Dl(e,o),_e(),yo(),o.colorScheme!==b&&Wh();let Ut=Fl.getForInstance(o.plugins);a.length=0,a.push(...Ut),Hy(),we=o.launcher?.enabled??!0,Qe=o.launcher?.autoExpand??!1,gn=o.features?.showReasoning??!0,Yn=o.features?.showToolCalls??!0,Eo=o.features?.scrollToBottom??{};let Wt=Nn();Qn=o.features?.scrollBehavior??{},Wt!==Nn()&&(vo(),kn()),Gh(),oh(),Gt();let dn=cn;if(cn=o.features?.showEventStreamToggle??!1,cn&&!dn){if(nt||(ie(),k.setSSEEventCallback((ee,Ge)=>{o.onSSEEvent?.(ee,Ge),oe(ee,Ge)})),!ot&&Te){let ee=o.features?.eventStream?.classNames,Ge="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"+(ee?.toggleButton?" "+ee.toggleButton:"");ot=M("button",Ge),ot.style.width="28px",ot.style.height="28px",ot.style.color=Cn.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let Xe=Bt(Ar.Activity,"18px","currentColor",1.5);Xe&&ot.appendChild(Xe);let it=Fe.clearChatButtonWrapper,Mt=Fe.closeButtonWrapper,an=it||Mt;an&&an.parentNode===Te?Te.insertBefore(ot,an):Te.appendChild(ot),ot.addEventListener("click",()=>{v?ci():gu()})}}else!cn&&dn&&(ci(),ot&&(ot.remove(),ot=null),nt?.clear(),Yo?.destroy(),nt=null,Yo=null,On?.reset(),On=null,go=null);if(o.launcher?.enabled===!1&&Rt&&(Rt.destroy(),Rt=null),o.launcher?.enabled===!1&&fn&&(fn.remove(),fn=null),o.launcher?.enabled!==!1&&!Rt&&!fn){let{instance:ee,element:Ge}=gf({config:o,plugins:a,onToggle:cb});Rt=ee,ee||(fn=Ge),e.appendChild(Ge)}Rt&&Rt.update(o),Qa(),cs&&o.launcher?.subtitle!==void 0&&(cs.textContent=o.launcher.subtitle);let tt=o.layout?.header;if(tt?.layout!==Ue&&Te){let ee=tt?sa(o,tt,{showClose:ke(),onClose:()=>mt(!1,"user")}):Cr({config:o,showClose:ke(),onClose:()=>mt(!1,"user")});Bn.replaceHeader(ee),Te=Bn.header.element,It=Bn.header.iconHolder,kr=Bn.header.headerTitle,cs=Bn.header.headerSubtitle,qe=Bn.header.closeButton,Ue=tt?.layout,Qa()}else if(tt){if(It&&(It.style.display=tt.showIcon===!1?"none":""),kr&&(kr.style.display=tt.showTitle===!1?"none":""),cs&&(cs.style.display=tt.showSubtitle===!1?"none":""),qe){let ee=ke()&&tt.showCloseButton!==!1;qe.style.display=ee?"":"none"}if(Fe.clearChatButtonWrapper){let ee=tt.showClearChat;if(ee!==void 0){Fe.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Ge}=Fe;Ge&&!Ge.classList.contains("persona-absolute")&&(ee?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}}let Do=o.layout?.showHeader!==!1;Te&&(Te.style.display=Do?"":"none");let gr=o.layout?.showFooter!==!1;He&&(He.style.display=gr?"":"none"),ps(),Gt(),we!==Ne?we?mt(Qe,"auto"):(be=!0,Ba()):Qe!==j&&mt(Qe,"auto"),j=Qe,Ne=we,Za(),bb();let Fs=JSON.stringify(o.toolCall)!==JSON.stringify(c),I=JSON.stringify(o.messageActions)!==JSON.stringify(g),Le=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),Be=o.loadingIndicator?.render!==w?.render||o.loadingIndicator?.renderIdle!==w?.renderIdle||o.loadingIndicator?.showBubble!==w?.showBubble,Ae=o.iterationDisplay!==W,Yt=(o.features?.showReasoning??!0)!==(z??!0)||(o.features?.showToolCalls??!0)!==(q??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(V)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(Z);(Fs||I||Le||Be||Ae||Yt)&&k&&(xs++,Zn(Pe,k.getMessages(),yt));let dt=o.features?.streamAnimation?.type;if(dt!==ae&&dt&&dt!=="none"){let ee=Su(dt,o.features?.streamAnimation?.plugins);ee&&Il(ee,e)}let Re=o.launcher??{},Co=Re.headerIconHidden??!1,Pt=o.layout?.header?.showIcon,sn=Co||Pt===!1,Qt=Re.headerIconName,Ot=Re.headerIconSize??"48px";if(It){let ee=Te,Ge=ee?.querySelector(".persona-flex-col");if(sn)It.style.display="none",ee&&Ge&&!ee.contains(Ge)&&ee.insertBefore(Ge,ee.firstChild);else{if(It.style.display="",It.style.height=Ot,It.style.width=Ot,ee&&Ge&&(ee.contains(It)?It.nextSibling!==Ge&&(It.remove(),ee.insertBefore(It,Ge)):ee.insertBefore(It,Ge)),Qt){let it=parseFloat(Ot)||24,Mt=ge(Qt,it*.6,"currentColor",1);Mt?It.replaceChildren(Mt):It.textContent=Re.agentIconText??"\u{1F4AC}"}else if(Re.iconUrl){let it=It.querySelector("img");if(it)it.src=Re.iconUrl,it.style.height=Ot,it.style.width=Ot;else{let Mt=document.createElement("img");Mt.src=Re.iconUrl,Mt.alt="",Mt.className="persona-rounded-xl persona-object-cover",Mt.style.height=Ot,Mt.style.width=Ot,It.replaceChildren(Mt)}}else{let it=It.querySelector("svg"),Mt=It.querySelector("img");(it||Mt)&&It.replaceChildren(),It.textContent=Re.agentIconText??"\u{1F4AC}"}let Xe=It.querySelector("img");Xe&&(Xe.style.height=Ot,Xe.style.width=Ot)}}let De=o.layout?.header?.showTitle,zn=o.layout?.header?.showSubtitle;if(kr&&(kr.style.display=De===!1?"none":""),cs&&(cs.style.display=zn===!1?"none":""),qe){let ee=ke()&&o.layout?.header?.showCloseButton!==!1;if(qe.style.display=ee?"":"none",!xe()){let tn=Re.closeButtonSize??"";qe.style.height=tn,qe.style.width=tn,qe.style.minWidth=tn,qe.style.minHeight=tn}let Ge=Re.closeButtonPlacement??"inline",{closeButtonWrapper:Xe}=Fe,it=Ge==="top-right",Mt=Xe?.classList.contains("persona-absolute");if(Xe&&it!==Mt)if(Xe.remove(),it){Xe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let tn=Ua??fe;tn.style.position="relative",tn.appendChild(Xe)}else{let tn=Re.clearChat?.placement??"inline",nn=Re.clearChat?.enabled??!0;Xe.className=nn&&tn==="inline"?"":"persona-ml-auto",Te&&Te.appendChild(Xe)}if(qe.style.color=Re.closeButtonColor||Cn.actionIconColor,Re.closeButtonBackgroundColor?(qe.style.backgroundColor=Re.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),Re.closeButtonBorderWidth||Re.closeButtonBorderColor){let tn=Re.closeButtonBorderWidth||"0px",nn=Re.closeButtonBorderColor||"transparent";qe.style.border=`${tn} solid ${nn}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");Re.closeButtonBorderRadius?(qe.style.borderRadius=Re.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),Re.closeButtonPaddingX?(qe.style.paddingLeft=Re.closeButtonPaddingX,qe.style.paddingRight=Re.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),Re.closeButtonPaddingY?(qe.style.paddingTop=Re.closeButtonPaddingY,qe.style.paddingBottom=Re.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom=""),up(qe,Re.closeButtonIconName??"x",{iconSize:xe()?cf:void 0,iconText:Re.closeButtonIconText??"\xD7"});let an=Re.closeButtonTooltipText??"Close chat",wo=Re.closeButtonShowTooltip??!0;qe.setAttribute("aria-label",an),Xe&&on({anchor:qe,trigger:Xe,text:()=>qe?.getAttribute("aria-label")??an,enabled:wo})}let{clearChatButton:ze,clearChatButtonWrapper:$e}=Fe;if(ze){let ee=Re.clearChat??{},Ge=ee.enabled??!0,Xe=o.layout?.header?.showClearChat,it=Xe!==void 0?Xe:Ge,Mt=ee.placement??"inline";if($e){$e.style.display=it?"":"none";let{closeButtonWrapper:an}=Fe;!xe()&&an&&!an.classList.contains("persona-absolute")&&(it?an.classList.remove("persona-ml-auto"):an.classList.add("persona-ml-auto"));let wo=Mt==="top-right",tn=$e.classList.contains("persona-absolute");if(!xe()&&wo!==tn&&it){if($e.remove(),wo){$e.className="persona-absolute persona-top-4 persona-z-50",$e.style.right="48px";let Fo=Ua??fe;Fo.style.position="relative",Fo.appendChild($e)}else{$e.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",$e.style.right="";let Fo=Fe.closeButtonWrapper;Te&&Fo&&Fo.parentElement===Te?Te.insertBefore($e,Fo):Te&&Te.appendChild($e)}let nn=Fe.closeButtonWrapper;nn&&!nn.classList.contains("persona-absolute")&&(wo?nn.classList.add("persona-ml-auto"):nn.classList.remove("persona-ml-auto"))}}if(it){if(!xe()){let nn=ee.size??"";ze.style.height=nn,ze.style.width=nn,ze.style.minWidth=nn,ze.style.minHeight=nn}let an=ee.iconColor??"";if(ze.style.color=an||Cn.actionIconColor,up(ze,ee.iconName??"refresh-cw",{iconSize:xe()?df:void 0}),ee.backgroundColor?(ze.style.backgroundColor=ee.backgroundColor,ze.classList.remove("hover:persona-bg-gray-100")):(ze.style.backgroundColor="",ze.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let nn=ee.borderWidth||"0px",Fo=ee.borderColor||"transparent";ze.style.border=`${nn} solid ${Fo}`,ze.classList.remove("persona-border-none")}else ze.style.border="",ze.classList.add("persona-border-none");ee.borderRadius?(ze.style.borderRadius=ee.borderRadius,ze.classList.remove("persona-rounded-full")):(ze.style.borderRadius="",ze.classList.add("persona-rounded-full")),ee.paddingX?(ze.style.paddingLeft=ee.paddingX,ze.style.paddingRight=ee.paddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),ee.paddingY?(ze.style.paddingTop=ee.paddingY,ze.style.paddingBottom=ee.paddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let wo=ee.tooltipText??"Clear chat",tn=ee.showTooltip??!0;ze.setAttribute("aria-label",wo),$e&&on({anchor:ze,trigger:$e,text:()=>ze?.getAttribute("aria-label")??wo,enabled:tn})}}let bt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[$l],st=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[oi.message,oi.messageAndClick];Oe=Ul({parsers:bt,handlers:st,getSessionMetadata:me,updateSessionMetadata:de,emit:A.emit,documentRef:typeof document<"u"?document:null}),yt=Xx(o,Oe,Xt),KA(),k.updateConfig(o),(o.features?.history?.enabled===!0!==ye||o.features?.history?.provider!==Ze||o.getIdentityProof!==ut||o.clientToken!==ft)&&(Ln({restoreFocus:!1}),My()),Ur(),$c(),Zn(Pe,k.getMessages(),yt),mi(),Mc(),zA(),_a(k.isStreaming()),Zt!==o.contextMentions&&Sb();let gt=o.voiceRecognition?.enabled===!0,vt=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),mr=o.voiceRecognition?.provider?.type==="runtype";if(gt&&(vt||mr))if(!se||!Dn){let ee=ta(o);if(ee){se=ee.button,Dn=ee.wrapper;let Ge=ko&&ko.parentElement===Gl?ko:null;Gl?Gl.insertBefore(Dn,Ge):mo?.appendChild(Dn),rt&&(rt.micButton=se),rt?.addListener(se,"click",Rg),se.disabled=k.isStreaming()}}else{let ee=o.voiceRecognition??{},Ge=o.sendButton??{},Xe=ee.iconName??"mic",it=ee.iconSize,Mt=parseFloat(it??"")||bn;se.classList.add(Kn),se.classList.toggle(xo,!it),se.style.width=it??"",se.style.height=it??"",se.style.minWidth=it??"",se.style.minHeight=it??"";let an=ee.iconColor??Ge.textColor;se.innerHTML="";let wo=ge(Xe,Mt,an||"currentColor",1.5);wo?se.appendChild(wo):se.textContent="\u{1F3A4}";let tn=ee.backgroundColor??Ge.backgroundColor;tn?se.style.backgroundColor=tn:se.style.backgroundColor="",an?se.style.color=an:se.style.color="var(--persona-text, #111827)",ee.borderWidth?(se.style.borderWidth=ee.borderWidth,se.style.borderStyle="solid"):(se.style.borderWidth="",se.style.borderStyle=""),ee.borderColor?se.style.borderColor=ee.borderColor:se.style.borderColor="",ee.paddingX?(se.style.paddingLeft=ee.paddingX,se.style.paddingRight=ee.paddingX):(se.style.paddingLeft="",se.style.paddingRight=""),ee.paddingY?(se.style.paddingTop=ee.paddingY,se.style.paddingBottom=ee.paddingY):(se.style.paddingTop="",se.style.paddingBottom="");let nn=ee.tooltipText??"Start voice recognition",Fo=ee.showTooltip??!1;se.setAttribute("aria-label",nn),Dn&&on({anchor:se,trigger:Dn,text:()=>se?.getAttribute("aria-label")??nn,enabled:Fo}),Dn.style.display="",se.disabled=k.isStreaming()}else se&&Dn&&(Dn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?k.isVoiceActive()&&k.toggleVoice():_o&&jr());if(o.attachments?.enabled===!0){if(!Mn||!kt){let ee=o.attachments??{};En||(En=M("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),En.style.display="none",(ue.parentElement??mo).insertBefore(En,ue)),xt||(xt=document.createElement("input"),xt.type="file",xt.accept=(ee.allowedTypes??vr).join(","),xt.multiple=(ee.maxFiles??4)>1,xt.style.display="none",xt.setAttribute("aria-label","Attach files"),(ue.parentElement??mo).insertBefore(xt,ue)),Mn=M("div","persona-send-button-wrapper"),kt=M("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Kn} ${xo}`),kt.type="button",kt.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let Ge=ee.buttonIconName??"paperclip";kt.style.fontSize="18px",kt.style.lineHeight="1";let Xe=ge(Ge,bn,"currentColor",1.5);Xe?kt.appendChild(Xe):kt.textContent="\u{1F4CE}",kt.addEventListener("click",Mt=>{Mt.preventDefault(),xt?.click()}),Mn.appendChild(kt);let it=ee.buttonTooltipText??"Attach file";on({anchor:kt,trigger:Mn,text:()=>kt?.getAttribute("aria-label")??it}),ru?ru.append(Mn):mo.appendChild(Mn),rt&&(rt.attachmentButton=kt,rt.attachmentInput=xt??void 0,rt.attachmentPreviews=En??void 0),!et&&xt&&En&&(et=Ks.fromConfig(ee,rh),et.setPreviewsContainer(En),rt?.addListener(xt,"change",async()=>{et&&xt?.files&&(await et.handleFileSelect(xt.files),xt.value="")}))}else{Mn.style.display="";let ee=o.attachments??{};xt&&(xt.accept=(ee.allowedTypes??vr).join(","),xt.multiple=(ee.maxFiles??4)>1),et&&et.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles,adapter:ee.adapter})}if(fe.querySelector(".persona-attachment-drop-overlay")?.remove(),fe.appendChild(Jx(o.attachments?.dropOverlay)),kt){let ee=o.attachments??{},Ge=ee.buttonTooltipText??"Attach file";kt.setAttribute("aria-label",Ge),kt.textContent="";let Xe=ge(ee.buttonIconName??"paperclip",bn,"currentColor",1.5);Xe?kt.appendChild(Xe):kt.textContent="\u{1F4CE}",Mn&&on({anchor:kt,trigger:Mn,text:()=>kt?.getAttribute("aria-label")??Ge})}}else Mn&&(Mn.style.display="none"),et&&et.clearAttachments(),fe.querySelector(".persona-attachment-drop-overlay")?.remove();let Ct=o.sendButton??{},Og=Ct.useIcon??!1,$s=Ct.iconText??"\u2191",rd=Ct.iconName,Hb=Ct.tooltipText??"Send message",lE=Ct.showTooltip??!1,nl=Ct.size,cE=parseFloat(nl??"")||wm,sd=Ct.backgroundColor,ol=Ct.textColor;if(Og){if(Ee.style.width=nl??"",Ee.style.height=nl??"",Ee.style.minWidth=nl??"",Ee.style.minHeight=nl??"",Ee.style.fontSize="18px",Ee.style.lineHeight="1",ol?Ee.style.color=ol:Ee.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!k.isStreaming())if(Ee.innerHTML="",rd){let ee=parseFloat(Ct.iconSize??"")||Math.round(cE*.5),Ge=ol?.trim()||"currentColor",Xe=Ct.iconStrokeWidth??2,it=ge(rd,ee,Ge,Xe),Mt=ge(Ct.stopIconName??"square",ee,Ge,Xe);it&&Mt?Ee.appendChild(xm(it,Mt)):it?Ee.appendChild(it):Ee.textContent=$s}else Ee.textContent=$s;Ee.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Kn}`,sd?(Ee.style.backgroundColor=sd,Ee.classList.remove("persona-bg-persona-primary")):(Ee.style.backgroundColor="",Ee.classList.add("persona-bg-persona-primary"))}else Ee.textContent=o.copy?.sendButtonLabel??"Send",Ee.style.width="",Ee.style.height="",Ee.style.minWidth="",Ee.style.minHeight="",Ee.style.fontSize="",Ee.style.lineHeight="",Ee.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",sd?(Ee.style.backgroundColor=sd,Ee.classList.remove("persona-bg-persona-accent")):Ee.classList.add("persona-bg-persona-accent"),ol?Ee.style.color=ol:Ee.classList.add("persona-text-white");Ct.borderWidth?(Ee.style.borderWidth=Ct.borderWidth,Ee.style.borderStyle="solid"):(Ee.style.borderWidth="",Ee.style.borderStyle=""),Ct.borderColor?Ee.style.borderColor=Ct.borderColor:Ee.style.borderColor="",Ct.paddingX?(Ee.style.paddingLeft=Ct.paddingX,Ee.style.paddingRight=Ct.paddingX):(Ee.style.paddingLeft="",Ee.style.paddingRight=""),Ct.paddingY?(Ee.style.paddingTop=Ct.paddingY,Ee.style.paddingBottom=Ct.paddingY):(Ee.style.paddingTop="",Ee.style.paddingBottom=""),k.isStreaming()||Ee.setAttribute("aria-label",Hb),Sc(),ko&&on({anchor:Ee,trigger:ko,text:()=>Ee.getAttribute("aria-label")??Hb,enabled:lE}),vh();let Wb=Jd(Se.getState().activeModeIds,o.composer?.modes);Se.setActiveModeIds(Wb),ii().length>0!==!!Jo&&fu(),Jo?.render(Wb,ii());for(let ee of[...ai.keys()])Xd(ee,o.composer?.modeGroups)||ai.delete(ee);ai.forEach(ee=>ee.repaint()),Lr?.repaint(),Io?.resolve();let id=os(o,xe());if(xu(),id){Pe.style.maxWidth=id,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%",_n.style.maxWidth=id,_n.style.marginLeft="auto",_n.style.marginRight="auto",_n.style.width="100%";for(let ee of[mo,Tr,En,lt])ee&&(ee.style.maxWidth=id,ee.style.marginLeft="auto",ee.style.marginRight="auto",ee.style.width="100%")}else{Pe.style.maxWidth="",Pe.style.marginLeft="",Pe.style.marginRight="",Pe.style.width="",_n.style.maxWidth="",_n.style.marginLeft="",_n.style.marginRight="",_n.style.width="";for(let ee of[mo,Tr,En,lt])ee&&(ee.style.maxWidth="",ee.style.marginLeft="",ee.style.marginRight="",ee.style.width="")}let zr=o.statusIndicator??{},dE=zr.visible??!0;if(lt.style.display=dE?"":"none",k){let ee=k.getStatus();Kl(lt,(Xe=>Xe==="idle"?zr.idleText??jt.idle:Xe==="connecting"?zr.connectingText??jt.connecting:Xe==="connected"?zr.connectedText??jt.connected:Xe==="error"?zr.errorText??jt.error:jt[Xe])(ee),zr,ee)}lt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let pE=zr.align==="left"?"persona-text-left":zr.align==="center"?"persona-text-center":"persona-text-right";lt.classList.add(pE),mu(),Ou(),fo(),qt()},open(){ke()&&mt(!0,"api")},close(){ke()&&mt(!1,"api")},toggle(){ke()&&mt(!be,"api")},reconnect(){k.reconnectNow()},clearChat(){Zo=!1,k.clearMessages(),Ft.clear(),kn();try{localStorage.removeItem(fa),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${fa}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==fa)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),Y?.clear&&fc(()=>Y.clear(),"[AgentWidget] Failed to clear storage adapter:"),Q={},Oe.syncFromMetadata(),et?.clearAttachments(),yc(),li(void 0),Lo(void 0),ws(),nt?.clear(),On?.reset(),J?.update()},setMessage(i){return!ue||k.isStreaming()||Nr()?!1:(!be&&ke()&&mt(!0,"system"),ue.value=i,ue.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(k.isStreaming()||ks())return!1;let c=i?.trim()||ue.value.trim();return c?(!be&&ke()&&mt(!0,"system"),ue.value="",ue.style.height="auto",Po(),Jc(c,{consumeDraft:!1}),!0):!1},getComposerState(){return Se.getState()},setQuote(i){let c=i?.text?.trim();c&&Lo({...i,text:c})},clearQuote(){Lo(void 0)},startVoiceRecognition(){return k.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(k.isVoiceActive()||(!be&&ke()&&mt(!0,"system"),Ke.manuallyDeactivated=!1,bo(),k.toggleVoice().then(()=>{Ke.active=k.isVoiceActive(),or("user"),k.isVoiceActive()&&Oi()})),!0):_o?!0:lb()?(!be&&ke()&&mt(!0,"system"),Ke.manuallyDeactivated=!1,bo(),ed("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?k.isVoiceActive()?(k.toggleVoice().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,bo(),or("user"),ur()}),!0):!1:_o?(Ke.manuallyDeactivated=!0,bo(),jr("user"),!0):!1},injectMessage(i){return!be&&ke()&&mt(!0,"system"),k.injectMessage(i)},injectAssistantMessage(i){!be&&ke()&&mt(!0,"system");let c=k.injectAssistantMessage(i);return Ie&&(Ie=!1,Tt&&(clearTimeout(Tt),Tt=null),setTimeout(()=>{k&&!k.isStreaming()&&k.continueConversation()},100)),c},injectUserMessage(i){return!be&&ke()&&mt(!0,"system"),k.injectUserMessage(i)},injectSystemMessage(i){return!be&&ke()&&mt(!0,"system"),k.injectSystemMessage(i)},injectMessageBatch(i){return!be&&ke()&&mt(!0,"system"),k.injectMessageBatch(i)},injectComponentDirective(i){return!be&&ke()&&mt(!0,"system"),k.injectComponentDirective(i)},injectTestMessage(i){!be&&ke()&&mt(!0,"system"),k.injectTestEvent(i)},async connectStream(i,c){return k.connectStream(i,c)},__pushEventStreamEvent(i){cn&&(ie(),oe(i.type,i.payload))},showEventStream(){cn&&gu()},hideEventStream(){v&&ci()},isEventStreamVisible(){return v},listConversations(i){return k.listConversations(i)},getActiveConversationId(){return k.getActiveConversationId()},openConversation(i,c){return yg(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return bg({focusComposer:i?.focus===!0})},deleteConversation(i){return Xy(i)},renameConversation(i,c){return vg(i,{title:c})},setConversationStarred(i,c){return vg(i,{starred:c})},clearConversationHistory(i){return Jy(i)},resetHistoryIdentity(){return Zy()},getHistoryIdentityStatus(){return jn?jn.getIdentityStatus():eg()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return Ya({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){Ln(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return le},showArtifacts(){xn(o)&&(Zo=!1,pi=!0,yo(),Ve?.setMobileOpen(!0))},hideArtifacts(){xn(o)&&(Zo=!0,yo())},upsertArtifact(i){return xn(o)?(Uo(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Zo=!1,pi=!0),k.upsertArtifact(i)):null},selectArtifact(i){xn(o)&&k.selectArtifact(i)},clearArtifacts(){xn(o)&&k.clearArtifacts()},getArtifacts(){return k?.getArtifacts()??[]},getSelectedArtifactId(){return k?.getSelectedArtifactId()??null},focusInput(){return we&&!be&&!xe()||!ue?!1:(ue.focus(),!0)},async resolveApproval(i,c,g){let b=k.getMessages().find(w=>w.variant==="approval"&&w.approval?.id===i);if(!b?.approval)throw new Error(`Approval not found: ${i}`);if(b.approval.toolType==="webmcp"){k.resolveWebMcpApproval(b.id,c);return}return k.resolveApproval(b.approval,c,g)},setFollowUpSuggestions(i){hA(i)},clearFollowUpSuggestions(){Kh()},getMessages(){return k.getMessages()},getStatus(){return k.getStatus()},getPersistentMetadata(){return{...Q}},updatePersistentMetadata(i){de(i)},on(i,c){return A.on(i,c)},off(i,c){A.off(i,c)},isOpen(){return ke()&&be},isVoiceActive(){return Ke.active},toggleReadAloud(i){k.toggleReadAloud(i)},stopReadAloud(){k.stopSpeaking()},getReadAloudState(i){return k.getReadAloudState(i)},onReadAloudChange(i){return k.onReadAloudChange(i)},getState(){return{open:ke()&&be,launcherEnabled:we,voiceActive:Ke.active,streaming:k.isStreaming()}},showCSATFeedback(i){!be&&ke()&&mt(!0,"system");let c=Pe.querySelector(".persona-feedback-container");c&&c.remove();let g=Dp({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){!be&&ke()&&mt(!0,"system");let c=Pe.querySelector(".persona-feedback-container");c&&c.remove();let g=Np({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(){Ku(),Is!=null&&(clearInterval(Is),Is=null),ve.forEach(i=>i()),Ye.remove(),Jt?.remove(),Rt?.destroy(),fn?.remove(),ys&&qe.removeEventListener("click",ys)}};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,ve.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),c=V=>{let Z=V.detail;(!Z?.instanceId||Z.instanceId===i)&&Ht.focusInput()};if(window.addEventListener("persona:focusInput",c),ve.push(()=>{window.removeEventListener("persona:focusInput",c)}),cn){let V=ae=>{let ye=ae.detail;(!ye?.instanceId||ye.instanceId===i)&&Ht.showEventStream()},Z=ae=>{let ye=ae.detail;(!ye?.instanceId||ye.instanceId===i)&&Ht.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",Z),ve.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",Z)})}let g=V=>{let Z=V.detail;(!Z?.instanceId||Z.instanceId===i)&&Ht.showHistory()},f=V=>{let Z=V.detail;(!Z?.instanceId||Z.instanceId===i)&&Ht.hideHistory()};window.addEventListener("persona:showHistory",g),window.addEventListener("persona:hideHistory",f),ve.push(()=>{window.removeEventListener("persona:showHistory",g),window.removeEventListener("persona:hideHistory",f)});let b=V=>{let Z=V.detail;(!Z?.instanceId||Z.instanceId===i)&&Ht.showArtifacts()},w=V=>{let Z=V.detail;(!Z?.instanceId||Z.instanceId===i)&&Ht.hideArtifacts()},W=V=>{let Z=V.detail;Z?.instanceId&&Z.instanceId!==i||Z?.artifact&&Ht.upsertArtifact(Z.artifact)},z=V=>{let Z=V.detail;Z?.instanceId&&Z.instanceId!==i||typeof Z?.id=="string"&&Ht.selectArtifact(Z.id)},q=V=>{let Z=V.detail;(!Z?.instanceId||Z.instanceId===i)&&Ht.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",w),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",z),window.addEventListener("persona:clearArtifacts",q),ve.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",w),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",z),window.removeEventListener("persona:clearArtifacts",q)})}let ro=O0(o.persistState);if(ro&&ke()){let i=B0(ro.storage),c=`${ro.keyPrefix}widget-open`,g=`${ro.keyPrefix}widget-voice`,f=`${ro.keyPrefix}widget-voice-mode`;if(i){let b=ro.persist?.openState&&i.getItem(c)==="true",w=ro.persist?.voiceState&&i.getItem(g)==="true",W=ro.persist?.voiceState&&i.getItem(f)==="true";if(b&&(Rt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Ht.open(),setTimeout(()=>{if(w||W)Ht.startVoiceRecognition();else if(ro.persist?.focusInput){let z=e.querySelector("textarea");z&&z.focus()}},100)},0)),ro.persist?.openState&&(A.on("widget:opened",()=>{i.setItem(c,"true")}),A.on("widget:closed",()=>{i.setItem(c,"false")})),ro.persist?.voiceState&&(A.on("voice:state",z=>{i.setItem(g,z.active?"true":"false")}),A.on("user:message",z=>{i.setItem(f,z.viaVoice?"true":"false")})),ro.clearOnChatClear){let z=()=>{i.removeItem(c),i.removeItem(g),i.removeItem(f)},q=()=>z();window.addEventListener("persona:clear-chat",q),ve.push(()=>{window.removeEventListener("persona:clear-chat",q)})}}}if(te&&ke()&&(Rt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Ht.open()},0)),wi(),!yA){let i=Di(()=>{k&&(xs++,Ft.clear(),Zn(Pe,k.getMessages(),yt))});ve.push(i)}S=()=>{k&&(xs++,Ft.clear(),Zn(Pe,k.getMessages(),yt))},k.getMessages().length>0&&xc(),T=()=>{k&&(xs++,Ft.clear(),Zn(Pe,k.getMessages(),yt))};let iE=zb(()=>{k&&(xs++,Ft.clear(),Zn(Pe,k.getMessages(),yt))});ve.push(iE);let aE=wf(()=>{k&&(xs++,Ft.clear(),Zn(Pe,k.getMessages(),yt),wr()?.updateInlineArtifactBlocks(Pe,Jn.artifacts,{suppressTransition:!0}),yo())});return ve.push(aE),Ht};var Zx=(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},N0=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},F0=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},$0=(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.")},eS=(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"},Df=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=""},tS=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Df(e)},Of=e=>{e.style.transition=""},Bf=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=""},_f=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Up=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},U0=(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))},j0=(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)},q0=e=>{let t=ns(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:vn(t,r)??r;return{inset:o(n?.inset,Zd),canvasBackground:o(n?.canvasBackground,ep)}},nS=(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},z0=(e,t,n,o,r,s,a,l)=>{let d=Hn(s),p=d.reveal==="push",u=l!=null,m=l?.inset??"",y=l?.canvasBackground??"";U0(e,t,n,o,p),j0(e,t,n,o,d.side,p),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=d.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let h=e.ownerDocument.defaultView,C=s?.launcher?.mobileFullscreen??!0,S=s?.launcher?.mobileBreakpoint??640,x=h!=null?h.innerWidth<=S:!1;if(C&&x&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Bf(t),Of(o),tS(o),_f(n),Up(r,o),nS(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??ln),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"),tS(o),N0(o,d.maxHeight),nS(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",Bf(t),Of(o),_f(n),Up(r,o);let O=d.animate?"transform 180ms ease":"none",$=d.side==="right"?"translateX(100%)":"translateX(-100%)",T=a?"translateX(0)":$;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=O,o.style.transform=T,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Of(o),Df(o),Up(r,o);let O=Zx(d.width,e.clientWidth),$=Math.max(0,e.clientWidth),T=d.animate?"margin-left 180ms ease":"none",R=d.side==="right"?a?-O:0:a?0:-O;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${$+O}px`,t.style.transition=T,t.style.marginLeft=`${R}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${$}px`,n.style.maxWidth=`${$}px`,n.style.minWidth=`${$}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Bf(t),Df(o),_f(n),Up(r,o);let O=d.reveal==="emerge";O?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let $=a?d.width:"0px",T=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",R=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${$}`,o.style.width=$,o.style.maxWidth=$,o.style.minWidth=$,o.style.minHeight="0",F0(o,d.maxHeight),o.style.overflow=O||R?"hidden":"visible",o.style.transition=T,O){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let A=u?`calc(${Zx(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"}}},V0=(e,t)=>{let n=e.ownerDocument.createElement("div");return eS(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){eS(n,o)},destroy(){n.remove()}}},K0=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),p=n.createElement("aside"),u=n.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",p.appendChild(u),o.insertBefore(a,e),d.appendChild(e);let y=null,h=()=>{y?.disconnect(),y=null},C=null,S=()=>{C=t?.launcher?.detachedPanel===!0?q0(t):null};S();let x=()=>{z0(a,l,d,p,u,t,m,C)},P=null,O=()=>{P?.(),P=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(P=na(()=>{S(),x()}))},$=()=>{h(),Hn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{x()}),y.observe(a)))},T=!1,R=()=>{x(),$(),m&&!T&&a.dataset.personaDockMobileFullscreen!=="true"&&(T=!0,$0(a,Hn(t)))},A=a.ownerDocument.defaultView,N=()=>{R()};return A?.addEventListener("resize",N),Hn(t).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),R(),O(),{mode:"docked",host:u,shell:a,syncWidgetState(Y){let ce=Y.launcherEnabled?Y.open:!0;m!==ce&&(m=ce,R())},updateConfig(Y){t=Y,(t?.launcher?.enabled??!0)===!1&&(m=!0),S(),R(),O()},destroy(){A?.removeEventListener("resize",N),P?.(),P=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},ql=(e,t)=>Et(t)?K0(e,t):V0(e,t);var G0=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},oS=(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)},jp=[],rS=()=>[...jp],Nf=e=>{let t=G0(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=ql(t,r),a,l=[],d=(x,P)=>{let $=!(P?.launcher?.enabled??!0)||Et(P),T=o.createElement("div");if(T.setAttribute("data-persona-root","true"),$&&(T.style.height="100%",T.style.display="flex",T.style.flexDirection="column",T.style.flex="1",T.style.minHeight="0",T.style.minWidth="0"),n){let R=x.attachShadow({mode:"open"});R.appendChild(T),oS(R,o)}else x.appendChild(T),oS(x,o);return t.id&&T.setAttribute("data-persona-instance",t.id),T},p=()=>{s.syncWidgetState(a.getState())},u=()=>{l.forEach(x=>x()),l=[a.on("widget:opened",p),a.on("widget:closed",p)],p()},m=()=>{let x=d(s.host,r);a=$p(x,r,{debugTools:e.debugTools}),u()},y=()=>{l.forEach(x=>x()),l=[],a.destroy()};m(),e.onChatReady?.();let h=x=>{y(),s.destroy(),s=ql(t,x),r=x,m()},C={update(x){let P=Rp(r??{},x),O=Et(r),$=Et(P),T=ss(r),R=ss(P);if(O!==$||T!==R){h(P);return}r=P,s.updateConfig(r),a.update(x),p()},destroy(){y(),s.destroy();let x=jp.indexOf(S);x!==-1&&jp.splice(x,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},S=new Proxy(C,{get(x,P,O){if(P==="host")return s.host;if(P in x)return Reflect.get(x,P,O);let $=a[P];return typeof $=="function"?$.bind(a):$}});return jp.push(S),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=S),S};var cS=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Y0=new Set(["button","a","input","select","textarea","details","summary"]),Q0=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ff=/\b(product|card|item|listing|result)\b/i,Uf=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,X0=3e3,J0=100;function dS(e){let t=typeof e.className=="string"?e.className:"";if(Ff.test(t)||e.id&&Ff.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Ff.test(o.value))return!0}return!1}function pS(e){return Uf.test((e.textContent??"").trim())}function uS(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 Z0(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function sS(e){let t=e.match(Uf);return t?t[0]:null}function iS(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 eL(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 tL="commerce-card",nL="result-card";function aS(e){return!dS(e)||!pS(e)||!uS(e)&&!Z0(e)?0:5200}function lS(e){return!dS(e)||pS(e)||!uS(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var jf=[{id:tL,scoreElement(e){return aS(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||Uf.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(aS(e)===0)return null;let{title:n,href:o}=iS(e),r=sS((e.textContent??"").trim())??sS(t.text)??"",s=eL(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
|
|
136
|
+
${Ee?"background: transparent !important;":""}
|
|
137
|
+
`)}if(!f&&!i){let Fe="max-height: -moz-available !important; max-height: stretch !important;",Se=c?"":"padding-top: 1.25em !important;",un=c?"":`z-index: ${o.launcher?.zIndex??an} !important;`;Qe.style.cssText+=Fe+Se+un}lu(),Rt()},xu=()=>{e.style.setProperty("--persona-content-max-width",Jr(o,Ce()))},Wh=!1,Oh=()=>{let i=_m(o,Ce());Ce()&&o.composer?.placement&&o.debug===!0&&!Wh&&(Wh=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=xo(o);e.setAttribute("data-persona-composer-placement",i),e.setAttribute("data-persona-conversation-state",Yl),e.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",c.composerGap??tp),Xl()},Bh=()=>{if(Ce())return;let i=At(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!pe)return;let f=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,C=o.launcher?.mobileBreakpoint??640;if(b&&f.innerWidth<=C)return;let W=f.innerHeight,U=64,$=o.launcher?.heightOffset??0,j=Math.max(200,W-U),X=Math.min(640,j);Me.style.height=`${Math.max(200,X-$)}px`};wu(),$s(e,o),Wl(e,o),Ol(e,o),xu(),Oh(),as=()=>{wu(),Bh(),$s(e,o),Wl(e,o),Ol(e,o),xu(),Oh(),ec?e.style.setProperty("--persona-artifact-welded-outer-radius",ec):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Vo(),tu()};let he=[];he.push(()=>{Ph=!0}),he.push(()=>{d.forEach(i=>i()),l.destroy()}),he.push(()=>{document.removeEventListener("keydown",Ih)}),he.push(()=>{ha!==null&&clearTimeout(ha)});let Lo=null,Io=null;he.push(()=>{Lo?.(),Lo=null,Io?.(),Io=null}),va&&he.push(()=>{va?.disconnect(),va=null}),he.push(()=>{xa?.(),xa=null,Cu(),wt&&(wt.remove(),wt=null),Ve?.element.style.removeProperty("width"),Ve?.element.style.removeProperty("maxWidth"),Ve?.destroy()}),S&&he.push(()=>{ze=!0,Ye=null,Ot!==null&&(cancelAnimationFrame(Ot),Ot=null),bt?.destroy(),bt=null,Oe?.destroy(),Oe=null,ke=null});let cs=null,_h=()=>{cs&&(cs(),cs=null),o.colorScheme==="auto"&&(cs=Qi(()=>{$s(e,o)}))};_h(),he.push(()=>{cs&&(cs(),cs=null)}),he.push(()=>{v=!0,h?.()}),he.push(()=>{O=!0});let Dh=!1;he.push(()=>{Dh=!0});let Su=(i,c)=>{let g=Ml(i,c);return g||!$w.includes(i)?g:(zw().then(f=>{if(Dh)return;Al(f.wipe),Al(f.glyphCycle);let b=Ml(i,c);b&&Pl(b,e)}).catch(()=>{}),null)},lc=o.features?.streamAnimation;if(lc?.type&&lc.type!=="none"){let i=Su(lc.type,lc.plugins);i&&Pl(i,e),he.push(()=>qw(e))}let Qo=Il(xr),Nh=Il(ou),Fh=Il(ua),ds=[Qo,Nh,Fh];he.push(()=>{ds.forEach(i=>i.destroy())});let ps=null,P,us=null,$h=!1,Uh=0,jh=null,qh=i=>i.reduce((c,g)=>g.role==="user"?c+1:c,0),zh=i=>{for(let c=i.length-1;c>=0;c--)if(_s(i[c]))return i[c].id??null;return null},Vh=!1,vA=()=>{Vh||o.debug!==!0||(Vh=!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".'))},Kh=!1,Gh=!1,Yh=(i,c)=>{Kh||o.debug!==!0||!c.enabled||c.expose||$h||Gh&&(P.isStreaming()||i.some(_s)||(Kh=!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.")))},li=i=>{if(!P)return;let c=i??P.getMessages(),g=j=>{j.render([],P,ce,c)},f=j=>{ds.forEach(X=>{X!==j&&g(X)})};us&&(qh(c)>Uh||zh(c)!==jh)&&(us=null);let b=Gr(o);Yh(c,b);let C=b.enabled?hd(c):null,W=us??C,U=us?"host":"agent";if(W){let j=o.suggestions?.followUps,X=j?.placement??(j?"auto":"composer"),me=(X==="auto"?Ce()?"composer":"after-message":X)==="after-message"?Fh:Qo;f(me),me.render(W,P,ce,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:Yc});return}if(c.some(j=>j.role==="user")){ds.forEach(g);return}let $=o.suggestions?.starters;if($){let j=ts(xo(o),c),X=$.placement??"auto",se=X==="auto"?j?"welcome":"composer":X;if(se==="welcome"&&!j){vA(),ds.forEach(g);return}let me=se==="welcome"?Nh:Qo;f(me),me.render($.items??o.suggestionChips,P,ce,c,o.suggestionChipsConfig,{surface:"starter",variant:$.variant??"card",behavior:$.behavior??"send",overflow:$.overflow??"wrap",maxItems:$.maxItems??4,config:o,plugins:a,submitPrompt:Yc});return}f(Qo),Qo.render(o.suggestionChips,P,ce,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a,submitPrompt:Yc})},Qh=()=>{us&&(us=null,li())},CA=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){Qh();return}let g=P?P.getMessages():[];us=c,$h=!0,Uh=qh(g),jh=zh(g),li(g)},jn=!1,$t=kw(),ci=new Map,gs=new Map,Pr=new Map,ms=null,kr=null;function fs(){if(!ms)return;let i=ms;ms=null,kr?.destroy(),kr=null,$t.delete(i),ue.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),P&&Zn(Le,P.getMessages(),mt)}let hs=0,wA=Do()!==null,qn=Ww(),zn=0,Lr=null,Tn=!1,cc=!1,Ir=0,Kt=null,ys=null,Au=!1,di=!1,bs=null,Sa=!0,dc=!1,pi=null,pc=!1,vs=()=>{pc=!0,MA()},Mu=null,xA=4,Xo=24,SA=80,AA=1e3,Jo=null,Xh=()=>{e.setAttribute("data-persona-scrollbar",su()),su()!=="on-scroll"&&(Jo!==null&&clearTimeout(Jo),Jo=null,oe.removeAttribute("data-persona-scrollbar-visible"))},MA=()=>{su()==="on-scroll"&&(oe.setAttribute("data-persona-scrollbar-visible",""),Jo!==null&&clearTimeout(Jo),Jo=setTimeout(()=>{Jo=null,Us(oe,Xo)&&oe.removeAttribute("data-persona-scrollbar-visible")},AA))};Xh(),he.push(()=>{Jo!==null&&clearTimeout(Jo)});let Eu=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};wh=()=>Ke.active,po();let Jh=o.voiceRecognition?.autoResume??!1,Zo=i=>{A.emit("voice:state",{active:Ke.active,source:i,timestamp:Date.now()})},mo=()=>{ae(i=>({...i,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},EA=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Wf(ee.voiceState),c=!!i.active,g=Number(i.timestamp??0);Ke.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-g<O0&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,Wn(o.voiceRecognition?.provider)?P.toggleVoice().then(()=>{Ke.active=P.isVoiceActive(),Zo("restore"),P.isVoiceActive()&&ki()}):Jc("restore"))},1e3)},TA=()=>P?Zx(P.getMessages()).filter(i=>!i.__skipPersist):[],uc=null,Zh=(i,c)=>{typeof console<"u"&&console.error(i,c)},gc=(i,c)=>{let g=()=>{try{let W=i();return!W||typeof W.then!="function"?null:Promise.resolve(W).catch(U=>{Zh(c,U)})}catch(W){return Zh(c,W),null}},f=uc,b=f?f.then(()=>g()??void 0):g();if(!b)return;let C=b.finally(()=>{uc===C&&(uc=null)});uc=C};function ui(i){if(!G?.save)return;let c=i?Zx(i):P?TA():[],g=le&&P?.getResumableHandle();g&&(ee={...ee,durableResume:{executionId:g.executionId,after:g.lastEventId}});let f={messages:c,metadata:ee,artifacts:Jn.artifacts,selectedArtifactId:Jn.selectedId,...Cs?{draft:Cs}:{}};gc(()=>G.save(f),"[AgentWidget] Failed to persist state:")}let Cs,mc=()=>!G?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,Aa=nw({write:()=>{if(!mc())return;let i=xe.getState(),c=ew({text:i.text,mentionRefs:i.mentionRefs,contentSegments:xg(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(Cs)&&(Cs=c,ui())}});function ey(){mc()&&Aa.schedule()}function Tu(){Aa.flush()}function ty(i){if(!mc())return;let c=tw(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(g=>g.id),modelIds:(o.composer?.models??[]).map(g=>g.id),modes:o.composer?.modes??[]});c&&(Cs=i,ce&&!ce.value&&(ce.value=c.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),Eo()),c.selectedModelId&&(xe.setSelectedModelId(c.selectedModelId),Mr?.repaint()),Jl(c.activeModeIds??[]),c.quote&&To(c.quote),Aa.cancel())}function fc(){Aa.cancel(),Cs&&(Cs=void 0,mc()&&ui())}let gi=null,ny=()=>Qe.querySelector("#persona-scroll-container")||oe,mi=()=>{gi!==null&&(cancelAnimationFrame(gi),gi=null),Tn=!1},oy=()=>{Lr!==null&&(cancelAnimationFrame(Lr),Lr=null),cc=!1,mi()},PA=()=>jn&&ku()&&(Un()!=="anchor-top"||rh()),Pu=()=>{let i=ga()||"Jump to latest",c=PA();Ft.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Ir>0?(rs.textContent=String(Ir),rs.style.display="",Ft.setAttribute("aria-label",`${i} (${Ir} new)`)):(rs.textContent="",rs.style.display="none",Ft.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},ry=()=>{Ir!==0&&(Ir=0,Pu())},kA=()=>{let i=Kt?.spacerHeight??0;return i<=0?Us(oe,Xo):vc(i)-oe.scrollTop-oe.clientHeight<=Xo},ku=()=>Ar()?!qn.isFollowing():!kA(),Lu=()=>!!P&&P.getMessages().length>0,Gt=()=>{if(!oA()||YS()){Ft.parentNode&&Ft.remove(),Ft.style.display="none";return}Ft.parentNode!==ue&&ue.appendChild(Ft),ss();let c=jo(oe)>0&&ku()&&Lu();c?Pu():ry(),Ft.style.display=c?"":"none"},Ma=()=>{qn.pause()&&(oy(),Gt())},Pn=()=>{qn.resume(),ry(),Gt()},Rr=(i=!1)=>{Ar()&&Lu()&&qn.isFollowing()&&(!i&&!jn||(Lr!==null&&(cancelAnimationFrame(Lr),Lr=null),cc=!0,Lr=requestAnimationFrame(()=>{Lr=null,cc=!1,qn.isFollowing()&&LA(ny(),i?220:140)})))},sy=(i,c,g,f=()=>!0)=>{let b=i.scrollTop,C=c(),W=C-b;if(mi(),Math.abs(W)<1){Tn=!0,i.scrollTop=C,zn=i.scrollTop,Tn=!1;return}let U=performance.now();Tn=!0;let $=X=>1-Math.pow(1-X,3),j=X=>{if(!f()){mi();return}let se=c();se!==C&&(C=se,W=C-b);let me=X-U,Ze=Math.min(me/g,1),ut=$(Ze),ht=b+W*ut;i.scrollTop=ht,zn=i.scrollTop,Ze<1?gi=requestAnimationFrame(j):(i.scrollTop=C,zn=i.scrollTop,gi=null,Tn=!1)};gi=requestAnimationFrame(j)},LA=(i,c=500)=>{let g=jo(i)-i.scrollTop;if(Math.abs(g)<1){zn=i.scrollTop;return}if(Math.abs(g)>=SA){mi(),Tn=!0,i.scrollTop=jo(i),zn=i.scrollTop,Tn=!1;return}sy(i,()=>jo(i),c,()=>qn.isFollowing())},hc=()=>{if(!Lu()){Gt();return}let i=ny();Tn=!0,i.scrollTop=jo(i),zn=i.scrollTop,Tn=!1,Gt()},ws=i=>{let c=0,g=i;for(;g&&g!==oe;)c+=g.offsetTop,g=g.offsetParent;return c},IA=()=>{let i=oe.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??oe.ownerDocument.getSelection()},yc=()=>_w(IA(),oe),Iu=()=>{if(rA()!=="last-user-turn")return!1;let i=P?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(C=>C.role==="user");if(!c)return!1;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=oe.querySelector(`[data-message-id="${g}"]`);if(!f)return!1;let b=Math.min(Math.max(0,ws(f)-ma()),jo(oe));return Tn=!0,oe.scrollTop=b,zn=oe.scrollTop,Tn=!1,Un()==="follow"&&!Us(oe,Xo)&&qn.pause(),Gt(),!0},bc=i=>{let c=Math.max(0,Math.round(i));Xn.style.height=`${c}px`,Xn.style.display=c>0?"":"none",Kt&&(Kt.spacerHeight=Math.max(0,i))},vc=i=>{let c=parseFloat(getComputedStyle(oe).paddingBottom)||0,g=0;for(let b of Array.from(oe.children)){if(b===Xn||b.offsetHeight===0)continue;let C=ws(b)+b.offsetHeight;C>g&&(g=C)}let f=oe.scrollHeight-i;return g>0?Math.min(g+c,f):f},RA=()=>{if(!Kt||Kt.spacerHeight<=0)return;let i=vc(Kt.spacerHeight),c=Math.max(0,Math.round(oe.scrollTop)+oe.clientHeight-i+Xo);c<Kt.spacerHeight&&(bc(c),Gt())},fo=()=>{ys!==null&&(cancelAnimationFrame(ys),ys=null),mi(),Kt=null,Xn.style.height="0px",Xn.style.display="none"},iy=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Ru=i=>oe.querySelector(`[data-message-id="${iy(i)}"]`),ay=i=>{ys!==null&&cancelAnimationFrame(ys),ys=requestAnimationFrame(()=>{ys=null;let c=iy(i),g=oe.querySelector(`[data-message-id="${c}"]`);if(!g)return;let f=ws(g),b=Kt?.spacerHeight??0,C=vc(b),{targetScrollTop:W,spacerHeight:U}=Fm({anchorOffsetTop:f,topOffset:ma(),viewportHeight:oe.clientHeight,contentHeight:C,slack:Xo});Kt={initialSpacerHeight:U,contentHeightAtAnchor:C,spacerHeight:U},bc(U),sy(oe,()=>g.isConnected?Math.max(0,ws(g)-ma()):W,220)})},kn=()=>{if(Un()!=="anchor-top"||!Kt||!pi)return;let i=Ru(pi);if(!i)return;mi();let c=Kt.spacerHeight,g=vc(c),{targetScrollTop:f,spacerHeight:b}=Fm({anchorOffsetTop:ws(i),topOffset:ma(),viewportHeight:oe.clientHeight,contentHeight:g,slack:Xo});Kt={initialSpacerHeight:b,contentHeightAtAnchor:g,spacerHeight:b},bc(b),Tn=!0,oe.scrollTop=f,zn=oe.scrollTop,Tn=!1,Gt()},HA=()=>{if(Ar()){if(!qn.isFollowing()||Us(oe,1))return;Rr(!jn);return}if(Kt&&Kt.initialSpacerHeight>0){let i=oe.scrollHeight-Kt.spacerHeight,c=Dw({initialSpacerHeight:Kt.initialSpacerHeight,contentHeightAtAnchor:Kt.contentHeightAtAnchor,currentContentHeight:i});c!==Kt.spacerHeight&&bc(c)}Gt()},WA=i=>{let c=Un();c==="follow"?(Pn(),Rr(!0)):c==="anchor-top"&&(Sa=!1,dc=!0,pc=!1,pi=i,ay(i))},OA=()=>{if(Un()==="anchor-top"){if(dc){Sa=!1;return}Sa=!0,fo(),Pn(),Rr(!0)}},BA=96,_A=i=>{if(bs===null)return!0;let c=Ru(bs),g=Ru(i);if(!c||!g)return!0;let f=ws(g)-ws(c);return ma()+f>oe.clientHeight-BA},DA=i=>{if(Un()!=="anchor-top"||!dc||pc||yc())return;let c=bs===null;for(let g of i){if(!c){g.id===bs&&(c=!0);continue}if(Hw(g)){if(g.id===pi||!_A(g.id))return;pi=g.id,ay(g.id);return}}},NA=i=>{let c=new Map;i.forEach(g=>{let f=Eu.get(g.id);c.set(g.id,{streaming:g.streaming,role:g.role}),!f&&g.role==="assistant"&&(A.emit("assistant:message",g),!di&&(Un()!=="anchor-top"||rh())&&ku()&&(Ir+=1,Pu(),Gt(),Gl(Ir===1?"1 new message below.":`${Ir} 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}))}),Eu.clear(),c.forEach((g,f)=>{Eu.set(f,g)})},Ea=(i,c)=>{let g=c==="user"?"user":"assistant",f=o.layout?.messages?.[g],b=f?.width??"content",C=f?.maxWidth??(b==="full"?"100%":void 0);i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${c}`,`persona-message-width-${b}`),i.classList.toggle("persona-justify-end",c==="user"),i.setAttribute("data-message-role",c),i.setAttribute("data-message-width",b),C?i.style.setProperty("--persona-message-row-max-width",C):i.style.removeProperty("--persona-message-row-max-width")},er=(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},FA=(i,c,g)=>{let f=document.createElement("div"),C=(()=>{let L=a.find(je=>je.renderLoadingIndicator);if(L?.renderLoadingIndicator)return L.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),W=(L,je)=>je==null?!1:typeof je=="string"?(L.textContent=je,!0):(L.appendChild(je),!0),U=new Set,$=new Map,j=new Set,X=a.some(L=>L.renderAskUserQuestion),se=[],me=[],Ze=o.enableComponentStreaming!==!1,ut=o.approval!==!1,ht=[],Jt=o.messageActions,jt=Jt?.showRegenerate===!0&&Jt.enabled!==!1&&pt.current?.isStreaming()!==!0?lC(c):null,Lt=Jt?.showEdit===!0&&Jt.enabled!==!1,cn=Jt?.showQuote===!0&&Jt.enabled!==!1,nt=null,dn=o.features?.reasoningDisplay?.completedVisibility,Bo=L=>dn==="removed"?!0:dn==="removed-when-short"?Ov(L,o.features?.reasoningDisplay?.shortThinkThreshold):!1,cr=o.features?.toolCallDisplay?.completedVisibility==="removed",ho=L=>L.variant==="reasoning"&&L.reasoning?.status==="complete"?Bo(L.reasoning):cr&&L.variant==="tool"&&L.toolCall?.status==="complete";if(c.forEach(L=>{if(ho(L))return;if(U.add(L.id),$.set(L.id,L.role),ms===L.id&&kr){let Se=er(L.id,L.role);Se.setAttribute("data-persona-message-edit-stub","true"),Se.setAttribute("data-preserve-runtime","true"),f.appendChild(Se),nt={messageId:L.id,element:kr.element};return}let je=X&&ur(L),Ee=ut&&L.variant==="approval"&&!!L.approval,ie=!je&&L.role==="assistant"&&!L.variant&&Ze&&Fl(L);!Ee&&Pr.has(L.id)&&(i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),Pr.delete(L.id)),!ie&&gs.has(L.id)&&(i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),gs.delete(L.id));let It=ur(L)?`:${L.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${L.agentMetadata?.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",qt={canRegenerate:jt===L.id,canEdit:Lt&&am(L),canQuote:cn&&!L.variant&&(L.content?.trim().length??0)>0},rn=`${qt.canRegenerate?"r":""}${qt.canEdit?"e":""}${qt.canQuote?"q":""}`,zt=Pw(L,hs)+It+`:${rn}`,Yt=je||Ee||ie?null:Lw($t,L.id,zt);if(Yt){f.appendChild(Yt.cloneNode(!0)),ur(L)&&L.toolCall?.id&&L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(j.add(L.toolCall.id),Ni(L,o,Ne.composerOverlay));return}let Rt=null,pn=a.find(Se=>!!(L.variant==="reasoning"&&Se.renderReasoning||L.variant==="tool"&&Se.renderToolCall||!L.variant&&Se.renderMessage)),We=o.layout?.messages;if(ur(L)&&L.agentMetadata?.askUserQuestionAnswered===!0){ci.delete(L.id),i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime");return}if(_s(L)&&Gr(o).enabled)return;if(ur(L)&&o.features?.askUserQuestion?.enabled!==!1){let Se=a.find(un=>typeof un.renderAskUserQuestion=="function");if(Se&&pt.current){let un=ci.get(L.id),Nr=un!==zt,In=null;if(Nr){let{payload:gt,complete:Be}=gr(L),dr=L.id,_t=()=>pt.current?.getMessages().find(Hn=>Hn.id===dr);In=Se.renderAskUserQuestion({message:L,payload:gt,complete:Be,resolve:Hn=>{let Xa=_t();Xa&&pt.current?.resolveAskUserQuestion(Xa,Hn)},dismiss:()=>{let Hn=_t();Hn?.agentMetadata?.awaitingLocalTool&&(pt.current?.markAskUserQuestionResolved(Hn),pt.current?.resolveAskUserQuestion(Hn,"(dismissed)"))},config:o})}let Rn=un!=null;if(Nr&&In===null&&!Rn){L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(j.add(L.toolCall.id),Ni(L,o,Ne.composerOverlay));return}let dt=er(L.id,L.role);dt.setAttribute("data-ask-plugin-stub","true"),dt.setAttribute("data-preserve-runtime","true"),f.appendChild(dt),se.push({messageId:L.id,fingerprint:zt,bubble:In});return}else{L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(j.add(L.toolCall.id),Ni(L,o,Ne.composerOverlay));return}}else if(Ee){let Se=k();if(!Se){f.appendChild(er(L.id,L.role));return}let un=a.find(dt=>typeof dt.renderApproval=="function")??y,In=Pr.get(L.id)!==zt,Rn=null;if(In&&un?.renderApproval){let dt=L.id,gt=(Be,dr)=>{let _t=pt.current?.getMessages().find(Hn=>Hn.id===dt);_t?.approval&&(_t.approval.toolType==="webmcp"?pt.current?.resolveWebMcpApproval(_t.id,Be):pt.current?.resolveApproval(_t.approval,Be,dr))};Rn=un.renderApproval({message:L,defaultRenderer:()=>Se.createApprovalBubble(L,o),config:o,approve:Be=>gt("approved",Be),deny:Be=>gt("denied",Be)})}if(In&&Rn===null)i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),Pr.delete(L.id),Rt=Se.createApprovalBubble(L,o);else{let dt=er(L.id,L.role);dt.setAttribute("data-approval-plugin-stub","true"),dt.setAttribute("data-preserve-runtime","true"),f.appendChild(dt),ht.push({messageId:L.id,fingerprint:zt,bubble:Rn});return}}else if(pn)if(L.variant==="reasoning"&&L.reasoning&&pn.renderReasoning){if(!xn)return;Rt=pn.renderReasoning({message:L,defaultRenderer:()=>ff(L,o),config:o})}else if(L.variant==="tool"&&L.toolCall&&pn.renderToolCall){if(!q)return;Rt=pn.renderToolCall({message:L,defaultRenderer:()=>yf(L,o),config:o})}else pn.renderMessage&&(Rt=pn.renderMessage({message:L,defaultRenderer:()=>{let Se=ea(L,g,We,o.messageActions,Js,{loadingIndicatorRenderer:C,widgetConfig:o,actionEligibility:qt});return L.role!=="user"&&I(Se,L,o,P),Se},config:o}));if(!Rt&&ie){let Se=Wp(L);if(Se){let un=gs.get(L.id),Nr=un!==zt,In=o.wrapComponentDirectiveInBubble!==!1&&So.getOptions(Se.component)?.bubbleChrome!==!1,Rn=null;if(Nr){let dt=Hp(Se,{config:o,message:L,transform:g});if(dt&&Se.component==="PersonaArtifactInline"){let gt=dt.hasAttribute("data-artifact-inline")?dt:dt.querySelector("[data-artifact-inline]"),Be=gt?.getAttribute("data-artifact-inline")??"",dr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Be):Be,_t=Be?i.querySelector(`#wrapper-${L.id}`)?.querySelector(`[data-artifact-inline="${dr}"]`)??null:null;gt&&_t&&_t!==gt&&yr()?.hasLiveInlineArtifactBlock(_t)&&(gt===dt?dt=_t:gt.replaceWith(_t))}if(dt)if(In){let gt=document.createElement("div");if(gt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),gt.id=`bubble-${L.id}`,gt.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let Be=document.createElement("div");Be.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Be.innerHTML=g({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),gt.appendChild(Be)}gt.appendChild(dt),Rn=gt}else{let gt=document.createElement("div");if(gt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",gt.id=`bubble-${L.id}`,gt.setAttribute("data-message-id",L.id),gt.setAttribute("data-persona-component-directive","true"),L.content&&L.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:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),gt.appendChild(Be)}gt.appendChild(dt),Rn=gt}}if(Rn||un!=null){let dt=er(L.id,L.role);dt.setAttribute("data-component-directive-stub","true"),dt.setAttribute("data-preserve-runtime","true"),f.appendChild(dt),me.push({messageId:L.id,fingerprint:zt,bubble:Rn});return}}}if(!Rt)if(L.variant==="reasoning"&&L.reasoning){if(!xn)return;Rt=ff(L,o)}else if(L.variant==="tool"&&L.toolCall){if(!q)return;Rt=yf(L,o)}else if(L.variant==="approval"&&L.approval){if(o.approval===!1)return;let Se=k();if(!Se)return;Rt=Se.createApprovalBubble(L,o)}else{let Se=o.layout?.messages;Se?.renderUserMessage&&L.role==="user"?Rt=Se.renderUserMessage({message:L,config:o,streaming:!!L.streaming}):Se?.renderAssistantMessage&&L.role==="assistant"?Rt=Se.renderAssistantMessage({message:L,config:o,streaming:!!L.streaming}):Rt=ea(L,g,Se,o.messageActions,Js,{loadingIndicatorRenderer:C,widgetConfig:o,actionEligibility:qt}),L.role!=="user"&&Rt&&I(Rt,L,o,P)}let Fe=er(L.id,L.role);Fe.appendChild(Rt),Iw($t,L.id,zt,Fe),f.appendChild(Fe)}),Ne.composerOverlay&&Ne.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(je=>{let Ee=je.getAttribute("data-persona-ask-sheet-for");Ee&&!j.has(Ee)&&Vr(Ne.composerOverlay,Ee)}),o.features?.toolCallDisplay?.grouped){let L=[],je=[],Ee=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(ie=>{if(ie.variant==="tool"&&ie.toolCall&&q){if(cr&&ie.toolCall.status==="complete")return;je.push(ie);return}ie.variant==="reasoning"&&(!xn||ie.reasoning?.status==="complete"&&Bo(ie.reasoning))||((je.length>1||Ee&&je.length>0)&&L.push(je),je=[])}),(je.length>1||Ee&&je.length>0)&&L.push(je),L.forEach(ie=>{let It=ie.map(We=>Array.from(f.children).find(Fe=>Fe instanceof HTMLElement&&Fe.getAttribute("data-wrapper-id")===We.id)).filter(We=>!!We);if(It.length<(Ee?1:2))return;let qt=er(`tool-group-${ie[0].id}`,"assistant");qt.setAttribute("data-persona-tool-group-row","true");let rn=document.createElement("div");rn.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",rn.setAttribute("data-persona-tool-group","true");let zt=document.createElement("div");zt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",zt.id=`tool-group-summary-${ie[0].id}`;let Yt=`Called ${ie.length} ${ie.length===1?"tool":"tools"}`,Rt=o.toolCall?.renderGroupedSummary?.({messages:ie,toolCalls:ie.map(We=>We.toolCall).filter(We=>!!We),defaultSummary:Yt,config:o});W(zt,Rt)||(zt.textContent=Yt);let pn=document.createElement("div");pn.className="persona-tool-group-stack persona-flex persona-flex-col",pn.id=`tool-group-stack-${ie[0].id}`,pn.setAttribute("data-persona-tool-group-stack","true"),rn.appendChild(zt),Ee||rn.appendChild(pn),qt.appendChild(rn),It[0].before(qt),It.forEach((We,Fe)=>{if(Ee){We.remove();return}We.style.setProperty("--persona-message-row-max-width","100%");let Se=document.createElement("div");Se.className="persona-tool-group-item persona-relative",Se.setAttribute("data-persona-tool-group-item","true"),Fe<It.length-1&&Se.setAttribute("data-persona-tool-group-connector","true"),Se.appendChild(We),pn.appendChild(Se)})})}Rw($t,U);let Qa=L=>L.variant==="tool"&&!q||L.variant==="reasoning"&&!xn||ho(L),Ws=c.some(L=>L.role==="assistant"&&L.streaming&&!Qa(L)),yo=c.length-1;for(;yo>=0&&Qa(c[yo]);)yo--;let on=yo>=0?c[yo]:void 0,bo=yo<c.length-1,Ii=on?.role==="assistant"&&!on.streaming&&on.variant!=="approval"&&!bo;if(jn&&c.some(L=>L.role==="user")&&!Ws&&!Ii){let L={config:o,streaming:!0,location:"standalone",defaultRenderer:Ks},je=a.find(ie=>ie.renderLoadingIndicator),Ee=null;if(je?.renderLoadingIndicator&&(Ee=je.renderLoadingIndicator(L)),Ee===null&&o.loadingIndicator?.render&&(Ee=o.loadingIndicator.render(L)),Ee===null&&(Ee=Ks()),Ee){let ie=document.createElement("div"),It=o.loadingIndicator?.showBubble!==!1,qt=o.layout?.messages?.layout??"bubble";ie.className=It?Hl("assistant",qt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),ie.setAttribute("data-typing-indicator","true"),It&&(ie.style.color="var(--persona-message-assistant-text, var(--persona-text))",qt!=="flat"&&(ie.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",ie.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),ie.appendChild(Ee);let rn=er("typing-indicator","assistant");rn.appendChild(ie),f.appendChild(rn)}}if(!jn&&c.length>0){let L=c[c.length-1],je={config:o,lastMessage:L,messageCount:c.length},Ee=a.find(It=>It.renderIdleIndicator),ie=null;if(Ee?.renderIdleIndicator&&(ie=Ee.renderIdleIndicator(je)),ie===null&&o.loadingIndicator?.renderIdle&&(ie=o.loadingIndicator.renderIdle(je)),ie){let It=document.createElement("div"),qt=o.loadingIndicator?.showBubble!==!1;It.className=qt?["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(" "),It.setAttribute("data-idle-indicator","true"),It.appendChild(ie);let rn=er("idle-indicator","assistant");rn.appendChild(It),f.appendChild(rn)}}if(dv(f),sp(i,f),jg(i),nt){let{messageId:L,element:je}=nt,Ee=i.querySelector(`#wrapper-${L}`);Ee&&je.parentElement!==Ee&&(Ea(Ee,$.get(L)??"user"),Ee.replaceChildren(je))}if(se.length>0)for(let{messageId:L,fingerprint:je,bubble:Ee}of se){let ie=i.querySelector(`#wrapper-${L}`);ie&&(Ea(ie,$.get(L)??"assistant"),Ee!==null&&(ie.replaceChildren(Ee),ie.setAttribute("data-bubble-fp",je),ci.set(L,je)))}if(ci.size>0)for(let L of ci.keys())U.has(L)||ci.delete(L);if(me.length>0)for(let{messageId:L,fingerprint:je,bubble:Ee}of me){let ie=i.querySelector(`#wrapper-${L}`);ie&&(Ea(ie,$.get(L)??"assistant"),Ee!==null&&(ie.replaceChildren(Ee),ie.setAttribute("data-bubble-fp",je),gs.set(L,je)))}if(gs.size>0)for(let L of gs.keys())U.has(L)||gs.delete(L);if(ht.length>0)for(let{messageId:L,fingerprint:je,bubble:Ee}of ht){let ie=i.querySelector(`#wrapper-${L}`);ie&&(Ea(ie,$.get(L)??"assistant"),Ee!==null&&(ie.replaceChildren(Ee),ie.setAttribute("data-bubble-fp",je),Pr.set(L,je)))}if(Pr.size>0)for(let L of Pr.keys())U.has(L)||Pr.delete(L)},Hu=!1,Cc=()=>{Hu||(Hu=!0,id().catch(()=>{Hu=!1}))},Zn=(i,c,g)=>{c.length>0&&Cc(),FA(i,c,g),Th()},Ta=null,$A=()=>{if(Ta)return;let i=g=>{let f=g.composedPath();f.includes(Qe)||Xt&&f.includes(Xt)||ft(!1,"user")};Ta=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},ly=()=>{if(!Ta)return;(e.ownerDocument??document).removeEventListener("pointerdown",Ta,!0),Ta=null};he.push(()=>ly());let Pa=null,UA=()=>{if(Pa)return;let i=g=>{g.key==="Escape"&&(g.isComposing||ft(!1,"user"))};Pa=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},cy=()=>{if(!Pa)return;(e.ownerDocument??document).removeEventListener("keydown",Pa,!0),Pa=null};he.push(()=>cy());let ka=!1,dy=new Set,jA=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},fi=()=>{if(!Ce())return;let i=Ne.peekBanner,c=Ne.peekTextNode;if(!i||!c)return;if(we){i.classList.remove("persona-pill-peek--visible");return}let g=P?.getMessages()??[],f;for(let jt=g.length-1;jt>=0;jt--){let Lt=g[jt];if(Lt.role==="assistant"&&Lt.content){f=Lt;break}}if(!f){i.classList.remove("persona-pill-peek--visible");return}let b=f.content,C=!!f.streaming,W=jA(),U=ip(W),$=U.type!=="none"?Su(U.type,W?.plugins):null,j=$?.isAnimating?.(f)===!0,X=$!==null&&(C||j);X&&$&&!dy.has($.name)&&(Pl($,e),dy.add($.name));let se=X&&$?.containerClass?$.containerClass:null,me=c.dataset.personaPeekStreamClass??null;me&&me!==se&&(c.classList.remove(me),delete c.dataset.personaPeekStreamClass),se&&me!==se&&(c.classList.add(se),c.dataset.personaPeekStreamClass=se),X?(c.style.setProperty("--persona-stream-step",`${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 Ze=X?ap(b,U.buffer,$,f,C):b;if(X&&U.placeholder==="skeleton"&&C&&(!Ze||!Ze.trim())){let jt=document.createElement("div"),Lt=Tl();Lt.classList.add("persona-pill-peek__skeleton"),jt.appendChild(Lt),sp(c,jt)}else{let jt=Math.max(0,Ze.length-100),Lt=Ze.length>100?Ze.slice(-100):Ze,cn=pr(Lt);if(!X||!$){let nt=Ze.length>100?`\u2026${Lt}`:Lt;c.textContent!==nt&&(c.textContent=nt)}else{let nt=cn;($.wrap==="char"||$.wrap==="word")&&(nt=El(cn,$.wrap,`peek-${f.id}`,{skipTags:$.skipTags,startIndex:jt}));let dn=document.createElement("div");if(dn.innerHTML=nt,$.useCaret&&Lt.length>0){let Bo=lp(),cr=dn.querySelectorAll(".persona-stream-char, .persona-stream-word"),ho=cr[cr.length-1];ho?.parentNode?ho.parentNode.insertBefore(Bo,ho.nextSibling):dn.appendChild(Bo)}sp(c,dn),$.onAfterRender?.({container:c,bubble:i,messageId:f.id,message:f,speed:U.speed,duration:U.duration})}}let Jt=jn||ka;i.classList.toggle("persona-pill-peek--visible",Jt)};if(Ce()){let i=Ne.peekBanner;if(i){let f=b=>{b.preventDefault(),b.stopPropagation(),ft(!0,"user")};i.addEventListener("pointerdown",f),he.push(()=>{i.removeEventListener("pointerdown",f)})}let c=()=>{ka||(ka=!0,fi())},g=()=>{ka&&(ka=!1,fi())};Me.addEventListener("pointerenter",c),Me.addEventListener("pointerleave",g),he.push(()=>{Me.removeEventListener("pointerenter",c),Me.removeEventListener("pointerleave",g)}),Xt&&(Xt.addEventListener("pointerenter",c),Xt.addEventListener("pointerleave",g),he.push(()=>{Xt.removeEventListener("pointerenter",c),Xt.removeEventListener("pointerleave",g)}))}let qA=i=>{let c=o.launcher?.composerBar??{},g=c.expandedSize??"anchored",f=c.bottomOffset??"16px",b=c.collapsedMaxWidth,C=c.expandedMaxWidth??"880px",W=c.expandedTopOffset??"5vh",U=c.modalMaxWidth??"880px",$=c.modalMaxHeight??"min(90vh, 800px)",j="calc(100vw - 32px)",X="var(--persona-pill-area-height, 80px)",se=Qe.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",Xt){let me=Xt.style;me.bottom=f,me.width=b??""}if(i&&g!=="fullscreen"){if(g==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=U,se.maxWidth=j,se.maxHeight=$,se.height=$;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${f} + ${X})`,se.top=W,se.width=C,se.maxWidth=j}},La=()=>{if(we&&Cc(),!De())return;if(Ce()){let j=(o.launcher?.composerBar??{}).expandedSize??"anchored",X=we?"expanded":"collapsed";Qe.dataset.state=X,Qe.dataset.expandedSize=j,Xt&&(Xt.dataset.state=X,Xt.dataset.expandedSize=j),Qe.style.removeProperty("display"),Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),qA(we),ue.style.display=we?"flex":"none",as(),we?($A(),UA()):(ly(),cy()),fi();return}let i=At(o),c=e.ownerDocument.defaultView??window,g=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,b=c.innerWidth<=g,C=f&&b&&pe,W=_n(o).reveal;we?(Qe.style.removeProperty("display"),Qe.style.display=i?"flex":"",Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-95","persona-opacity-0"),Me.classList.add("persona-scale-100","persona-opacity-100"),Pt?(Pt.setPanelOpen(!0),Pt.element.style.display="none"):mn&&(mn.style.display="none")):(i?i&&(W==="overlay"||W==="push")&&!C?(Qe.style.removeProperty("display"),Qe.style.display="flex",Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Qe.style.setProperty("display","none","important"),Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Qe.style.display="",Qe.classList.add("persona-pointer-events-none","persona-opacity-0"),Me.classList.remove("persona-scale-100","persona-opacity-100"),Me.classList.add("persona-scale-95","persona-opacity-0")),Pt?(Pt.setPanelOpen(!1),Pt.element.style.display=i?"none":""):mn&&(mn.style.display=i?"none":""))},ft=(i,c="user")=>{if(!De()||we===i)return;let g=we;we=i,La();let f=(()=>{let C=o.launcher?.sidebarMode??!1,W=e.ownerDocument.defaultView??window,U=o.launcher?.mobileFullscreen??!0,$=o.launcher?.mobileBreakpoint??640,j=W.innerWidth<=$,X=At(o)&&U&&j,se=Ce()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return C||U&&j&&pe||X||se})();if(we&&f){if(!Lo){let C=e.getRootNode(),W=C instanceof ShadowRoot?C.host:e.closest(".persona-host");W&&(Lo=jm(W,o.launcher?.zIndex??an))}Io||(Io=qm(e.ownerDocument))}else we||(Lo?.(),Lo=null,Io?.(),Io=null);we&&(Ka(),Iu()||(Un()==="follow"?Rr(!0):hc()));let b={open:we,source:c,timestamp:Date.now()};we&&!g?A.emit("widget:opened",b):!we&&g&&A.emit("widget:closed",b),A.emit("widget:state",{open:we,launcherEnabled:pe,voiceActive:Ke.active,streaming:P.isStreaming()})},Hr={inputDisabled:!1,sendDisabled:!1},Ro=()=>Hr.inputDisabled,Wu=()=>Wn(o.voiceRecognition?.provider)&&!!P&&(P.isBargeInActive()||["listening","processing","speaking"].includes(P.getVoiceStatus())),xs=()=>Hr.inputDisabled||Hr.sendDisabled,zA=()=>(Hr.inputDisabled?Hr.inputReason:void 0)??(Hr.sendDisabled?Hr.sendReason:void 0);function Ou(){if(!Te)return;if(xe.getState().phase==="streaming"){Te.disabled=!1;return}let i=tt?!tt.isReady():!1;Te.disabled=xs()||i}function wc(){if(!Mo)return;let i=xe.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;Mo.toggleAttribute("data-persona-send-hidden",c)}function VA(){let i=zA();if(Ce()){let c=co??Re;i?c.setAttribute("title",i):c.removeAttribute("title"),Re.toggleAttribute(da,!!i);return}if(i){lt.setAttribute("role","status"),lt.setAttribute("aria-live","polite"),lt.setAttribute(da,""),lt.textContent=i;return}if(lt.hasAttribute(da)&&(lt.removeAttribute("role"),lt.removeAttribute("aria-live"),lt.removeAttribute(da),p)){let c=P.getStatus();zl(lt,th(c),o.statusIndicator??{},c)}}function Bu(){let i=vm(o.composer?.inputDisabled),c=vm(o.composer?.sendDisabled);Hr={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},xe.setInputDisabled(i.disabled),xe.setSendDisabled(c.disabled);let g=xe.getState().phase==="streaming",f=i.disabled,b=g||f;ce&&(ce instanceof HTMLTextAreaElement?ce.disabled=f:ce.setAttribute("contenteditable",f?"false":"true"),ce.setAttribute("aria-disabled",f?"true":"false")),Mt&&(Mt.disabled=f),vt&&(vt.disabled=f);for(let C of Bt?.affordanceButtons??[])C.querySelectorAll("button").forEach(W=>{W.disabled=f});re&&(re.disabled=f||g&&!Wu()),ds.forEach(C=>{C.elements.forEach(W=>{W.toggleAttribute("data-disabled",b),W instanceof HTMLButtonElement||W.setAttribute("aria-disabled",b?"true":"false")}),C.buttons.forEach(W=>{W.disabled=b})}),$u.forEach(C=>{C.toggleAttribute("data-disabled",b),C instanceof HTMLButtonElement?C.disabled=b:C.setAttribute("aria-disabled",b?"true":"false"),C.querySelectorAll("button").forEach(W=>{W.disabled=b})}),Re.dataset.personaComposerStreaming=g?"true":"false",Re.dataset.personaComposerInputDisabled=f?"true":"false",Re.dataset.personaComposerSendDisabled=xs()?"true":"false",Re.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(C=>{(C instanceof HTMLButtonElement||C instanceof HTMLInputElement||C instanceof HTMLTextAreaElement||C instanceof HTMLSelectElement)&&(C.disabled=g)}),Ou(),VA()}let Ia=i=>{xe.setStreaming(i),nh(i?"stop":"send"),Bu()},Ss=()=>{Ke.active||ce&&ce.focus()};A.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Ss(),200)});let As=null,Ra=!1,_u=!An.hidden,Wr=null,Du=!M,xc=null;he.push(()=>{xc?.cancel(),xc=null});let KA=i=>{let c=px(i);if(c===Yl)return;Yl=c,e.setAttribute("data-persona-conversation-state",c);let g=au();Xl(),Du&&(xc?.cancel(),xc=cx(Re,c==="active"?g:au(),c==="active"?"drop":"rise")),kn()},py=null,uy,gy=null,hi=null,Nu=!1,Ha=i=>{let c=xo(o),g=`${c.variant}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(g!==py||c.icon!==uy)&&(py=g,uy=c.icon,hp({host:An,iconHolder:QS,kicker:XS,title:JS,subtitle:ZS,starterSuggestions:ou},c));let f=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;f!==gy&&(gy=f,yp(Fn,c.message,o));let b=i??(P?P.getMessages():o.initialMessages);KA(b);let C=Ra,W=!C&&ts(c,b),U=W!==_u;if(_u=W,hi){Wr?.cancel(),Wr=null,C!==Nu&&(Nu=C,C?af(oe,An,null):sf(oe,An,hi)),ta(oe,An,!C);return}if(U&&!W&&!C&&c.dismiss==="on-first-message"&&Du){Wr=lx(An,j=>{Wr===j&&(Wr=null),!_u&&!hi&&(ta(oe,An,!1),kn()),j?.cancel()});return}if(Wr){if(!W&&!C)return;Wr.cancel(),Wr=null}let $=!An.hidden;ta(oe,An,W),!W&&$&&kn()},Fu=[],$u=[],Uu=!1,my=null,fy,hy=()=>{$u.length=0;let i=Fu.splice(0,Fu.length);for(let c of i)try{c()}catch(g){console.warn("[persona] renderWelcome cleanup threw",g)}};he.push(hy);let GA=(i,c)=>{let g=Vm(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=Km({item:{...g,behavior:g.behavior??f?.behavior??"send"},index:c,surface:"starter",source:"config",variant:f?.variant??"card",streaming:p?P.isStreaming():!1,config:o,plugins:a,chipsConfig:o.suggestionChipsConfig,session:P,getTextarea:()=>ce,eventTarget:An,submitPrompt:Yc});return $u.push(b),b},ju=()=>{if(Uu)return;Uu=!0;let i=xo(o);my=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,fy=i.icon;try{hy(),af(oe,An,hi),hi=null,Nu=!1;let c=P?P.getMessages():o.initialMessages,g=ts(i,c),f=0,b=null;for(let C of a)if(C.renderWelcome&&(b=C.renderWelcome({config:i,variant:i.variant,visible:g,defaultRenderer:()=>An,sendMessage:W=>{if(!P||P.isStreaming())return;let U=W.trim();U&&P.sendMessage(U)},requestRender:()=>ju(),renderStarter:W=>GA(W,f++),storage:u(C.id),onCleanup:W=>{Fu.push(W)}}),b))break;b&&b!==An&&(hi=b,sf(oe,An,b))}finally{Uu=!1}Ha()},YA=()=>{let i=xo(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===my&&i.icon===fy||ju()},Sc=()=>{Ha(),ri||(ce.placeholder=YC(xe.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!P?.isStreaming()&&(Te.textContent=o.copy?.sendButtonLabel??"Send")),ce.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ce.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},QA=!!o.setStoredConversationId,yi=i=>ae(c=>{let g={...c};return delete g[i],g}),Ac=i=>{let c=ee[i];return typeof c=="string"?c:null},yy=()=>{let i=ee.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:()=>Ac("sessionId"),setStoredSessionId:i=>{ae(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>yi("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Ac("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{ae(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>yi("conversationId"))});let by=()=>o.clientToken??null,vy=i=>jx(i,Q(),o.persistState===!1),Cy=by(),tr=Cy?vy(Cy):null,nr={...tr?{visitorStore:tr}:{},historyBootstrapReady:H,getStoredMessageCursor:()=>Ac("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){yi("historyMessageCursor");return}ae(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=ee.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){yi("pendingDisplayProjections");return}ae(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:yy,setStoredResumableHandle:i=>{if(!i){yi("durableResume");return}ae(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>le&&yy()!==null,...QA?{}:{getStoredConversationRevision:()=>Ac("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){yi("conversationRevision");return}ae(c=>({...c,conversationRevision:i}))}}};if(le){let i=o.onExecutionState,c=e.ownerDocument.defaultView,g=!1,f=()=>g=!0,b=()=>g=!1;c?.addEventListener("pagehide",f),c?.addEventListener("pageshow",b),he.push(()=>{c?.removeEventListener("pagehide",f),c?.removeEventListener("pageshow",b)}),o={...o,reconnectStream:o.reconnectStream??(C=>P.getClient().reconnectClientTokenStream(C)),onExecutionState:C=>{(C||!g)&&nr.setStoredResumableHandle?.(C?{executionId:C.executionId,after:C.lastEventId}:null),i?.(C)}}}let XA=()=>{let i=by();if(i&&tr?.matches(i,Q(),o.persistState===!1)||!i&&!tr)return;tr?.destroy(),tr=i?vy(i):null;let c={...nr};tr?c.visitorStore=tr:delete c.visitorStore,nr=c,P.setHistoryInternals(nr)},Ms=null,JA=()=>{Ms==null&&(Ms=setInterval(()=>{let i=Le.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=vd(c-f))})},100))},qu=(i,c)=>{if(Object.is(i,c))return!0;if(i===null||c===null||typeof i!="object"||typeof c!="object")return!1;if(Array.isArray(i)||Array.isArray(c))return!Array.isArray(i)||!Array.isArray(c)||i.length!==c.length?!1:i.every((W,U)=>qu(W,c[U]));let g=i,f=c,b=Object.keys(g),C=Object.keys(f);return b.length===C.length&&b.every(W=>Object.prototype.hasOwnProperty.call(f,W)&&qu(g[W],f[W]))},wy=i=>{let{content:c,rawContent:g,llmContent:f,...b}=i;return b},zu=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Fl(i),ZA=(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))&&zu(f)&&zu(b)&&qu(wy(f),wy(b))},Vu=null,bi=null,Es=null,or=null,Ku=null,eM=i=>{if(!le)return ui(i);Ku=i,queueMicrotask(()=>{Ku===i&&(Ku=null,ui(i))})},Mc=i=>{Vu=i;let c,g;bi=null;for(let b=i.length-1;b>=0;b-=1){let C=i[b];if(!c&&C.role==="user"&&(c=C),!g&&C.role==="assistant"&&(g=C),!bi&&zu(C)&&(bi={index:b,id:C.id}),c&&g&&bi)break}Zn(Le,i,mt),yr()?.updateInlineArtifactBlocks(Le,Jn.artifacts,{suppressTransition:jn}),JA(),Ha(i),li(i),Rr(!jn),NA(i),i.length===0&&(fo(),Sa=!0,dc=!1,pi=null,pc=!1),!Au||di?(Au=!0,bs=c?.id??null,Mu=g?.id??null):c&&c.id!==bs?(bs=c.id,WA(c.id)):g&&g.id!==Mu&&OA(),g&&(Mu=g.id),DA(i);let f=Ke.lastUserMessageId;c&&c.id!==f&&(Ke.lastUserMessageId=c.id,A.emit("user:message",c)),Ke.lastUserMessageWasVoice=!!c?.viaVoice,eM(i),fi()},Gu=()=>{or!==null&&(cancelAnimationFrame(or),or=null);let i=Es;Es=null,i&&Mc(i)},xy=()=>{or!==null&&cancelAnimationFrame(or),or=null,Es=null},tM=i=>{let c=Es??Vu;if(jn&&c&&bi&&ZA(c,i,bi)){Es=i,or===null&&(or=requestAnimationFrame(()=>{or=null;let g=Es;Es=null,g&&Mc(g)}));return}if(i.length===0){xy(),Mc(i);return}Gu(),Mc(i)};P=new zi(o,{onMessagesChanged(i){tM(i)},onStatusChanged(i){let c=o.statusIndicator??{};zl(lt,(f=>f==="idle"?c.idleText??Vt.idle:f==="connecting"?c.connectingText??Vt.connecting:f==="connected"?c.connectedText??Vt.connected:f==="error"?c.errorText??Vt.error:f==="paused"?c.pausedText??Vt.paused:f==="resuming"?c.resumingText??Vt.resuming:Vt[f])(i),c,i),nu()},onStreamingChanged(i){i||(P?.getMessages().length===0?xy():Gu()),jn=i,Ia(i),nu(),P&&Zn(Le,P.getMessages(),mt),i||(Rr(!0),RA(),Gh=!0,P&&Yh(P.getMessages(),Gr(o))),Gt(),Gl(i?"Responding\u2026":"Response complete."),fi()},onVoiceStatusChanged(i){if(A.emit("voice:status",{status:i,timestamp:Date.now()}),!(i!=="disconnected"&&!Wn(o.voiceRecognition?.provider)))switch(i){case"listening":lr(),ki();break;case"processing":lr(),oE();break;case"speaking":lr(),rE();break;default:i==="idle"&&P.isBargeInActive()?(lr(),ki(),re?.setAttribute("aria-label","End voice session")):(Ke.active=!1,lr(),Zo("system"),mo());break}},onArtifactsState(i){Jn=i,i.artifacts.length===0&&(si=!1),yr()?.updateInlineArtifactBlocks(Le,i.artifacts,{suppressTransition:jn}),go(),ui()},onHistoryStateChanged(i){Zf(i)},onHistoryNotice(i){eh(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})}},nr),pt.current=P,he.push(()=>P.cancel()),he.push(()=>{P.destroy(),tr?.destroy()});let Yu=null;if(P.onReadAloudChange((i,c)=>{Mh=i,Eh=c,Th();let g=i??Yu;i&&(Yu=i);let f=g?P.getMessages().find(b=>b.id===g)??null:null;A.emit("message:read-aloud",{messageId:g,message:f,state:c,timestamp:Date.now()}),c==="idle"&&(Yu=null)}),p=!0,Au=!0,o.voiceRecognition?.enabled===!0&&Wn(o.voiceRecognition.provider))try{P.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let nM=720,oM=250,Je=Hf(o.features?.history?.copy),Vn=null,Qu=!1,ct=null,Ec=null,Tc="conversation",Xu=null,gn=null,Ho=null,Pc=P.getHistoryState(),Ju=null,Wa=0,Zu=null,kc=null,Lc=null,eg=`persona-history-${Math.random().toString(36).slice(2,8)}`,tg=()=>o.features?.history?.enabled===!0,Wo=()=>tg()&&!!Vn&&!Qu,Sy=()=>{let i=P.getStatus();return jn||i==="paused"||i==="resuming"},ng=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",g=Vn?.capabilities.scopes;return!g||g.includes(c)?c:g[0]??c},vi=()=>Ec?.scope??ng(),Ay=()=>P.getClientSession()?.targetId??null,My=i=>`${i.state}:${"reason"in i?i.reason:""}`,rM=i=>{let c=My(i);c!==Ju&&(Ju=c,A.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},Ic=i=>{i&&(Ko.textContent="",Ko.textContent=i)},Ey=null,Ty=null,sM=()=>{if(!tg())return null;let i=Kx();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(Ey!==c&&(Ey=c,Ty=c()),Ty):P.isClientTokenMode()?Gx({client:P.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:g=>P.bindActivatedSession(g),getClient:()=>P.getClient()}):null},Py=()=>{kc?.(),kc=null,Lc?.(),Lc=null,Qu=!1,Vn=sM();let i={...nr};Vn?i.historyProvider=Vn:delete i.historyProvider,nr=i,P.setHistoryInternals(nr),Vn&&(kc=Vn.subscribeAvailability?.(c=>{Qu=!c,c||Ln({restoreFocus:!1}),Br()})??null,Lc=Vn.subscribeIdentityStatus(c=>rM(c)),Ju=My(Vn.getIdentityStatus()))},og=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!pe||At(o)))return"panel";let c=ko??ue;return(c.getBoundingClientRect().width||c.clientWidth)>=nM?"rail":"panel"},eo=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},Rc="data-persona-history-suppressed",Kn=null,Or=null,Ts=null,Oa=null,rg=null,ky="",Ly=()=>Pe===rg?ky:o.layout?.showHeader===!1?"none":"",iM=()=>Nt==="panel"&&!!Ts&&Oa===Ts.element&&o.layout?.showHeader!==!1&&Ly()!=="none",aM=()=>{for(let i of Array.from(Pe.children))i!==Kn&&i.setAttribute(Rc,"")},lM=()=>{for(let i of Array.from(ue.querySelectorAll(`[${Rc}]`)))i.removeAttribute(Rc)},cM=()=>{let i=Ts;if(!i)return;if(Array.from(Pe.children).some(f=>f!==Kn&&!f.hasAttribute(Rc))){Or&&Or!==Pe&&(Or.style.removeProperty("min-height"),Or=null);let f=Pe.offsetHeight;f>0&&(Pe.style.minHeight=`${f}px`,Or=Pe)}Kn||(Kn=E("div","persona-history-header-host")),i.setHeaderPlacement("external");let g=i.getHeaderElement();g.parentNode!==Kn&&Kn.replaceChildren(g),Kn.parentNode!==Pe&&Pe.appendChild(Kn),aM()},Iy=()=>{Or&&(Or.style.removeProperty("min-height"),Or=null),Kn&&(Ts?.setHeaderPlacement("inline"),Kn.remove(),Kn=null,lM())},Hc=null,sg=()=>{if(Hc){if(oe.style.display="none",eo(oe,!0),Re.hidden=!0,eo(Re,!0),iM()){cM(),Pe.style.display=Ly(),eo(Pe,!1);return}Iy(),Pe.style.display="none",eo(Pe,!0)}};tu=sg;let dM=i=>{let c=oe.style.display,g=Re.hidden,f=Re,b=Pe,C=Pe.style.display;rg=b,ky=C,Hc=()=>{Hc=null,Iy(),rg=null,oe.style.display=c,eo(oe,!1),f.hidden=g,eo(f,!1),Re!==f&&(Re.hidden=!1,eo(Re,!1)),b.style.display=C,eo(b,!1),Pe!==b&&(Pe.style.display=o.layout?.showHeader===!1?"none":"",eo(Pe,!1))},Re.parentNode?.insertBefore(i,Re),sg()},Ci=null,Ps=null,Ba=null,wi=null,Ry=()=>[Pe,Ne.closeButtonWrapper,Ne.clearChatButtonWrapper,oe,Re],pM=52,Wc=()=>o.features?.history?.rail?.collapsible!==!1,xi=()=>o.features?.history?.rail?.side==="right"?"right":"left",ig=200,ag=400,lg=i=>Math.min(ag,Math.max(ig,Math.round(i))),uM=()=>o.features?.history?.rail?.resizable===!0,_a,gM=()=>{if(_a===void 0&&(_a=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Q()}rail-width`));i&&(_a=i)}catch{}return _a},Da=()=>lg(gM()??o.features?.history?.rail?.width??260),mM=i=>{if(_a=i,o.persistState!==!1)try{window.localStorage.setItem(`${Q()}rail-width`,String(i))}catch{}},Oc=()=>Wc()&&o.features?.history?.rail?.collapsedBehavior==="overlay",Ut=!1,Hy=i=>{let c=E("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},fM=()=>{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=Hy(i.iconUrl):g=i.icon?de(i.icon,20):null),g?g.cloneNode(!0):null}},hM=()=>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=Hy(f.iconUrl):b=f.icon?de(f.icon,20):null}catch(C){g(C),b=null}return b},onSelect:()=>{try{f.onSelect()}catch(C){g(C)}}}})}})??[],yM=i=>{let c=hM();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},Na=null,Wy=()=>`${Q()}rail-collapsed`,cg=()=>{if(Na===null&&(Na=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(Wy());i&&(Na=i==="1")}catch{}return Na},dg=i=>{if(Na=i,o.persistState!==!1)try{window.localStorage.setItem(Wy(),i?"1":"0")}catch{}},Fa=()=>Nt==="rail"&&Wc()&&!Oc()&&cg(),pg=()=>{},Oy=()=>{if(Oc()){pg();return}dg(!cg()),ct?.view.setCollapsed(Fa()),Vo(),kn()},ug=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!op(i)?null:{combo:i,hint:rp(i),aria:wl(i)}},By=()=>{d.forEach(c=>c()),d=[];let i=ug();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Et&&Nt==="rail"&&Wc()||Ai(),run:()=>Oc()?pg():Oy()}));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}`}))};By();let bM=300,Bc="var(--persona-history-overlay-margin,8px)",to=null,rr=null,_c=0,sr=null,Si=null,ks=!1,gg=0,_y=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Ai=()=>Wo()&&Oc()&&(Nt??og())==="rail",vM=()=>Et&&!Ut,$a=()=>{Si!==null&&clearTimeout(Si),Si=null},CM=()=>{Lf().catch(()=>{})},Dy=()=>{$a(),Ut&&(Si=setTimeout(()=>{Si=null,!(ks||!Ut)&&(sr?.contains(document.activeElement)||Ln({restoreFocus:!1}))},bM))},wM=(i,c)=>{let g=sr?.getBoundingClientRect();if(!g)return!1;let f=to?.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},mg=i=>{Ut&&(ks=wM(i.clientX,i.clientY),ks?$a():Si===null&&Dy())},Ny=i=>{Et||!Ai()||(Ut=!0,ja({invoker:to,keyboard:i?.keyboard===!0}).then(()=>{Et?!ks&&document.activeElement!==to&&Ln():Ut=!1}))},Fy=()=>{let i=Oa?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",Ut?Je.expandLabel:Je.collapseLabel),i.setAttribute("aria-expanded",Ut?"false":"true"))},$y=()=>{dg(!1);let i=ct;if(!Ut||!i){ja({invoker:to});return}let c=document.activeElement===to;Ut=!1,Dc(),i.element.remove(),hg(i.element),Fy(),c&&Fc(),kn(),Br()},xM=()=>{dg(!0),Ln()};pg=()=>{!Et||Ut?$y():xM()};let SM=()=>{let i=ug(),c=js({ariaLabel:Je.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":eg,...i?{"aria-keyshortcuts":i.aria}:{}}}),g=c.button;g.addEventListener("mouseenter",()=>{ks=!0,$a(),!(_y()||Date.now()<gg)&&Ny()}),g.addEventListener("mouseleave",()=>{ks=!1,gg=0,Dy()}),g.addEventListener("focus",()=>{Et||CM()}),g.addEventListener("click",f=>{Wo()&&(f.detail!==0&&_y()&&!Et?Ny():$y())}),to=g,rr=c.wrapper},Ua=()=>{if(rr&&!rr.isConnected&&(rr=null,to=null),!Ai()){rr?.remove(),rr=null,to=null;return}to||SM();let i=rr,c=to;if(!i||!c)return;let g=xi()!=="right"?Pe.firstChild:null;(g??Pe.lastChild)!==i&&Pe.insertBefore(i,g),i.style.display=vM()||_c>0?"none":"",c.setAttribute("aria-label",Je.expandLabel),c.setAttribute("aria-expanded",Et?"true":"false"),sr&&Vo()},Uy=i=>{if(!Ut)return;let c=i.target;c instanceof Node&&(sr?.contains(c)||rr?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||Ln({restoreFocus:!1}))};document.addEventListener("pointerdown",Uy,!0),he.push(()=>{document.removeEventListener("pointerdown",Uy,!0),document.removeEventListener("pointermove",mg),Mi?.(),$a()});let fg=null,Mi=null,jy=16,qy=i=>{mM(lg(i)),Vo(),kn()},AM=()=>{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(ig)),i.setAttribute("aria-valuemax",String(ag)),i.addEventListener("pointerdown",c=>{let g=Ps;if(!g||c.button!==0)return;c.preventDefault(),Mi?.();let f=c.clientX,b=g.getBoundingClientRect().width||Da(),C=xi()==="right"?-1:1,W=b,U=e.ownerDocument;g.style.transition="none";let $=X=>{W=lg(b+C*(X.clientX-f)),g.style.flex=`0 0 ${W}px`,i.setAttribute("aria-valuenow",String(W))},j=()=>{Mi=null,U.removeEventListener("pointermove",$),U.removeEventListener("pointerup",j),U.removeEventListener("pointercancel",j),g.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}qy(W)};Mi=j,U.addEventListener("pointermove",$),U.addEventListener("pointerup",j),U.addEventListener("pointercancel",j);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let g=xi()==="right"?-jy:jy,f=Da(),b=c.key==="ArrowRight"?f+g:c.key==="ArrowLeft"?f-g:c.key==="Home"?ig:c.key==="End"?ag:null;b!==null&&(c.preventDefault(),qy(b))}),i},MM=(i,c)=>{if(!uM()||Fa()){Mi?.(),fg?.remove();return}let g=fg??AM();fg=g,g.setAttribute("aria-label",Je.resizeLabel),g.setAttribute("aria-valuenow",String(Da())),g.nextElementSibling!==c&&i.insertBefore(g,c)};Vo=()=>{ct?.view.setRailSide(xi());let i=xi()==="right",c=sr;if(c){let U=to?to.getBoundingClientRect().bottom-ue.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(U))}px + ${Bc})`,c.style.width=`${Da()}px`,c.style.left=i?"":Bc,c.style.right=i?Bc:""}let g=Ps,f=Ci,b=Ba;if(!g||!f||!b)return;g.style.flex=`0 0 ${Fa()?pM:Da()}px`;let C="1px solid var(--persona-divider,#e5e7eb)";g.style.borderRight=i?"":C,g.style.borderLeft=i?C:"";let W=i?b:g;f.firstElementChild!==W&&f.append(W,i?g:b),MM(f,i?g:b)};let zy=i=>{if(wi&&Ps){wi.replaceWith(i),wi=null,Vo();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",ue.insertBefore(c,Pe.parentNode===ue?Pe:oe);for(let b of Ry())b?.parentNode===ue&&g.appendChild(b);c.append(f,g),f.appendChild(i),Ci=c,Ps=f,Ba=g,Vo()},EM=()=>{if(Ci)return;let i=E("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",wi=i,zy(i),kn()},Vy=()=>{wi&&(Dc(),kn())},TM=i=>{let c=E("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${Bc};display:flex;overflow:hidden;z-index:${Vi-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,ue.style.position="relative",ue.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",mg),sr=c,Vo(),Fy()},Dc=()=>{Hc?.(),sr&&(ks&&(gg=Date.now()+150),document.removeEventListener("pointermove",mg),sr.remove(),sr=null);let i=Ci;if(i){Mi?.();for(let c of Ry())c&&i.contains(c)&&ue.insertBefore(c,i);i.remove(),Ci=null,Ps=null,Ba=null,wi=null}},Ky=i=>{Oa=i,i.id=eg,i.style.flex="1 1 auto",i.style.minHeight="0"},hg=i=>{Ky(i),(Nt!=="rail"||Ut)&&Vy(),Nt!=="rail"?dM(i):Ut?TM(i):zy(i)},Nc=()=>{if(Ua(),rb(),!Et||!ct)return;let i=og();if(i===Nt)return;let c=document.activeElement,g=c instanceof HTMLElement&&(ct.element.contains(c)||Kn?.contains(c)===!0)?c:null;Dc(),ct.element.remove(),ct.view.setHeaderPlacement("inline"),Nt=i,ct.view.setPresentation(i),ct.view.setCollapsed(Fa()),ct.requestRender(),ct.element.isConnected||hg(ct.element),g?.isConnected?g.focus():Fc(),Gt(),kn(),Br()},Gy=(i,c)=>Kn?.querySelector(c)??i.querySelector(c),Fc=()=>{let i=ct?.element??Oa;if(!i)return;let c=Gy(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let g=Gy(i,".persona-history-title")??i;g.tabIndex=-1,g.focus()},ja=async i=>{if(!Wo()||Et)return;let c=Vn;if(!c)return;if(!Ut&&Ai()&&cg()){Ua();return}$c();let g=++Wa;Tc=i?.returnSurface??"conversation",Xu=i?.invoker??gn;let f=Ai()&&!Ut;f&&(_c+=1,Ua(),EM());let b;try{b=await Lf()}catch{Ic(Je.openHistoryLabel),f&&(_c-=1,g===Wa&&(Vy(),Ua()));return}if(f&&(_c-=1),g!==Wa||Et)return;Ec={scope:ng()},Nt=og(),Et=!0;let C=Nt==="panel"&&o.layout?.showHeader!==!1&&Pe.style.display!=="none"?"external":"inline",W=o.features?.history?.rowAvatar,U=ug(),$=U?{hint:U.hint,aria:U.aria}:null,j={provider:c,context:Ec,targetId:Ay(),presentation:Nt,collapsible:Wc(),collapsed:Fa(),railSide:xi(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:fM(),onToggleCollapse:Oy,...$?{collapseShortcut:$}:{},headerPlacement:C,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:W===!1?!1:typeof W=="string"?W:o.launcher?.iconUrl,activeConversationId:P.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:X=>bg(X,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:X=>Ls(X),attachTooltip:tn,onStartNew:()=>vg({focusComposer:!0}),onClose:()=>Ln(),onRequestDeleteConversation:X=>ob(X),onRequestClearHistory:()=>HM(),...c.resetDevice?{onRequestResetIdentity:()=>WM()}:{}};ct=Vx({plugins:a,config:o,getPresentation:()=>Nt??"panel",getReturnSurface:()=>Tc,close:()=>Ln(),createView:({slots:X,renderDom:se,onModelChange:me,railSections:Ze})=>(Ts=b.createHistoryView({...j,railSections:yM(Ze),slots:X,renderDom:se,onModelChange:me,onAnnounce:Ic}),Ts),onElementChanged:(X,se)=>{if(!se?.isConnected)return hg(X);Ky(X),se.replaceWith(X),sg()}}),ct.view.setNewConversationRequired(Pc.recovery==="new_conversation_required"),i?.focus!==!1&&(Nt!=="rail"||i?.keyboard===!0)&&Fc(),Gt(),kn(),Br(),A.emit("history:opened",{presentation:Nt,returnSurface:Tc,timestamp:Date.now()})},$c=()=>{},Ln=i=>{if(!Et)return;Wa+=1;let c=Tc,g=Xu,f=ct,b=i?.restoreFocus!==!1;Et=!1;let C=!1,W=null,U=()=>{if(!C){if(C=!0,$c=()=>{},W!==null&&clearTimeout(W),Ut=!1,$a(),Dc(),f?.dispose(),f?.view.destroy(),f?.element.remove(),ct===f&&(ct=null,Ts=null,Oa=null,Nt=null,Ec=null,Xu=null),Gt(),kn(),Br(),b){let j=g??gn;j?.isConnected?j.focus():Ss()}A.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},$=f&&f.element===f.view.element?f.view.playExit():null;if(!$){U();return}$c=U,W=setTimeout(U,oM),$.then(U)},Yy=i=>{if(!(i.key!=="Escape"||!Et||!ct)){if(Nt==="rail"){let c=i.target;if(!(c instanceof Node)||!(ct.element.contains(c)||Ut&&rr?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Ln()}};ue.addEventListener("keydown",Yy),he.push(()=>ue.removeEventListener("keydown",Yy));let Uc=null,Qy=!1,qa=()=>{if(!Sr)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&Uc?.trim()||null;Sr.textContent=c??o.launcher?.title??"Chat Assistant";let g=Sr.closest(".persona-combo-btn");if(!g)return;let f=!i||P.getActiveConversationId()!==null;g.setAttribute("data-persona-menu-locked",f?"false":"true"),g.setAttribute("aria-haspopup",f?"true":"false"),f||g.setAttribute("aria-expanded","false"),g.style.cursor=f?"pointer":"default";let b=g.querySelector("svg");b&&(b.style.display=f?"":"none")},PM=i=>{i!==Uc&&(Uc=i,qa())},Ls=i=>{Qy=i?.starred===!0,PM(i&&i.title.trim()||null),qa()};qa(),ue.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,g=P.getActiveConversationId();g&&(c==="delete"?ob(g):c==="star"&&P.canUpdateConversations()&&Cg(g,{starred:!Qy}).catch(()=>{}))});let jc=0,kM=250,qc=null,zc=()=>{qc&&clearTimeout(qc),qc=null};he.push(zc);let Xy=()=>{zc();let i=As;i&&(Ra=!0,i.hidden=!1,Le.style.display="none",Ha())},Vc=()=>{jc+=1,zc(),As&&(As.remove(),As=null,Ra=!1,Le.style.removeProperty("display"),eo(Re,!1),Ha())},LM=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;Le.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},yg=(i,c)=>Y("div",{className:hn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),Jy=()=>Y("div",{className:"persona-conversation-loading-body"},yg("58%",!1),yg("72%",!0),yg("44%",!1)),Zy=i=>{As?.remove(),As=i,i.hidden=!Ra,oe.insertBefore(i,Le),zc(),Ra||(qc=setTimeout(Xy,kM)),eo(Re,!0)},IM=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Jy},c=null,g=a.find(f=>f.renderLoadingIndicator);g?.renderLoadingIndicator&&(c=g.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),Zy(Y("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Je.openConversationLoadingLabel}},c??Jy()))},RM=i=>{let c=()=>{bg(i,{focusComposer:!0}).catch(()=>{})},g=Wo()?()=>{Vc(),ja()}:void 0,f=(U,$)=>{let j=Y("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:U});return j.addEventListener("click",$),j},b=()=>Y("div",{className:"persona-conversation-loading-error-body"},Y("p",{className:"persona-conversation-loading-error-title",text:Je.openConversationErrorTitle}),Y("div",{className:"persona-conversation-loading-error-actions"},f(Je.openConversationRetryLabel,c),g?f(Je.openConversationBackLabel,g):null)),C=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Je.openConversationErrorTitle,retryLabel:Je.openConversationRetryLabel,backLabel:Je.openConversationBackLabel}),retry:c,...g?{back:g}:{},defaultRenderer:b}),W=null;for(let U of a)if(U.renderHistoryOpenError){try{W=U.renderHistoryOpenError(C)}catch($){console.warn("[persona] renderHistoryOpenError threw",$),W=null}if(W)break}Zy(Y("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},W??b())),Xy()};A.on("history:closed",()=>{As&&eo(Re,!0)});let bg=async(i,{focusComposer:c=!1}={})=>{let g=vi(),f=!!ct;ct?.view.setActiveConversationId(i),Vc();let b=jc;IM(),Et&&(Nt==="panel"||Ut)&&Ln({restoreFocus:!1}),di=!0;try{await P.openConversation(i,{scope:g})}catch(C){throw b===jc&&RM(i),C}finally{di=!1}b===jc&&(Vc(),$t.clear(),fo(),Pn(),Iu()||hc(),LM(),ir(),f||Ls(null),A.emit("history:conversationOpened",{conversationId:i,title:Uc,scope:g,timestamp:Date.now()}),c&&Ss())},vg=async({focusComposer:i=!1}={})=>{Vc(),await P.startNewConversation({scope:vi()}),Ls(null),$t.clear(),fo(),Pn(),hc(),ir();let c=P.getActiveConversationId();ct?.view.setActiveConversationId(c),A.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),Et&&(Nt==="panel"||Ut)&&Ln({restoreFocus:!1}),i&&Ss()},Cg=async(i,c)=>{let g=await P.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return ct?.view.applyConversationSummary(g),!ct&&i===P.getActiveConversationId()&&Ls(g),g},eb=async i=>{let c=vi(),g=P.getActiveConversationId()===i;await P.deleteConversation(i,{scope:c}),ct?.view.removeConversationSummary(i),g&&(Ls(null),$t.clear(),fo(),Pn(),ir()),A.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:g,timestamp:Date.now()})},tb=async i=>{let c=i?.scope??vi(),g=i?.allTargets?null:i?.targetId??Ay(),f=await P.clearConversationHistory({...g?{targetId:g}:{},scope:c});return Ls(null),$t.clear(),fo(),Pn(),ir(),A.emit("history:cleared",{deleted:f.deleted,scope:c,targetId:g,timestamp:Date.now()}),f},nb=async()=>{if(!Vn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await P.resetHistoryDevice()).remoteRevocationConfirmed}finally{Ls(null),P.clearArtifacts(),$t.clear(),Vu=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),ee={},ve.syncFromMetadata(),G?.clear&&gc(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),fo(),Pn(),ir(),Ln({restoreFocus:!1}),Ss(),we||Pt?.launcher.element.focus()}return Ic(i?Je.identityResetNotice:Je.identityResetUnconfirmedNotice),A.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},wg=()=>ko?Me:ue,ob=async i=>await Ip({host:wg(),title:Je.deleteConversationConfirmTitle,description:Je.deleteConversationConfirm,confirmLabel:Je.deleteConversationConfirmLabel,cancelLabel:Je.confirmCancelLabel})?(await eb(i),"deleted"):"cancelled",HM=async()=>{let i=vi()==="verified-user";return await Ip({host:wg(),title:Je.clearHistoryConfirmTitle,description:i?Je.clearHistoryVerifiedConfirm:Je.clearHistoryConfirm,confirmLabel:Je.clearHistoryConfirmLabel,cancelLabel:Je.confirmCancelLabel})?(await tb(),"cleared"):"cancelled"},WM=async()=>{if(!await Ip({host:wg(),title:Je.resetIdentityConfirmTitle,description:Je.resetIdentityConfirm,confirmLabel:Je.resetIdentityConfirmLabel,cancelLabel:Je.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await nb();return{outcome:"reset",remoteRevocationConfirmed:c}},no=E("button","persona-history-earlier");no.type="button",no.textContent=Je.showEarlierMessagesLabel,no.setAttribute("data-persona-history-earlier",""),Object.assign(no.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 ir=()=>{if(!(Wo()&&!!Pc.nextMessageCursor&&!!P.getActiveConversationId())){no.remove();return}no.textContent=Je.showEarlierMessagesLabel,no.parentNode!==oe&&oe.insertBefore(no,oe.firstChild)};no.addEventListener("click",()=>{let i=P.getActiveConversationId(),c=Pc.nextMessageCursor;if(!i||!c||no.disabled)return;no.disabled=!0;let g=oe.scrollHeight,f=oe.scrollTop;P.loadOlderMessages(i,c,{scope:vi()}).then(()=>{oe.scrollTop=f+(oe.scrollHeight-g),kn()}).catch(()=>{}).finally(()=>{no.disabled=!1,ir()})});let OM=()=>{let i=js({ariaLabel:Je.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(!(!Wo()||Sy())){if(Et){Ln();return}ja({invoker:i.button,keyboard:c.detail===0})}}),i},rb=()=>{if(!Wo()){Ho?.remove(),gn=null,Ho=null;return}if(Ho&&!Ho.isConnected&&(gn=null,Ho=null),!gn&&Pe){let f=OM();gn=f.button,Ho=f.wrapper;let b=Ne.clearChatButtonWrapper||Ne.closeButtonWrapper;b?.parentNode&&Pe.contains(b)?b.parentNode.insertBefore(Ho,b):Pe.appendChild(Ho)}if(!gn||!Ho)return;let i=Ai()||Et&&Nt==="rail";if(Ho.style.display=i?"none":"",i){document.activeElement===gn&&Fc();return}let c=Sy();gn.disabled=c,gn.setAttribute("aria-disabled",c?"true":"false");let g=c?Je.openHistoryBusyLabel:Je.openHistoryLabel;gn.setAttribute("aria-label",g),(o.features?.history?.presentation??"panel")==="panel"?(gn.removeAttribute("aria-expanded"),gn.removeAttribute("aria-controls")):(gn.setAttribute("aria-expanded",Et?"true":"false"),gn.setAttribute("aria-controls",eg))},Kc=!1,BM=()=>{let i=Ne.clearChatButton;if(i){if(Wo()){Kc||(Zu=i.getAttribute("aria-label")??"",Kc=!0),i.setAttribute("aria-label",Je.newConversationLabel),i.removeAttribute("title");return}Kc&&(Kc=!1,Zu&&i.setAttribute("aria-label",Zu))}},Br=()=>{Je=Hf(o.features?.history?.copy),rb(),Ua(),BM(),ir()};nu=Br,Zf=i=>{Pc=i,ct?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),Ia(i.sendBlocked||jn),ir()},eh=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&($t.clear(),fo(),Pn()),Ic(i.message),ct?.view.refresh()},Py(),Br(),he.push(()=>{kc?.(),Lc?.(),Wa+=1,$c(),ct?.dispose(),ct?.view.destroy(),ct=null}),o.clientToken&&P.initClientSession().then(()=>{if(Wo())return P.reconcileBootConversation({scope:ng()})}).then(()=>{ir()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(S||o.onSSEEvent)&&P.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),eu(i,c)});let sb=()=>{let i=o.resume??(le?nr.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&P.resumeFromHandle(i)};M?M.then(i=>{if(i){if(i.metadata&&(ee=Wf(i.metadata),ve.syncFromMetadata()),i.messages?.length){di=!0;try{P.hydrateMessages(i.messages)}finally{di=!1}Cc()}i.artifacts?.length&&P.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),ty(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{Du=!0,B(),sb()}):(ty(R),sb());let _M=()=>{!Ce()||we||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ft(!0,"auto")},DM=(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),U0(b)}}:i:c,xg=()=>{let c=ce.getInlineMessageFields?.();return c&&c.contentSegments.some(f=>f.kind==="mention")?c.contentSegments:void 0},ar=!1,Is=null,Gc=()=>{ce.value="",ce.style.height="auto",Eo(),Va()},Sg="data-persona-composer-notice",Ei=null;function NM(i){Gl(i),!(Ce()||!lt)&&(lt.hasAttribute(da)||(lt.setAttribute(Sg,""),lt.setAttribute("role","status"),lt.setAttribute("aria-live","polite"),lt.textContent=i,Ei&&clearTimeout(Ei),Ei=setTimeout(()=>{if(Ei=null,!!lt?.hasAttribute(Sg)&&(lt.removeAttribute(Sg),lt.removeAttribute("role"),lt.removeAttribute("aria-live"),p)){let c=P.getStatus();zl(lt,th(c),o.statusIndicator??{},c)}},4e3)))}function FM(){let i=xe.getState().pendingSubmission;i&&(ni(void 0),ce&&(ce.value=i.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),Eo()),i.options.selectedModelId&&(xe.setSelectedModelId(i.options.selectedModelId),Mr?.repaint()),i.options.activeModeIds?.length&&Jl(i.options.activeModeIds),i.options.quote&&To(i.options.quote),ce?.focus())}let $M=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},ib=(i={})=>{let c=(i.overrideText??ce?.value??"").trim();return i.resolveInlineCommand&&c?(Bt?.takeInlineCommand(c)??Promise.resolve(null)).then(g=>ab(i,c,g)):ab(i,c,null)},ab=(i,c,g)=>{if(g?.kind==="action"){Gc(),Bt?.clear(),is();return}let f=g?.kind==="server"?g.mentions:null,b=g?.kind==="prompt"?g.sendText:c,C=i.pending?.contentParts,W=(tt?.hasAttachments()??!1)||(C?.length??0)>0;if(!lw({text:b,hasAttachments:W,attachmentsReady:tt?.isReady()??!0,hasMentions:Bt?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:Ro(),sendDisabled:xs()}))return;let U=P.isStreaming()?pu():"block";if(U==="defer-one"&&!i.pending){if(xe.getState().pendingSubmission){NM("One message is already queued. Edit or remove it first.");return}UM({intent:i,sendText:b,serverMentions:f});return}let $={text:b,mentionRefs:[...Bt?.getMentionRefs()??[],...f?.refs??[]],contentSegments:g?.kind==="prompt"?void 0:xg(),options:{...xe.getState().selectedModelId&&{selectedModelId:xe.getState().selectedModelId},...xe.getState().activeModeIds.length>0&&{activeModeIds:[...xe.getState().activeModeIds]},...xe.getState().quote&&{quote:{...xe.getState().quote}}},viaVoice:i.viaVoice};i.pending&&($.options={...i.pending.options},$.contentSegments=i.pending.contentSegments,$.mentionRefs=[...i.pending.mentionRefs],$.viaVoice=i.pending.viaVoice);let j=()=>{if(C?.length)return[...C];if(!tt?.hasAttachments())return;let ht=[...tt.getContentParts()];return $.text&&ht.push(io($.text)),ht};$.contentParts=j();let X=()=>{fs(),_M();let ht=Bt?.collectForSubmit()??null,Jt=DM(ht,f),jt=j();i.consumeDraft!==!1&&Gc();let Lt={selectedModelId:$.options.selectedModelId,activeModeIds:$.options.activeModeIds},cn=U==="interrupt";cn&&P.cancel(),P.sendMessage($.text,{contentParts:jt,mentions:Jt??void 0,contentSegments:$.contentSegments,viaVoice:$.viaVoice,composerOptions:Lt,...$.options.quote&&{quote:$.options.quote},...cn&&{interrupt:!0}}),tt?.hasAttachments()&&tt.clearAttachments(),ht&&Bt?.clear(),is();let nt=xe.getState().activeModeIds,dn=GC(nt,o.composer?.modes);dn.length!==nt.length&&Jl(dn),xe.getState().quote&&To(void 0),fc(),hu.release(),po()},se=o.composer?.onBeforeSend;if(!se){X();return}let me=new AbortController;Is=me;let Ze=ht=>{if(Is=null,ht.status==="error"){$M(ht.error);return}ht.status==="proceed"&&X()},ut=cw(se,$,me.signal);if(!(ut instanceof Promise)){Ze(ut);return}return xe.setPreparing(!0),ut.then(Ze).finally(()=>xe.setPreparing(!1))};function UM(i){let c=xe.getState(),g=tt?.hasAttachments()??!1,f=g?[...tt.getContentParts()]:[];g&&i.sendText&&f.push(io(i.sendText));let b=Lm({text:i.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Bt?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:xg(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});ni(b),i.intent.consumeDraft!==!1&&Gc(),g&&tt.clearAttachments(),Bt?.clear(),is(),c.quote&&To(void 0),fc(),hu.release(),po(),Gl("Message queued. It sends when the response finishes.")}function jM(){let i=xe.getState().pendingSubmission;i&&(ni(void 0),Qc(i.text,{consumeDraft:!1,pending:i}))}function qM(i){if(o.messageActions?.showEdit!==!0)return;let c=P.getMessages().find(g=>g.id===i);!c||!am(c)||ms!==i&&(fs(),ms=i,kr=ZC({messageId:i,initialText:c.content,onSave:g=>zM(i,g),onCancel:()=>fs()}),$t.delete(i),Zn(Le,P.getMessages(),mt),kr.focus())}function zM(i,c){let g=kr;if(ms=null,kr=null,g?.destroy(),$t.delete(i),!P.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){Zn(Le,P.getMessages(),mt);return}kn()}function VM(i){if(P.isStreaming())return;let c=im(P.getMessages(),i);c&&(fs(),P.resubmitFrom(c,{reason:"retry"})&&kn())}Zl={regenerate:VM,edit:qM,quote:i=>{let g=P.getMessages().find(f=>f.id===i)?.content?.trim();g&&(To({text:g,messageId:i}),ce?.focus())}};let za=async i=>{if(!ar){ar=!0;try{await ib({resolveInlineCommand:!0,...i})}finally{ar=!1}}};function Yc(i){xs()||(Gc(),Qc(i,{consumeDraft:!1}))}let Qc=(i,c)=>{if(ar)return;ar=!0;let g=()=>{ar=!1};try{let f=ib({...c,overrideText:i});f instanceof Promise?f.finally(g):g()}catch(f){throw g(),f}},KM=i=>{if(i.preventDefault(),P.isStreaming()){P.cancel(),at?.reset(),bt?.update();return}ar||za()},GM=()=>o.features?.composerHistory!==!1,Ag={...Nm},Mg=!1,Va=()=>{Ag={...Nm}},YM=()=>P.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),QM=i=>{if(!ce)return;Mg=!0,ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),Mg=!1;let c=ce.value.length;ce.setSelectionRange(c,c)},XM=i=>{Mg||(i.isComposing||Bt?.handleInput(i.inputType??void 0),Va())},JM=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:hl(ce)}),ZM=i=>{if(ce&&!Ro()&&!(!i.isComposing&&Bt?.handleKeydown(i))){if(GM()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let c=ce.selectionStart===0&&ce.selectionEnd===0,g=Tw({direction:i.key==="ArrowUp"?"up":"down",history:YM(),currentValue:ce.value,atStart:c,state:Ag});if(Ag=g.state,g.handled){i.preventDefault(),g.value!==void 0&&QM(g.value);return}}if(RC(i,JM())){if(P.isStreaming()){if(i.preventDefault(),pu()==="block"||ar||xs())return;Va(),za();return}if(ar){i.preventDefault();return}if(xs()){i.preventDefault();return}Va(),i.preventDefault(),Te.click()}}},lb=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(ue)){if(Is){Is.abort(),Is=null,i.preventDefault(),i.stopImmediatePropagation();return}P.isStreaming()&&(P.cancel(),at?.reset(),bt?.update(),Va(),i.preventDefault(),i.stopImmediatePropagation())}},eE=async i=>{if(o.attachments?.enabled!==!0||!tt||Ro())return;let c=D0(i.clipboardData);c.length!==0&&(i.preventDefault(),await tt.handleFiles(c))},oo=null,Oo=!1,Ti=null,xt=null,Eg=()=>o.voiceRecognition?.completionBehavior==="review";function Rs(i){re?.setAttribute("data-state",i),i==="recording"?nE():Lg()}let cb="--persona-voice-level",Tg=.5,Pi=null,Pg=-1,Xc=0,db=()=>{let i=[],c=$n??re?.parentElement??null;return c&&i.push(c),Re&&i.push(Re),i},kg=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==Pg){Pg=c;for(let g of db())g.style.setProperty(cb,String(c))}},tE=()=>{Pg=-1,Xc=0;for(let i of db())i.style.removeProperty(cb)};function nE(){if(Pi!==null)return;if(typeof requestAnimationFrame!="function"){kg(p?P.getVoiceLevel()??Tg:Tg);return}let i=()=>{Pi=requestAnimationFrame(i);let c=p?P.getVoiceLevel():null;if(c===null){kg(Tg);return}Xc+=(c-Xc)*.3,kg(Xc)};Pi=requestAnimationFrame(i)}function Lg(){Pi!==null&&(cancelAnimationFrame(Pi),Pi=null),tE()}let pb=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Jc=(i="user")=>{if(Oo||P.isStreaming())return;let c=pb();if(!c)return;oo=new c;let g=o.voiceRecognition??{},f=g.pauseDuration??2e3;oo.continuous=g.provider?.browser?.continuous??!0,oo.interimResults=!0,oo.lang=g.provider?.browser?.language??"en-US";let b=ce.value;oo.onresult=C=>{let W="",U="";for(let j=0;j<C.results.length;j++){let X=C.results[j],se=X[0].transcript;X.isFinal?W+=se+" ":U=se}let $=b+W+U;ce.value=$,Eo(),Ti&&clearTimeout(Ti),(W||U)&&(Ti=window.setTimeout(()=>{if(ce.value.trim()&&oo&&Oo){if(_r(),Eg())return;za({viaVoice:!0})}},f))},oo.onerror=C=>{C.error!=="no-speech"&&_r()},oo.onend=()=>{if(Oo){let C=ce.value.trim();!Eg()&&C&&C!==b.trim()&&za({viaVoice:!0}),_r()}};try{if(oo.start(),Oo=!0,Ke.active=!0,i!=="system"&&(Ke.manuallyDeactivated=!1),Zo(i),mo(),po(),re){let C=o.voiceRecognition??{};xt={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:C.iconName??"mic",iconSize:parseFloat(C.iconSize??"")||yn};let W=C.recordingBackgroundColor,U=C.recordingIconColor,$=C.recordingBorderColor;if(re.classList.add("persona-voice-recording"),Rs("recording"),re.style.backgroundColor=W??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=U??"var(--persona-voice-recording-indicator, #ffffff)",U){let j=re.querySelector("svg");j&&j.setAttribute("stroke",U)}$&&(re.style.borderColor=$),re.setAttribute("aria-label","Stop voice recognition")}}catch{_r("system")}},_r=(i="user")=>{if(Oo){if(Oo=!1,Ti&&(clearTimeout(Ti),Ti=null),oo){try{oo.stop()}catch{}oo=null}if(Ke.active=!1,Zo(i),mo(),po(),re){if(re.classList.remove("persona-voice-recording"),Rs("idle"),xt){re.style.backgroundColor=xt.backgroundColor,re.style.color=xt.color,re.style.borderColor=xt.borderColor;let c=re.querySelector("svg");c&&c.setAttribute("stroke",xt.color||"currentColor"),xt=null}re.setAttribute("aria-label","Start voice recognition")}}},Ig=()=>{if(!re||xt)return;let i=o.voiceRecognition??{};xt={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||yn}},Rg=(i,c)=>{if(!re)return;let g=re.querySelector("svg");g&&g.remove();let f=xt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||yn),b=de(i,f,c,1.5);b&&re.appendChild(b)},Zc=()=>{re&&re.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ki=()=>{if(!re)return;Ig();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,g=i.recordingIconColor,f=i.recordingBorderColor;if(Zc(),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")},oE=()=>{if(!re)return;Ig();let i=o.voiceRecognition??{},c=P.getVoiceInterruptionMode(),g=i.processingIconName??"loader",f=i.processingIconColor??xt?.color??"",b=i.processingBackgroundColor??xt?.backgroundColor??"",C=i.processingBorderColor??xt?.borderColor??"";Zc(),re.classList.add("persona-voice-processing"),Rs("processing"),re.style.backgroundColor=b,re.style.borderColor=C;let W=f||"currentColor";re.style.color=W,Rg(g,W),re.setAttribute("aria-label","Processing voice input"),c==="none"&&(re.style.cursor="default")},rE=()=>{if(!re)return;Ig();let i=o.voiceRecognition??{},c=P.getVoiceInterruptionMode(),g=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",f=i.speakingIconName??g,b=i.speakingIconColor??(c==="barge-in"?i.recordingIconColor??xt?.color??"":xt?.color??""),C=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":xt?.backgroundColor??""),W=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":xt?.borderColor??"");Zc(),re.classList.add("persona-voice-speaking"),Rs("speaking"),re.style.backgroundColor=C,re.style.borderColor=W;let U=b||"currentColor";re.style.color=U,Rg(f,U);let $=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";re.setAttribute("aria-label",$),c==="none"&&(re.style.cursor="default"),c==="barge-in"&&re.classList.add("persona-voice-recording")},lr=()=>{re&&(Zc(),Rs("idle"),xt&&(re.style.backgroundColor=xt.backgroundColor??"",re.style.color=xt.color??"",re.style.borderColor=xt.borderColor??"",Rg(xt.iconName,xt.color||"currentColor"),xt=null),re.style.cursor="",re.setAttribute("aria-label","Start voice recognition"))},Hg=()=>{if(!Ro()){if(Wn(o.voiceRecognition?.provider)){let i=P.getVoiceStatus(),c=P.getVoiceInterruptionMode();if(c==="none"&&(i==="processing"||i==="speaking"))return;if(c==="cancel"&&(i==="processing"||i==="speaking")){P.stopVoicePlayback();return}if(P.isBargeInActive()){P.stopVoicePlayback(),P.deactivateBargeIn().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,mo(),Zo("user"),lr()});return}P.toggleVoice().then(()=>{Ke.active=P.isVoiceActive(),Ke.manuallyDeactivated=!P.isVoiceActive(),mo(),Zo("user"),P.isVoiceActive()?ki():lr()});return}if(Oo){let i=ce.value.trim();Ke.manuallyDeactivated=!0,mo(),_r("user"),i&&!Eg()&&za()}else Ke.manuallyDeactivated=!1,mo(),Jc("user")}};uu=Hg,re&&he.push(()=>{Wn(o.voiceRecognition?.provider)?(P.isVoiceActive()&&P.toggleVoice(),lr()):_r("system")});let sE=A.on("assistant:complete",()=>{xe.getState().pendingSubmission&&setTimeout(()=>{P.isStreaming()||jM()},0)});he.push(sE);let iE=A.on("assistant:complete",()=>{Jh&&(Ke.active||Ke.manuallyDeactivated||Jh==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(Wn(o.voiceRecognition?.provider)?P.toggleVoice().then(()=>{Ke.active=P.isVoiceActive(),Zo("auto"),P.isVoiceActive()&&ki()}):Jc("auto"))},600))});he.push(iE);let aE=A.on("action:resubmit",()=>{setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)});he.push(aE);let ub=()=>{ft(!we,"user")},Pt=null,mn=null;if(pe&&!Ce()){let{instance:i,element:c}=gf({config:o,plugins:a,onToggle:ub});Pt=i,i||(mn=c)}Pt?e.appendChild(Pt.element):mn&&e.appendChild(mn),La(),li(),Sc(),ju(),Ia(P.isStreaming()),Iu()||(Un()==="follow"?Rr(!0):hc()),EA(),ye&&(!pe||Ce()?setTimeout(()=>Ss(),0):we&&setTimeout(()=>Ss(),200));let Hs=null,gb=()=>{Hs&&(Hs.disconnect(),Hs.observe(Re),Hs.observe(ue))},Ka=()=>{if(Ce()){ss(),La();return}let i=At(o),c=o.launcher?.sidebarMode??!1,g=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640,C=g.innerWidth<=b,W=f&&C&&pe;try{if(W){as(),Ca=ac();return}let U=!1;Dt&&(Dt=!1,as(),U=!0);let $=ac();if(!U&&$!==Ca&&(as(),U=!0),Ca=$,U&&oc(),!pe&&!i){Me.style.height="",Me.style.width="";return}if(!c&&!i){let X=o?.launcher?.width??o?.launcherWidth??Gn;Me.style.width=X,Me.style.maxWidth=X}ic(),Bh()}finally{if(ss(),Xl(),La(),we&&pe){let $=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),j=o.launcher?.sidebarMode??!1,X=o.launcher?.mobileFullscreen??!0,se=At(o)&&X&&$,me=j||X&&$&&pe||se;if(me&&!Io){let Ze=e.getRootNode(),ut=Ze instanceof ShadowRoot?Ze.host:e.closest(".persona-host");ut&&!Lo&&(Lo=jm(ut,o.launcher?.zIndex??an)),Io=qm(e.ownerDocument)}else me||(Lo?.(),Lo=null,Io?.(),Io=null)}}};Ka();let ed=e.ownerDocument.defaultView??window;if(ed.addEventListener("resize",Ka),he.push(()=>ed.removeEventListener("resize",Ka)),typeof ResizeObserver<"u"){Hs=new ResizeObserver(()=>{Xl()}),gb(),he.push(()=>{Hs?.disconnect(),Hs=null});let i=new ResizeObserver(()=>{Nc()});i.observe(ue),he.push(()=>i.disconnect())}ed.addEventListener("resize",Nc),he.push(()=>ed.removeEventListener("resize",Nc)),zn=oe.scrollTop;let mb=jo(oe),fb=()=>{let i=oe.scrollTop,c=jo(oe),g=c<mb;if(mb=c,!Ar()){zn=i,Gt();return}let{action:f,nextLastScrollTop:b}=Ow({following:qn.isFollowing(),currentScrollTop:i,lastScrollTop:zn,nearBottom:Us(oe,Xo),userScrollThreshold:xA,isAutoScrolling:Tn||cc||g,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(zn=b,f==="resume"){yc()||Pn();return}f==="pause"&&Ma()};if(oe.addEventListener("scroll",fb,{passive:!0}),he.push(()=>oe.removeEventListener("scroll",fb)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{HA(),jg(Le)});i.observe(Le),i.observe(oe),he.push(()=>i.disconnect())}let hb=()=>{Ar()&&qn.isFollowing()&&yc()&&Ma()},yb=oe.ownerDocument;yb.addEventListener("selectionchange",hb),he.push(()=>{yb.removeEventListener("selectionchange",hb)});let lE=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),bb=i=>{lE.has(i.key)&&(vs(),oh()&&Ar()&&qn.isFollowing()&&Ma())},vb=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(vs(),oh()&&Ar()&&qn.isFollowing()&&Ma())};oe.addEventListener("keydown",bb),oe.addEventListener("focusin",vb),he.push(()=>{oe.removeEventListener("keydown",bb),oe.removeEventListener("focusin",vb)});let Cb=i=>{if(i.deltaY!==0&&vs(),!Ar())return;let c=Bw({following:qn.isFollowing(),deltaY:i.deltaY,nearBottom:Us(oe,Xo),resumeWhenNearBottom:!0});c==="pause"?Ma():c==="resume"&&!yc()&&Pn()};oe.addEventListener("wheel",Cb,{passive:!0}),oe.addEventListener("touchmove",vs,{passive:!0}),oe.addEventListener("pointerdown",vs,{passive:!0}),he.push(()=>{oe.removeEventListener("touchmove",vs),oe.removeEventListener("pointerdown",vs)}),he.push(()=>oe.removeEventListener("wheel",Cb)),Ft.addEventListener("click",()=>{fo(),oe.scrollTop=oe.scrollHeight,zn=oe.scrollTop,Pn(),Rr(!0),Gt()}),he.push(()=>Ft.remove()),he.push(()=>{oy(),fo()});let wb=()=>{Ue&&(ps&&(Ue.removeEventListener("click",ps),ps=null),De()?(Ue.style.display="",ps=()=>{ft(!1,"user")},Ue.addEventListener("click",ps)):Ue.style.display="none")};wb(),(()=>{let{clearChatButton:i}=Ne;i&&i.addEventListener("click",()=>{if(Wo()){vg({focusComposer:!0}).catch(g=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",g)});return}P.clearMessages(),$t.clear(),Pn(),Vr(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),G?.clear&&gc(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ee={},ve.syncFromMetadata(),tt?.clearAttachments(),fc(),ni(void 0),To(void 0),fs(),Oe?.clear(),at?.reset(),bt?.update()})})();let xb=[["keydown",ZM],["input",XM],["input",Eo],["input",is],["keyup",is],["paste",eE],["focus",dA]],Sb=i=>{if(i)for(let[c,g]of xb)rt?.addListener(i,c,g)},cE=i=>{if(i)for(let[c,g]of xb)rt?.removeListener(i,c,g)},Ab=()=>{rt&&(rt.addListener(rt.form,"submit",KM),rt.addListener(rt.footer,"click",is),Sb(ce),re&&rt.addListener(re,"click",Hg))};Ab();let Mb=()=>{Bt?.onComposerSwap((i,c)=>{cE(c),ce=i,rt&&(rt.input=i),Sb(i),mu(),Bu(),Eo()})};Mb();let Wg=!1;function Eb(){if(!Wg){Wg=!0;try{let i=ce?.value??"",c=Re.ownerDocument??document,g=ce?c.activeElement===ce:!1;Lg(),rt?.destroy(),rt=null,Bt?.destroy(),Bt=null;let f=null,b=()=>(f=Ce()?gp({config:o}):Vs({config:o}),f.footer),C=gh(b)??b();Nn.replaceComposer(C),Re=Nn.composer.footer;let W=f!==null&&C===f.footer;ri=!W,nh=W?f.setSendButtonMode:()=>{},uh(Re),fh(Re),hh(),yh(),bh(),Mb(),vh(),fu(),Ch(),Ab();let U=ds.indexOf(Qo);Qo.destroy(),Qo=Il(xr),U>=0&&(ds[U]=Qo),ce&&(ce.value=i),Eo(),is(),Sc(),li(),Ia(P.isStreaming()),Ke.active&&Rs("recording"),as(),gb(),ss(),po(),wc(),g&&ce?.focus()}finally{Wg=!1}}}let Ga=e.ownerDocument??document;Ga.addEventListener("keydown",lb,!0);let Tb=()=>{Tu()},Pb=()=>{Ga.visibilityState==="hidden"&&Tu()};typeof window<"u"&&(window.addEventListener("pagehide",Tb),Ga.addEventListener("visibilitychange",Pb),he.push(()=>{window.removeEventListener("pagehide",Tb),Ga.removeEventListener("visibilitychange",Pb)}));let kb="persona-attachment-drop-active",Ya=0,Og=()=>{Ya=0,ue.classList.remove(kb)},Li=()=>o.attachments?.enabled===!0&&tt!==null&&!Ro(),Lb=i=>{!_p(i.dataTransfer)||!Li()||(Ya++,Ya===1&&ue.classList.add(kb))},Ib=i=>{!_p(i.dataTransfer)||!Li()||(Ya--,Ya<=0&&Og())},Rb=i=>{!_p(i.dataTransfer)||!Li()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Hb=i=>{if(!_p(i.dataTransfer)||!Li())return;i.preventDefault(),i.stopPropagation(),Og();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&tt.handleFiles(c)},Dr=!0;ue.addEventListener("dragenter",Lb,Dr),ue.addEventListener("dragleave",Ib,Dr),e.addEventListener("dragover",Rb,Dr),e.addEventListener("drop",Hb,Dr);let td=e.ownerDocument,Wb=i=>{Li()&&i.preventDefault()},Ob=i=>{Li()&&i.preventDefault()};td.addEventListener("dragover",Wb),td.addEventListener("drop",Ob),he.push(()=>{rt?.destroy(),rt=null,Lg(),Po?.destroy(),Po=null,Go?.destroy(),Go=null,Er?.destroy(),Er=null,Tr?.destroy(),Tr=null,Mr=null,du=null,Tu(),Aa.destroy(),Ei&&clearTimeout(Ei),fs(),Is?.abort(),Is=null,tt?.destroy(),tt=null,xe.destroy(),Ga.removeEventListener("keydown",lb,!0),Bt?.destroy()}),he.push(()=>{ue.removeEventListener("dragenter",Lb,Dr),ue.removeEventListener("dragleave",Ib,Dr),e.removeEventListener("dragover",Rb,Dr),e.removeEventListener("drop",Hb,Dr),td.removeEventListener("dragover",Wb),td.removeEventListener("drop",Ob),Og()}),he.push(()=>{P.cancel()}),Pt?he.push(()=>{Pt?.destroy()}):mn&&he.push(()=>{mn?.remove()});let kt={update(i){let c=o.toolCall,g=o.messageActions,f=o.layout?.messages,b=o.colorScheme,C=o.loadingIndicator,W=o.iterationDisplay,U=o.features?.showReasoning,$=o.features?.showToolCalls,j=o.features?.toolCallDisplay,X=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type,me=o.features?.history?.enabled===!0,Ze=o.features?.history?.provider,ut=o.getIdentityProof,ht=o.clientToken,Jt=o.contextMentions;o=kp({...o,features:s},i),s=o.features,o=Bl(o),r(),wu(),$s(e,o),Wl(e,o),Ol(e,o),Vo(),go(),o.colorScheme!==b&&_h();let jt=_l.getForInstance(o.plugins);a.length=0,a.push(...jt),By(),pe=o.launcher?.enabled??!0,et=o.launcher?.autoExpand??!1,xn=o.features?.showReasoning??!0,q=o.features?.showToolCalls??!0,N=o.features?.scrollToBottom??{};let Lt=Un();z=o.features?.scrollBehavior??{},Lt!==Un()&&(fo(),Pn()),Xh(),ih(),Gt();let cn=S;if(S=o.features?.showEventStreamToggle??!1,S&&!cn){if(Oe||(ql(),P.setSSEEventCallback((J,Ge)=>{o.onSSEEvent?.(J,Ge),eu(J,Ge)})),!ot&&Pe){let J=o.features?.eventStream?.classNames,Ge="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:"");ot=E("button",Ge),ot.style.width="28px",ot.style.height="28px",ot.style.color=vn.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let Xe=Ht(Cr.Activity,"18px","currentColor",1.5);Xe&&ot.appendChild(Xe);let st=Ne.clearChatButtonWrapper,St=Ne.closeButtonWrapper,sn=st||St;sn&&sn.parentNode===Pe?Pe.insertBefore(ot,sn):Pe.appendChild(ot),ot.addEventListener("click",()=>{Qt?oi():gu()})}}else!S&&cn&&(oi(),ot&&(ot.remove(),ot=null),Oe?.clear(),ke?.destroy(),Oe=null,ke=null,at?.reset(),at=null,Ye=null);if(o.launcher?.enabled===!1&&Pt&&(Pt.destroy(),Pt=null),o.launcher?.enabled===!1&&mn&&(mn.remove(),mn=null),o.launcher?.enabled!==!1&&!Pt&&!mn){let{instance:J,element:Ge}=gf({config:o,plugins:a,onToggle:ub});Pt=J,J||(mn=Ge),e.appendChild(Ge)}Pt&&Pt.update(o),qa(),os&&o.launcher?.subtitle!==void 0&&(os.textContent=o.launcher.subtitle);let nt=o.layout?.header;if(nt?.layout!==qe&&Pe){let J=nt?Zi(o,nt,{showClose:De(),onClose:()=>ft(!1,"user")}):hr({config:o,showClose:De(),onClose:()=>ft(!1,"user")});Nn.replaceHeader(J),Pe=Nn.header.element,Tt=Nn.header.iconHolder,Sr=Nn.header.headerTitle,os=Nn.header.headerSubtitle,Ue=Nn.header.closeButton,qe=nt?.layout,qa()}else if(nt){if(Tt&&(Tt.style.display=nt.showIcon===!1?"none":""),Sr&&(Sr.style.display=nt.showTitle===!1?"none":""),os&&(os.style.display=nt.showSubtitle===!1?"none":""),Ue){let J=De()&&nt.showCloseButton!==!1;Ue.style.display=J?"":"none"}if(Ne.clearChatButtonWrapper){let J=nt.showClearChat;if(J!==void 0){Ne.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:Ge}=Ne;Ge&&!Ge.classList.contains("persona-absolute")&&(J?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}}let Bo=o.layout?.showHeader!==!1;Pe&&(Pe.style.display=Bo?"":"none");let cr=o.layout?.showFooter!==!1;Re&&(Re.style.display=cr?"":"none"),ss(),Gt(),pe!==_e?pe?ft(et,"auto"):(we=!0,La()):et!==F&&ft(et,"auto"),F=et,_e=pe,Ka(),wb();let Ws=JSON.stringify(o.toolCall)!==JSON.stringify(c),yo=JSON.stringify(o.messageActions)!==JSON.stringify(g),on=JSON.stringify(o.layout?.messages)!==JSON.stringify(f),bo=o.loadingIndicator?.render!==C?.render||o.loadingIndicator?.renderIdle!==C?.renderIdle||o.loadingIndicator?.showBubble!==C?.showBubble,Ii=o.iterationDisplay!==W,L=(o.features?.showReasoning??!0)!==(U??!0)||(o.features?.showToolCalls??!0)!==($??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(j)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(X);(Ws||yo||on||bo||Ii||L)&&P&&(hs++,Zn(Le,P.getMessages(),mt));let Ee=o.features?.streamAnimation?.type;if(Ee!==se&&Ee&&Ee!=="none"){let J=Su(Ee,o.features?.streamAnimation?.plugins);J&&Pl(J,e)}let ie=o.launcher??{},It=ie.headerIconHidden??!1,qt=o.layout?.header?.showIcon,rn=It||qt===!1,zt=ie.headerIconName,Yt=ie.headerIconSize??"48px";if(Tt){let J=Pe,Ge=J?.querySelector(".persona-flex-col");if(rn)Tt.style.display="none",J&&Ge&&!J.contains(Ge)&&J.insertBefore(Ge,J.firstChild);else{if(Tt.style.display="",Tt.style.height=Yt,Tt.style.width=Yt,J&&Ge&&(J.contains(Tt)?Tt.nextSibling!==Ge&&(Tt.remove(),J.insertBefore(Tt,Ge)):J.insertBefore(Tt,Ge)),zt){let st=parseFloat(Yt)||24,St=de(zt,st*.6,"currentColor",1);St?Tt.replaceChildren(St):Tt.textContent=ie.agentIconText??"\u{1F4AC}"}else if(ie.iconUrl){let st=Tt.querySelector("img");if(st)st.src=ie.iconUrl,st.style.height=Yt,st.style.width=Yt;else{let St=document.createElement("img");St.src=ie.iconUrl,St.alt="",St.className="persona-rounded-xl persona-object-cover",St.style.height=Yt,St.style.width=Yt,Tt.replaceChildren(St)}}else{let st=Tt.querySelector("svg"),St=Tt.querySelector("img");(st||St)&&Tt.replaceChildren(),Tt.textContent=ie.agentIconText??"\u{1F4AC}"}let Xe=Tt.querySelector("img");Xe&&(Xe.style.height=Yt,Xe.style.width=Yt)}}let Rt=o.layout?.header?.showTitle,pn=o.layout?.header?.showSubtitle;if(Sr&&(Sr.style.display=Rt===!1?"none":""),os&&(os.style.display=pn===!1?"none":""),Ue){let J=De()&&o.layout?.header?.showCloseButton!==!1;if(Ue.style.display=J?"":"none",!Ce()){let Zt=ie.closeButtonSize??"";Ue.style.height=Zt,Ue.style.width=Zt,Ue.style.minWidth=Zt,Ue.style.minHeight=Zt}let Ge=ie.closeButtonPlacement??"inline",{closeButtonWrapper:Xe}=Ne,st=Ge==="top-right",St=Xe?.classList.contains("persona-absolute");if(Xe&&st!==St)if(Xe.remove(),st){Xe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Zt=Ba??ue;Zt.style.position="relative",Zt.appendChild(Xe)}else{let Zt=ie.clearChat?.placement??"inline",en=ie.clearChat?.enabled??!0;Xe.className=en&&Zt==="inline"?"":"persona-ml-auto",Pe&&Pe.appendChild(Xe)}if(Ue.style.color=ie.closeButtonColor||vn.actionIconColor,ie.closeButtonBackgroundColor?(Ue.style.backgroundColor=ie.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),ie.closeButtonBorderWidth||ie.closeButtonBorderColor){let Zt=ie.closeButtonBorderWidth||"0px",en=ie.closeButtonBorderColor||"transparent";Ue.style.border=`${Zt} solid ${en}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");ie.closeButtonBorderRadius?(Ue.style.borderRadius=ie.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),ie.closeButtonPaddingX?(Ue.style.paddingLeft=ie.closeButtonPaddingX,Ue.style.paddingRight=ie.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),ie.closeButtonPaddingY?(Ue.style.paddingTop=ie.closeButtonPaddingY,Ue.style.paddingBottom=ie.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom=""),cp(Ue,ie.closeButtonIconName??"x",{iconSize:Ce()?cf:void 0,iconText:ie.closeButtonIconText??"\xD7"});let sn=ie.closeButtonTooltipText??"Close chat",vo=ie.closeButtonShowTooltip??!0;Ue.setAttribute("aria-label",sn),Xe&&tn({anchor:Ue,trigger:Xe,text:()=>Ue?.getAttribute("aria-label")??sn,enabled:vo})}let{clearChatButton:We,clearChatButtonWrapper:Fe}=Ne;if(We){let J=ie.clearChat??{},Ge=J.enabled??!0,Xe=o.layout?.header?.showClearChat,st=Xe!==void 0?Xe:Ge,St=J.placement??"inline";if(Fe){Fe.style.display=st?"":"none";let{closeButtonWrapper:sn}=Ne;!Ce()&&sn&&!sn.classList.contains("persona-absolute")&&(st?sn.classList.remove("persona-ml-auto"):sn.classList.add("persona-ml-auto"));let vo=St==="top-right",Zt=Fe.classList.contains("persona-absolute");if(!Ce()&&vo!==Zt&&st){if(Fe.remove(),vo){Fe.className="persona-absolute persona-top-4 persona-z-50",Fe.style.right="48px";let _o=Ba??ue;_o.style.position="relative",_o.appendChild(Fe)}else{Fe.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Fe.style.right="";let _o=Ne.closeButtonWrapper;Pe&&_o&&_o.parentElement===Pe?Pe.insertBefore(Fe,_o):Pe&&Pe.appendChild(Fe)}let en=Ne.closeButtonWrapper;en&&!en.classList.contains("persona-absolute")&&(vo?en.classList.add("persona-ml-auto"):en.classList.remove("persona-ml-auto"))}}if(st){if(!Ce()){let en=J.size??"";We.style.height=en,We.style.width=en,We.style.minWidth=en,We.style.minHeight=en}let sn=J.iconColor??"";if(We.style.color=sn||vn.actionIconColor,cp(We,J.iconName??"refresh-cw",{iconSize:Ce()?df:void 0}),J.backgroundColor?(We.style.backgroundColor=J.backgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let en=J.borderWidth||"0px",_o=J.borderColor||"transparent";We.style.border=`${en} solid ${_o}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");J.borderRadius?(We.style.borderRadius=J.borderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),J.paddingX?(We.style.paddingLeft=J.paddingX,We.style.paddingRight=J.paddingX):(We.style.paddingLeft="",We.style.paddingRight=""),J.paddingY?(We.style.paddingTop=J.paddingY,We.style.paddingBottom=J.paddingY):(We.style.paddingTop="",We.style.paddingBottom="");let vo=J.tooltipText??"Clear chat",Zt=J.showTooltip??!0;We.setAttribute("aria-label",vo),Fe&&tn({anchor:We,trigger:Fe,text:()=>We?.getAttribute("aria-label")??vo,enabled:Zt})}}let Se=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dl],un=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Qs.message,Qs.messageAndClick];ve=Nl({parsers:Se,handlers:un,getSessionMetadata:ge,updateSessionMetadata:ae,emit:A.emit,documentRef:typeof document<"u"?document:null}),mt=eS(o,ve,Wt),XA(),P.updateConfig(o),(o.features?.history?.enabled===!0!==me||o.features?.history?.provider!==Ze||o.getIdentityProof!==ut||o.clientToken!==ht)&&(Ln({restoreFocus:!1}),Py()),Br(),Nc(),Zn(Le,P.getMessages(),mt),li(),Sc(),YA(),Ia(P.isStreaming()),Jt!==o.contextMentions&&Eb();let Nr=o.voiceRecognition?.enabled===!0,In=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Rn=Wn(o.voiceRecognition?.provider);if(Nr&&(In||Rn))if(!re||!$n){let J=Yi(o);if(J){re=J.button,$n=J.wrapper;let Ge=Mo&&Mo.parentElement===Vl?Mo:null;Vl?Vl.insertBefore($n,Ge):co?.appendChild($n),rt&&(rt.micButton=re),rt?.addListener(re,"click",Hg),re.disabled=Ro()||P.isStreaming()&&!Wu()}}else{let J=o.voiceRecognition??{},Ge=o.sendButton??{},Xe=J.iconName??"mic",st=J.iconSize,St=parseFloat(st??"")||yn;re.classList.add(Yn),re.classList.toggle(wo,!st),re.style.width=st??"",re.style.height=st??"",re.style.minWidth=st??"",re.style.minHeight=st??"";let sn=J.iconColor??Ge.textColor;re.innerHTML="";let vo=de(Xe,St,sn||"currentColor",1.5);vo?re.appendChild(vo):re.textContent="\u{1F3A4}";let Zt=J.backgroundColor??Ge.backgroundColor;Zt?re.style.backgroundColor=Zt:re.style.backgroundColor="",sn?re.style.color=sn: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 en=J.tooltipText??"Start voice recognition",_o=J.showTooltip??!1;re.setAttribute("aria-label",en),$n&&tn({anchor:re,trigger:$n,text:()=>re?.getAttribute("aria-label")??en,enabled:_o}),$n.style.display="",re.disabled=Ro()||P.isStreaming()&&!Wu()}else re&&$n&&($n.style.display="none",Wn(o.voiceRecognition?.provider)?P.isVoiceActive()&&P.toggleVoice():Oo&&_r());if(o.attachments?.enabled===!0){if(!Mn||!Mt){let J=o.attachments??{};En||(En=E("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),En.style.display="none",(ce.parentElement??co).insertBefore(En,ce)),vt||(vt=document.createElement("input"),vt.type="file",vt.accept=(J.allowedTypes??fr).join(","),vt.multiple=(J.maxFiles??4)>1,vt.style.display="none",vt.setAttribute("aria-label","Attach files"),(ce.parentElement??co).insertBefore(vt,ce)),Mn=E("div","persona-send-button-wrapper"),Mt=E("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Yn} ${wo}`),Mt.type="button",Mt.setAttribute("aria-label",J.buttonTooltipText??"Attach file");let Ge=J.buttonIconName??"paperclip";Mt.style.fontSize="18px",Mt.style.lineHeight="1";let Xe=de(Ge,yn,"currentColor",1.5);Xe?Mt.appendChild(Xe):Mt.textContent="\u{1F4CE}",Mt.addEventListener("click",St=>{St.preventDefault(),vt?.click()}),Mn.appendChild(Mt);let st=J.buttonTooltipText??"Attach file";tn({anchor:Mt,trigger:Mn,text:()=>Mt?.getAttribute("aria-label")??st}),ru?ru.append(Mn):co.appendChild(Mn),rt&&(rt.attachmentButton=Mt,rt.attachmentInput=vt??void 0,rt.attachmentPreviews=En??void 0),!tt&&vt&&En&&(tt=Fs.fromConfig(J,ah),tt.setPreviewsContainer(En),rt?.addListener(vt,"change",async()=>{tt&&vt?.files&&(await tt.handleFileSelect(vt.files),vt.value="")}))}else{Mn.style.display="";let J=o.attachments??{};vt&&(vt.accept=(J.allowedTypes??fr).join(","),vt.multiple=(J.maxFiles??4)>1),tt&&tt.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles,adapter:J.adapter})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(tS(o.attachments?.dropOverlay)),Mt){let J=o.attachments??{},Ge=J.buttonTooltipText??"Attach file";Mt.setAttribute("aria-label",Ge),Mt.textContent="";let Xe=de(J.buttonIconName??"paperclip",yn,"currentColor",1.5);Xe?Mt.appendChild(Xe):Mt.textContent="\u{1F4CE}",Mn&&tn({anchor:Mt,trigger:Mn,text:()=>Mt?.getAttribute("aria-label")??Ge})}}else Mn&&(Mn.style.display="none"),tt&&tt.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Be=o.sendButton??{},dr=Be.useIcon??!1,_t=Be.iconText??"\u2191",Hn=Be.iconName,Xa=Be.tooltipText??"Send message",uE=Be.showTooltip??!1,Ja=Be.size,gE=parseFloat(Ja??"")||wm,nd=Be.backgroundColor,Za=Be.textColor;if(dr){if(Te.style.width=Ja??"",Te.style.height=Ja??"",Te.style.minWidth=Ja??"",Te.style.minHeight=Ja??"",Te.style.fontSize="18px",Te.style.lineHeight="1",Za?Te.style.color=Za:Te.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!P.isStreaming())if(Te.innerHTML="",Hn){let J=parseFloat(Be.iconSize??"")||Math.round(gE*.5),Ge=Za?.trim()||"currentColor",Xe=Be.iconStrokeWidth??2,st=de(Hn,J,Ge,Xe),St=de(Be.stopIconName??"square",J,Ge,Xe);st&&St?Te.appendChild(xm(st,St)):st?Te.appendChild(st):Te.textContent=_t}else Te.textContent=_t;Te.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Yn}`,nd?(Te.style.backgroundColor=nd,Te.classList.remove("persona-bg-persona-primary")):(Te.style.backgroundColor="",Te.classList.add("persona-bg-persona-primary"))}else Te.textContent=o.copy?.sendButtonLabel??"Send",Te.style.width="",Te.style.height="",Te.style.minWidth="",Te.style.minHeight="",Te.style.fontSize="",Te.style.lineHeight="",Te.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",nd?(Te.style.backgroundColor=nd,Te.classList.remove("persona-bg-persona-accent")):Te.classList.add("persona-bg-persona-accent"),Za?Te.style.color=Za:Te.classList.add("persona-text-white");Be.borderWidth?(Te.style.borderWidth=Be.borderWidth,Te.style.borderStyle="solid"):(Te.style.borderWidth="",Te.style.borderStyle=""),Be.borderColor?Te.style.borderColor=Be.borderColor:Te.style.borderColor="",Be.paddingX?(Te.style.paddingLeft=Be.paddingX,Te.style.paddingRight=Be.paddingX):(Te.style.paddingLeft="",Te.style.paddingRight=""),Be.paddingY?(Te.style.paddingTop=Be.paddingY,Te.style.paddingBottom=Be.paddingY):(Te.style.paddingTop="",Te.style.paddingBottom=""),P.isStreaming()||Te.setAttribute("aria-label",Xa),wc(),Mo&&tn({anchor:Te,trigger:Mo,text:()=>Te.getAttribute("aria-label")??Xa,enabled:uE}),xh();let Bb=Yd(xe.getState().activeModeIds,o.composer?.modes);xe.setActiveModeIds(Bb),ei().length>0!==!!Go&&fu(),Go?.render(Bb,ei());for(let J of[...ti.keys()])Gd(J,o.composer?.modeGroups)||ti.delete(J);ti.forEach(J=>J.repaint()),Mr?.repaint(),Po?.resolve();let od=Jr(o,Ce());if(xu(),od){Le.style.maxWidth=od,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%",Fn.style.maxWidth=od,Fn.style.marginLeft="auto",Fn.style.marginRight="auto",Fn.style.width="100%";for(let J of[co,xr,En,lt])J&&(J.style.maxWidth=od,J.style.marginLeft="auto",J.style.marginRight="auto",J.style.width="100%")}else{Le.style.maxWidth="",Le.style.marginLeft="",Le.style.marginRight="",Le.style.width="",Fn.style.maxWidth="",Fn.style.marginLeft="",Fn.style.marginRight="",Fn.style.width="";for(let J of[co,xr,En,lt])J&&(J.style.maxWidth="",J.style.marginLeft="",J.style.marginRight="",J.style.width="")}let Fr=o.statusIndicator??{},mE=Fr.visible??!0;if(lt.style.display=mE?"":"none",P){let J=P.getStatus();zl(lt,(Xe=>Xe==="idle"?Fr.idleText??Vt.idle:Xe==="connecting"?Fr.connectingText??Vt.connecting:Xe==="connected"?Fr.connectedText??Vt.connected:Xe==="error"?Fr.errorText??Vt.error:Vt[Xe])(J),Fr,J)}lt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let fE=Fr.align==="left"?"persona-text-left":Fr.align==="center"?"persona-text-center":"persona-text-right";lt.classList.add(fE),mu(),Bu(),po(),tu()},open(){De()&&ft(!0,"api")},close(){De()&&ft(!1,"api")},toggle(){De()&&ft(!we,"api")},reconnect(){P.reconnectNow()},clearChat(){Yo=!1,P.clearMessages(),$t.clear(),Pn();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),G?.clear&&gc(()=>G.clear(),"[AgentWidget] Failed to clear storage adapter:"),ee={},ve.syncFromMetadata(),tt?.clearAttachments(),fc(),ni(void 0),To(void 0),fs(),Oe?.clear(),at?.reset(),bt?.update()},setMessage(i){return!ce||P.isStreaming()||Ro()?!1:(!we&&De()&&ft(!0,"system"),ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(P.isStreaming()||xs())return!1;let c=i?.trim()||ce.value.trim();return c?(!we&&De()&&ft(!0,"system"),ce.value="",ce.style.height="auto",Eo(),Qc(c,{consumeDraft:!1}),!0):!1},getComposerState(){return xe.getState()},setQuote(i){let c=i?.text?.trim();c&&To({...i,text:c})},clearQuote(){To(void 0)},startVoiceRecognition(){return P.isStreaming()?!1:Wn(o.voiceRecognition?.provider)?(P.isVoiceActive()||P.isBargeInActive()||(!we&&De()&&ft(!0,"system"),Ke.manuallyDeactivated=!1,mo(),P.toggleVoice().then(()=>{Ke.active=P.isVoiceActive(),Zo("user"),P.isVoiceActive()&&ki()})),!0):Oo?!0:pb()?(!we&&De()&&ft(!0,"system"),Ke.manuallyDeactivated=!1,mo(),Jc("user"),!0):!1},stopVoiceRecognition(){return Wn(o.voiceRecognition?.provider)?!P.isVoiceActive()&&!P.isBargeInActive()?!1:((P.isBargeInActive()?P.deactivateBargeIn():P.toggleVoice()).then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,mo(),Zo("user"),lr()}),!0):Oo?(Ke.manuallyDeactivated=!0,mo(),_r("user"),!0):!1},injectMessage(i){return!we&&De()&&ft(!0,"system"),P.injectMessage(i)},injectAssistantMessage(i){!we&&De()&&ft(!0,"system");let c=P.injectAssistantMessage(i);return Ae&&(Ae=!1,Ct&&(clearTimeout(Ct),Ct=null),setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)),c},injectUserMessage(i){return!we&&De()&&ft(!0,"system"),P.injectUserMessage(i)},injectSystemMessage(i){return!we&&De()&&ft(!0,"system"),P.injectSystemMessage(i)},injectMessageBatch(i){return!we&&De()&&ft(!0,"system"),P.injectMessageBatch(i)},injectComponentDirective(i){return!we&&De()&&ft(!0,"system"),P.injectComponentDirective(i)},injectTestMessage(i){!we&&De()&&ft(!0,"system"),P.injectTestEvent(i)},async connectStream(i,c){return P.connectStream(i,c)},__pushEventStreamEvent(i){S&&(ql(),eu(i.type,i.payload))},showEventStream(){S&&gu()},hideEventStream(){Qt&&oi()},isEventStreamVisible(){return Qt},listConversations(i){return P.listConversations(i)},getActiveConversationId(){return P.getActiveConversationId()},openConversation(i,c){return bg(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return vg({focusComposer:i?.focus===!0})},deleteConversation(i){return eb(i)},renameConversation(i,c){return Cg(i,{title:c})},setConversationStarred(i,c){return Cg(i,{starred:c})},clearConversationHistory(i){return tb(i)},resetHistoryIdentity(){return nb()},getHistoryIdentityStatus(){return Vn?Vn.getIdentityStatus():tg()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return ja({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){Ln(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return Et},showArtifacts(){wn(o)&&(Yo=!1,si=!0,go(),Ve?.setMobileOpen(!0))},hideArtifacts(){wn(o)&&(Yo=!0,go())},upsertArtifact(i){return wn(o)?(No(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Yo=!1,si=!0),P.upsertArtifact(i)):null},selectArtifact(i){wn(o)&&P.selectArtifact(i)},clearArtifacts(){wn(o)&&P.clearArtifacts()},getArtifacts(){return P?.getArtifacts()??[]},getSelectedArtifactId(){return P?.getSelectedArtifactId()??null},focusInput(){return pe&&!we&&!Ce()||!ce?!1:(ce.focus(),!0)},async resolveApproval(i,c,g){let b=P.getMessages().find(C=>C.variant==="approval"&&C.approval?.id===i);if(!b?.approval)throw new Error(`Approval not found: ${i}`);if(b.approval.toolType==="webmcp"){P.resolveWebMcpApproval(b.id,c);return}return P.resolveApproval(b.approval,c,g)},setFollowUpSuggestions(i){CA(i)},clearFollowUpSuggestions(){Qh()},getMessages(){return P.getMessages()},getStatus(){return P.getStatus()},getPersistentMetadata(){return{...ee}},updatePersistentMetadata(i){ae(i)},on(i,c){return A.on(i,c)},off(i,c){A.off(i,c)},isOpen(){return De()&&we},isVoiceActive(){return Ke.active},toggleReadAloud(i){P.toggleReadAloud(i)},stopReadAloud(){P.stopSpeaking()},getReadAloudState(i){return P.getReadAloudState(i)},onReadAloudChange(i){return P.onReadAloudChange(i)},getState(){return{open:De()&&we,launcherEnabled:pe,voiceActive:Ke.active,streaming:P.isStreaming()}},showCSATFeedback(i){!we&&De()&&ft(!0,"system");let c=Le.querySelector(".persona-feedback-container");c&&c.remove();let g=Op({onSubmit:async(f,b)=>{P.isClientTokenMode()&&await P.submitCSATFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});Le.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!we&&De()&&ft(!0,"system");let c=Le.querySelector(".persona-feedback-container");c&&c.remove();let g=Bp({onSubmit:async(f,b)=>{P.isClientTokenMode()&&await P.submitNPSFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});Le.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,c){return P.submitCSATFeedback(i,c)},async submitNPSFeedback(i,c){return P.submitNPSFeedback(i,c)},destroy(){Gu(),Ms!=null&&(clearInterval(Ms),Ms=null),he.forEach(i=>i()),Qe.remove(),Xt?.remove(),Pt?.destroy(),mn?.remove(),ps&&Ue.removeEventListener("click",ps)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:kt,getMessages:kt.getMessages,getStatus:kt.getStatus,getMetadata:kt.getPersistentMetadata,updateMetadata:kt.updatePersistentMetadata,clearHistory:()=>kt.clearChat(),setVoiceActive:g=>g?kt.startVoiceRecognition():kt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,he.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 X=j.detail;(!X?.instanceId||X.instanceId===i)&&kt.focusInput()};if(window.addEventListener("persona:focusInput",c),he.push(()=>{window.removeEventListener("persona:focusInput",c)}),S){let j=se=>{let me=se.detail;(!me?.instanceId||me.instanceId===i)&&kt.showEventStream()},X=se=>{let me=se.detail;(!me?.instanceId||me.instanceId===i)&&kt.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",X),he.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",X)})}let g=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===i)&&kt.showHistory()},f=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===i)&&kt.hideHistory()};window.addEventListener("persona:showHistory",g),window.addEventListener("persona:hideHistory",f),he.push(()=>{window.removeEventListener("persona:showHistory",g),window.removeEventListener("persona:hideHistory",f)});let b=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===i)&&kt.showArtifacts()},C=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===i)&&kt.hideArtifacts()},W=j=>{let X=j.detail;X?.instanceId&&X.instanceId!==i||X?.artifact&&kt.upsertArtifact(X.artifact)},U=j=>{let X=j.detail;X?.instanceId&&X.instanceId!==i||typeof X?.id=="string"&&kt.selectArtifact(X.id)},$=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===i)&&kt.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",C),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",U),window.addEventListener("persona:clearArtifacts",$),he.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",C),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",U),window.removeEventListener("persona:clearArtifacts",$)})}let ro=N0(o.persistState);if(ro&&De()){let i=F0(ro.storage),c=`${ro.keyPrefix}widget-open`,g=`${ro.keyPrefix}widget-voice`,f=`${ro.keyPrefix}widget-voice-mode`;if(i){let b=ro.persist?.openState&&i.getItem(c)==="true",C=ro.persist?.voiceState&&i.getItem(g)==="true",W=ro.persist?.voiceState&&i.getItem(f)==="true";if(b&&(Pt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open(),setTimeout(()=>{if(C||W)kt.startVoiceRecognition();else if(ro.persist?.focusInput){let U=e.querySelector("textarea");U&&U.focus()}},100)},0)),ro.persist?.openState&&(A.on("widget:opened",()=>{i.setItem(c,"true")}),A.on("widget:closed",()=>{i.setItem(c,"false")})),ro.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")})),ro.clearOnChatClear){let U=()=>{i.removeItem(c),i.removeItem(g),i.removeItem(f)},$=()=>U();window.addEventListener("persona:clear-chat",$),he.push(()=>{window.removeEventListener("persona:clear-chat",$)})}}}if(Z&&De()&&(Pt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open()},0)),fi(),!wA){let i=Ri(()=>{P&&(hs++,$t.clear(),Zn(Le,P.getMessages(),mt))});he.push(i)}x=()=>{P&&(hs++,$t.clear(),Zn(Le,P.getMessages(),mt))},P.getMessages().length>0&&Cc(),T=()=>{P&&(hs++,$t.clear(),Zn(Le,P.getMessages(),mt))};let dE=Kb(()=>{P&&(hs++,$t.clear(),Zn(Le,P.getMessages(),mt))});he.push(dE);let pE=wf(()=>{P&&(hs++,$t.clear(),Zn(Le,P.getMessages(),mt),yr()?.updateInlineArtifactBlocks(Le,Jn.artifacts,{suppressTransition:!0}),go())});return he.push(pE),kt};var nS=(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},j0=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},q0=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},z0=(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.")},oS=(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"},Df=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=""},rS=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Df(e)},Of=e=>{e.style.transition=""},Bf=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=""},_f=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Np=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},V0=(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))},K0=(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)},G0=e=>{let t=Xr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:bn(t,r)??r;return{inset:o(n?.inset,Qd),canvasBackground:o(n?.canvasBackground,Xd)}},sS=(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},Y0=(e,t,n,o,r,s,a,l)=>{let d=_n(s),p=d.reveal==="push",u=l!=null,m=l?.inset??"",y=l?.canvasBackground??"";V0(e,t,n,o,p),K0(e,t,n,o,d.side,p),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=d.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let h=e.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,x=s?.launcher?.mobileBreakpoint??640,w=h!=null?h.innerWidth<=x:!1;if(v&&w&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Bf(t),Of(o),rS(o),_f(n),Np(r,o),sS(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??an),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"),rS(o),j0(o,d.maxHeight),sS(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",Bf(t),Of(o),_f(n),Np(r,o);let O=d.animate?"transform 180ms ease":"none",D=d.side==="right"?"translateX(100%)":"translateX(-100%)",T=a?"translateX(0)":D;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=O,o.style.transform=T,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Of(o),Df(o),Np(r,o);let O=nS(d.width,e.clientWidth),D=Math.max(0,e.clientWidth),T=d.animate?"margin-left 180ms ease":"none",I=d.side==="right"?a?-O:0:a?0:-O;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${D+O}px`,t.style.transition=T,t.style.marginLeft=`${I}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${D}px`,n.style.maxWidth=`${D}px`,n.style.minWidth=`${D}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Bf(t),Df(o),_f(n),Np(r,o);let O=d.reveal==="emerge";O?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let D=a?d.width:"0px",T=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",I=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${D}`,o.style.width=D,o.style.maxWidth=D,o.style.minWidth=D,o.style.minHeight="0",q0(o,d.maxHeight),o.style.overflow=O||I?"hidden":"visible",o.style.transition=T,O){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let A=u?`calc(${nS(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"}}},Q0=(e,t)=>{let n=e.ownerDocument.createElement("div");return oS(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){oS(n,o)},destroy(){n.remove()}}},X0=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),p=n.createElement("aside"),u=n.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",p.appendChild(u),o.insertBefore(a,e),d.appendChild(e);let y=null,h=()=>{y?.disconnect(),y=null},v=null,x=()=>{v=t?.launcher?.detachedPanel===!0?G0(t):null};x();let w=()=>{Y0(a,l,d,p,u,t,m,v)},k=null,O=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=Qi(()=>{x(),w()}))},D=()=>{h(),_n(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{w()}),y.observe(a)))},T=!1,I=()=>{w(),D(),m&&!T&&a.dataset.personaDockMobileFullscreen!=="true"&&(T=!0,z0(a,_n(t)))},A=a.ownerDocument.defaultView,_=()=>{I()};return A?.addEventListener("resize",_),_n(t).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),I(),O(),{mode:"docked",host:u,shell:a,syncWidgetState(G){let le=G.launcherEnabled?G.open:!0;m!==le&&(m=le,I())},updateConfig(G){t=G,(t?.launcher?.enabled??!0)===!1&&(m=!0),x(),I(),O()},destroy(){A?.removeEventListener("resize",_),k?.(),k=null,h(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},$l=(e,t)=>At(t)?X0(e,t):Q0(e,t);var J0=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},iS=(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)},Fp=[],aS=()=>[...Fp],Nf=e=>{let t=J0(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=$l(t,r),a,l=[],d=(w,k)=>{let D=!(k?.launcher?.enabled??!0)||At(k),T=o.createElement("div");if(T.setAttribute("data-persona-root","true"),D&&(T.style.height="100%",T.style.display="flex",T.style.flexDirection="column",T.style.flex="1",T.style.minHeight="0",T.style.minWidth="0"),n){let I=w.attachShadow({mode:"open"});I.appendChild(T),iS(I,o)}else w.appendChild(T),iS(w,o);return t.id&&T.setAttribute("data-persona-instance",t.id),T},p=()=>{s.syncWidgetState(a.getState())},u=()=>{l.forEach(w=>w()),l=[a.on("widget:opened",p),a.on("widget:closed",p)],p()},m=()=>{let w=d(s.host,r);a=Dp(w,r,{debugTools:e.debugTools}),u()},y=()=>{l.forEach(w=>w()),l=[],a.destroy()};m(),e.onChatReady?.();let h=w=>{y(),s.destroy(),s=$l(t,w),r=w,m()},v={update(w){let k=kp(r??{},w),O=At(r),D=At(k),T=es(r),I=es(k);if(O!==D||T!==I){h(k);return}r=k,s.updateConfig(r),a.update(w),p()},destroy(){y(),s.destroy();let w=Fp.indexOf(x);w!==-1&&Fp.splice(w,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},x=new Proxy(v,{get(w,k,O){if(k==="host")return s.host;if(k in w)return Reflect.get(w,k,O);let D=a[k];return typeof D=="function"?D.bind(a):D}});return Fp.push(x),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=x),x};var uS=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Z0=new Set(["button","a","input","select","textarea","details","summary"]),eL=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ff=/\b(product|card|item|listing|result)\b/i,Uf=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,tL=3e3,nL=100;function gS(e){let t=typeof e.className=="string"?e.className:"";if(Ff.test(t)||e.id&&Ff.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Ff.test(o.value))return!0}return!1}function mS(e){return Uf.test((e.textContent??"").trim())}function fS(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 oL(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function lS(e){let t=e.match(Uf);return t?t[0]:null}function cS(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 rL(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 sL="commerce-card",iL="result-card";function dS(e){return!gS(e)||!mS(e)||!fS(e)&&!oL(e)?0:5200}function pS(e){return!gS(e)||mS(e)||!fS(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var jf=[{id:sL,scoreElement(e){return dS(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||Uf.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(dS(e)===0)return null;let{title:n,href:o}=cS(e),r=lS((e.textContent??"").trim())??lS(t.text)??"",s=rL(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:iL,scoreElement(e){return pS(e)},formatSummary(e,t){if(pS(e)===0)return null;let{title:n,href:o}=cS(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
139
|
+
`)}}];function aL(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function lL(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??jf;return l==="simple"&&e.rules&&e.rules.length>0?(aL(),p=[]):l==="simple"&&(p=[]),{mode:l,maxElements:n,maxCandidates:d,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:p}}function $f(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var cL=["data-testid","data-product","data-action","data-id","data-name","data-type"];function dL(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"||Z0.has(t)||n&&eL.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function hS(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 pL(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 qf(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${$f(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of cL){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${$f(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=>$f(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 uL(e){return e==="static"?nL:tL}function yS(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:qf(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:dL(e),attributes:pL(e)}}function gL(e,t,n,o){let r=uL(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 mL(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 fL(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(uS.has(u)){l=a.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){l=a.nextNode();continue}}catch{}if(e.visibleOnly&&!hS(p)){l=a.nextNode();continue}let m=yS(p,e.maxTextLength),y=m.text.length>0,h=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(w=>w==="role");if(!y&&!h){l=a.nextNode();continue}if(o.has(m.selector)){l=a.nextNode();continue}o.add(m.selector);let{score:v,formattingRule:x}=gL(p,m,e.rules,n);r.push({el:p,domIndex:s,enriched:m,score:v,formattingRule:x}),s+=1}l=a.nextNode()}r.sort((p,u)=>{let m=p.enriched.interactivity==="static"?1:0,y=u.enriched.interactivity==="static"?1:0;return m!==y?m-y:u.score!==p.score?u.score-p.score:p.domIndex-u.domIndex});let d=[];for(let p of r){if(d.length>=e.maxElements)break;mL(d,p)||d.push(p)}return d.sort((p,u)=>{let m=p.enriched.interactivity==="static"?1:0,y=u.enriched.interactivity==="static"?1:0;return m!==y?m-y:m===1&&u.score!==p.score?u.score-p.score:p.domIndex-u.domIndex}),d.map(p=>{let u;if(p.formattingRule?.formatSummary){let y=p.formattingRule.formatSummary(p.el,p.enriched,n);y&&(u=y)}let m={...p.enriched};return u&&(m.formattedSummary=u),m})}function hL(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(uS.has(p)){s=r.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!hS(d)){s=r.nextNode();continue}let u=yS(d,e.maxTextLength),m=u.text.length>0,y=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(h=>h==="role");if(!m&&!y){s=r.nextNode();continue}o.has(u.selector)||(o.add(u.selector),n.push(u))}s=r.nextNode()}let a=[],l=[];for(let d of n)d.interactivity!=="static"?a.push(d):l.push(d);return[...a,...l].slice(0,e.maxElements)}function bS(e={}){let t=lL(e),n=t.root??document.body;return n?t.mode==="simple"?hL(t,n):fL(t,n):[]}var $p=100;function vS(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);s.length>0&&o.push(`Structured summaries:
|
|
140
140
|
${s.map(a=>`- ${a.split(`
|
|
141
141
|
`).join(`
|
|
142
142
|
`)}`).join(`
|
|
143
|
-
`)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(a=>`- ${a.selector}: "${a.text.substring(0
|
|
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,$p)}" (clickable)`);o.push(`Interactive elements:
|
|
144
144
|
${s.join(`
|
|
145
|
-
`)}`)}if(r.navigable.length>0){let s=r.navigable.map(a=>`- ${a.selector}${a.attributes.href?`[href="${a.attributes.href}"]`:""}: "${a.text.substring(0
|
|
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,$p)}" (navigable)`);o.push(`Navigation links:
|
|
146
146
|
${s.join(`
|
|
147
|
-
`)}`)}if(r.input.length>0){let s=r.input.map(a=>`- ${a.selector}${a.attributes.type?`[type="${a.attributes.type}"]`:""}: "${a.text.substring(0
|
|
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,$p)}" (input)`);o.push(`Form inputs:
|
|
148
148
|
${s.join(`
|
|
149
|
-
`)}`)}if(r.static.length>0){let s=r.static.map(a=>`- ${a.selector}: "${a.text.substring(0
|
|
149
|
+
`)}`)}if(r.static.length>0){let s=r.static.map(a=>`- ${a.selector}: "${a.text.substring(0,$p)}"`);o.push(`Content:
|
|
150
150
|
${s.join(`
|
|
151
151
|
`)}`)}return o.join(`
|
|
152
152
|
|
|
153
|
-
`)}var
|
|
153
|
+
`)}var yL={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"}}},CS={components:{panel:{borderRadius:"0",shadow:"none"}}},zf={id:"shop",label:"Shopping Assistant",config:{theme:yL,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Gn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},Vf={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:CS}},Kf={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:CS}},Gf={shop:zf,minimal:Vf,fullscreen:Kf};function wS(e){return Gf[e]}var xS=Nf;function SS(){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 AS(){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 MS(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:zo(e.colors.primary,.95),100:zo(e.colors.primary,.9),200:zo(e.colors.primary,.8),300:zo(e.colors.primary,.7),400:zo(e.colors.primary,.6),500:e.colors.primary,600:zo(e.colors.primary,.8),700:zo(e.colors.primary,.7),800:zo(e.colors.primary,.6),900:zo(e.colors.primary,.5),950:zo(e.colors.primary,.45)}}),{...t,palette:n}}}}function ES(){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 TS(){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 zo(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 PS(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}function Yf(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@${Co}/dist`}function wr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function bL(e){if(e)return{getHeaders:wr(e.getHeaders),onFeedback:wr(e.onFeedback),onCopy:wr(e.onCopy),requestMiddleware:wr(e.requestMiddleware),actionHandlers:wr(e.actionHandlers),actionParsers:wr(e.actionParsers),postprocessMessage:wr(e.postprocessMessage),contextProviders:wr(e.contextProviders),streamParser:wr(e.streamParser)}}var kS=`({ text, message }: any) => {
|
|
154
154
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
155
155
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
156
156
|
let cleanJson = jsonSource
|
|
@@ -163,7 +163,7 @@ ${s.join(`
|
|
|
163
163
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
164
164
|
} catch (e) { return null; }
|
|
165
165
|
return null;
|
|
166
|
-
}`,
|
|
166
|
+
}`,LS=`function(ctx) {
|
|
167
167
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
168
168
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
169
169
|
var cleanJson = jsonSource
|
|
@@ -176,7 +176,7 @@ ${s.join(`
|
|
|
176
176
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
177
177
|
} catch (e) { return null; }
|
|
178
178
|
return null;
|
|
179
|
-
}`,
|
|
179
|
+
}`,IS=`(action: any, context: any) => {
|
|
180
180
|
if (action.type !== 'nav_then_click') return;
|
|
181
181
|
const payload = action.payload || action.raw || {};
|
|
182
182
|
const url = payload?.page;
|
|
@@ -193,7 +193,7 @@ ${s.join(`
|
|
|
193
193
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
194
194
|
window.location.href = targetUrl;
|
|
195
195
|
return { handled: true, displayText: text };
|
|
196
|
-
}`,
|
|
196
|
+
}`,RS=`function(action, context) {
|
|
197
197
|
if (action.type !== 'nav_then_click') return;
|
|
198
198
|
var payload = action.payload || action.raw || {};
|
|
199
199
|
var url = payload.page;
|
|
@@ -210,27 +210,27 @@ ${s.join(`
|
|
|
210
210
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
211
211
|
window.location.href = targetUrl;
|
|
212
212
|
return { handled: true, displayText: text };
|
|
213
|
-
}`,
|
|
213
|
+
}`,vL=`(parsed: any) => {
|
|
214
214
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
215
215
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
216
216
|
if (parsed.action === 'message') return parsed.text || '';
|
|
217
217
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
218
218
|
return parsed.text || null;
|
|
219
|
-
}`,
|
|
219
|
+
}`,CL=`function(parsed) {
|
|
220
220
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
221
221
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
222
222
|
if (parsed.action === 'message') return parsed.text || '';
|
|
223
223
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
224
224
|
return parsed.text || null;
|
|
225
|
-
}`;function
|
|
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 CL(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: '${zl(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&&as(o,"theme",e.theme," "),e.launcher&&as(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(...Yp(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(...Vp(e," ")),o.push(...Kp(e," ",n)),o.push(...Gp(e," ")),o.push(...Qp(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(${fL}),`)),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(` ${ES}`),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(` ${ES}`),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(` ${kS}`),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(` ${kS}`),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
|
|
225
|
+
}`;function wL(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 Up(e){return e.parserType??wL(e.streamParser)??"plain"}function jp(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 qp(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 zp(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 Vp(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
|
|
226
|
+
`);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,a=r===n.length-1?",":"";return`${s}${o}${a}`})}function Kp(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 Qf(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 HS(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}: {`),HS(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function ns(e,t,n,o){n&&(e.push(`${o}${t}: {`),HS(e,n,`${o} `),e.push(`${o}},`))}function Ul(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function WS(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:bL(n.hooks)}:void 0;return t==="esm"?xL(o,r):t==="script-installer"?ML(o,r):t==="script-advanced"?TL(o,r):t==="react-component"?SL(o,r):t==="react-advanced"?AL(o,r):EL(o,r)}function xL(e,t){let n=t?.hooks,o=Up(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ul(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ns(s,"theme",e.theme," "),e.launcher&&ns(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(...Vp(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(...jp(e," ")),s.push(...qp(e," ",n)),s.push(...zp(e," ")),s.push(...Kp(e," ")),s.push(...Qf(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
|
|
227
|
+
`)}function SL(e,t){let n=t?.hooks,o=Up(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: '${Ul(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ns(s,"theme",e.theme," "),e.launcher&&ns(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(...Vp(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(...jp(e," ")),s.push(...qp(e," ",n)),s.push(...zp(e," ")),s.push(...Kp(e," ")),s.push(...Qf(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
|
|
228
|
+
`)}function AL(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: '${Ul(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&&ns(o,"theme",e.theme," "),e.launcher&&ns(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(...Vp(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(...jp(e," ")),o.push(...qp(e," ",n)),o.push(...zp(e," ")),o.push(...Kp(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(${vL}),`)),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(` ${kS}`),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(` ${kS}`),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(` ${IS}`),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(` ${IS}`),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 OS(e){let t=Up(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestions&&(o.suggestions=e.suggestions),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&(r[s]=a)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,a])=>{s!=="onFeedback"&&s!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(r[s]=a)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([a,l])=>{a!=="render"&&(typeof l=="string"||typeof l=="boolean")&&(s[a]=l)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([a,l])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof l=="object"&&l!==null)s.avatar=l;else if(a==="timestamp"&&typeof l=="object"&&l!==null){let d={};Object.entries(l).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(d[p]=u)}),Object.keys(d).length>0&&(s.timestamp=d)}else(typeof l=="string"||typeof l=="boolean")&&(s[a]=l)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function ML(e,t){let n=OS(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="${Yf(t)}/install.global.js" data-config='${s}'></script>`}function EL(e,t){let n=t?.hooks,o=Up(e),r=o!=="plain",s=Yf(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: '${Ul(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),r&&a.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ns(a,"theme",e.theme," "),e.launcher&&ns(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(...Vp(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(...jp(e," ")),a.push(...qp(e," ",n)),a.push(...zp(e," ")),a.push(...Kp(e," ")),a.push(...Qf(n," ")),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),a.push(" }"),a.push(" });"),a.push("</script>"),a.join(`
|
|
230
|
+
`)}function TL(e,t){let n=t?.hooks,o=OS(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
|
|
231
231
|
`).map((a,l)=>l===0?a:" "+a).join(`
|
|
232
|
-
`)};`,""," // Constants",` var CDN_BASE = '${Yf(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(${
|
|
233
|
-
`)}var
|
|
232
|
+
`)};`,""," // Constants",` var CDN_BASE = '${Yf(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(${CL});`),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(` ${LS}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${LS}`),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(` ${RS}`),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(` ${RS}`),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: '${Ul(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
|
|
233
|
+
`)}var $S=require("lucide");var BS={desktop:{w:1280,h:800},mobile:{w:390,h:844}},_S=.1,DS=.15,NS=1.5,Xf=24,FS=40,PL=`
|
|
234
234
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
235
235
|
.persona-dc-root {
|
|
236
236
|
display: flex;
|
|
@@ -471,10 +471,10 @@ ${s.join(`
|
|
|
471
471
|
min-height: 300px;
|
|
472
472
|
}
|
|
473
473
|
}
|
|
474
|
-
`;function ML(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=AL,document.head.appendChild(e)}function EL(e,t){let n=e.clientWidth-Xf*2-_S,o=e.clientHeight-Xf*2-_S;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function TL(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 NS(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");ML();let u=Math.max(0,Math.min(o,n.length-1)),m=r,y=s,h=null,C=1,S=!1,x=M("div","persona-dc-root"),P=M("div","persona-dc-toolbar"),O=M("div","persona-dc-toolbar-lead"),$=M("div","persona-dc-toolbar-trail"),T=Wn({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ue(-1)}),R=M("div");R.style.position="relative";let A=M("button","persona-dc-title-btn");A.type="button",A.setAttribute("aria-expanded","false"),A.setAttribute("aria-haspopup","listbox");let N=M("span","persona-dc-title-text"),Y=M("span","persona-dc-title-chevron"),ce=Bt(DS.ChevronDown,12,"currentColor",2);ce&&Y.appendChild(ce),A.append(N,Y);let Q=M("div","persona-dc-dropdown");Q.setAttribute("role","listbox"),Q.style.display="none";let E=!1;function B(){Q.innerHTML="";for(let Ie=0;Ie<n.length;Ie++){let Tt=n[Ie],Xt=M("button","persona-dc-dropdown-item");Xt.type="button",Xt.setAttribute("role","option"),Xt.setAttribute("aria-current",Ie===u?"true":"false");let yt=M("span");if(yt.textContent=Tt.title,Xt.appendChild(yt),Tt.description){let gn=M("span","persona-dc-dropdown-desc");gn.textContent=Tt.description,Xt.appendChild(gn)}Xt.addEventListener("click",()=>{L(),ht(Ie)}),Q.appendChild(Xt)}}function H(){E=!E,Q.style.display=E?"":"none",A.setAttribute("aria-expanded",E?"true":"false"),E&&B()}function L(){E&&(E=!1,Q.style.display="none",A.setAttribute("aria-expanded","false"))}A.addEventListener("click",Ie=>{Ie.stopPropagation(),H()});let te=()=>L();document.addEventListener("click",te),R.append(A,Q);let K=Wn({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ue(1)}),me=M("span","persona-dc-counter");O.append(T,R,K,me);let de=null;l&&(de=Ol({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:Ie=>{m=Ie,Qe.dataset.device=m,h=null,xe()}}),$.appendChild(de.element));let he=null;if(a){let Ie=M("div","persona-dc-zoom-controls"),Tt=Wn({icon:"minus",label:"Zoom out",size:14,onClick:()=>{h=Math.max(OS,(h??C)-WS),xe()}});he=M("span","persona-dc-zoom-level"),he.title="Reset to 100%",he.style.cursor="pointer",he.addEventListener("click",()=>{h=1,xe()});let Xt=Wn({icon:"plus",label:"Zoom in",size:14,onClick:()=>{h=Math.min(BS,(h??C)+WS),xe()}}),yt=Wn({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{h=null,xe()}});Ie.append(Tt,he,Xt,yt),$.appendChild(Ie)}if(d){let Ie=M("div","persona-dc-separator");$.appendChild(Ie);let Tt=Ol({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:Xt=>{y=Xt,Qe.dataset.colorScheme=y,j()}});$.appendChild(Tt.element)}let We=M("div","persona-dc-separator");$.appendChild(We);let Oe=Wn({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[u].url,"_blank")}});$.appendChild(Oe),P.append(O,$);let we=M("div","persona-dc-stage"),Qe=M("div","persona-dc-iframe-wrapper");Qe.dataset.device=m,Qe.dataset.colorScheme=y;let Ce=M("iframe","persona-dc-iframe");Ce.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),Ce.setAttribute("loading","lazy"),Ce.title=n[u].title,Qe.appendChild(Ce),we.appendChild(Qe),x.append(P,we),e.appendChild(x);function j(){try{let Ie=Ce.contentDocument?.body;if(!Ie)return;y==="dark"?Ie.classList.add("theme-dark"):Ie.classList.remove("theme-dark")}catch{}}Ce.addEventListener("load",()=>j());function Ne(){let Ie=n[u];N.textContent=Ie.title,me.textContent=`${u+1} / ${n.length}`,Ce.title=Ie.title}function Ue(Ie){let Tt=((u+Ie)%n.length+n.length)%n.length;ht(Tt)}function ht(Ie){Ie<0||Ie>=n.length||(u=Ie,Ce.src=n[u].url,Ne(),p?.(u,n[u]))}function xe(){if(S)return;let Ie=HS[m]??HS.desktop;C=EL(we,Ie);let Tt=Math.max(OS,Math.min(BS,h??C));TL(Qe,Ce,Ie,Tt,m),he&&(he.textContent=`${Math.round(Tt*100)}%`)}let ke=new ResizeObserver(()=>xe());ke.observe(we),Ne(),Ce.src=n[u].url,requestAnimationFrame(()=>xe());function be(){S||(S=!0,ke.disconnect(),document.removeEventListener("click",te),x.remove())}return{element:x,goTo:ht,next:()=>Ue(1),prev:()=>Ue(-1),getIndex:()=>u,setDevice(Ie){m=Ie,Qe.dataset.device=Ie,de?.setSelected(Ie),h=null,xe()},setColorScheme(Ie){y=Ie,Qe.dataset.colorScheme=Ie},setZoom(Ie){h=Ie,xe()},destroy:be}}dm();var FS=16e3,kL=24e3,PL=4096,LL=4,IL=1380533830;function RL(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===IL?new Uint8Array(e,44):new Uint8Array(e)}function HL(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 Vl=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:FS,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:FS});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Qi(kL);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=`${HL(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(PL,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*LL));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=RL(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 ri=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 ya(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Vl(e.runtype);case"browser":if(!ri.isSupported())throw new Error("Browser speech recognition not supported");return new ri(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 Xp(e){if(e?.type==="custom"&&e.custom)return ya({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return ya({type:"runtype",runtype:e.runtype});if(ri.isSupported())return ya({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Jf(e){try{return Xp(e),!0}catch{return!1}}var $S="webmcp:",WL=e=>e.startsWith($S)?e.slice($S.length):e,Jp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},eu=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 Jp.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=BL(r.annotations);return{name:r.name,description:r.description,parametersSchema:_L(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 Mo("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let C=typeof document<"u"&&!!document.modelContext;return Mo(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=WL(t),a;try{a=await r.getTools()}catch(C){let S=C instanceof Error?C.message:String(C);return Mo(`Failed to read WebMCP registry: ${S}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(C=>C.name===s);if(!l)return Mo(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Mo(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Mo("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 Mo("User declined the tool call.");if(o?.aborted)return Mo("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,$L(n),{signal:u.signal});return DL(C)}catch(C){if(m)return Mo(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Mo("Aborted by cancel()");let S=C instanceof Error?C.message:String(C);return Mo(S)}finally{clearTimeout(y),o&&o.removeEventListener("abort",h)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(await this.deps.loadPolyfill()).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Jp.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,Jp.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??NL;try{return await n(t)}catch(o){return Jp.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=>OL(t,o))}},OL=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Zp={type:"object",properties:{}},BL=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},_L=e=>{if(e===void 0||e==="")return{...Zp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Zp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Zp}}catch{return{...Zp}}},DL=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:UL(t)}]}},Mo=e=>({isError:!0,content:[{type:"text",text:e}]}),NL=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=FL(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
474
|
+
`;function kL(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=PL,document.head.appendChild(e)}function LL(e,t){let n=e.clientWidth-Xf*2-FS,o=e.clientHeight-Xf*2-FS;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function IL(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 US(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");kL();let u=Math.max(0,Math.min(o,n.length-1)),m=r,y=s,h=null,v=1,x=!1,w=E("div","persona-dc-root"),k=E("div","persona-dc-toolbar"),O=E("div","persona-dc-toolbar-lead"),D=E("div","persona-dc-toolbar-trail"),T=Dn({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>qe(-1)}),I=E("div");I.style.position="relative";let A=E("button","persona-dc-title-btn");A.type="button",A.setAttribute("aria-expanded","false"),A.setAttribute("aria-haspopup","listbox");let _=E("span","persona-dc-title-text"),G=E("span","persona-dc-title-chevron"),le=Ht($S.ChevronDown,12,"currentColor",2);le&&G.appendChild(le),A.append(_,G);let ee=E("div","persona-dc-dropdown");ee.setAttribute("role","listbox"),ee.style.display="none";let M=!1;function B(){ee.innerHTML="";for(let Ae=0;Ae<n.length;Ae++){let Ct=n[Ae],Wt=E("button","persona-dc-dropdown-item");Wt.type="button",Wt.setAttribute("role","option"),Wt.setAttribute("aria-current",Ae===u?"true":"false");let mt=E("span");if(mt.textContent=Ct.title,Wt.appendChild(mt),Ct.description){let xn=E("span","persona-dc-dropdown-desc");xn.textContent=Ct.description,Wt.appendChild(xn)}Wt.addEventListener("click",()=>{R(),Dt(Ae)}),ee.appendChild(Wt)}}function H(){M=!M,ee.style.display=M?"":"none",A.setAttribute("aria-expanded",M?"true":"false"),M&&B()}function R(){M&&(M=!1,ee.style.display="none",A.setAttribute("aria-expanded","false"))}A.addEventListener("click",Ae=>{Ae.stopPropagation(),H()});let Z=()=>R();document.addEventListener("click",Z),I.append(A,ee);let V=Dn({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>qe(1)}),ge=E("span","persona-dc-counter");O.append(T,I,V,ge);let ae=null;l&&(ae=Rl({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:Ae=>{m=Ae,et.dataset.device=m,h=null,Ce()}}),D.appendChild(ae.element));let fe=null;if(a){let Ae=E("div","persona-dc-zoom-controls"),Ct=Dn({icon:"minus",label:"Zoom out",size:14,onClick:()=>{h=Math.max(DS,(h??v)-_S),Ce()}});fe=E("span","persona-dc-zoom-level"),fe.title="Reset to 100%",fe.style.cursor="pointer",fe.addEventListener("click",()=>{h=1,Ce()});let Wt=Dn({icon:"plus",label:"Zoom in",size:14,onClick:()=>{h=Math.min(NS,(h??v)+_S),Ce()}}),mt=Dn({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{h=null,Ce()}});Ae.append(Ct,fe,Wt,mt),D.appendChild(Ae)}if(d){let Ae=E("div","persona-dc-separator");D.appendChild(Ae);let Ct=Rl({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:Wt=>{y=Wt,et.dataset.colorScheme=y,F()}});D.appendChild(Ct.element)}let He=E("div","persona-dc-separator");D.appendChild(He);let ve=Dn({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[u].url,"_blank")}});D.appendChild(ve),k.append(O,D);let pe=E("div","persona-dc-stage"),et=E("div","persona-dc-iframe-wrapper");et.dataset.device=m,et.dataset.colorScheme=y;let ye=E("iframe","persona-dc-iframe");ye.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ye.setAttribute("loading","lazy"),ye.title=n[u].title,et.appendChild(ye),pe.appendChild(et),w.append(k,pe),e.appendChild(w);function F(){try{let Ae=ye.contentDocument?.body;if(!Ae)return;y==="dark"?Ae.classList.add("theme-dark"):Ae.classList.remove("theme-dark")}catch{}}ye.addEventListener("load",()=>F());function _e(){let Ae=n[u];_.textContent=Ae.title,ge.textContent=`${u+1} / ${n.length}`,ye.title=Ae.title}function qe(Ae){let Ct=((u+Ae)%n.length+n.length)%n.length;Dt(Ct)}function Dt(Ae){Ae<0||Ae>=n.length||(u=Ae,ye.src=n[u].url,_e(),p?.(u,n[u]))}function Ce(){if(x)return;let Ae=BS[m]??BS.desktop;v=LL(pe,Ae);let Ct=Math.max(DS,Math.min(NS,h??v));IL(et,ye,Ae,Ct,m),fe&&(fe.textContent=`${Math.round(Ct*100)}%`)}let De=new ResizeObserver(()=>Ce());De.observe(pe),_e(),ye.src=n[u].url,requestAnimationFrame(()=>Ce());function we(){x||(x=!0,De.disconnect(),document.removeEventListener("click",Z),w.remove())}return{element:w,goTo:Dt,next:()=>qe(1),prev:()=>qe(-1),getIndex:()=>u,setDevice(Ae){m=Ae,et.dataset.device=Ae,ae?.setSelected(Ae),h=null,Ce()},setColorScheme(Ae){y=Ae,et.dataset.colorScheme=Ae},setZoom(Ae){h=Ae,Ce()},destroy:we}}dm();var jS=16e3,RL=24e3,HL=4096,WL=4,OL=1380533830;function BL(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===OL?new Uint8Array(e,44):new Uint8Array(e)}function _L(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 jl=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:jS,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:jS});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new qi(RL);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=`${_L(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(HL,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*WL));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=BL(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 Xs=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 pa(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new jl(e.runtype);case"browser":if(!Xs.isSupported())throw new Error("Browser speech recognition not supported");return new Xs(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 Gp(e){if(e?.type==="custom"&&e.custom)return pa({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return pa({type:"runtype",runtype:e.runtype});if(Xs.isSupported())return pa({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Jf(e){try{return Gp(e),!0}catch{return!1}}var qS="webmcp:",DL=e=>e.startsWith(qS)?e.slice(qS.length):e,Yp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Xp=class{constructor(t,n){this.config=t;this.deps=n;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return Yp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.deps.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s=FL(r.annotations);return{name:r.name,description:r.description,parametersSchema:$L(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 Ao("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let v=typeof document<"u"&&!!document.modelContext;return Ao(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=DL(t),a;try{a=await r.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return Ao(`Failed to read WebMCP registry: ${x}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(v=>v.name===s);if(!l)return Ao(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Ao(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Ao("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 Ao("User declined the tool call.");if(o?.aborted)return Ao("Aborted by cancel()");let u=new AbortController,m=!1,y=setTimeout(()=>{m=!0,u.abort()},this.timeoutMs),h=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",h,{once:!0}));try{let v=await r.executeTool(l,zL(n),{signal:u.signal});return UL(v)}catch(v){if(m)return Ao(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Ao("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return Ao(x)}finally{clearTimeout(y),o&&o.removeEventListener("abort",h)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(await this.deps.loadPolyfill()).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Yp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Yp.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){let n=this.confirmHandler??jL;try{return await n(t)}catch(o){return Yp.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>NL(t,o))}},NL=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Qp={type:"object",properties:{}},FL=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},$L=e=>{if(e===void 0||e==="")return{...Qp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Qp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Qp}}catch{return{...Qp}}},UL=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:VL(t)}]}},Ao=e=>({isError:!0,content:[{type:"text",text:e}]}),jL=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=qL(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
475
475
|
|
|
476
476
|
Arguments:
|
|
477
477
|
${t}`:"")+(e.description?`
|
|
478
478
|
|
|
479
|
-
${e.description}`:"");return window.confirm(n)},
|
|
479
|
+
${e.description}`:"");return window.confirm(n)},qL=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)}},zL=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},VL=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Jp=class extends Xp{constructor(t){super(t,{recordToolDisplayTitles:dd,getToolDisplayTitle:Oi,loadPolyfill:pd})}};function KL(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 GL(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:KL(o,n)?2:3}function zS(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Zp(e,t){let n=t.trim();if(!n)return[...e].sort(zS);let o=[];for(let r of e){let s=GL(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:zS(r.item,s.item)),o.map(r=>r.item)}function YL(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 VS(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Zp(e.items,t),resolve:e.resolve}}function KS(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=>Zp(t,YL(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 GS(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,l=m=>{typeof m.scrollIntoView=="function"&&m.scrollIntoView({block:"nearest",inline:"nearest"})},d=m=>{let y=m;return s.findIndex(h=>h===y||h.contains(y))},p=m=>{let y=d(m.target);if(y<0)return;let h=y;if(m.key===r)h=Math.min(y+1,s.length-1);else if(m.key===o)h=Math.max(y-1,0);else if(m.key==="Home")h=0;else if(m.key==="End")h=s.length-1;else return;m.preventDefault(),h!==y&&t.onSelect(h)},u=m=>{let y=d(m.target);y>=0&&l(s[y])};return e.addEventListener("keydown",p),e.addEventListener("focusin",u),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(m,y){if(s=m,m.forEach((h,v)=>{h.setAttribute("role","tab");let x=v===y;h.setAttribute("aria-selected",x?"true":"false"),h.tabIndex=x||y<0&&v===0?0:-1}),a){let h=(y>=0?m[y]:void 0)??m[0];h&&typeof h.focus=="function"&&(l(h),h.focus())}},destroy(){e.removeEventListener("keydown",p),e.removeEventListener("focusin",u)}}}0&&(module.exports={ASK_USER_QUESTION_CLIENT_TOOL,ASK_USER_QUESTION_PARAMETERS_SCHEMA,ASK_USER_QUESTION_TOOL_NAME,AgentWidgetClient,AgentWidgetSession,AttachmentManager,BrowserSpeechEngine,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,HistoryProviderError,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,ReadAloudController,SUGGEST_REPLIES_CLIENT_TOOL,SUGGEST_REPLIES_PARAMETERS_SCHEMA,SUGGEST_REPLIES_TOOL_NAME,THEME_ZONES,VERSION,WEBMCP_TOOL_PREFIX,WebMcpBridge,accessibilityPlugin,animationsPlugin,applyFeaturePreferences,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,builtInClientToolsForDispatch,canonicalArtifactDisplayMode,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createAskUserQuestionBubble,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createRovingTablist,createSlashCommandsSource,createSplitButton,createStandardBubble,createStaticMentionSource,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultMentionFilter,defaultParseRules,detectColorScheme,directivePostprocessor,ensureAskUserQuestionSheet,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getAgentWidgetHandles,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isAskUserQuestionMessage,isComponentDirectiveType,isDockedMountMode,isHistoryProviderError,isSuggestRepliesMessage,isVoiceSupported,isWebMcpToolName,isWelcomeVisible,latestAgentSuggestions,listRegisteredStreamAnimations,loadMarkdownParsers,markdownPostprocessor,mergeWithDefaults,normalizeContent,normalizeMediaType,onMarkdownParsersReady,parseAskUserQuestionPayload,parseSuggestRepliesPayload,parseWidgetPreferenceSlice,pickBestVoice,pluginRegistry,reducedMotionPlugin,registerIcons,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveArtifactDisplay,resolveArtifactDisplayMode,resolveConfigPreferences,resolveDockConfig,resolveSanitizer,resolveTokens,resolveWelcomeConfig,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
|
|
480
480
|
//# sourceMappingURL=index.cjs.map
|