@runtypelabs/persona 4.24.0 → 4.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/approval-ui.d.cts +63 -0
- package/dist/approval-ui.d.ts +63 -0
- package/dist/artifacts-ui.d.cts +63 -0
- package/dist/artifacts-ui.d.ts +63 -0
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions.d.cts +63 -0
- package/dist/context-mentions.d.ts +63 -0
- package/dist/event-stream-view.d.cts +63 -0
- package/dist/event-stream-view.d.ts +63 -0
- package/dist/forms-ui.d.cts +74 -0
- package/dist/forms-ui.d.ts +74 -0
- package/dist/index.cjs +42 -42
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +75 -1
- package/dist/index.d.ts +75 -1
- package/dist/index.global.js +27 -27
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +42 -42
- package/dist/index.js.map +1 -1
- package/dist/session-reconnect.d.cts +63 -0
- package/dist/session-reconnect.d.ts +63 -0
- package/dist/smart-dom-reader.d.cts +63 -0
- package/dist/smart-dom-reader.d.ts +63 -0
- package/dist/theme-editor-preview.cjs +49 -49
- package/dist/theme-editor-preview.d.cts +63 -0
- package/dist/theme-editor-preview.d.ts +63 -0
- package/dist/theme-editor-preview.js +27 -27
- package/dist/theme-editor.d.cts +63 -0
- package/dist/theme-editor.d.ts +63 -0
- package/dist/voice-runtime-7DA7MJH4.js +1 -0
- package/dist/voice-runtime.cjs +1 -1
- package/dist/voice-runtime.d.cts +33 -0
- package/dist/voice-runtime.d.ts +33 -0
- package/dist/voice-runtime.js +1 -1
- package/package.json +1 -1
- package/src/index-core.ts +2 -0
- package/src/session.ts +30 -1
- package/src/session.voice.test.ts +72 -1
- package/src/types.ts +71 -0
- package/src/ui.ts +59 -0
- package/src/ui.voice-prewarm.test.ts +222 -0
- package/src/voice/runtype-voice-provider.ts +238 -27
- package/src/voice/voice.test.ts +272 -2
- package/dist/voice-runtime-EFR3R5ES.js +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
"use strict";var TT=Object.create;var Sd=Object.defineProperty;var PT=Object.getOwnPropertyDescriptor;var kT=Object.getOwnPropertyNames;var LT=Object.getPrototypeOf,IT=Object.prototype.hasOwnProperty;var yl=(e,t)=>()=>(e&&(t=e(e=0)),t);var mm=(e,t)=>{for(var n in t)Sd(e,n,{get:t[n],enumerable:!0})},Rv=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of kT(t))!IT.call(e,r)&&r!==n&&Sd(e,r,{get:()=>t[r],enumerable:!(o=PT(t,r))||o.enumerable});return e};var yn=(e,t,n)=>(n=e!=null?TT(LT(e)):{},Rv(t||!e||!e.__esModule?Sd(n,"default",{value:e,enumerable:!0}):n,e)),RT=e=>Rv(Sd({},"__esModule",{value:!0}),e);var Ov={};mm(Ov,{DOMPurify:()=>Wv.default,Marked:()=>Hv.Marked});var Hv,Wv,Bv=yl(()=>{"use strict";Hv=require("marked"),Wv=yn(require("dompurify"),1)});var ga,ef=yl(()=>{"use strict";ga=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 nk(e){return e.replace(/\/+$/,"")}async function ok(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 sp,Cw=yl(()=>{"use strict";ef();sp=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 ga(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=`${nk(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 ok(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 ip,ww=yl(()=>{"use strict";ip=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 xw={};mm(xw,{FallbackSpeechEngine:()=>ip,RuntypeSpeechEngine:()=>sp});var Sw=yl(()=>{"use strict";Cw();ww()});var TR={};mm(TR,{ASK_USER_QUESTION_CLIENT_TOOL:()=>jm,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Um,ASK_USER_QUESTION_TOOL_NAME:()=>Tl,AgentWidgetClient:()=>oi,AgentWidgetSession:()=>ma,AttachmentManager:()=>si,BrowserSpeechEngine:()=>ls,DEFAULT_COMPONENTS:()=>kx,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Zv,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Js,DEFAULT_PALETTE:()=>Ex,DEFAULT_SEMANTIC:()=>Px,DEFAULT_WIDGET_CONFIG:()=>tC,HistoryProviderError:()=>po,PRESETS:()=>_h,PRESET_FULLSCREEN:()=>Dh,PRESET_MINIMAL:()=>Bh,PRESET_SHOP:()=>Oh,ReadAloudController:()=>ri,SUGGEST_REPLIES_CLIENT_TOOL:()=>Vd,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Fm,SUGGEST_REPLIES_TOOL_NAME:()=>qo,THEME_ZONES:()=>Ix,VERSION:()=>So,WEBMCP_TOOL_PREFIX:()=>Al,WebMcpBridge:()=>xu,accessibilityPlugin:()=>_A,animationsPlugin:()=>NA,applyFeaturePreferences:()=>hh,applyThemeVariables:()=>ai,attachHeaderToContainer:()=>di,brandPlugin:()=>FA,buildComposer:()=>ui,buildDefaultHeader:()=>Nf,buildHeader:()=>Sr,buildHeaderWithLayout:()=>Ca,buildMinimalHeader:()=>Ff,builtInClientToolsForDispatch:()=>la,canonicalArtifactDisplayMode:()=>Wn,collectEnrichedPageContext:()=>HA,componentRegistry:()=>Eo,createActionManager:()=>ic,createAgentExperience:()=>au,createAskUserQuestionBubble:()=>NC,createBestAvailableVoiceProvider:()=>bu,createBubbleWithLayout:()=>hS,createCSATFeedback:()=>ru,createComboButton:()=>Fp,createComponentMiddleware:()=>uA,createComponentStreamParser:()=>tu,createDefaultSanitizer:()=>Lm,createDemoCarousel:()=>oM,createDirectivePostprocessor:()=>cC,createDropdownMenu:()=>pi,createFlexibleJsonStreamParser:()=>qC,createIconButton:()=>Dn,createImagePart:()=>tp,createJsonStreamParser:()=>Jd,createLabelButton:()=>_f,createLocalStorageAdapter:()=>Zp,createMarkdownProcessor:()=>xl,createMarkdownProcessorFromConfig:()=>Sl,createMessageActions:()=>zf,createNPSFeedback:()=>su,createPlainTextParser:()=>Qd,createPlugin:()=>jA,createRegexJsonParser:()=>Xd,createRovingTablist:()=>cM,createSlashCommandsSource:()=>lM,createSplitButton:()=>lS,createStandardBubble:()=>wa,createStaticMentionSource:()=>aM,createTextPart:()=>co,createTheme:()=>_l,createThemeObserver:()=>ya,createToggleGroup:()=>Zl,createTypingIndicator:()=>gi,createVoiceProvider:()=>Ia,createWidgetHostLayout:()=>lc,createXmlParser:()=>Zd,default:()=>DA,defaultActionHandlers:()=>yi,defaultJsonActionParser:()=>sc,defaultMentionFilter:()=>Su,defaultParseRules:()=>Hh,detectColorScheme:()=>Fl,directivePostprocessor:()=>dC,ensureAskUserQuestionSheet:()=>aa,escapeHtml:()=>br,extractComponentDirectiveFromMessage:()=>ou,fileToImagePart:()=>YC,formatEnrichedContext:()=>WA,generateAssistantMessageId:()=>ns,generateCodeSnippet:()=>YA,generateMessageId:()=>MC,generateStableSelector:()=>Wh,generateUserMessageId:()=>ra,getActiveTheme:()=>Mo,getAgentWidgetHandles:()=>xA,getColorScheme:()=>ii,getDisplayText:()=>ep,getHeaderLayout:()=>$f,getImageParts:()=>GC,getPreset:()=>BA,hasComponentDirective:()=>ac,hasImages:()=>pa,headerLayouts:()=>$p,highContrastPlugin:()=>UA,initAgentWidget:()=>kh,isAskUserQuestionMessage:()=>vr,isComponentDirectiveType:()=>pA,isDockedMountMode:()=>Ct,isHistoryProviderError:()=>bw,isSuggestRepliesMessage:()=>ni,isVoiceSupported:()=>Uh,isWebMcpToolName:()=>es,isWelcomeVisible:()=>gs,latestAgentSuggestions:()=>qd,listRegisteredStreamAnimations:()=>nS,loadMarkdownParsers:()=>Md,markdownPostprocessor:()=>km,mergeWithDefaults:()=>ta,normalizeContent:()=>KC,normalizeMediaType:()=>ts,onMarkdownParsersReady:()=>Ji,parseAskUserQuestionPayload:()=>Cr,parseSuggestRepliesPayload:()=>$m,parseWidgetPreferenceSlice:()=>fh,pickBestVoice:()=>ua,pluginRegistry:()=>rc,reducedMotionPlugin:()=>$A,registerIcons:()=>jv,registerStreamAnimationPlugin:()=>ql,removeAskUserQuestionSheet:()=>ss,renderComponentDirective:()=>nu,renderLoadingIndicatorWithFallback:()=>qf,renderLucideIcon:()=>le,resolveArtifactDisplay:()=>Wm,resolveArtifactDisplayMode:()=>Vo,resolveConfigPreferences:()=>oc,resolveDockConfig:()=>Bn,resolveSanitizer:()=>_d,resolveTokens:()=>kp,resolveWelcomeConfig:()=>Sa,stripWebMcpPrefix:()=>Hm,themeToCssVariables:()=>Lp,unregisterStreamAnimationPlugin:()=>tS,validateImageFile:()=>QC,validateTheme:()=>Af});module.exports=RT(TR);var Nv=require("marked"),Fv=yn(require("dompurify"),1);var xt=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:DR,load:HT,provide:WT,getSync:fm}=xt({fallbackImport:()=>Promise.resolve().then(()=>(Bv(),Ov))}),Ad=new Set,Dv=()=>{let e=[...Ad];Ad.clear();for(let t of e)try{t()}catch{}};var Md=()=>{let e=fm();return e?Promise.resolve(e):HT().then(t=>(Dv(),t))},Ji=e=>fm()?()=>{}:(Ad.add(e),()=>{Ad.delete(e)}),_v=e=>{WT(e),Dv()},jo=fm;_v({Marked:Nv.Marked,DOMPurify:Fv.default});var G=require("lucide"),$v={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 Mt=(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:jR,load:OT}=xt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")});var Ed=OT;var ee=require("lucide"),BT={activity:ee.Activity,"arrow-down":ee.ArrowDown,"arrow-up":ee.ArrowUp,"arrow-up-right":ee.ArrowUpRight,bot:ee.Bot,"chevron-down":ee.ChevronDown,"chevron-up":ee.ChevronUp,"chevron-right":ee.ChevronRight,"chevron-left":ee.ChevronLeft,check:ee.Check,clipboard:ee.Clipboard,"clipboard-copy":ee.ClipboardCopy,"code-xml":ee.CodeXml,copy:ee.Copy,file:ee.File,"file-code":ee.FileCode,"file-spreadsheet":ee.FileSpreadsheet,"file-text":ee.FileText,"image-plus":ee.ImagePlus,loader:ee.Loader,"loader-circle":ee.LoaderCircle,mic:ee.Mic,paperclip:ee.Paperclip,quote:ee.Quote,"refresh-cw":ee.RefreshCw,search:ee.Search,send:ee.Send,"shield-alert":ee.ShieldAlert,"shield-check":ee.ShieldCheck,"shield-x":ee.ShieldX,square:ee.Square,"thumbs-down":ee.ThumbsDown,"thumbs-up":ee.ThumbsUp,upload:ee.Upload,"volume-2":ee.Volume2,x:ee.X,"at-sign":ee.AtSign,"arrow-left":ee.ArrowLeft,"arrow-right":ee.ArrowRight,"external-link":ee.ExternalLink,ellipsis:ee.Ellipsis,"ellipsis-vertical":ee.EllipsisVertical,menu:ee.Menu,"panel-left":ee.PanelLeft,plus:ee.Plus,minus:ee.Minus,pencil:ee.Pencil,trash:ee.Trash,"trash-2":ee.Trash2,download:ee.Download,maximize:ee.Maximize,minimize:ee.Minimize,"message-square":ee.MessageSquare,star:ee.Star,eye:ee.Eye,history:ee.History},DT=["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"],Ys=new Map(Object.entries(BT)),Zi=new Set,ea=!1,Td=new Set,ym=e=>{let t=[...Td];e&&Td.clear();for(let n of t)try{n()}catch{}},Uv=e=>ea?()=>{}:(Td.add(e),()=>{Td.delete(e)}),bm=()=>{let e=0;for(let t of[...Zi]){let n=Ys.get(t.name);if(!n)continue;Zi.delete(t),e++;let o=Mt(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},jv=e=>{for(let[t,n]of Object.entries(e))Ys.set(t,n);bm()>0&&!ea&&ym(!1)},Vv=e=>{if(!ea){for(let[t,n]of Object.entries(e))Ys.has(t)||Ys.set(t,n);ea=!0,bm(),ym(!0)}},hm=!1,_T=()=>{Ed().then(e=>{if(!ea){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))Ys.has(t)||Ys.set(t,n);ea=!0,bm(),ym(!0)}}).catch(e=>{hm=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},NT=(e,t,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},le=(e,t=24,n="currentColor",o=2)=>{let r=Ys.get(e);if(r)return Mt(r,t,n,o);if(DT.includes(e)){hm&&(hm=!1);let s=NT(t,n,o);if(Zi.size>=500){let a=Zi.values().next().value;a&&Zi.delete(a)}return Zi.add({el:s,name:e,size:t,color:n,strokeWidth:o}),_T(),s}return console.warn(`Lucide icon "${e}" is not in the Persona registry. Register it via registerIcons(), or add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null};Vv($v);var Bd=require("lucide");var qv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function xo(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];qv(s)&&qv(r)?n[o]=xo(s,r):n[o]=r}return n}var vm=Symbol("persona.defaultsProvenance"),Cm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Pd(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return Cm(o)?Pd(o,r):[r]})}function zv(e,t){for(let n of t.split(".")){if(!Cm(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function Kv(e,t){return e?.[vm]??t.filter(n=>zv(e,n)==="explicit")}function wm(e,t){return Object.defineProperty(e,vm,{value:t,enumerable:!0,configurable:!0}),e}function xm(e,t,n){return wm(e,Kv(t,Pd(n)))}function Gv(e,t,n){let o=t[vm];if(o)return o;let r=new Set(Kv(e,n));for(let s of n){let a=zv(t,s);a==="clear"&&r.delete(s),a==="explicit"&&r.add(s)}return[...r]}function Yv(e,t,n){let o={...e};for(let r of t){if(n.includes(r))continue;let s=r.split("."),a=o;for(let l of s.slice(0,-1)){let d=a[l];if(!Cm(d)){a=void 0;break}a[l]={...d},a=a[l]}a&&delete a[s[s.length-1]]}return o}var Qv="var(--persona-components-panel-width)",Sm=Symbol("persona.panelAliasProvenance"),Qs=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),kd=(e,t)=>Qs(e,t)&&e[t]!==void 0,FT=e=>({launcherWidth:kd(e?.launcher,"width"),legacyLauncherWidth:kd(e,"launcherWidth"),sidebarWidth:kd(e?.launcher,"sidebarWidth"),dockWidth:kd(e?.launcher?.dock,"width")}),fr=e=>{let t=e?.[Sm];return t?{...t}:FT(e)},Am=(e,t)=>(Object.defineProperty(e,Sm,{value:t,enumerable:!0,configurable:!0}),e),Mm=(e,t)=>Am(e,fr(t)),Xv=(e,t)=>{let n=t[Sm];if(n)return{...n};let o=fr(e);return Qs(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),Qs(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(Qs(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),Qs(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),Qs(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:Qs(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)};var Js="min(440px, calc(100vw - 24px))",Zv="440px",Cl="40px",Em="How can I help...",hr={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},Zs={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},$T={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:Js,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:Cl,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)"},UT={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:$T,copy:{inputPlaceholder:Em,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:hr,reasoningDisplay:Zs,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},jT={},VT={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},Xs={launcher:VT,features:{toolCallDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,grouped:!0,groupedMode:"collapsible",loadingAnimation:"shimmer"},reasoningDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,loadingAnimation:"shimmer"}},composer:{layout:"single-row",placement:"overlay"},sendButton:{iconName:"arrow-up"},statusIndicator:{mode:"transient"},layout:{contentMaxWidth:"768px",topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:"full"}}}};function Jr(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function eC(e){let t=Jr(e)==="v5"?Xs:jT;return xo(UT,t)}var tC=eC();function Jv(e,t){if(!(!e&&!t))return e?t?xo(e,t):e:t}function ta(e){let t=eC(e);return e?xm(Mm({...t,...e,theme:Jv(t.theme,e.theme),darkTheme:Jv(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let n=t.features?.artifacts,o=e.features?.artifacts,r=t.features?.scrollToBottom,s=e.features?.scrollToBottom,a=t.features?.scrollBehavior,l=e.features?.scrollBehavior,d=t.features?.streamAnimation,p=e.features?.streamAnimation,u=t.features?.askUserQuestion,m=e.features?.askUserQuestion,h=t.features?.history,y=e.features?.history,v=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},C=r===void 0&&s===void 0?void 0:{...r,...s},x=a===void 0&&l===void 0?void 0:{...a,...l},E=d===void 0&&p===void 0?void 0:{...d,...p},H=u===void 0&&m===void 0?void 0:{...u,...m,styles:{...u?.styles,...m?.styles}},B=h===void 0&&y===void 0?void 0:{...h,...y,copy:{...h?.copy,...y?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...C!==void 0?{scrollToBottom:C}:{},...x!==void 0?{scrollBehavior:x}:{},...v!==void 0?{artifacts:v}:{},...E!==void 0?{streamAnimation:E}:{},...H!==void 0?{askUserQuestion:H}:{},...B!==void 0?{history:B}:{}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,Xs):xm(Mm(t),void 0,Xs)}var S=(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},bn=(...e)=>e.filter(Boolean).join(" ");var Ld=require("lucide");var qT=["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"],zT="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",KT="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",GT=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Id=(e,t)=>{let n=S("div",["persona-message-bubble",e,...qT].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},Rd=e=>{let t=S("button",e.expandable?zT:KT);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},Tm=(e,t,n)=>{e.innerHTML="";let o=Mt(t?Ld.ChevronUp:Ld.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},na=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=S("div","persona-flex persona-items-center");Tm(o,n.expanded,n.iconColor);let r=S("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),e.append(t,r),o},Hd=e=>{let t=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();GT(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Wd=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&Tm(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"},Od=(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&&Tm(d,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};function Dd(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?hr:Zs,...e?.future?.v5Defaults===!0?Xs.features?.[n]:{},...e?.features?.[n]}}}}function Zr(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function wl(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?"a moment":t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function yr(e,t,n,o){if(Zr(n,o)!=="row")return e;e.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,e.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=e.querySelector(":scope > button");if(!r)return e;r.className="persona-activity-header";let s=o==="tool"?t.toolCall:t.reasoning,a=s?.status!=="complete",l=t.approval?.status??t.toolCall?.approvalStatus,d=l==="denied"?"denied":l==="pending"?"awaiting-approval":t.toolCall?.success===!1?"error":a?s?.status==="pending"?"pending":"running":"done";e.dataset.activityState=d;let p=S("span","persona-activity-icon");p.dataset.activityIcon=d;let u={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},m=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,h=m?le(m,16,"currentColor",2):d==="pending"?Mt(Bd.Circle,16,"currentColor",2):d==="awaiting-approval"?Mt(Bd.Clock,16,"currentColor",2):le(u[d],16,"currentColor",2);h&&p.appendChild(h),r.querySelector(".persona-reasoning-header-icon")?.remove();let y=o==="tool"?"toolCallDisplay":"reasoningDisplay",v=n.features?.[y]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((v==="always"||v==="active"&&d!=="done")&&r.prepend(p),o==="tool"&&s){let H=S("span","persona-activity-duration");a&&s.startedAt&&H.setAttribute("data-tool-elapsed",String(s.startedAt));let B=(o==="tool"?t.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);H.textContent=B===void 0?"":wl(B),r.appendChild(H)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let E=e.querySelector(":scope > .persona-border-t");return E?.classList.add("persona-activity-body"),E&&(E.id=`activity-details-${t.id}`,r.setAttribute("aria-controls",E.id)),e}function nC(e){let t=new Set,n=new Set,o=new Set,r=new Map,s=a=>{clearTimeout(r.get(a)),r.delete(a)};return{observe(a,l,d,p={}){let u=l==="tool"?a.toolCall:a.reasoning;if(!(!u||n.has(a.id))&&(!t.has(a.id)&&u.status!=="complete"&&u.chunks?.some(Boolean)&&(t.add(a.id),p.autoExpand!==!1&&d.add(a.id)),t.has(a.id)&&u.status==="complete"&&!o.has(a.id))){if(o.add(a.id),p.autoCollapseDelay===!1)return;r.set(a.id,setTimeout(()=>{r.delete(a.id),d.delete(a.id),e(a.id,l)},p.autoCollapseDelay??1e3))}},manual(a){n.add(a),s(a)},prune(a){for(let l of new Set([...t,...n,...o]))a.has(l)||(s(l),t.delete(l),n.delete(l),o.delete(l))},clear(){for(let a of r.keys())s(a);t.clear(),n.clear(),o.clear()}}}function oC(e,t,n,o){let r=S("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let s=S("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let a=S("div","");typeof o=="string"?a.textContent=o:a.appendChild(o),na(s,a,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=S("div","persona-border-t");return l.id=`activity-details-${e.id}`,l.style.display=n?"":"none",s.setAttribute("aria-controls",l.id),r.append(s,l),yr(r,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",t.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:l}}var YT=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),ei=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=YT(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},Pm=(e,t,n)=>{!t.parentElement||e.parentElement!==t.parentElement||(n.mode==="transient"?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))};function rC(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 Hn(e){return e?.type==="runtype"||e?.type==="custom"}var QT=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function sC(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:QT()}catch{return!1}}var XT=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},xl=e=>{let t=null;return n=>{let o=jo();if(!o)return br(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=XT(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Sl=e=>e?xl({markedOptions:e.options,renderer:e.renderer}):xl(),JT=xl(),km=e=>JT(e),br=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),aC=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),iC=e=>`%%FORM_PLACEHOLDER_${e}%%`,lC=(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=iC(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=iC(t.length);return t.push({token:s,type:r}),s}),n},cC=e=>{let t=Sl(e);return n=>{let o=[],r=lC(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="${aC(l)}"></div>`;s=s.replace(d,u)}),s}},dC=e=>{let t=[],n=lC(e,t),o=km(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="${aC(s)}"></div>`;o=o.replace(a,d)}),o};var ZT={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},eP=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Lm=()=>{let e=null;return t=>{let n=jo();if(!n)return br(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!eP.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,ZT)}},_d=e=>e===!1?null:typeof e=="function"?e:Lm();var pC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,uC=e=>e.includes("|"),gC=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},tP=e=>`| ${e.join(" | ")} |`,nP=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,oP=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),mC=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 fC="var(--persona-md-table-scroll-fade, 24px)",hC=new WeakSet;function bC(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 yC(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":fC),e.style.setProperty("--persona-fade-r",r<=1?"0px":fC)}function Im(e){hC.has(e)||(hC.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&yC(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(yC)}var Al="webmcp:",Rm=new Map,Nd=e=>{Rm.clear();for(let t of e){let n=t.title?.trim();n&&Rm.set(t.name,n)}},oa=e=>Rm.get(Hm(e)),vC=null;function wC(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${rP(t.join(""))}`}function CC(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function rP(e){let t=CC(e,0).toString(36),n=CC(e,2654435761).toString(36);return`${t}.${n}`}var Hm=e=>e.startsWith(Al)?e.slice(Al.length):e,es=e=>e.startsWith(Al),Fd=()=>vC?vC():import("@mcp-b/webmcp-polyfill");var{setLoader:EH,load:sP}=xt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var xC=sP;function Wn(e){return e==="card"?"collapsed":e}function ts(e){return e.split(";",1)[0].trim().toLowerCase()}function iP(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(ts(r)===t)return{mode:Wn(s),selector:ts(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(ts(r)===o)return{mode:Wn(s),selector:o}}function Wm(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:Wn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?ts(t.file.mimeType):void 0,d=l?iP(o.files.byMediaType,l):void 0;if(l&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:l,selector:d.selector}};if(o.files.default)return{mode:Wn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:Wn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:Wn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:Wn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:Wn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Vo(e,t){return Wm(e,t).mode}function Ml(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var aP="agent_",lP="flow_";function SC(e){return e.startsWith(aP)?{kind:"agentId",agentId:e}:e.startsWith(lP)?{kind:"flowId",flowId:e}:null}function AC(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=SC(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=SC(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 MC(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ra(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ns(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function EC(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}var os=require("partial-json");var Tl="ask_user_question",El=8,sa="data-persona-ask-sheet-for",cP="Other",dP="Other\u2026",PC="Type your own answer here",kC="Send",pP="Next",uP="Back",gP="Submit all",mP="Skip",fP=3,Om="data-ask-current-index",Bm="data-ask-question-count",LC="data-ask-answers",Dm="data-ask-grouped",IC="data-ask-layout",hP=e=>e.layout==="pills"?"pills":"rows",yP=e=>e.getAttribute(IC)==="pills"?"pills":"rows",TC=!1,RC=e=>e.replace(/["\\]/g,"\\$&"),vr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Tl,$d=e=>e?.features?.askUserQuestion??{},Cr=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,os.parse)(r,os.STR|os.OBJ|os.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>El&&!TC&&(TC=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${El}.`)),t.slice(0,El)},bP=e=>Pl(e)[0]??null,vP=(e,t)=>Pl(e)[t]??null,HC=(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))},WC=(e,t,n)=>{if(e!=="rows")return null;let o=S("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=S("span","persona-ask-row-check");o.appendChild(r)}else{let r=S("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},CP=(e,t,n,o)=>{let s=S("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=S("span","persona-ask-row-content"),l=S("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let p=S("span","persona-ask-row-description");p.textContent=e.description,a.appendChild(p)}s.appendChild(a);let d=WC(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},wP=e=>{let n=S("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},xP=(e,t,n,o)=>{let s=S("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,d=(Array.isArray(e?.options)?e.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<fP;u++)s.appendChild(wP(o));return s}if(d.forEach((u,m)=>{s.appendChild(CP(u,m,o,a))}),e?.allowFreeText!==!1){let u=o==="rows"?cP:dP;if(o==="rows"){let m=S("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(d.length)),m.setAttribute("data-ask-other-row","true");let h=S("span","persona-ask-row-content"),y=document.createElement("input");y.type="text",y.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",y.placeholder=t.freeTextPlaceholder??PC,y.setAttribute("data-ask-free-text-input","true"),y.setAttribute("aria-label",t.freeTextLabel??u),h.appendChild(y),m.appendChild(h);let v=WC(o,a,d.length);v&&m.appendChild(v),s.appendChild(m)}else{let m=S("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=t.freeTextLabel??u,s.appendChild(m)}}return s},OC=(e,t)=>{let o=S("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??PC,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=S("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??kC,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},SP=e=>{let t=S("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=S("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??kC,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},AP=(e,t,n)=>{let o=S("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=S("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??uP,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=S("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=S("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??mP,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=S("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=e===t-1;return l.textContent=d?n.submitAllLabel??gP:n.nextLabel??pP,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},ti=e=>{let t=e.getAttribute(LC);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},BC=(e,t)=>{e.setAttribute(LC,JSON.stringify(t))},lo=e=>{let t=Number(e.getAttribute(Om)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},MP=(e,t)=>{e.setAttribute(Om,String(Math.max(0,Math.floor(t))))},ia=e=>{let t=Number(e.getAttribute(Bm)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},rs=e=>e.getAttribute(Dm)==="true",EP=(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},TP=(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)))},Ud=(e,t)=>{let{payload:n}=Cr(t),o=Pl(n),r=ti(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},DC=e=>{let t=ti(e),n=lo(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="")},_C=e=>{if(!rs(e))return;let t=ti(e),n=lo(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}},_m=(e,t,n)=>{let o=$d(n),r=yP(e),{payload:s,complete:a}=Cr(t),l=rs(e),d=lo(e),p=ia(e),u=l?vP(s,d):bP(s),m=!!u?.multiSelect,h=e.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=l?`${d+1}/${p}`:"");let y=e.querySelector('[data-ask-stepper="true"]');y&&y.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let H=typeof u?.question=="string"?u.question:"";v.textContent=H,v.classList.toggle("persona-ask-question-skeleton",!H&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let H=xP(u,o,a,r);C.replaceWith(H)}if(r!=="rows"){let H=e.querySelector('[data-ask-free-text-row="true"]');H&&H.replaceWith(OC(o,r))}let x=e.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!x?e.appendChild(SP(o)):(!m||l)&&x&&x.remove(),e.setAttribute("data-multi-select",m?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(l){let H=AP(d,p,o);E?E.replaceWith(H):e.appendChild(H)}else E&&E.remove();DC(e),_C(e)},PP=(e,t,n)=>{let o=$d(t),r=hP(o),s=e.toolCall.id,a=Pl(n),l=Math.max(1,a.length),d=l>1,p=EP(e,a),u=d?TP(e,l):0,m=S("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(sa,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",e.id),m.setAttribute(Bm,String(l)),m.setAttribute(Om,String(u)),m.setAttribute(Dm,d?"true":"false"),m.setAttribute(IC,r),BC(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`),HC(m,o);let h=S("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),y=S("div","persona-ask-sheet-question persona-flex-1");y.setAttribute("data-ask-question","true"),y.textContent="",h.appendChild(y);let v=S("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",h.appendChild(v),m.appendChild(h);let x=S("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return x.setAttribute("data-ask-pill-list","true"),x.setAttribute("role","group"),m.appendChild(x),r!=="rows"&&m.appendChild(OC(o,r)),_m(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},kP=(e,t,n)=>{let{payload:o}=Cr(t),r=Math.max(1,Pl(o).length);r>ia(e)&&(e.setAttribute(Bm,String(r)),r>1&&!rs(e)&&e.setAttribute(Dm,"true")),_m(e,t,n)},NC=(e,t)=>{let n=S("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=$d(t);HC(n,o);let r=S("span","persona-ask-stub-label"),{complete:s}=Cr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},aa=(e,t,n)=>{if(!n||!vr(e)||$d(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${sa}]`).forEach(p=>{p.getAttribute(sa)!==r&&p.remove()});let a=n.querySelector(`[${sa}="${RC(r)}"]`);if(a){kP(a,e,t);return}let{payload:l}=Cr(e),d=PP(e,t,l);n.appendChild(d)},ss=(e,t)=>{if(!e)return;let n=t?`[${sa}="${RC(t)}"]`:`[${sa}]`;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)})},Nm=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),is=(e,t)=>{let n=ti(e),o=lo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,BC(e,n),DC(e),_C(e)},jd=(e,t,n,o)=>{let r=ia(e),s=Math.max(0,Math.min(r-1,o));MP(e,s),_m(e,t,n)};var qo="suggest_replies";var Fm={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},Vd={name:qo,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:Fm,origin:"sdk",annotations:{readOnlyHint:!0}},$C=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ni=e=>e.variant==="tool"&&e.toolCall?.name===qo,$m=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},qd=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!ni(n))continue;let o=$m(n.toolCall?.args);return o.length>0?o:null}return null},FC=new Set,LP=(e,t,n)=>{let o=`${e}:${t}:${n}`;FC.has(o)||(FC.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},as=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&&LP(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 Um={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:El,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},jm={name:Tl,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:Um,origin:"sdk",annotations:{readOnlyHint:!0}},la=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(jm),as(e).expose&&t.push(Vd),t};var IP=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),RP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),HP=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=IP(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:RP(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},Vm=(e,t)=>{let n=[],o=[],r=[],s="",a,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let d of e){let p=HP(d);if(p){let m=d.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(m===void 0||m!==a)&&l(),o.length===0&&(s=d.createdAt,a=m),o.some(h=>h.toolCallId===p.call.toolCallId)||(o.push(p.call),r.push(p.result));continue}let u=t(d);u&&(l(),n.push(u))}return l(),n};var wr=require("partial-json"),zd=e=>e.replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ca=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)}},
|
|
1
|
+
"use strict";var DT=Object.create;var Sd=Object.defineProperty;var _T=Object.getOwnPropertyDescriptor;var NT=Object.getOwnPropertyNames;var FT=Object.getPrototypeOf,$T=Object.prototype.hasOwnProperty;var yl=(e,t)=>()=>(e&&(t=e(e=0)),t);var hm=(e,t)=>{for(var n in t)Sd(e,n,{get:t[n],enumerable:!0})},$v=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of NT(t))!$T.call(e,r)&&r!==n&&Sd(e,r,{get:()=>t[r],enumerable:!(o=_T(t,r))||o.enumerable});return e};var yn=(e,t,n)=>(n=e!=null?DT(FT(e)):{},$v(t||!e||!e.__esModule?Sd(n,"default",{value:e,enumerable:!0}):n,e)),UT=e=>$v(Sd({},"__esModule",{value:!0}),e);var Vv={};hm(Vv,{DOMPurify:()=>jv.default,Marked:()=>Uv.Marked});var Uv,jv,qv=yl(()=>{"use strict";Uv=require("marked"),jv=yn(require("dompurify"),1)});var ga,nf=yl(()=>{"use strict";ga=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 uk(e){return e.replace(/\/+$/,"")}async function gk(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 sp,kw=yl(()=>{"use strict";nf();sp=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 ga(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=`${uk(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 gk(a));let l=a.body.getReader();for(;;){let{done:d,value:u}=await l.read();if(t!==this.generation){await l.cancel().catch(()=>{});return}if(d)break;u&&u.byteLength>0&&r.enqueue(u)}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 ip,Lw=yl(()=>{"use strict";ip=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 Iw={};hm(Iw,{FallbackSpeechEngine:()=>ip,RuntypeSpeechEngine:()=>sp});var Rw=yl(()=>{"use strict";kw();Lw()});var jR={};hm(jR,{ASK_USER_QUESTION_CLIENT_TOOL:()=>qm,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Vm,ASK_USER_QUESTION_TOOL_NAME:()=>Tl,AgentWidgetClient:()=>oi,AgentWidgetSession:()=>ma,AttachmentManager:()=>si,BrowserSpeechEngine:()=>ls,DEFAULT_COMPONENTS:()=>_x,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>lC,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Js,DEFAULT_PALETTE:()=>Ox,DEFAULT_SEMANTIC:()=>Dx,DEFAULT_WIDGET_CONFIG:()=>dC,HistoryProviderError:()=>po,PRESETS:()=>Fh,PRESET_FULLSCREEN:()=>Nh,PRESET_MINIMAL:()=>_h,PRESET_SHOP:()=>Dh,ReadAloudController:()=>ri,SUGGEST_REPLIES_CLIENT_TOOL:()=>Vd,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Um,SUGGEST_REPLIES_TOOL_NAME:()=>qo,THEME_ZONES:()=>Fx,VERSION:()=>So,WEBMCP_TOOL_PREFIX:()=>Al,WebMcpBridge:()=>xu,accessibilityPlugin:()=>KA,animationsPlugin:()=>GA,applyFeaturePreferences:()=>bh,applyThemeVariables:()=>ai,attachHeaderToContainer:()=>di,brandPlugin:()=>YA,buildComposer:()=>ui,buildDefaultHeader:()=>$f,buildHeader:()=>Sr,buildHeaderWithLayout:()=>Ca,buildMinimalHeader:()=>Uf,builtInClientToolsForDispatch:()=>la,canonicalArtifactDisplayMode:()=>Wn,collectEnrichedPageContext:()=>UA,componentRegistry:()=>Eo,createActionManager:()=>ic,createAgentExperience:()=>au,createAskUserQuestionBubble:()=>GC,createBestAvailableVoiceProvider:()=>bu,createBubbleWithLayout:()=>MS,createCSATFeedback:()=>ru,createComboButton:()=>Fp,createComponentMiddleware:()=>wA,createComponentStreamParser:()=>tu,createDefaultSanitizer:()=>Rm,createDemoCarousel:()=>uM,createDirectivePostprocessor:()=>bC,createDropdownMenu:()=>pi,createFlexibleJsonStreamParser:()=>ew,createIconButton:()=>Dn,createImagePart:()=>tp,createJsonStreamParser:()=>Jd,createLabelButton:()=>Ff,createLocalStorageAdapter:()=>Zp,createMarkdownProcessor:()=>xl,createMarkdownProcessorFromConfig:()=>Sl,createMessageActions:()=>Gf,createNPSFeedback:()=>su,createPlainTextParser:()=>Qd,createPlugin:()=>JA,createRegexJsonParser:()=>Xd,createRovingTablist:()=>vM,createSlashCommandsSource:()=>bM,createSplitButton:()=>yS,createStandardBubble:()=>wa,createStaticMentionSource:()=>yM,createTextPart:()=>co,createTheme:()=>_l,createThemeObserver:()=>ya,createToggleGroup:()=>Zl,createTypingIndicator:()=>gi,createVoiceProvider:()=>Ia,createWidgetHostLayout:()=>lc,createXmlParser:()=>Zd,default:()=>zA,defaultActionHandlers:()=>yi,defaultJsonActionParser:()=>sc,defaultMentionFilter:()=>Su,defaultParseRules:()=>Oh,detectColorScheme:()=>Fl,directivePostprocessor:()=>vC,ensureAskUserQuestionSheet:()=>aa,escapeHtml:()=>br,extractComponentDirectiveFromMessage:()=>ou,fileToImagePart:()=>rw,formatEnrichedContext:()=>jA,generateAssistantMessageId:()=>ns,generateCodeSnippet:()=>rM,generateMessageId:()=>WC,generateStableSelector:()=>Bh,generateUserMessageId:()=>ra,getActiveTheme:()=>Mo,getAgentWidgetHandles:()=>IA,getColorScheme:()=>ii,getDisplayText:()=>ep,getHeaderLayout:()=>jf,getImageParts:()=>ow,getPreset:()=>qA,hasComponentDirective:()=>ac,hasImages:()=>pa,headerLayouts:()=>$p,highContrastPlugin:()=>XA,initAgentWidget:()=>Ih,isAskUserQuestionMessage:()=>vr,isComponentDirectiveType:()=>CA,isDockedMountMode:()=>Ct,isHistoryProviderError:()=>Tw,isSuggestRepliesMessage:()=>ni,isVoiceSupported:()=>Vh,isWebMcpToolName:()=>es,isWelcomeVisible:()=>gs,latestAgentSuggestions:()=>qd,listRegisteredStreamAnimations:()=>pS,loadMarkdownParsers:()=>Md,markdownPostprocessor:()=>Im,mergeWithDefaults:()=>ta,normalizeContent:()=>nw,normalizeMediaType:()=>ts,onMarkdownParsersReady:()=>Ji,parseAskUserQuestionPayload:()=>Cr,parseSuggestRepliesPayload:()=>jm,parseWidgetPreferenceSlice:()=>yh,pickBestVoice:()=>ua,pluginRegistry:()=>rc,reducedMotionPlugin:()=>QA,registerIcons:()=>Jv,registerStreamAnimationPlugin:()=>ql,removeAskUserQuestionSheet:()=>ss,renderComponentDirective:()=>nu,renderLoadingIndicatorWithFallback:()=>Kf,renderLucideIcon:()=>le,resolveArtifactDisplay:()=>Bm,resolveArtifactDisplayMode:()=>Vo,resolveConfigPreferences:()=>oc,resolveDockConfig:()=>Bn,resolveSanitizer:()=>_d,resolveTokens:()=>kp,resolveWelcomeConfig:()=>Sa,stripWebMcpPrefix:()=>Om,themeToCssVariables:()=>Lp,unregisterStreamAnimationPlugin:()=>dS,validateImageFile:()=>sw,validateTheme:()=>Ef});module.exports=UT(jR);var Gv=require("marked"),Yv=yn(require("dompurify"),1);var xt=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:p=>{o=p,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:p=>{r=p},getSync:()=>r}};var{setLoader:ZR,load:jT,provide:VT,getSync:ym}=xt({fallbackImport:()=>Promise.resolve().then(()=>(qv(),Vv))}),Ad=new Set,zv=()=>{let e=[...Ad];Ad.clear();for(let t of e)try{t()}catch{}};var Md=()=>{let e=ym();return e?Promise.resolve(e):jT().then(t=>(zv(),t))},Ji=e=>ym()?()=>{}:(Ad.add(e),()=>{Ad.delete(e)}),Kv=e=>{VT(e),zv()},jo=ym;Kv({Marked:Gv.Marked,DOMPurify:Yv.default});var G=require("lucide"),Qv={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 Mt=(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(([u,p])=>{u!=="stroke"&&d.setAttribute(u,String(p))}),r.appendChild(d)}),r};var{setLoader:sH,load:qT}=xt({fallbackImport:()=>import("@runtypelabs/persona/icons-extra")});var Ed=qT;var ee=require("lucide"),zT={activity:ee.Activity,"arrow-down":ee.ArrowDown,"arrow-up":ee.ArrowUp,"arrow-up-right":ee.ArrowUpRight,bot:ee.Bot,"chevron-down":ee.ChevronDown,"chevron-up":ee.ChevronUp,"chevron-right":ee.ChevronRight,"chevron-left":ee.ChevronLeft,check:ee.Check,clipboard:ee.Clipboard,"clipboard-copy":ee.ClipboardCopy,"code-xml":ee.CodeXml,copy:ee.Copy,file:ee.File,"file-code":ee.FileCode,"file-spreadsheet":ee.FileSpreadsheet,"file-text":ee.FileText,"image-plus":ee.ImagePlus,loader:ee.Loader,"loader-circle":ee.LoaderCircle,mic:ee.Mic,paperclip:ee.Paperclip,quote:ee.Quote,"refresh-cw":ee.RefreshCw,search:ee.Search,send:ee.Send,"shield-alert":ee.ShieldAlert,"shield-check":ee.ShieldCheck,"shield-x":ee.ShieldX,square:ee.Square,"thumbs-down":ee.ThumbsDown,"thumbs-up":ee.ThumbsUp,upload:ee.Upload,"volume-2":ee.Volume2,x:ee.X,"at-sign":ee.AtSign,"arrow-left":ee.ArrowLeft,"arrow-right":ee.ArrowRight,"external-link":ee.ExternalLink,ellipsis:ee.Ellipsis,"ellipsis-vertical":ee.EllipsisVertical,menu:ee.Menu,"panel-left":ee.PanelLeft,plus:ee.Plus,minus:ee.Minus,pencil:ee.Pencil,trash:ee.Trash,"trash-2":ee.Trash2,download:ee.Download,maximize:ee.Maximize,minimize:ee.Minimize,"message-square":ee.MessageSquare,star:ee.Star,eye:ee.Eye,history:ee.History},KT=["user","mail","phone","calendar","clock","building","map-pin","lock","key","credit-card","hash","globe","link","circle-check","circle-x","triangle-alert","info","ban","shield","house","pen-line","save","share","funnel","settings","rotate-cw","shopping-cart","shopping-bag","package","truck","tag","gift","receipt","wallet","store","dollar-sign","percent","play","pause","volume-x","camera","image","film","headphones","message-circle","bell","heart","eye-off","bookmark","calendar-days","timer","folder","folder-open","files","chart-column","sparkles","zap","sun","moon","flag","lightbulb","monitor","smartphone"],Ys=new Map(Object.entries(zT)),Zi=new Set,ea=!1,Td=new Set,vm=e=>{let t=[...Td];e&&Td.clear();for(let n of t)try{n()}catch{}},Xv=e=>ea?()=>{}:(Td.add(e),()=>{Td.delete(e)}),Cm=()=>{let e=0;for(let t of[...Zi]){let n=Ys.get(t.name);if(!n)continue;Zi.delete(t),e++;let o=Mt(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},Jv=e=>{for(let[t,n]of Object.entries(e))Ys.set(t,n);Cm()>0&&!ea&&vm(!1)},Zv=e=>{if(!ea){for(let[t,n]of Object.entries(e))Ys.has(t)||Ys.set(t,n);ea=!0,Cm(),vm(!0)}},bm=!1,GT=()=>{Ed().then(e=>{if(!ea){for(let[t,n]of Object.entries(e.EXTRA_LUCIDE_ICONS))Ys.has(t)||Ys.set(t,n);ea=!0,Cm(),vm(!0)}}).catch(e=>{bm=!0,console.warn("[Persona] Failed to load the icons-extra chunk",e)})},YT=(e,t,n)=>{let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(n)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),o.setAttribute("data-persona-icon-pending","true"),o},le=(e,t=24,n="currentColor",o=2)=>{let r=Ys.get(e);if(r)return Mt(r,t,n,o);if(KT.includes(e)){bm&&(bm=!1);let s=YT(t,n,o);if(Zi.size>=500){let a=Zi.values().next().value;a&&Zi.delete(a)}return Zi.add({el:s,name:e,size:t,color:n,strokeWidth:o}),GT(),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};Zv(Qv);var Bd=require("lucide");var eC=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function xo(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];eC(s)&&eC(r)?n[o]=xo(s,r):n[o]=r}return n}var wm=Symbol("persona.defaultsProvenance"),xm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Pd(e,t=""){return Object.entries(e).flatMap(([n,o])=>{let r=t?`${t}.${n}`:n;return xm(o)?Pd(o,r):[r]})}function tC(e,t){for(let n of t.split(".")){if(!xm(e)||!Object.prototype.hasOwnProperty.call(e,n))return"absent";if(e=e[n],e===void 0)return"clear"}return"explicit"}function nC(e,t){return e?.[wm]??t.filter(n=>tC(e,n)==="explicit")}function Sm(e,t){return Object.defineProperty(e,wm,{value:t,enumerable:!0,configurable:!0}),e}function Am(e,t,n){return Sm(e,nC(t,Pd(n)))}function oC(e,t,n){let o=t[wm];if(o)return o;let r=new Set(nC(e,n));for(let s of n){let a=tC(t,s);a==="clear"&&r.delete(s),a==="explicit"&&r.add(s)}return[...r]}function rC(e,t,n){let o={...e};for(let r of t){if(n.includes(r))continue;let s=r.split("."),a=o;for(let l of s.slice(0,-1)){let d=a[l];if(!xm(d)){a=void 0;break}a[l]={...d},a=a[l]}a&&delete a[s[s.length-1]]}return o}var sC="var(--persona-components-panel-width)",Mm=Symbol("persona.panelAliasProvenance"),Qs=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),kd=(e,t)=>Qs(e,t)&&e[t]!==void 0,QT=e=>({launcherWidth:kd(e?.launcher,"width"),legacyLauncherWidth:kd(e,"launcherWidth"),sidebarWidth:kd(e?.launcher,"sidebarWidth"),dockWidth:kd(e?.launcher?.dock,"width")}),fr=e=>{let t=e?.[Mm];return t?{...t}:QT(e)},Em=(e,t)=>(Object.defineProperty(e,Mm,{value:t,enumerable:!0,configurable:!0}),e),Tm=(e,t)=>Em(e,fr(t)),iC=(e,t)=>{let n=t[Mm];if(n)return{...n};let o=fr(e);return Qs(t,"launcherWidth")&&(o.legacyLauncherWidth=t.launcherWidth!==void 0),Qs(t,"launcher")&&t.launcher===void 0?(o.launcherWidth=!1,o.sidebarWidth=!1,o.dockWidth=!1,o):(Qs(t.launcher,"width")&&(o.launcherWidth=t.launcher?.width!==void 0),Qs(t.launcher,"sidebarWidth")&&(o.sidebarWidth=t.launcher?.sidebarWidth!==void 0),Qs(t.launcher,"dock")&&t.launcher?.dock===void 0?o.dockWidth=!1:Qs(t.launcher?.dock,"width")&&(o.dockWidth=t.launcher?.dock?.width!==void 0),o)};var Js="min(440px, calc(100vw - 24px))",lC="440px",Cl="40px",Pm="How can I help...",hr={collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},Zs={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},XT={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:Js,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:Cl,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)"},JT={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:XT,copy:{inputPlaceholder:Pm,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:hr,reasoningDisplay:Zs,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},ZT={},eP={variant:"circle",width:"min(400px, calc(100vw - 24px))",headerIconSize:"20px"},Xs={launcher:eP,features:{toolCallDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,grouped:!0,groupedMode:"collapsible",loadingAnimation:"shimmer"},reasoningDisplay:{variant:"row",iconVisibility:"active",autoExpand:!1,loadingAnimation:"shimmer"}},composer:{layout:"single-row",placement:"overlay"},sendButton:{iconName:"arrow-up"},statusIndicator:{mode:"transient"},layout:{contentMaxWidth:"768px",topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:"full"}}}};function Jr(e){return e?.future?.v5Defaults===!0?"v5":"v4"}function cC(e){let t=Jr(e)==="v5"?Xs:ZT;return xo(JT,t)}var dC=cC();function aC(e,t){if(!(!e&&!t))return e?t?xo(e,t):e:t}function ta(e){let t=cC(e);return e?Am(Tm({...t,...e,theme:aC(t.theme,e.theme),darkTheme:aC(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let n=t.features?.artifacts,o=e.features?.artifacts,r=t.features?.scrollToBottom,s=e.features?.scrollToBottom,a=t.features?.scrollBehavior,l=e.features?.scrollBehavior,d=t.features?.streamAnimation,u=e.features?.streamAnimation,p=t.features?.askUserQuestion,m=e.features?.askUserQuestion,h=t.features?.history,y=e.features?.history,v=n===void 0&&o===void 0?void 0:{...n,...o,layout:{...n?.layout,...o?.layout}},C=r===void 0&&s===void 0?void 0:{...r,...s},x=a===void 0&&l===void 0?void 0:{...a,...l},E=d===void 0&&u===void 0?void 0:{...d,...u},H=p===void 0&&m===void 0?void 0:{...p,...m,styles:{...p?.styles,...m?.styles}},B=h===void 0&&y===void 0?void 0:{...h,...y,copy:{...h?.copy,...y?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay},...C!==void 0?{scrollToBottom:C}:{},...x!==void 0?{scrollBehavior:x}:{},...v!==void 0?{artifacts:v}:{},...E!==void 0?{streamAnimation:E}:{},...H!==void 0?{askUserQuestion:H}:{},...B!==void 0?{history:B}:{}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,Xs):Am(Tm(t),void 0,Xs)}var S=(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},bn=(...e)=>e.filter(Boolean).join(" ");var Ld=require("lucide");var tP=["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"],nP="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",oP="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",rP=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Id=(e,t)=>{let n=S("div",["persona-message-bubble",e,...tP].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},Rd=e=>{let t=S("button",e.expandable?nP:oP);return t.type="button",e.expandable&&(t.setAttribute("aria-expanded",e.expanded?"true":"false"),t.setAttribute("data-expand-header","true")),t.setAttribute("data-bubble-type",e.bubbleType),t},km=(e,t,n)=>{e.innerHTML="";let o=Mt(t?Ld.ChevronUp:Ld.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},na=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=S("div","persona-flex persona-items-center");km(o,n.expanded,n.iconColor);let r=S("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return r.append(o),e.append(t,r),o},Hd=e=>{let t=S("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(t.setAttribute("data-persona-collapsed-preview",e.previewKind),t.style.display="none",t.style.whiteSpace="pre-wrap",!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let n=e.renderPreview?.();rP(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Wd=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&km(e.toggleIcon,e.expanded,e.iconColor),e.content.style.display=e.expanded?"":"none",e.collapsedPreview.style.display=e.expanded?"none":e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?"":"none"},Od=(e,t,n)=>{let o=n.stateSet.has(e),r=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),a=t.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!r||!s)return;r.setAttribute("aria-expanded",o?"true":"false");let d=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");d&&km(d,o,n.iconColor),s.style.display=o?"":"none",a&&(a.style.display=o?"none":a.textContent||a.childNodes.length?"":"none")};function Dd(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?hr:Zs,...e?.future?.v5Defaults===!0?Xs.features?.[n]:{},...e?.features?.[n]}}}}function Zr(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function wl(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?"a moment":t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function yr(e,t,n,o){if(Zr(n,o)!=="row")return e;e.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,e.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(e.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let r=e.querySelector(":scope > button");if(!r)return e;r.className="persona-activity-header";let s=o==="tool"?t.toolCall:t.reasoning,a=s?.status!=="complete",l=t.approval?.status??t.toolCall?.approvalStatus,d=l==="denied"?"denied":l==="pending"?"awaiting-approval":t.toolCall?.success===!1?"error":a?s?.status==="pending"?"pending":"running":"done";e.dataset.activityState=d;let u=S("span","persona-activity-icon");u.dataset.activityIcon=d;let p={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},m=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,h=m?le(m,16,"currentColor",2):d==="pending"?Mt(Bd.Circle,16,"currentColor",2):d==="awaiting-approval"?Mt(Bd.Clock,16,"currentColor",2):le(p[d],16,"currentColor",2);h&&u.appendChild(h),r.querySelector(".persona-reasoning-header-icon")?.remove();let y=o==="tool"?"toolCallDisplay":"reasoningDisplay",v=n.features?.[y]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((v==="always"||v==="active"&&d!=="done")&&r.prepend(u),o==="tool"&&s){let H=S("span","persona-activity-duration");a&&s.startedAt&&H.setAttribute("data-tool-elapsed",String(s.startedAt));let B=(o==="tool"?t.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);H.textContent=B===void 0?"":wl(B),r.appendChild(H)}r.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),r.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let E=e.querySelector(":scope > .persona-border-t");return E?.classList.add("persona-activity-body"),E&&(E.id=`activity-details-${t.id}`,r.setAttribute("aria-controls",E.id)),e}function pC(e){let t=new Set,n=new Set,o=new Set,r=new Map,s=a=>{clearTimeout(r.get(a)),r.delete(a)};return{observe(a,l,d,u={}){let p=l==="tool"?a.toolCall:a.reasoning;if(!(!p||n.has(a.id))&&(!t.has(a.id)&&p.status!=="complete"&&p.chunks?.some(Boolean)&&(t.add(a.id),u.autoExpand!==!1&&d.add(a.id)),t.has(a.id)&&p.status==="complete"&&!o.has(a.id))){if(o.add(a.id),u.autoCollapseDelay===!1)return;r.set(a.id,setTimeout(()=>{r.delete(a.id),d.delete(a.id),e(a.id,l)},u.autoCollapseDelay??1e3))}},manual(a){n.add(a),s(a)},prune(a){for(let l of new Set([...t,...n,...o]))a.has(l)||(s(l),t.delete(l),n.delete(l),o.delete(l))},clear(){for(let a of r.keys())s(a);t.clear(),n.clear(),o.clear()}}}function uC(e,t,n,o){let r=S("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let s=S("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let a=S("div","");typeof o=="string"?a.textContent=o:a.appendChild(o),na(s,a,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=S("div","persona-border-t");return l.id=`activity-details-${e.id}`,l.style.display=n?"":"none",s.setAttribute("aria-controls",l.id),r.append(s,l),yr(r,e,{...t,features:{...t.features,toolCallDisplay:{...t.features?.toolCallDisplay,variant:"row"}}},"tool"),r.dataset.personaToolGroup="true",t.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(r.dataset.activityGroupShimmer="true"),{bubble:r,body:l}}var sP=(e,t)=>e.visible!==!1&&(e.mode!=="transient"||t==="connecting"||t==="paused"||t==="resuming"||t==="error"),ei=(e,t,n)=>{let o=t.mode==="transient",r=e.hasAttribute("data-persona-composer-reason")||e.hasAttribute("data-persona-composer-notice");e.style.display=sP(t,n)||o&&r&&t.visible!==!1?"":"none",e.classList.toggle("persona-mt-2",!o),e.classList.toggle("persona-mb-2",o)},Lm=(e,t,n)=>{!t.parentElement||e.parentElement!==t.parentElement||(n.mode==="transient"?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))};function gC(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 vn(e){return e?.type==="runtype"||e?.type==="custom"}var iP=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function mC(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:iP()}catch{return!1}}var aP=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},xl=e=>{let t=null;return n=>{let o=jo();if(!o)return br(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=aP(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Sl=e=>e?xl({markedOptions:e.options,renderer:e.renderer}):xl(),lP=xl(),Im=e=>lP(e),br=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),hC=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),fC=e=>`%%FORM_PLACEHOLDER_${e}%%`,yC=(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=fC(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=fC(t.length);return t.push({token:s,type:r}),s}),n},bC=e=>{let t=Sl(e);return n=>{let o=[],r=yC(n,o),s=t(r);return o.forEach(({token:a,type:l})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${hC(l)}"></div>`;s=s.replace(d,p)}),s}},vC=e=>{let t=[],n=yC(e,t),o=Im(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="${hC(s)}"></div>`;o=o.replace(a,d)}),o};var cP={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"]},dP=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Rm=()=>{let e=null;return t=>{let n=jo();if(!n)return br(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!dP.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,cP)}},_d=e=>e===!1?null:typeof e=="function"?e:Rm();var CC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,wC=e=>e.includes("|"),xC=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())},pP=e=>`| ${e.join(" | ")} |`,uP=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,gP=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),SC=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(!wC(r)||CC.test(r)||!CC.test(s))continue;let a=xC(r).length;if(a<1)continue;let l=uP(a);t[o+1]!==l&&(t[o+1]=l,n=!0);let d=o+2;for(;d<t.length;d++){let u=t[d];if(u.trim()===""||!wC(u))break;let p=pP(gP(xC(u),a));t[d]!==p&&(t[d]=p,n=!0)}o=d-1}return n?t.join(`
|
|
3
|
+
`):e};var AC="var(--persona-md-table-scroll-fade, 24px)",MC=new WeakSet;function TC(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 EC(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":AC),e.style.setProperty("--persona-fade-r",r<=1?"0px":AC)}function Hm(e){MC.has(e)||(MC.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&EC(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(EC)}var Al="webmcp:",Wm=new Map,Nd=e=>{Wm.clear();for(let t of e){let n=t.title?.trim();n&&Wm.set(t.name,n)}},oa=e=>Wm.get(Om(e)),PC=null;function LC(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}:${mP(t.join(""))}`}function kC(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 mP(e){let t=kC(e,0).toString(36),n=kC(e,2654435761).toString(36);return`${t}.${n}`}var Om=e=>e.startsWith(Al)?e.slice(Al.length):e,es=e=>e.startsWith(Al),Fd=()=>PC?PC():import("@mcp-b/webmcp-polyfill");var{setLoader:UH,load:fP}=xt({fallbackImport:()=>import("@runtypelabs/persona/webmcp-runtime")});var IC=fP;function Wn(e){return e==="card"?"collapsed":e}function ts(e){return e.split(";",1)[0].trim().toLowerCase()}function hP(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(ts(r)===t)return{mode:Wn(s),selector:ts(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(ts(r)===o)return{mode:Wn(s),selector:o}}function Bm(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:Wn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?ts(t.file.mimeType):void 0,d=l?hP(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:Wn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:Wn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:Wn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:Wn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:Wn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Vo(e,t){return Bm(e,t).mode}function Ml(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 yP="agent_",bP="flow_";function RC(e){return e.startsWith(yP)?{kind:"agentId",agentId:e}:e.startsWith(bP)?{kind:"flowId",flowId:e}:null}function HC(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 u=RC(l);if(u)return u;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=RC(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 WC(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ra(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ns(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function OC(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}var os=require("partial-json");var Tl="ask_user_question",El=8,sa="data-persona-ask-sheet-for",vP="Other",CP="Other\u2026",DC="Type your own answer here",_C="Send",wP="Next",xP="Back",SP="Submit all",AP="Skip",MP=3,Dm="data-ask-current-index",_m="data-ask-question-count",NC="data-ask-answers",Nm="data-ask-grouped",FC="data-ask-layout",EP=e=>e.layout==="pills"?"pills":"rows",TP=e=>e.getAttribute(FC)==="pills"?"pills":"rows",BC=!1,$C=e=>e.replace(/["\\]/g,"\\$&"),vr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Tl,$d=e=>e?.features?.askUserQuestion??{},Cr=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,os.parse)(r,os.STR|os.OBJ|os.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>El&&!BC&&(BC=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${El}.`)),t.slice(0,El)},PP=e=>Pl(e)[0]??null,kP=(e,t)=>Pl(e)[t]??null,UC=(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))},jC=(e,t,n)=>{if(e!=="rows")return null;let o=S("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=S("span","persona-ask-row-check");o.appendChild(r)}else{let r=S("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},LP=(e,t,n,o)=>{let s=S("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=S("span","persona-ask-row-content"),l=S("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let u=S("span","persona-ask-row-description");u.textContent=e.description,a.appendChild(u)}s.appendChild(a);let d=jC(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},IP=e=>{let n=S("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},RP=(e,t,n,o)=>{let s=S("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,d=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(d.length===0&&!n){for(let p=0;p<MP;p++)s.appendChild(IP(o));return s}if(d.forEach((p,m)=>{s.appendChild(LP(p,m,o,a))}),e?.allowFreeText!==!1){let p=o==="rows"?vP:CP;if(o==="rows"){let m=S("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");m.setAttribute("data-ask-user-action","focus-free-text"),m.setAttribute("data-option-index",String(d.length)),m.setAttribute("data-ask-other-row","true");let h=S("span","persona-ask-row-content"),y=document.createElement("input");y.type="text",y.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",y.placeholder=t.freeTextPlaceholder??DC,y.setAttribute("data-ask-free-text-input","true"),y.setAttribute("aria-label",t.freeTextLabel??p),h.appendChild(y),m.appendChild(h);let v=jC(o,a,d.length);v&&m.appendChild(v),s.appendChild(m)}else{let m=S("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");m.type="button",m.setAttribute("data-ask-user-action","open-free-text"),m.textContent=t.freeTextLabel??p,s.appendChild(m)}}return s},VC=(e,t)=>{let o=S("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??DC,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=S("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??_C,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},HP=e=>{let t=S("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=S("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??_C,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},WP=(e,t,n)=>{let o=S("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=S("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??xP,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=S("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=S("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??AP,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=S("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=e===t-1;return l.textContent=d?n.submitAllLabel??SP:n.nextLabel??wP,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},ti=e=>{let t=e.getAttribute(NC);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},qC=(e,t)=>{e.setAttribute(NC,JSON.stringify(t))},lo=e=>{let t=Number(e.getAttribute(Dm)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},OP=(e,t)=>{e.setAttribute(Dm,String(Math.max(0,Math.floor(t))))},ia=e=>{let t=Number(e.getAttribute(_m)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},rs=e=>e.getAttribute(Nm)==="true",BP=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},DP=(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)))},Ud=(e,t)=>{let{payload:n}=Cr(t),o=Pl(n),r=ti(e),s={},a=new Set;return o.forEach((l,d)=>{let u=typeof l?.question=="string"?l.question:"";u&&(a.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),a.add(u),Object.prototype.hasOwnProperty.call(r,d)&&(s[u]=r[d]))}),s},zC=e=>{let t=ti(e),n=lo(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 u=d.getAttribute("data-option-label")??"",p=r.has(u);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});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="")},KC=e=>{if(!rs(e))return;let t=ti(e),n=lo(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}},Fm=(e,t,n)=>{let o=$d(n),r=TP(e),{payload:s,complete:a}=Cr(t),l=rs(e),d=lo(e),u=ia(e),p=l?kP(s,d):PP(s),m=!!p?.multiSelect,h=e.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=l?`${d+1}/${u}`:"");let y=e.querySelector('[data-ask-stepper="true"]');y&&y.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let H=typeof p?.question=="string"?p.question:"";v.textContent=H,v.classList.toggle("persona-ask-question-skeleton",!H&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let H=RP(p,o,a,r);C.replaceWith(H)}if(r!=="rows"){let H=e.querySelector('[data-ask-free-text-row="true"]');H&&H.replaceWith(VC(o,r))}let x=e.querySelector('[data-ask-multi-actions="true"]');!l&&m&&!x?e.appendChild(HP(o)):(!m||l)&&x&&x.remove(),e.setAttribute("data-multi-select",m?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(l){let H=WP(d,u,o);E?E.replaceWith(H):e.appendChild(H)}else E&&E.remove();zC(e),KC(e)},_P=(e,t,n)=>{let o=$d(t),r=EP(o),s=e.toolCall.id,a=Pl(n),l=Math.max(1,a.length),d=l>1,u=BP(e,a),p=d?DP(e,l):0,m=S("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(sa,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",e.id),m.setAttribute(_m,String(l)),m.setAttribute(Dm,String(p)),m.setAttribute(Nm,d?"true":"false"),m.setAttribute(FC,r),qC(m,u),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),UC(m,o);let h=S("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),y=S("div","persona-ask-sheet-question persona-flex-1");y.setAttribute("data-ask-question","true"),y.textContent="",h.appendChild(y);let v=S("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",h.appendChild(v),m.appendChild(h);let x=S("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return x.setAttribute("data-ask-pill-list","true"),x.setAttribute("role","group"),m.appendChild(x),r!=="rows"&&m.appendChild(VC(o,r)),Fm(m,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},NP=(e,t,n)=>{let{payload:o}=Cr(t),r=Math.max(1,Pl(o).length);r>ia(e)&&(e.setAttribute(_m,String(r)),r>1&&!rs(e)&&e.setAttribute(Nm,"true")),Fm(e,t,n)},GC=(e,t)=>{let n=S("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=$d(t);UC(n,o);let r=S("span","persona-ask-stub-label"),{complete:s}=Cr(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},aa=(e,t,n)=>{if(!n||!vr(e)||$d(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${sa}]`).forEach(u=>{u.getAttribute(sa)!==r&&u.remove()});let a=n.querySelector(`[${sa}="${$C(r)}"]`);if(a){NP(a,e,t);return}let{payload:l}=Cr(e),d=_P(e,t,l);n.appendChild(d)},ss=(e,t)=>{if(!e)return;let n=t?`[${sa}="${$C(t)}"]`:`[${sa}]`;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)})},$m=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),is=(e,t)=>{let n=ti(e),o=lo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,qC(e,n),zC(e),KC(e)},jd=(e,t,n,o)=>{let r=ia(e),s=Math.max(0,Math.min(r-1,o));OP(e,s),Fm(e,t,n)};var qo="suggest_replies";var Um={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},Vd={name:qo,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:Um,origin:"sdk",annotations:{readOnlyHint:!0}},QC=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ni=e=>e.variant==="tool"&&e.toolCall?.name===qo,jm=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},qd=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!ni(n))continue;let o=jm(n.toolCall?.args);return o.length>0?o:null}return null},YC=new Set,FP=(e,t,n)=>{let o=`${e}:${t}:${n}`;YC.has(o)||(YC.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},as=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&&FP(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 Vm={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:El,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},qm={name:Tl,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:Vm,origin:"sdk",annotations:{readOnlyHint:!0}},la=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(qm),as(e).expose&&t.push(Vd),t};var $P=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),UP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),jP=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=$P(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:UP(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},zm=(e,t)=>{let n=[],o=[],r=[],s="",a,l=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:s,toolCalls:o},{role:"tool",content:"",createdAt:s,toolResults:r}),o=[],r=[])};for(let d of e){let u=jP(d);if(u){let m=d.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(m===void 0||m!==a)&&l(),o.length===0&&(s=d.createdAt,a=m),o.some(h=>h.toolCallId===u.call.toolCallId)||(o.push(u.call),r.push(u.result));continue}let p=t(d);p&&(l(),n.push(p))}return l(),n};var wr=require("partial-json"),zd=e=>e.replace(/\\n/g,`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ca=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)}},VP=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`},XC=e=>e.status==="complete"?VP(e):e.status==="pending"?"Waiting":"",qP=15e3,zP=1200,JC=(e,t)=>{let n=t?.durationMs??qP,o=t?.chars??zP;return typeof e.durationMs=="number"?e.durationMs<n:(e.chunks??[]).join("").length<o},KP=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 ZC=e=>e.status==="complete"?KP(e):"Using tool...",Kd=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ll=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 Kd(t)},Gd=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Kd(t)},Km=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Ll(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Yd=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&kl(o,n.slice(s,a.index),[]),a[1]!==void 0?kl(o,a[1],["bold"]):a[2]!==void 0?kl(o,a[2],["italic"]):a[3]!==void 0&&kl(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&kl(o,n.slice(s),[]),o},kl=(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})},GP=()=>{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()=>{}}},Il=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Qd=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Xd=()=>{let e=_P();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Jd=()=>{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,wr.parse)(n,wr.STR|wr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?zd(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=zd(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},qC=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=l=>typeof l=="string"?zd(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?zd(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,wr.parse)(s,wr.STR|wr.OBJ),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Zd=()=>{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 zC="4.24.0";var So=zC;var da="[Image]";function KC(e){return typeof e=="string"?[{type:"text",text:e}]:e}function ep(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function pa(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function GC(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function co(e){return{type:"text",text:e}}function tp(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function YC(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 QC(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 XC=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],FP=["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"],xr=[...XC,...FP];function $P(e){return XC.includes(e)||e.startsWith("image/")}function np(e){return $P(e.type)}function JC(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function ZC(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;np(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 ew(e,t=xr,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 UP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function tw(e,t){let n=UP(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 jP=["user","assistant","system"],VP=0;function nw(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function op(e){return typeof e=="string"?e:void 0}function qP(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?co(t.text):null;case"image":return typeof t.image=="string"?tp(t.image,{mimeType:op(t.mimeType),alt:op(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?JC(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...op(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...op(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function zP(e,t){let n=nw(t),o=e.map(a=>nw(a.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let a=o[s];if(a!==null){r[s]=a,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let d=l-s+1,p=s>0?r[s-1]:null,u=l+1<o.length?o[l+1]:null,m=u!==null&&n!==null?Math.min(u,n):u??n;for(let h=0;h<d;h+=1)r[s+h]=m!==null?m-(d-h):p!==null?p+h+1:VP+h;s=l+1}return r.map(a=>new Date(a).toISOString())}function ow(e,t){let n=zP(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!jP.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(qP).filter(u=>u!==null),p=ep(d);o.push({id:r.id,role:a,content:p||(pa(d)?da:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Rl(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 KP="https://api.runtype.com/v1/dispatch",rw="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)}},sw=32768,zm=49152,iw=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:""}},aw=e=>"reason"in e?e.reason:void 0,lw="The identity proof was not admitted; account history is unavailable",Km="The identity proof was rejected",cw="The request carried no visitor credential",dw="The stored visitor belongs to a different signed-in user",Gm=(e,t)=>e instanceof je&&e.code===t;function GP(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 Ym=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),pw=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),uw=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function YP(e){switch(e){case"json":return Jd;case"regex-json":return Xd;case"xml":return Zd;default:return Qd}}var gw=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function QP(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=gw(n);if(!gw(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Il(e);return Il(t)!==null&&a===null?t:e}var oi=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.sessionWarmLatch=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??KP,this.headers={"Content-Type":"application/json","X-Persona-Version":So,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??YP(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 xC().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Nd,getToolDisplayTitle:oa,loadPolyfill:Fd});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=AC(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$/,"")||rw}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":So,"X-Visitor-Token":s},signal:t.signal});if(d.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(d),null,!0);continue}if(!d.ok)throw await this.historyErrorFor(d,!0);return d}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.sessionInitPromise||t&&new Date<t.expiresAt||this.sessionWarmLatch===t?null:(this.sessionWarmLatch=t,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;let t=this.sessionInitPromise=this._doInitSession().then(n=>this.sessionInitPromise!==t?this.initSession():(this.clientSession=n,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.sessionInitPromise===t&&(this.sessionInitPromise=null)});return t}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let t=this.historyIdentityStatus;return t?.state==="browser_only"?t:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&aw(n)===aw(t);if(this.historyIdentityStatus=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let n=this.isHistoryCapable()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.routing(),a=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,d={token:this.config.clientToken,...a&&{flowId:a},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...l?{conversationId:l}:t.storedSessionId?{sessionId:t.storedSessionId}:{}};t.signal?.throwIfAborted();let p=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":So},body:JSON.stringify(d),signal:t.signal});if(!p.ok){let m=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&m.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),l)throw new 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?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.isHistoryCapable()&&!n)return this.ordinaryInit(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.createClientSession({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.finishInit(r,t,!1)}catch(r){if(!Gm(r,"not_found")&&!Gm(r,"visitor_required")&&!Gm(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(t,n)):this.doOrdinaryInit(t,n)}async doOrdinaryInit(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,t,n)}async reinitWithProof(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:t}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),s}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&t.durableRecovery?.enabled!==!0)return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new 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.sessionWarmLatch=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":So},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.sessionWarmLatch=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}historyUrl(t,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveChatIdentityProof(t){t?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let r,s;try{let a=Promise.resolve().then(()=>o());r=t?await Promise.race([a,new Promise((l,d)=>{s=()=>d(t.reason),t.addEventListener("abort",s,{once:!0}),t.aborted&&s()})]):await a}catch{throw t?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{s&&t?.removeEventListener("abort",s)}if(typeof r!="string"||!r.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:r}}async resolveIdentityProof(t,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new 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",lw);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",Km);if(r.includes("visitor token required"))throw new je("visitor_token_missing",cw);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",dw);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",lw);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",Km)):r.includes("visitor token required")?new je("visitor_token_missing",cw):r.includes("visitor_identity_mismatch")?new je("visitor_identity_mismatch",dw):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":So,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let m=u.headers.get("X-History-Identity-Status"),h=await u.json().catch(()=>{});if(a&&a.revision()!==d)throw new je("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(m,s!==null,o),h}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new 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(iw),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:iw(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>sw)throw new je("payload_too_large",`displayContent exceeds the ${sw} character limit`);o+=p}if(o>zm)throw new je("payload_too_large",`Display projection batch exceeds the ${zm} 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<=zm,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=EC();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();a();let d=async()=>{a();let E=l,H=E.durableRecovery?.enabled===!0;if(H&&(!E.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");a();let B=await this.createClientSession({...H||this.isHistoryCapable()?{conversationId:E.conversationId,durableResume:H}:{storedSessionId:E.sessionId},signal:t.signal});if(a(),E.conversationId&&B.conversationId!==E.conversationId||H&&B.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.finishInit(B,E.conversationId??null,!1),this.clientSession=l,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await d();let p=await this.buildPayload(t.messages),u=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,m=this.isHistoryCapable(),h={sessionId:l.sessionId,messages:t.messages.filter(Ym).map(E=>{let H=m?Rl(E):void 0;return{id:E.id,role:E.role,content:E.contentParts??E.llmContent??E.rawContent??E.content,...H!==void 0&&{displayContent:H}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},y=async()=>{a();let E=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return a(),this.sendWithClientToolsDiff(l.sessionId,p.clientTools,async H=>{a();let B=await this.resolveChatIdentityProof(t.signal);a();let A={...h,sessionId:l.sessionId,...H,...B&&{identityProof:B}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...A,...B&&{identityProof:{provider:B.provider,token:"[REDACTED]"}}}),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":So,...E?{"X-Visitor-Token":E}:{}},body:JSON.stringify(A),signal:t.signal})})},v=await y();if(a(),v.response.status===401){let E=await v.response.clone().json().catch(()=>null);a(),E?.error==="Session not found or expired"&&(await d(),v=await y(),a())}let{response:C,commit:x}=v;if(!C.ok){let E=await C.json().catch(()=>({error:"Chat request failed"}));if(C.status===401&&E.error==="invalid_identity_proof"){let B=new je("invalid_identity_proof",Km);throw s({type:"error",error:B}),B}if(C.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let B=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:B}),B}if(C.status===429){let B=new Error(E.hint||"Message limit reached for this session.");throw s({type:"error",error:B}),B}if(C.status===410&&E.error==="conversation_deleted"){let B=new je("conversation_deleted","This conversation was deleted");throw s({type:"error",error:B}),B}let H=new Error(E.error||"Failed to send message");throw s({type:"error",error:H}),H}if(!C.body){let E=new Error("No response body received");throw s({type:"error",error:E}),E}x(),s({type:"status",status:"connected"});try{await this.streamResponse(C.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof 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?wC(n):void 0,l=this.clientToolsFingerprintSessionId===t,d=s&&l&&this.lastSentClientToolsFingerprint===a,p=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,u=!1,m;for(let h=0;;h++){if(m=await o({...s&&(u||!d)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),m.status===409&&h===0&&s&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:p&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||rw}/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=[...la(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:h}=await this.sendWithClientToolsDiff(a,u,y=>{let v={...p,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",v),fetch(s,{method:"POST",headers:d,body:JSON.stringify(v),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&h(),m}return fetch(s,{method:"POST",headers:d,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}normalizeComposerOptions(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}applyInlineAgentModel(t,n){let o=n?.selectedModelId;return!o||!("model"in t)?t:this.config.composer?.models?.some(s=>s.id===o)?{...t,model:o}:t}async buildAgentPayload(t,n){let o=this.routing().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=Vm(pw(t),p=>Ym(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?uw(p):null),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...la(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=Vm(pw(t),p=>Ym(p)?uw(p):null),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[p,u]of Object.entries(r.targetPayload))p!=="messages"&&(s[p]=u);let a=[...la(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(s.clientTools=a);let l=await this.buildContextAggregate(t);l&&(s.context=l);let d=this.normalizeComposerOptions(n);if(d&&(s.composerOptions=d),this.requestMiddleware)try{let p=await this.requestMiddleware({payload:{...s},config:this.config});if(p&&typeof p=="object"){let u=p;return s.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=s.clientTools),u}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return s}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=m,r(m),m},p=u=>o.current?o.current:d(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",d=Date.now(),p=0,u=()=>d+p++,m=j=>{let M=j.reasoning?{...j.reasoning,chunks:[...j.reasoning.chunks]}:void 0,N=j.toolCall?{...j.toolCall,chunks:j.toolCall.chunks?[...j.toolCall.chunks]:void 0}:void 0,z=j.tools?j.tools.map(J=>({...J,chunks:J.chunks?[...J.chunks]:void 0})):void 0;return{...j,reasoning:M,toolCall:N,tools:z}},h=j=>{if(j.role!=="assistant"||j.variant)return!0;let M=Array.isArray(j.contentParts)&&j.contentParts.length>0,N=typeof j.rawContent=="string"&&j.rawContent.trim()!=="";return typeof j.content=="string"&&j.content.trim()!==""||M||N||!!j.stopReason},y=j=>{h(j)&&n({type:"message",message:m(j)})},v=null,C=null,x={current:null},E={current:null},H=null,B="",A=new Map,O=new Map,L=new Map,$=new Map,K=new Map,ae=o,oe=!1,P=()=>{if(v)return v;let j,M="",N=H;return!oe&&ae?(j=ae,oe=!0,M=r??""):ae&&N?j=`${ae}_${N}`:j=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:j,role:"assistant",content:M,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},y(v),v},k=j=>{let M=$.get(j);if(M)return M;let N={id:`reason-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:j,status:"streaming",chunks:[]}};return $.set(j,N),y(N),N},_=new Set,I=new Map,te=new Set,U=new Map,pe=j=>{if(!j)return!1;let M=j.replace(/_+/g,"_").replace(/^_|_$/g,"");return M==="emit_artifact_markdown"||M==="emit_artifact_component"},ue=j=>{let M=K.get(j);if(M)return M;let N={id:`tool-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:j,status:"pending"}};return K.set(j,N),y(N),N},ge=j=>{if(typeof j=="number"&&Number.isFinite(j))return j;if(typeof j=="string"){let M=Number(j);if(!Number.isNaN(M)&&Number.isFinite(M))return M;let N=Date.parse(j);if(!Number.isNaN(N))return N}return Date.now()},Ie=j=>{if(typeof j=="string")return j;if(j==null)return"";try{return JSON.stringify(j)}catch{return String(j)}},Se=new Map,ye=new Map,dt=(j,M)=>{let N=Ie(M),z=ye.get(j.id),J=QP(z,N);j.rawContent=J;let X=Se.get(j.id),fe=et=>{let ze=j.content??"";et.trim()!==""&&(ze.trim().length===0||et.startsWith(ze)||et.trimStart().startsWith(ze.trim()))&&(j.content=et)},Ae=()=>{if(X){let et=X.close?.();et instanceof Promise&&et.catch(()=>{})}Se.delete(j.id),ye.delete(j.id),j.streaming=!1,y(j)};if(!X){fe(N),Ae();return}let Me=Il(J);if(Me!==null&&Me.trim()!==""){fe(Me),Ae();return}let mt=et=>{let ze=typeof et=="string"?et:et?.text??null;if(ze!==null&&ze.trim()!=="")return ze;let ft=X.getExtractedText();return ft!==null&&ft.trim()!==""?ft:N},Nt;try{Nt=X.processChunk(J)}catch{fe(N),Ae();return}if(Nt instanceof Promise){Nt.then(et=>{fe(mt(et)),Ae()}).catch(()=>{fe(N),Ae()});return}fe(mt(Nt)),Ae()},it=null,Ce=(j,M,N,z)=>{j.rawContent=M,Se.has(j.id)||Se.set(j.id,this.createStreamParser());let J=Se.get(j.id),X=M.trim().startsWith("{")||M.trim().startsWith("[");if(X&&ye.set(j.id,M),J.__isPlainTextParser===!0){j.content=z!==void 0?M:j.content+N,ye.delete(j.id),Se.delete(j.id),j.rawContent=void 0,y(j);return}let Ae=J.processChunk(M);if(Ae instanceof Promise)Ae.then(Me=>{let mt=typeof Me=="string"?Me:Me?.text??null;mt!==null&&mt.trim()!==""?(j.content=mt,y(j)):!X&&!M.trim().startsWith("<")&&(j.content=z!==void 0?M:j.content+N,ye.delete(j.id),Se.delete(j.id),j.rawContent=void 0,y(j))}).catch(()=>{j.content=z!==void 0?M:j.content+N,ye.delete(j.id),Se.delete(j.id),j.rawContent=void 0,y(j)});else{let Me=typeof Ae=="string"?Ae:Ae?.text??null;Me!==null&&Me.trim()!==""?(j.content=Me,y(j)):!X&&!M.trim().startsWith("<")&&(j.content=z!==void 0?M:j.content+N,ye.delete(j.id),Se.delete(j.id),j.rawContent=void 0,y(j))}},D=(j,M)=>{let N=M??j.content;if(N==null||N===""){j.streaming=!1,y(j);return}let J=ye.get(j.id)??Ie(N);j.rawContent=J;let X=Se.get(j.id),fe=null,Ae=!1;if(X&&(fe=X.getExtractedText(),fe===null&&(fe=Il(J)),fe===null)){let Me=X.processChunk(J);Me instanceof Promise?(Ae=!0,Me.then(mt=>{let Nt=typeof mt=="string"?mt:mt?.text??null;Nt!==null&&(j.content=Nt,j.streaming=!1,Se.delete(j.id),ye.delete(j.id),y(j))}).catch(()=>{})):fe=typeof Me=="string"?Me:Me?.text??null}if(!Ae){fe!==null&&fe.trim()!==""?j.content=fe:ye.has(j.id)||(j.content=Ie(N));let Me=Se.get(j.id);if(Me){let mt=Me.close?.();mt instanceof Promise&&mt.catch(()=>{}),Se.delete(j.id)}ye.delete(j.id),j.streaming=!1,y(j)}},Ne=(j,M,N)=>{let z=O.get(j);if(z)return z;let J={id:`nested-${M}-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...N?{variant:N}:{},...N==="reasoning"?{reasoning:{id:j,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:M}};return O.set(j,J),y(J),J},Fe=[],Et,Gt=new Map,jt=0,ke="agent",we=!1,Be=null,Ee=null,Sn=this.config.iterationDisplay??"separate";for(Et=()=>{for(let j=0;j<Fe.length;j++){let M=Fe[j];if(!we&&ke!=="flow"&&typeof M.stepType=="string"&&(ke="flow"),M.type==="reasoning_start"){let N=typeof M.id=="string"?M.id:null,z=typeof M.parentToolCallId=="string"&&M.parentToolCallId?M.parentToolCallId:null;if(N&&z){A.set(N,z),Ne(N,z,"reasoning");continue}let J=M.id,X=k(J);X.reasoning=X.reasoning??{id:J,status:"streaming",chunks:[]},X.reasoning.startedAt=X.reasoning.startedAt??Date.now(),X.reasoning.completedAt=void 0,X.reasoning.durationMs=void 0,(M.scope==="loop"||M.scope==="turn")&&(X.reasoning.scope=M.scope),X.streaming=!0,X.reasoning.status="streaming",y(X)}else if(M.type==="reasoning_delta"){let N=typeof M.id=="string"?M.id:null;if(N&&A.has(N)&&O.has(N)){let X=O.get(N),fe=M.delta;fe&&X.reasoning&&(X.reasoning.chunks.push(String(fe)),y(X));continue}let z=M.id,J=k(z);J.reasoning=J.reasoning??{id:z,status:"streaming",chunks:[]},J.reasoning.startedAt=J.reasoning.startedAt??Date.now(),M.delta&&J.reasoning.chunks.push(M.delta),J.reasoning.status="streaming",J.streaming=!0,y(J)}else if(M.type==="reasoning_complete"){let N=typeof M.id=="string"?M.id:null;if(N&&A.has(N)&&O.has(N)){let fe=O.get(N);if(fe.reasoning){let Ae=typeof M.text=="string"?M.text:"";Ae&&fe.reasoning.chunks.length===0&&fe.reasoning.chunks.push(Ae),fe.reasoning.status="complete",fe.streaming=!1,y(fe)}A.delete(N),O.delete(N);continue}let z=M.id,J=typeof M.text=="string"?M.text:"";!$.get(z)&&(J||M.scope==="loop")&&k(z);let X=$.get(z);if(X?.reasoning){(M.scope==="loop"||M.scope==="turn")&&(X.reasoning.scope=M.scope),J&&X.reasoning.chunks.length===0&&X.reasoning.chunks.push(J),X.reasoning.status="complete",X.reasoning.completedAt=Date.now();let fe=X.reasoning.startedAt??Date.now();X.reasoning.durationMs=Math.max(0,(X.reasoning.completedAt??Date.now())-fe),X.streaming=!1,y(X)}}else if(M.type==="tool_start"){v&&(v.streaming=!1,y(v),v=null),typeof M.iteration=="number"&&(jt=M.iteration);let N=M.toolCallId,z=M.toolName;if(pe(z)){_.add(N);continue}let J=ue(N),X=J.toolCall??{id:N,status:"pending"};X.name=z??X.name,X.status="running",X.success=void 0,X.error=void 0,X.duration=void 0,M.parameters!==void 0&&(X.args=M.parameters),X.startedAt=X.startedAt??ge(M.startedAt),X.completedAt=void 0,X.durationMs=void 0,J.toolCall=X,J.streaming=!0,M.executionId&&(J.agentMetadata={executionId:M.executionId,iteration:M.iteration}),y(J)}else if(M.type==="tool_output_delta"){let N=M.toolCallId;if(_.has(N))continue;let z=ue(N),J=z.toolCall??{id:N,status:"running"};J.startedAt=J.startedAt??Date.now();let X=M.delta;X&&(J.chunks=J.chunks??[],J.chunks.push(String(X))),J.status="running",z.toolCall=J,z.streaming=!0,M.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:M.executionId,iteration:jt}),y(z)}else if(M.type==="tool_complete"){let N=M.toolCallId;if(_.has(N)){_.delete(N);continue}let z=ue(N),J=z.toolCall??{id:N,status:"running"};J.status="complete",M.result!==void 0&&(J.result=M.result),J.name=M.toolName??J.name,J.success=M.success,J.error=M.error,J.completedAt=Date.now();let X=M.executionTime;if(typeof X=="number")J.durationMs=X,J.duration=X;else{let fe=J.startedAt??Date.now();J.durationMs=Math.max(0,(J.completedAt??Date.now())-fe)}z.toolCall=J,z.streaming=!1,M.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:M.executionId,iteration:M.iteration??jt}),y(z)}else if(M.type==="await"&&M.toolName){let N=typeof M.toolCallId=="string"&&M.toolCallId.length>0?M.toolCallId:void 0,z=N??M.toolId??`local-${u()}`,J=ue(z),X=M.toolName,fe=M.origin==="webmcp"&&!es(X)?`webmcp:${X}`:X,Ae=es(fe),Me=J.toolCall??{id:z,status:"pending"};Me.name=fe,Me.args=M.parameters,Me.status=Ae?"running":"complete",Me.chunks=Me.chunks??[],Me.startedAt=Me.startedAt??ge(M.awaitedAt),Ae?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=Me.completedAt??Me.startedAt,J.toolCall=Me,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:M.executionId??J.agentMetadata?.executionId,awaitingLocalTool:!0,...N?{webMcpToolCallId:N}:{}},y(J)}else if(M.type==="text_start"){let N=typeof M.id=="string"?M.id:null,z=typeof M.parentToolCallId=="string"&&M.parentToolCallId?M.parentToolCallId:null;if(N&&z){A.set(N,z);continue}let J=v;J&&(ke==="flow"?(D(J),it=J):(J.streaming=!1,y(J)),v=null),H=typeof M.id=="string"?M.id:H,B=""}else if(M.type==="text_delta"){let N=typeof M.id=="string"?M.id:null,z=N?A.get(N):void 0;if(N&&z){let fe=typeof M.delta=="string"?M.delta:"",Ae=(L.get(N)??"")+fe;if(L.set(N,Ae),Ae.trim()==="")continue;let Me=Ne(N,z);Me.agentMetadata={...Me.agentMetadata,executionId:M.executionId,parentToolId:z},Ce(Me,Ae,fe,void 0);continue}if(H=typeof M.id=="string"?M.id:H,ke==="flow"){let fe=typeof M.delta=="string"?M.delta:"";if(B+=fe,B.trim()==="")continue;let Ae=P();Ae.agentMetadata={executionId:M.executionId,iteration:jt},Ce(Ae,B,fe,void 0),C=Ae;continue}let J=typeof M.delta=="string"?M.delta:"";B+=J;let X=P();X.agentMetadata={executionId:M.executionId,iteration:jt,turnId:Be??void 0,agentName:Ee?.agentName},Ce(X,B,J,void 0),C=X}else if(M.type==="text_complete"){let N=typeof M.id=="string"?M.id:null;if(N&&A.has(N)){let J=O.get(N);J&&D(J),A.delete(N),L.delete(N),O.delete(N);continue}let z=v;z&&(ke==="flow"?(D(z),it=z):((z.content??"")===""&&typeof M.text=="string"&&(z.content=M.text),z.streaming=!1,y(z)),v=null),H=null,B=""}else if(M.type==="step_complete"){if(M.stepType==="tool")continue;if(M.success===!1){let N=M.error||"Step failed";n({type:"error",error:new Error(N)});let z=v;z&&z.streaming&&(z.streaming=!1,y(z)),n({type:"status",status:"idle"});continue}{let N=it;it=null;let z=M.stopReason,X=(M.result&&typeof M.result=="object"?M.result:null)?.response;if(N)z&&(N.stopReason=z),X!=null?dt(N,X):N.streaming!==!1&&(Se.delete(N.id),ye.delete(N.id),N.streaming=!1,y(N));else{let fe=X!=null&&X!=="";if(fe||z){let Ae=P();z&&(Ae.stopReason=z),fe?D(Ae,X):(Ae.streaming=!1,y(Ae))}}continue}}else if(M.type==="execution_start")ke=M.kind==="flow"?"flow":"agent",we=!0,ke==="agent"&&(Ee={executionId:M.executionId,agentId:M.agentId??"virtual",agentName:M.agentName??""});else if(M.type==="turn_start"){let N=typeof M.iteration=="number"?M.iteration:jt;if(N!==jt){if(Sn==="separate"&&N>1){let z=v;z&&(z.streaming=!1,y(z),v=null)}jt=N}Be=typeof M.id=="string"?M.id:null,C=null}else if(M.type==="tool_input_delta"){let N=M.toolCallId;if(N){let z=K.get(N);z?.toolCall&&(z.toolCall.chunks=z.toolCall.chunks??[],z.toolCall.chunks.push(M.delta??""),y(z))}}else if(M.type==="tool_input_complete"){if(_.has(M.toolCallId))continue;let N=ue(M.toolCallId),z=N.toolCall;z.args=M.parameters,z.name=M.toolName??z.name,y(N)}else if(M.type==="turn_complete"){let N=M.stopReason,z=v??C;if(N&&z!==null){let J=M.id;(!J||z.agentMetadata?.turnId===J)&&(z.stopReason=N,y(z))}Be===M.id&&(Be=null)}else if(M.type==="media_start"){let N=String(M.id);Gt.set(N,{mediaType:typeof M.mediaType=="string"?M.mediaType:void 0,toolCallId:M.toolCallId,parts:[]})}else if(M.type==="media_delta"){let N=Gt.get(String(M.id));N&&typeof M.delta=="string"&&N.parts.push(M.delta)}else if(M.type==="media_complete"){let N=String(M.id),z=Gt.get(N);Gt.delete(N);let J=(typeof M.mediaType=="string"?M.mediaType:void 0)??z?.mediaType??"application/octet-stream",X=typeof M.data=="string"?M.data:void 0,fe=typeof M.url=="string"?M.url:z&&z.parts.length>0?z.parts.join(""):void 0,Ae=null;if(X)Ae={type:"media",data:X,mediaType:J};else if(fe){let et=J.toLowerCase();Ae={type:et==="image"||et.startsWith("image/")?"image-url":"file-url",url:fe,mediaType:J}}let Me=M.toolCallId??z?.toolCallId,mt=Ae?[Ae]:[],Nt=[];for(let et of mt){if(!et||typeof et!="object")continue;let ze=et,ft=typeof ze.type=="string"?ze.type:void 0,Zt=typeof ze.mediaType=="string"?ze.mediaType.toLowerCase():"",It=null,gn="";if(ft==="media"){let ht=typeof ze.data=="string"?ze.data:void 0;if(!ht)continue;gn=Zt.length>0?Zt:"application/octet-stream",It=`data:${gn};base64,${ht}`}else if(ft==="image-url"){let ht=typeof ze.url=="string"?ze.url:void 0;if(!ht)continue;gn=Zt,It=ht}else if(ft==="file-url"){let ht=typeof ze.url=="string"?ze.url:void 0;if(!ht)continue;gn=Zt,It=ht}else continue;if(It)if(ft==="image-url"||gn.startsWith("image/"))Nt.push({type:"image",image:It,...gn.includes("/")?{mimeType:gn}:{}});else if(gn.startsWith("audio/"))Nt.push({type:"audio",audio:It,mimeType:gn});else if(gn.startsWith("video/"))Nt.push({type:"video",video:It,mimeType:gn});else{let ht=gn||"application/octet-stream";Nt.push({type:"file",data:It,mimeType:ht,filename:GP(ht)})}}if(Nt.length>0){let et=u(),ze=Me,Zt={id:`agent-media-${typeof ze=="string"&&ze.length>0?`${ze}-${et}`:String(et)}`,role:"assistant",content:"",contentParts:Nt,createdAt:new Date().toISOString(),streaming:!1,sequence:et,agentMetadata:{executionId:M.executionId,iteration:jt}};y(Zt);let It=v;It&&(It.streaming=!1,y(It)),v=null,x.current=null}}else if(M.type==="execution_complete"){let N=v;N&&(M.kind==="flow"&&N.streaming!==!1?D(N):(N.streaming=!1,y(N)),v=null),H=null,B="",it=null,n({type:"status",status:"idle",terminal:!0})}else if(M.type==="execution_error"){let N=typeof M.error=="string"?M.error:M.error?.message??"Execution error";n({type:"error",error:new Error(N)})}else if(M.type!=="ping"){if(M.type==="approval_start"){let N=M.approvalId??`approval-${u()}`,z={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:"pending",agentId:Ee?.agentId??"virtual",executionId:M.executionId??Ee?.executionId??"",toolName:M.toolName??"",toolType:M.toolType,description:M.description??`Execute ${M.toolName??"tool"}`,...typeof M.reason=="string"&&M.reason?{reason:M.reason}:{},parameters:M.parameters}};y(z)}else if(M.type==="approval_complete"){let N=M.approvalId;if(N){let J={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:N,status:M.decision??"approved",agentId:Ee?.agentId??"virtual",executionId:M.executionId??Ee?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};y(J)}}else if(M.type==="artifact_start"||M.type==="artifact_delta"||M.type==="artifact_update"||M.type==="artifact_complete"){if(M.type==="artifact_start"){let N=M.artifactType,z=String(M.id),J=typeof M.title=="string"?M.title:void 0,X=M.file,fe;if(X&&typeof X=="object"&&!Array.isArray(X)&&typeof X.path=="string"&&typeof X.mimeType=="string"&&(fe={path:X.path,mimeType:X.mimeType,...typeof X.language=="string"?{language:X.language}:{}}),n({type:"artifact_start",id:z,artifactType:N,title:J,component:typeof M.component=="string"?M.component:void 0,...fe?{file:fe}:{}}),U.set(z,{markdown:"",title:J,file:fe}),!te.has(z)){te.add(z);let Ae=Vo(this.config.features?.artifacts,{artifactType:N,...fe?{file:fe}:{}}),Me=typeof M.component=="string"?M.component:void 0,mt={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:Ml(Ae,{artifactId:z,title:J,artifactType:N,status:"streaming",...fe?{file:fe}:{},...Me?{component:Me}:{}})};I.set(z,mt),y(mt)}}else if(M.type==="artifact_delta"){let N=String(M.id),z=typeof M.delta=="string"?M.delta:String(M.delta??"");n({type:"artifact_delta",id:N,artDelta:z});let J=U.get(N);J&&(J.markdown+=z)}else if(M.type==="artifact_update"){let N=M.props&&typeof M.props=="object"&&!Array.isArray(M.props)?M.props:{};n({type:"artifact_update",id:String(M.id),props:N,component:typeof M.component=="string"?M.component:void 0});let z=U.get(String(M.id));z&&(z.props={...z.props??{},...N})}else if(M.type==="artifact_complete"){let N=String(M.id);n({type:"artifact_complete",id:N});let z=I.get(N);if(z){z.streaming=!1;try{let J=JSON.parse(z.rawContent??"{}");if(J.props){J.props.status="complete";let X=U.get(N);X?.markdown&&(J.props.markdown=X.markdown),X?.file&&(J.props.file=X.file),J.component==="PersonaArtifactInline"&&X?.props&&Object.keys(X.props).length>0&&(J.props.componentProps=X.props)}z.rawContent=JSON.stringify(J)}catch{}U.delete(N),y(z),I.delete(N)}}}else if(M.type==="error"&&M.recoverable===!1&&M.error!=null&&M.error!==""){let N=typeof M.error=="string"?M.error:M.error?.message!=null?String(M.error.message):"Execution error";n({type:"error",error:new Error(N)});let z=v;z&&z.streaming&&(z.streaming=!1,y(z)),n({type:"status",status:"idle"})}}}Fe.length=0};;){let{done:j,value:M}=await s.read();if(j)break;l+=a.decode(M,{stream:!0});let N=l.split(`
|
|
6
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Il=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Qd=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Xd=()=>{let e=GP();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)}},Jd=()=>{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,wr.parse)(n,wr.STR|wr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?zd(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=zd(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},ew=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=l=>typeof l=="string"?zd(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?zd(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,wr.parse)(s,wr.STR|wr.OBJ),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Zd=()=>{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 tw="4.25.0";var So=tw;var da="[Image]";function nw(e){return typeof e=="string"?[{type:"text",text:e}]:e}function ep(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function pa(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function ow(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function co(e){return{type:"text",text:e}}function tp(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function rw(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 sw(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 iw=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],QP=["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"],xr=[...iw,...QP];function XP(e){return iw.includes(e)||e.startsWith("image/")}function np(e){return XP(e.type)}function aw(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function lw(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;np(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 cw(e,t=xr,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 JP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function dw(e,t){let n=JP(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 ZP=["user","assistant","system"],ek=0;function pw(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function op(e){return typeof e=="string"?e:void 0}function tk(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?co(t.text):null;case"image":return typeof t.image=="string"?tp(t.image,{mimeType:op(t.mimeType),alt:op(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?aw(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...op(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...op(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function nk(e,t){let n=pw(t),o=e.map(a=>pw(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,u=s>0?r[s-1]:null,p=l+1<o.length?o[l+1]:null,m=p!==null&&n!==null?Math.min(p,n):p??n;for(let h=0;h<d;h+=1)r[s+h]=m!==null?m-(d-h):u!==null?u+h+1:ek+h;s=l+1}return r.map(a=>new Date(a).toISOString())}function uw(e,t){let n=nk(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!ZP.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(tk).filter(p=>p!==null),u=ep(d);o.push({id:r.id,role:a,content:u||(pa(d)?da:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function Rl(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 ok="https://api.runtype.com/v1/dispatch",gw="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)}},mw=32768,Gm=49152,fw=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:""}},hw=e=>"reason"in e?e.reason:void 0,yw="The identity proof was not admitted; account history is unavailable",Ym="The identity proof was rejected",bw="The request carried no visitor credential",vw="The stored visitor belongs to a different signed-in user",Qm=(e,t)=>e instanceof je&&e.code===t;function rk(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 Xm=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),Cw=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),ww=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function sk(e){switch(e){case"json":return Jd;case"regex-json":return Xd;case"xml":return Zd;default:return Qd}}var xw=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ik(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=xw(n);if(!xw(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Il(e);return Il(t)!==null&&a===null?t:e}var oi=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.currentClientTurnId=null;this.clientSession=null;this.sessionInitPromise=null;this.sessionWarmLatch=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;this.webMcpBridge=null;this.webMcpBridgePromise=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??ok,this.headers={"Content-Type":"application/json","X-Persona-Version":So,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??sk(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 IC().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:Nd,getToolDisplayTitle:oa,loadPolyfill:Fd});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=HC(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$/,"")||gw}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":So,"X-Visitor-Token":s},signal:t.signal});if(d.status===401&&!o){o=!0,n=await this.recoverFromUnauthorized(await this.readErrorCode(d),null,!0);continue}if(!d.ok)throw await this.historyErrorFor(d,!0);return d}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.sessionInitPromise||t&&new Date<t.expiresAt||this.sessionWarmLatch===t?null:(this.sessionWarmLatch=t,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;let t=this.sessionInitPromise=this._doInitSession().then(n=>this.sessionInitPromise!==t?this.initSession():(this.clientSession=n,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.sessionInitPromise===t&&(this.sessionInitPromise=null)});return t}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let t=this.historyIdentityStatus;return t?.state==="browser_only"?t:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&hw(n)===hw(t);if(this.historyIdentityStatus=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let n=this.isHistoryCapable()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.routing(),a=s.agentId??s.flowId,l=n||t.durableResume?t.conversationId:void 0,d={token:this.config.clientToken,...a&&{flowId:a},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&r?{visitorToken:r}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...l?{conversationId:l}:t.storedSessionId?{sessionId:t.storedSessionId}:{}};t.signal?.throwIfAborted();let u=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":So},body:JSON.stringify(d),signal:t.signal});if(!u.ok){let m=await u.json().catch(()=>({error:"Session initialization failed"}));if(n&&u.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 u.status===403&&m.error==="durable_recovery_disabled"?new je("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&u.status===401&&m.error==="visitor_required"?new je("visitor_required","Visitor credential no longer resolves"):l&&u.status===404?new je("not_found","Conversation not found"):u.status===401?new Error(`Invalid client token: ${m.hint||m.error}`):u.status===403?new Error(`Origin not allowed: ${m.hint||m.error}`):new Error(m.error||"Failed to initialize session")}let p=await u.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId?{targetId:p.targetId}:{},...p.conversationRevision?{conversationRevision:p.conversationRevision}:{},...p.durableRecovery?{durableRecovery:p.durableRecovery}:{},...p.visitor?{visitor:p.visitor}:{},config:{welcomeMessage:p.config.welcomeMessage,placeholder:p.config.placeholder,theme:p.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(!Qm(r,"not_found")&&!Qm(r,"visitor_required")&&!Qm(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(t,n)):this.doOrdinaryInit(t,n)}async doOrdinaryInit(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,t,n)}async reinitWithProof(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:t}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),s}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable()&&t.durableRecovery?.enabled!==!0)return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new 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.sessionWarmLatch=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":So},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.sessionWarmLatch=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}historyUrl(t,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveChatIdentityProof(t){t?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let r,s;try{let a=Promise.resolve().then(()=>o());r=t?await Promise.race([a,new Promise((l,d)=>{s=()=>d(t.reason),t.addEventListener("abort",s,{once:!0}),t.aborted&&s()})]):await a}catch{throw t?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{s&&t?.removeEventListener("abort",s)}if(typeof r!="string"||!r.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:r}}async resolveIdentityProof(t,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new 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",yw);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",Ym);if(r.includes("visitor token required"))throw new je("visitor_token_missing",bw);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",vw);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",yw);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",Ym)):r.includes("visitor token required")?new je("visitor_token_missing",bw):r.includes("visitor_identity_mismatch")?new je("visitor_identity_mismatch",vw):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,u=await this.readVisitorToken();if(!u&&!n.visitorTokenOptional)throw new je("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(this.historyUrl(t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":So,...u?{"X-Visitor-Token":u}:{},...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(p.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(p),s,o);continue}if(!p.ok)throw await this.historyErrorFor(p,o);let m=p.headers.get("X-History-Identity-Status"),h=await p.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),h}}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(fw),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:fw(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 u=d.displayContent.length;if(u>mw)throw new je("payload_too_large",`displayContent exceeds the ${mw} character limit`);o+=u}if(o>Gm)throw new je("payload_too_large",`Display projection batch exceeds the ${Gm} 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<=Gm,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=OC();this.currentClientTurnId=o;let r=()=>this.currentClientTurnId===o,s=a=>{r()&&n(a)};n({type:"status",status:"connecting"});try{let a=()=>{if(t.signal?.throwIfAborted(),!r())throw new DOMException("Turn superseded","AbortError")},l=this.clientSession??await this.initSession();a();let d=async()=>{a();let E=l,H=E.durableRecovery?.enabled===!0;if(H&&(!E.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");a();let B=await this.createClientSession({...H||this.isHistoryCapable()?{conversationId:E.conversationId,durableResume:H}:{storedSessionId:E.sessionId},signal:t.signal});if(a(),E.conversationId&&B.conversationId!==E.conversationId||H&&B.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.finishInit(B,E.conversationId??null,!1),this.clientSession=l,this.sessionWarmLatch=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await d();let u=await this.buildPayload(t.messages),p=u.metadata?Object.fromEntries(Object.entries(u.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,m=this.isHistoryCapable(),h={sessionId:l.sessionId,messages:t.messages.filter(Xm).map(E=>{let H=m?Rl(E):void 0;return{id:E.id,role:E.role,content:E.contentParts??E.llmContent??E.rawContent??E.content,...H!==void 0&&{displayContent:H}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...u.inputs&&Object.keys(u.inputs).length>0&&{inputs:u.inputs},...u.context&&{context:u.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},y=async()=>{a();let E=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return a(),this.sendWithClientToolsDiff(l.sessionId,u.clientTools,async H=>{a();let B=await this.resolveChatIdentityProof(t.signal);a();let A={...h,sessionId:l.sessionId,...H,...B&&{identityProof:B}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...A,...B&&{identityProof:{provider:B.provider,token:"[REDACTED]"}}}),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":So,...E?{"X-Visitor-Token":E}:{}},body:JSON.stringify(A),signal:t.signal})})},v=await y();if(a(),v.response.status===401){let E=await v.response.clone().json().catch(()=>null);a(),E?.error==="Session not found or expired"&&(await d(),v=await y(),a())}let{response:C,commit:x}=v;if(!C.ok){let E=await C.json().catch(()=>({error:"Chat request failed"}));if(C.status===401&&E.error==="invalid_identity_proof"){let B=new je("invalid_identity_proof",Ym);throw s({type:"error",error:B}),B}if(C.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let B=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:B}),B}if(C.status===429){let B=new Error(E.hint||"Message limit reached for this session.");throw s({type:"error",error:B}),B}if(C.status===410&&E.error==="conversation_deleted"){let B=new je("conversation_deleted","This conversation was deleted");throw s({type:"error",error:B}),B}let H=new Error(E.error||"Failed to send message");throw s({type:"error",error:H}),H}if(!C.body){let E=new Error("No response body received");throw s({type:"error",error:E}),E}x(),s({type:"status",status:"connected"});try{await this.streamResponse(C.body,s,t.assistantMessageId)}finally{s({type:"status",status:"idle"})}}catch(a){let l=a instanceof Error?a:new Error(String(a));throw!(l instanceof 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?LC(n):void 0,l=this.clientToolsFingerprintSessionId===t,d=s&&l&&this.lastSentClientToolsFingerprint===a,u=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,m;for(let h=0;;h++){if(m=await o({...s&&(p||!d)&&n?{clientTools:n}:{},...u?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),m.status===409&&h===0&&s&&(await m.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:m,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||gw}/resume`,a,l=null;if(r){let p=await this.initSession();a=p.sessionId,p.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 u={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(a&&(u.sessionId=a),r&&a){let p=[...la(this.config),...await(await this.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:m,commit:h}=await this.sendWithClientToolsDiff(a,p,y=>{let v={...u,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",v),fetch(s,{method:"POST",headers:d,body:JSON.stringify(v),signal:o?.signal})},{emptyMeansReplace:!0});return m.ok&&h(),m}return fetch(s,{method:"POST",headers:d,body:JSON.stringify(u),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=zm(Cw(t),u=>Xm(u)&&(u.role==="user"||u.role==="assistant"||u.role==="system")&&(!u.variant||u.variant==="assistant")?ww(u):null),s=this.normalizeComposerOptions(n),a={agent:this.applyInlineAgentModel(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(a.composerOptions=s);let l=[...la(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=zm(Cw(t),u=>Xm(u)?ww(u):null),r=this.routing(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[u,p]of Object.entries(r.targetPayload))u!=="messages"&&(s[u]=p);let a=[...la(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 u=await this.requestMiddleware({payload:{...s},config:this.config});if(u&&typeof u=="object"){let p=u;return s.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=s.clientTools),p}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",u)}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=p=>{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(),...p!==void 0&&{partId:p}};return o.current=m,r(m),m},u=p=>o.current?o.current:d(p);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 p=u(l.partId);l.partId!==void 0&&!p.partId&&(p.partId=l.partId),p.content+=l.text,r(p)}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(),u=0,p=()=>d+u++,m=j=>{let M=j.reasoning?{...j.reasoning,chunks:[...j.reasoning.chunks]}:void 0,N=j.toolCall?{...j.toolCall,chunks:j.toolCall.chunks?[...j.toolCall.chunks]:void 0}:void 0,z=j.tools?j.tools.map(J=>({...J,chunks:J.chunks?[...J.chunks]:void 0})):void 0;return{...j,reasoning:M,toolCall:N,tools:z}},h=j=>{if(j.role!=="assistant"||j.variant)return!0;let M=Array.isArray(j.contentParts)&&j.contentParts.length>0,N=typeof j.rawContent=="string"&&j.rawContent.trim()!=="";return typeof j.content=="string"&&j.content.trim()!==""||M||N||!!j.stopReason},y=j=>{h(j)&&n({type:"message",message:m(j)})},v=null,C=null,x={current:null},E={current:null},H=null,B="",A=new Map,O=new Map,L=new Map,$=new Map,K=new Map,ae=o,oe=!1,P=()=>{if(v)return v;let j,M="",N=H;return!oe&&ae?(j=ae,oe=!0,M=r??""):ae&&N?j=`${ae}_${N}`:j=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:j,role:"assistant",content:M,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},y(v),v},k=j=>{let M=$.get(j);if(M)return M;let N={id:`reason-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:j,status:"streaming",chunks:[]}};return $.set(j,N),y(N),N},_=new Set,I=new Map,te=new Set,U=new Map,pe=j=>{if(!j)return!1;let M=j.replace(/_+/g,"_").replace(/^_|_$/g,"");return M==="emit_artifact_markdown"||M==="emit_artifact_component"},ue=j=>{let M=K.get(j);if(M)return M;let N={id:`tool-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:j,status:"pending"}};return K.set(j,N),y(N),N},ge=j=>{if(typeof j=="number"&&Number.isFinite(j))return j;if(typeof j=="string"){let M=Number(j);if(!Number.isNaN(M)&&Number.isFinite(M))return M;let N=Date.parse(j);if(!Number.isNaN(N))return N}return Date.now()},Ie=j=>{if(typeof j=="string")return j;if(j==null)return"";try{return JSON.stringify(j)}catch{return String(j)}},Se=new Map,ye=new Map,dt=(j,M)=>{let N=Ie(M),z=ye.get(j.id),J=ik(z,N);j.rawContent=J;let X=Se.get(j.id),fe=et=>{let ze=j.content??"";et.trim()!==""&&(ze.trim().length===0||et.startsWith(ze)||et.trimStart().startsWith(ze.trim()))&&(j.content=et)},Ae=()=>{if(X){let et=X.close?.();et instanceof Promise&&et.catch(()=>{})}Se.delete(j.id),ye.delete(j.id),j.streaming=!1,y(j)};if(!X){fe(N),Ae();return}let Me=Il(J);if(Me!==null&&Me.trim()!==""){fe(Me),Ae();return}let mt=et=>{let ze=typeof et=="string"?et:et?.text??null;if(ze!==null&&ze.trim()!=="")return ze;let ft=X.getExtractedText();return ft!==null&&ft.trim()!==""?ft:N},Nt;try{Nt=X.processChunk(J)}catch{fe(N),Ae();return}if(Nt instanceof Promise){Nt.then(et=>{fe(mt(et)),Ae()}).catch(()=>{fe(N),Ae()});return}fe(mt(Nt)),Ae()},it=null,Ce=(j,M,N,z)=>{j.rawContent=M,Se.has(j.id)||Se.set(j.id,this.createStreamParser());let J=Se.get(j.id),X=M.trim().startsWith("{")||M.trim().startsWith("[");if(X&&ye.set(j.id,M),J.__isPlainTextParser===!0){j.content=z!==void 0?M:j.content+N,ye.delete(j.id),Se.delete(j.id),j.rawContent=void 0,y(j);return}let Ae=J.processChunk(M);if(Ae instanceof Promise)Ae.then(Me=>{let mt=typeof Me=="string"?Me:Me?.text??null;mt!==null&&mt.trim()!==""?(j.content=mt,y(j)):!X&&!M.trim().startsWith("<")&&(j.content=z!==void 0?M:j.content+N,ye.delete(j.id),Se.delete(j.id),j.rawContent=void 0,y(j))}).catch(()=>{j.content=z!==void 0?M:j.content+N,ye.delete(j.id),Se.delete(j.id),j.rawContent=void 0,y(j)});else{let Me=typeof Ae=="string"?Ae:Ae?.text??null;Me!==null&&Me.trim()!==""?(j.content=Me,y(j)):!X&&!M.trim().startsWith("<")&&(j.content=z!==void 0?M:j.content+N,ye.delete(j.id),Se.delete(j.id),j.rawContent=void 0,y(j))}},D=(j,M)=>{let N=M??j.content;if(N==null||N===""){j.streaming=!1,y(j);return}let J=ye.get(j.id)??Ie(N);j.rawContent=J;let X=Se.get(j.id),fe=null,Ae=!1;if(X&&(fe=X.getExtractedText(),fe===null&&(fe=Il(J)),fe===null)){let Me=X.processChunk(J);Me instanceof Promise?(Ae=!0,Me.then(mt=>{let Nt=typeof mt=="string"?mt:mt?.text??null;Nt!==null&&(j.content=Nt,j.streaming=!1,Se.delete(j.id),ye.delete(j.id),y(j))}).catch(()=>{})):fe=typeof Me=="string"?Me:Me?.text??null}if(!Ae){fe!==null&&fe.trim()!==""?j.content=fe:ye.has(j.id)||(j.content=Ie(N));let Me=Se.get(j.id);if(Me){let mt=Me.close?.();mt instanceof Promise&&mt.catch(()=>{}),Se.delete(j.id)}ye.delete(j.id),j.streaming=!1,y(j)}},Ne=(j,M,N)=>{let z=O.get(j);if(z)return z;let J={id:`nested-${M}-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...N?{variant:N}:{},...N==="reasoning"?{reasoning:{id:j,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:M}};return O.set(j,J),y(J),J},Fe=[],Et,Gt=new Map,jt=0,ke="agent",we=!1,Be=null,Ee=null,An=this.config.iterationDisplay??"separate";for(Et=()=>{for(let j=0;j<Fe.length;j++){let M=Fe[j];if(!we&&ke!=="flow"&&typeof M.stepType=="string"&&(ke="flow"),M.type==="reasoning_start"){let N=typeof M.id=="string"?M.id:null,z=typeof M.parentToolCallId=="string"&&M.parentToolCallId?M.parentToolCallId:null;if(N&&z){A.set(N,z),Ne(N,z,"reasoning");continue}let J=M.id,X=k(J);X.reasoning=X.reasoning??{id:J,status:"streaming",chunks:[]},X.reasoning.startedAt=X.reasoning.startedAt??Date.now(),X.reasoning.completedAt=void 0,X.reasoning.durationMs=void 0,(M.scope==="loop"||M.scope==="turn")&&(X.reasoning.scope=M.scope),X.streaming=!0,X.reasoning.status="streaming",y(X)}else if(M.type==="reasoning_delta"){let N=typeof M.id=="string"?M.id:null;if(N&&A.has(N)&&O.has(N)){let X=O.get(N),fe=M.delta;fe&&X.reasoning&&(X.reasoning.chunks.push(String(fe)),y(X));continue}let z=M.id,J=k(z);J.reasoning=J.reasoning??{id:z,status:"streaming",chunks:[]},J.reasoning.startedAt=J.reasoning.startedAt??Date.now(),M.delta&&J.reasoning.chunks.push(M.delta),J.reasoning.status="streaming",J.streaming=!0,y(J)}else if(M.type==="reasoning_complete"){let N=typeof M.id=="string"?M.id:null;if(N&&A.has(N)&&O.has(N)){let fe=O.get(N);if(fe.reasoning){let Ae=typeof M.text=="string"?M.text:"";Ae&&fe.reasoning.chunks.length===0&&fe.reasoning.chunks.push(Ae),fe.reasoning.status="complete",fe.streaming=!1,y(fe)}A.delete(N),O.delete(N);continue}let z=M.id,J=typeof M.text=="string"?M.text:"";!$.get(z)&&(J||M.scope==="loop")&&k(z);let X=$.get(z);if(X?.reasoning){(M.scope==="loop"||M.scope==="turn")&&(X.reasoning.scope=M.scope),J&&X.reasoning.chunks.length===0&&X.reasoning.chunks.push(J),X.reasoning.status="complete",X.reasoning.completedAt=Date.now();let fe=X.reasoning.startedAt??Date.now();X.reasoning.durationMs=Math.max(0,(X.reasoning.completedAt??Date.now())-fe),X.streaming=!1,y(X)}}else if(M.type==="tool_start"){v&&(v.streaming=!1,y(v),v=null),typeof M.iteration=="number"&&(jt=M.iteration);let N=M.toolCallId,z=M.toolName;if(pe(z)){_.add(N);continue}let J=ue(N),X=J.toolCall??{id:N,status:"pending"};X.name=z??X.name,X.status="running",X.success=void 0,X.error=void 0,X.duration=void 0,M.parameters!==void 0&&(X.args=M.parameters),X.startedAt=X.startedAt??ge(M.startedAt),X.completedAt=void 0,X.durationMs=void 0,J.toolCall=X,J.streaming=!0,M.executionId&&(J.agentMetadata={executionId:M.executionId,iteration:M.iteration}),y(J)}else if(M.type==="tool_output_delta"){let N=M.toolCallId;if(_.has(N))continue;let z=ue(N),J=z.toolCall??{id:N,status:"running"};J.startedAt=J.startedAt??Date.now();let X=M.delta;X&&(J.chunks=J.chunks??[],J.chunks.push(String(X))),J.status="running",z.toolCall=J,z.streaming=!0,M.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:M.executionId,iteration:jt}),y(z)}else if(M.type==="tool_complete"){let N=M.toolCallId;if(_.has(N)){_.delete(N);continue}let z=ue(N),J=z.toolCall??{id:N,status:"running"};J.status="complete",M.result!==void 0&&(J.result=M.result),J.name=M.toolName??J.name,J.success=M.success,J.error=M.error,J.completedAt=Date.now();let X=M.executionTime;if(typeof X=="number")J.durationMs=X,J.duration=X;else{let fe=J.startedAt??Date.now();J.durationMs=Math.max(0,(J.completedAt??Date.now())-fe)}z.toolCall=J,z.streaming=!1,M.executionId&&(z.agentMetadata=z.agentMetadata??{executionId:M.executionId,iteration:M.iteration??jt}),y(z)}else if(M.type==="await"&&M.toolName){let N=typeof M.toolCallId=="string"&&M.toolCallId.length>0?M.toolCallId:void 0,z=N??M.toolId??`local-${p()}`,J=ue(z),X=M.toolName,fe=M.origin==="webmcp"&&!es(X)?`webmcp:${X}`:X,Ae=es(fe),Me=J.toolCall??{id:z,status:"pending"};Me.name=fe,Me.args=M.parameters,Me.status=Ae?"running":"complete",Me.chunks=Me.chunks??[],Me.startedAt=Me.startedAt??ge(M.awaitedAt),Ae?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=Me.completedAt??Me.startedAt,J.toolCall=Me,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:M.executionId??J.agentMetadata?.executionId,awaitingLocalTool:!0,...N?{webMcpToolCallId:N}:{}},y(J)}else if(M.type==="text_start"){let N=typeof M.id=="string"?M.id:null,z=typeof M.parentToolCallId=="string"&&M.parentToolCallId?M.parentToolCallId:null;if(N&&z){A.set(N,z);continue}let J=v;J&&(ke==="flow"?(D(J),it=J):(J.streaming=!1,y(J)),v=null),H=typeof M.id=="string"?M.id:H,B=""}else if(M.type==="text_delta"){let N=typeof M.id=="string"?M.id:null,z=N?A.get(N):void 0;if(N&&z){let fe=typeof M.delta=="string"?M.delta:"",Ae=(L.get(N)??"")+fe;if(L.set(N,Ae),Ae.trim()==="")continue;let Me=Ne(N,z);Me.agentMetadata={...Me.agentMetadata,executionId:M.executionId,parentToolId:z},Ce(Me,Ae,fe,void 0);continue}if(H=typeof M.id=="string"?M.id:H,ke==="flow"){let fe=typeof M.delta=="string"?M.delta:"";if(B+=fe,B.trim()==="")continue;let Ae=P();Ae.agentMetadata={executionId:M.executionId,iteration:jt},Ce(Ae,B,fe,void 0),C=Ae;continue}let J=typeof M.delta=="string"?M.delta:"";B+=J;let X=P();X.agentMetadata={executionId:M.executionId,iteration:jt,turnId:Be??void 0,agentName:Ee?.agentName},Ce(X,B,J,void 0),C=X}else if(M.type==="text_complete"){let N=typeof M.id=="string"?M.id:null;if(N&&A.has(N)){let J=O.get(N);J&&D(J),A.delete(N),L.delete(N),O.delete(N);continue}let z=v;z&&(ke==="flow"?(D(z),it=z):((z.content??"")===""&&typeof M.text=="string"&&(z.content=M.text),z.streaming=!1,y(z)),v=null),H=null,B=""}else if(M.type==="step_complete"){if(M.stepType==="tool")continue;if(M.success===!1){let N=M.error||"Step failed";n({type:"error",error:new Error(N)});let z=v;z&&z.streaming&&(z.streaming=!1,y(z)),n({type:"status",status:"idle"});continue}{let N=it;it=null;let z=M.stopReason,X=(M.result&&typeof M.result=="object"?M.result:null)?.response;if(N)z&&(N.stopReason=z),X!=null?dt(N,X):N.streaming!==!1&&(Se.delete(N.id),ye.delete(N.id),N.streaming=!1,y(N));else{let fe=X!=null&&X!=="";if(fe||z){let Ae=P();z&&(Ae.stopReason=z),fe?D(Ae,X):(Ae.streaming=!1,y(Ae))}}continue}}else if(M.type==="execution_start")ke=M.kind==="flow"?"flow":"agent",we=!0,ke==="agent"&&(Ee={executionId:M.executionId,agentId:M.agentId??"virtual",agentName:M.agentName??""});else if(M.type==="turn_start"){let N=typeof M.iteration=="number"?M.iteration:jt;if(N!==jt){if(An==="separate"&&N>1){let z=v;z&&(z.streaming=!1,y(z),v=null)}jt=N}Be=typeof M.id=="string"?M.id:null,C=null}else if(M.type==="tool_input_delta"){let N=M.toolCallId;if(N){let z=K.get(N);z?.toolCall&&(z.toolCall.chunks=z.toolCall.chunks??[],z.toolCall.chunks.push(M.delta??""),y(z))}}else if(M.type==="tool_input_complete"){if(_.has(M.toolCallId))continue;let N=ue(M.toolCallId),z=N.toolCall;z.args=M.parameters,z.name=M.toolName??z.name,y(N)}else if(M.type==="turn_complete"){let N=M.stopReason,z=v??C;if(N&&z!==null){let J=M.id;(!J||z.agentMetadata?.turnId===J)&&(z.stopReason=N,y(z))}Be===M.id&&(Be=null)}else if(M.type==="media_start"){let N=String(M.id);Gt.set(N,{mediaType:typeof M.mediaType=="string"?M.mediaType:void 0,toolCallId:M.toolCallId,parts:[]})}else if(M.type==="media_delta"){let N=Gt.get(String(M.id));N&&typeof M.delta=="string"&&N.parts.push(M.delta)}else if(M.type==="media_complete"){let N=String(M.id),z=Gt.get(N);Gt.delete(N);let J=(typeof M.mediaType=="string"?M.mediaType:void 0)??z?.mediaType??"application/octet-stream",X=typeof M.data=="string"?M.data:void 0,fe=typeof M.url=="string"?M.url:z&&z.parts.length>0?z.parts.join(""):void 0,Ae=null;if(X)Ae={type:"media",data:X,mediaType:J};else if(fe){let et=J.toLowerCase();Ae={type:et==="image"||et.startsWith("image/")?"image-url":"file-url",url:fe,mediaType:J}}let Me=M.toolCallId??z?.toolCallId,mt=Ae?[Ae]:[],Nt=[];for(let et of mt){if(!et||typeof et!="object")continue;let ze=et,ft=typeof ze.type=="string"?ze.type:void 0,Zt=typeof ze.mediaType=="string"?ze.mediaType.toLowerCase():"",It=null,gn="";if(ft==="media"){let ht=typeof ze.data=="string"?ze.data:void 0;if(!ht)continue;gn=Zt.length>0?Zt:"application/octet-stream",It=`data:${gn};base64,${ht}`}else if(ft==="image-url"){let ht=typeof ze.url=="string"?ze.url:void 0;if(!ht)continue;gn=Zt,It=ht}else if(ft==="file-url"){let ht=typeof ze.url=="string"?ze.url:void 0;if(!ht)continue;gn=Zt,It=ht}else continue;if(It)if(ft==="image-url"||gn.startsWith("image/"))Nt.push({type:"image",image:It,...gn.includes("/")?{mimeType:gn}:{}});else if(gn.startsWith("audio/"))Nt.push({type:"audio",audio:It,mimeType:gn});else if(gn.startsWith("video/"))Nt.push({type:"video",video:It,mimeType:gn});else{let ht=gn||"application/octet-stream";Nt.push({type:"file",data:It,mimeType:ht,filename:rk(ht)})}}if(Nt.length>0){let et=p(),ze=Me,Zt={id:`agent-media-${typeof ze=="string"&&ze.length>0?`${ze}-${et}`:String(et)}`,role:"assistant",content:"",contentParts:Nt,createdAt:new Date().toISOString(),streaming:!1,sequence:et,agentMetadata:{executionId:M.executionId,iteration:jt}};y(Zt);let It=v;It&&(It.streaming=!1,y(It)),v=null,x.current=null}}else if(M.type==="execution_complete"){let N=v;N&&(M.kind==="flow"&&N.streaming!==!1?D(N):(N.streaming=!1,y(N)),v=null),H=null,B="",it=null,n({type:"status",status:"idle",terminal:!0})}else if(M.type==="execution_error"){let N=typeof M.error=="string"?M.error:M.error?.message??"Execution error";n({type:"error",error:new Error(N)})}else if(M.type!=="ping"){if(M.type==="approval_start"){let N=M.approvalId??`approval-${p()}`,z={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:N,status:"pending",agentId:Ee?.agentId??"virtual",executionId:M.executionId??Ee?.executionId??"",toolName:M.toolName??"",toolType:M.toolType,description:M.description??`Execute ${M.toolName??"tool"}`,...typeof M.reason=="string"&&M.reason?{reason:M.reason}:{},parameters:M.parameters}};y(z)}else if(M.type==="approval_complete"){let N=M.approvalId;if(N){let J={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:N,status:M.decision??"approved",agentId:Ee?.agentId??"virtual",executionId:M.executionId??Ee?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};y(J)}}else if(M.type==="artifact_start"||M.type==="artifact_delta"||M.type==="artifact_update"||M.type==="artifact_complete"){if(M.type==="artifact_start"){let N=M.artifactType,z=String(M.id),J=typeof M.title=="string"?M.title:void 0,X=M.file,fe;if(X&&typeof X=="object"&&!Array.isArray(X)&&typeof X.path=="string"&&typeof X.mimeType=="string"&&(fe={path:X.path,mimeType:X.mimeType,...typeof X.language=="string"?{language:X.language}:{}}),n({type:"artifact_start",id:z,artifactType:N,title:J,component:typeof M.component=="string"?M.component:void 0,...fe?{file:fe}:{}}),U.set(z,{markdown:"",title:J,file:fe}),!te.has(z)){te.add(z);let Ae=Vo(this.config.features?.artifacts,{artifactType:N,...fe?{file:fe}:{}}),Me=typeof M.component=="string"?M.component:void 0,mt={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:Ml(Ae,{artifactId:z,title:J,artifactType:N,status:"streaming",...fe?{file:fe}:{},...Me?{component:Me}:{}})};I.set(z,mt),y(mt)}}else if(M.type==="artifact_delta"){let N=String(M.id),z=typeof M.delta=="string"?M.delta:String(M.delta??"");n({type:"artifact_delta",id:N,artDelta:z});let J=U.get(N);J&&(J.markdown+=z)}else if(M.type==="artifact_update"){let N=M.props&&typeof M.props=="object"&&!Array.isArray(M.props)?M.props:{};n({type:"artifact_update",id:String(M.id),props:N,component:typeof M.component=="string"?M.component:void 0});let z=U.get(String(M.id));z&&(z.props={...z.props??{},...N})}else if(M.type==="artifact_complete"){let N=String(M.id);n({type:"artifact_complete",id:N});let z=I.get(N);if(z){z.streaming=!1;try{let J=JSON.parse(z.rawContent??"{}");if(J.props){J.props.status="complete";let X=U.get(N);X?.markdown&&(J.props.markdown=X.markdown),X?.file&&(J.props.file=X.file),J.component==="PersonaArtifactInline"&&X?.props&&Object.keys(X.props).length>0&&(J.props.componentProps=X.props)}z.rawContent=JSON.stringify(J)}catch{}U.delete(N),y(z),I.delete(N)}}}else if(M.type==="error"&&M.recoverable===!1&&M.error!=null&&M.error!==""){let N=typeof M.error=="string"?M.error:M.error?.message!=null?String(M.error.message):"Execution error";n({type:"error",error:new Error(N)});let z=v;z&&z.streaming&&(z.streaming=!1,y(z)),n({type:"status",status:"idle"})}}}Fe.length=0};;){let{done:j,value:M}=await s.read();if(j)break;l+=a.decode(M,{stream:!0});let N=l.split(`
|
|
7
7
|
|
|
8
8
|
`);l=N.pop()??"";for(let z of N){let J=z.split(`
|
|
9
|
-
`),X="message",fe="",Ae=null;for(let ze of J)ze.startsWith("event:")?X=ze.replace("event:","").trim():ze.startsWith("data:")?fe+=ze.replace("data:","").trim():ze.startsWith("id:")&&(Ae=ze.slice(3).trim());let Me=()=>{Ae!==null&&Ae!==""&&n({type:"cursor",id:Ae})};if(!fe){Me();continue}let mt;try{mt=JSON.parse(fe)}catch(ze){n({type:"error",error:ze instanceof Error?ze:new Error("Failed to parse chat stream payload")});continue}let Nt=mt!==null&&typeof mt=="object"&&!Array.isArray(mt)?mt:null,et=X!=="message"?X:typeof Nt?.type=="string"?Nt.type:"message";if(this.onSSEEvent?.(et,mt),this.parseSSEEvent){x.current=v;let ze=await this.handleCustomSSEEvent(mt,n,x,y,
|
|
10
|
-
`)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function
|
|
9
|
+
`),X="message",fe="",Ae=null;for(let ze of J)ze.startsWith("event:")?X=ze.replace("event:","").trim():ze.startsWith("data:")?fe+=ze.replace("data:","").trim():ze.startsWith("id:")&&(Ae=ze.slice(3).trim());let Me=()=>{Ae!==null&&Ae!==""&&n({type:"cursor",id:Ae})};if(!fe){Me();continue}let mt;try{mt=JSON.parse(fe)}catch(ze){n({type:"error",error:ze instanceof Error?ze:new Error("Failed to parse chat stream payload")});continue}let Nt=mt!==null&&typeof mt=="object"&&!Array.isArray(mt)?mt:null,et=X!=="message"?X:typeof Nt?.type=="string"?Nt.type:"message";if(this.onSSEEvent?.(et,mt),this.parseSSEEvent){x.current=v;let ze=await this.handleCustomSSEEvent(mt,n,x,y,p,E);if(x.current&&x.current!==v&&(v=x.current),ze){Me();continue}}Nt&&(Fe.push({...Nt,type:et}),Et()),Me()}}Et()}};function ak(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 Sw(e,t){let n="`".repeat(Math.max(3,ak(t)+1));return`${n}${e}
|
|
11
11
|
${t}
|
|
12
|
-
${n}`}var
|
|
12
|
+
${n}`}var lk=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function ck(e){let t=e?.text?.trim()??"";return t?Sw(lk(e),t):""}function Aw(e){let t=ck(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[co(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
|
|
13
13
|
|
|
14
|
-
`)}:{}}function rp(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function
|
|
14
|
+
`)}:{}}function rp(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Mw(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 Jm(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 Ew(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 Jm(e,n.id)?n.id:null}return null}function Zm(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 po=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function Tw(e){return e instanceof po}function ua(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 ls=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):ua(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 ri=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 Wl=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:PW,load:dk}=xt({fallbackImport:()=>import("@runtypelabs/persona/voice-runtime")});var ef=dk;function tf(e){if(!e)return"";let t=pk(e);return Pw(t!==null?t:e)}function pk(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 Pw(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 Hw=null;var of=()=>Hw?Hw():Promise.resolve().then(()=>(Rw(),Iw));var{setLoader:NW,load:mk}=xt({fallbackImport:()=>import("@runtypelabs/persona/session-reconnect")});var Ww=mk;var fk=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","identityProvider","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function hk(e,t){return fk.some(n=>e[n]!==t[n])}var zo=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function rf(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 of=e=>({isError:!0,content:[{type:"text",text:e}]}),ak=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ew=e=>es(e)||e===qo,ma=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 Wl;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new ri(()=>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&&(es(n.name)||n.name===qo&&as(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 oi(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&&Jm().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||tf().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 sC(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=ls.isSupported()?new ls({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 tf().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=Jm().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 Wl,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async disconnectVoice(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}settlePendingVoiceTurn(t){let n=t?this.pendingVoiceUserMessageId:null,o=this.pendingVoiceAssistantMessageId;!n&&!o||(o&&this.voiceTurns.cancel(),t&&(this.pendingVoiceUserMessageId=null),this.pendingVoiceAssistantMessageId=null,o&&this.ttsSpokenMessageIds.add(o),this.messages=this.messages.flatMap(r=>r.id!==n&&r.id!==o?[r]:r.id===o&&!r.content.trim()?[]:[{...r,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),o&&this.setStreaming(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}warmClientSession(){let t=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,t)})}setClientSession(t,n){this.clientSession=t,this.injectWelcomeMessage(t,n)}injectWelcomeMessage(t,n=!this.messages.length){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||!n)return;let o=this.messages[0],r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.nextSequence()};this.appendMessage(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new zo("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 po("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 zo("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 zo("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new zo("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 zo("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 zo("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 zo("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 zo("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(t){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(t,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let a=await t.getPage(n,{context:o}),l=new Set(a.messages.map(m=>m.id)),d=this.messages.some(m=>l.has(m.id)),p=a.messages[0]?.createdAt,u;if(!d)u=a.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,h=this.messages.filter(y=>l.has(y.id)||y.id===m?!0:p!==void 0&&y.createdAt<p);u=Hl(h,a.messages).map(y=>this.ensureSequence(y))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of a.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let n of t){let o=Rl(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=Rl(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=rC(this.config,o),s=ik(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&Hn(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 oi(this.config,this.historyInternals),a&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),l&&this.client.setSSEEventCallback(l)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:d,streaming:p=!1,voiceProcessing:u,rawContent:m}=t,y={id:a??(n==="user"?ra():n==="assistant"?ns():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:d,createdAt:p,sequence:u,streaming:m=!1,voiceProcessing:h,rawContent:y}=o,C={id:d??(r==="user"?ra():r==="assistant"?ns():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...h!==void 0&&{voiceProcessing:h},...y!==void 0&&{rawContent:y}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:d}=t,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
18
|
+
_Details: ${n.message}_`:o}var sf=e=>({isError:!0,content:[{type:"text",text:e}]}),yk=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ow=e=>es(e)||e===qo,ma=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 Wl;this.voiceDisconnectPromise=Promise.resolve();this.ttsSpokenMessageIds=new Set;this.readAloud=new ri(()=>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&&(es(n.name)||n.name===qo&&as(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 oi(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&&ef().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||of().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 mC(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=ls.isSupported()?new ls({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 of().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let u=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new d(u,n,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):u});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=ef().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,u)=>{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 p=this.injectMessage({role:"user",content:l,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=p.id}if(d){this.voiceTurns.start(u?.turnId),this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(!this.voiceTurns.accepts(u?.turnId))return;if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:l,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let p=this.injectMessage({role:"assistant",content:l,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=p.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)}}}prewarmVoice(){if(!vn(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let t=this.voiceSetupGeneration,n=()=>{let o=this.voiceProvider;!o?.prewarm||t!==this.voiceSetupGeneration||this.voiceActive||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.voiceProvider&&this.voiceSetupPromise){this.voiceSetupPromise.then(n,()=>{});return}n()}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 Wl,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,prewarmMode:t.runtype?.prewarmMode,attachIdleMs:t.runtype?.attachIdleMs}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}warmClientSession(){let t=!this.messages.length;this.client.warmSession().then(n=>{n&&this.client.getClientSession()===n&&this.setClientSession(n,t)})}setClientSession(t,n){this.clientSession=t,this.injectWelcomeMessage(t,n)}injectWelcomeMessage(t,n=!this.messages.length){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||!n)return;let o=this.messages[0],r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:o?.createdAt??new Date().toISOString(),sequence:o?(o.sequence??0)-1:this.nextSequence()};this.appendMessage(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.cleanupVoice(),this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new zo("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 po("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 zo("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 zo("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new zo("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 u=this.fetchOlderPage(r,t,a,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,u),u}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 zo("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 zo("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 zo("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 zo("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)),u=a.messages[0]?.createdAt,p;if(!d)p=a.messages.map(m=>this.ensureSequence(m));else{let m=this.resumable?this.activeAssistantMessageId:null,h=this.messages.filter(y=>l.has(y.id)||y.id===m?!0:u!==void 0&&y.createdAt<u);p=Hl(h,a.messages).map(y=>this.ensureSequence(y))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let m of a.messages)this.acknowledgedProjections.set(m.id,m.content);this.persistConversationMetadata(),this.messages=this.sortMessages(p),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=Rl(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=Rl(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=gC(this.config,o),s=hk(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&vn(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 oi(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:u=!1,voiceProcessing:p,rawContent:m}=t,y={id:a??(n==="user"?ra():n==="assistant"?ns():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...m!==void 0&&{rawContent:m}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:d,createdAt:u,sequence:p,streaming:m=!1,voiceProcessing:h,rawContent:y}=o,C={id:d??(r==="user"?ra():r==="assistant"?ns():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:u??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...h!==void 0&&{voiceProcessing:h},...y!==void 0&&{rawContent:y}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:d}=t,u={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(u),...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(co(s)),p.push(...r.contentParts),p.push(...t.contentParts),t.contentParts=p}else if(d){let p=[];a&&p.push(co(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=ra(),a=ns();this.activeAssistantMessageId=null;let l=n?.contentParts&&pa(n.contentParts)?da:"",d={id:s,role:"user",content:o||l,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments},...n?.composerOptions&&{composerOptions:n.composerOptions},...n?.replayFields??{}};this.appendMessage(d),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let m=this.messages.find(h=>h.id===s)??d;if(await this.applyMentionBundle(m,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(y=>y.id===s)??d,h=fw({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});h.contentParts&&(m.contentParts=h.contentParts),h.llmContent!==void 0&&(m.llmContent=h.llmContent),(h.contentParts||h.llmContent!==void 0)&&(m.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,p,a,s,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let h=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!h){let y=nf(m,this.config.errorMessage);if(y){let v={id:a,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(v)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(t,n){let o=hw(this.messages,t);if(!o)return!1;let r=this.messages[o.start],s=n.replacement,a=s?s.text:r.content,l=s?s.contentParts:r.contentParts;if(!(!!a?.trim()||(l?.length??0)>0||!s&&(r.llmContent?.trim()?.length??0)>0))return!1;let p=s?void 0:{...r.llmContent!==void 0&&{llmContent:r.llmContent},...r.rawContent!==void 0&&{rawContent:r.rawContent},...r.mentionContext&&{mentionContext:r.mentionContext},...r.contextMentions&&{contextMentions:r.contextMentions},...r.quote&&{quote:r.quote}},u=s?this.toComposerOptionsPayload(s.options):r.composerOptions,m=s?s.contentSegments:r.contentSegments,h=s?s.options?.quote:void 0,y=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(a??"",{...l?.length?{contentParts:[...l]}:{},...m?.length?{contentSegments:[...m]}:{},...u?{composerOptions:u}:{},...h?{quote:h}:{},...p&&Object.keys(p).length>0?{replayFields:p}:{},viaVoice:y===!0}),!0}toComposerOptionsPayload(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=ns();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=nf(r,this.config.errorMessage);if(a){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(u=>u.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,p=d&&typeof d=="object"?d.onDecision:void 0;try{let u;if(p?u=await p({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):u=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),u){let m=null;if(u instanceof Response){if(!u.ok){let h=await u.json().catch(()=>null);throw new Error(h?.error??`Approval request failed: ${u.status}`)}m=u.body}else u instanceof ReadableStream&&(m=u);m?await this.connectStream(m,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(u=>u.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let u=t.toolCall?.args,m=Array.isArray(u?.questions)?u.questions:[];if(m.length===1){let h=typeof m[0]?.question=="string"?m[0].question:"";h&&(a={[h]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,d=t.toolCall?.args,p=Array.isArray(d?.questions)?d.questions:[];if(p.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=a??{};p.forEach((m,h)=>{let y=typeof m?.question=="string"?m.question:"";if(!y)return;let v=u[y],C=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${h}`,role:"assistant",content:y,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${h}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let m=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==qo?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=new AbortController;this.webMcpResolveControllers.add(r),this.setStreaming(!0);let s=async d=>{let p=d.toolCall?.name,u=d.toolCall?.id;if(!p||!u)return null;let m=`${t}:${u}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(m),o.push(m);let h=this.markWebMcpToolRunning(d),y=d.agentMetadata?.webMcpToolCallId??p;if(p===qo)return{dedupeKey:m,resumeKey:y,output:$C(),toolMessage:d,startedAt:h,completedAt:Date.now()};let v=this.client.executeWebMcpToolCall(p,d.toolCall?.args,r.signal),C;if(!v)C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{C=await v}catch(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));return E||this.callbacks.onError?.(x instanceof Error?x:new Error(String(x))),this.markWebMcpToolComplete(d,of(E?"Aborted by cancel()":ak(x)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,of("Aborted by cancel()"),h),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:y,output:C,toolMessage:d,startedAt:h,completedAt:Date.now()}},a;if(this.config.webmcp?.execution==="sequential"){a=[];for(let d of n)a.push(await s(d))}else a=await Promise.all(n.map(s));let l=[];try{if(l=a.filter(m=>m!==null),l.length===0)return;let d={};for(let m of l)d[m.resumeKey]=m.output;let p=await this.client.resumeFlow(t,d,{signal:r.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!p.ok){let m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}let u=l[0].dedupeKey;for(let m of l){this.webMcpResolvedKeys.add(m.dedupeKey);let h=m.toolMessage.toolCall?.name,y=m.toolMessage.agentMetadata?.webMcpToolCallId;this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt,{...h===qo?{suggestRepliesResolved:!0}:{},...h&&y?{clientToolAnswer:{toolCallId:y,toolName:h,args:m.toolMessage.toolCall?.args,result:m.output,batch:u}}:{}})}p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,of("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=Vo(this.config.features?.artifacts,t),r=Ml(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=Vo(this.config.features?.artifacts,n),s=Ml(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=Mw().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=>nf(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=ns(),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=Zm(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ua(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Zm(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let l=r.agentMetadata?.clientToolAnswer;if(l&&a.agentMetadata&&!a.agentMetadata.clientToolAnswer&&(a.agentMetadata={...a.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let m=r.approval,h=n.approval;a.approval={...m,...h,executionId:h.executionId||m.executionId,toolName:h.toolName||m.toolName,description:h.description||m.description,toolType:h.toolType??m.toolType,reason:h.reason??m.reason,parameters:h.parameters??m.parameters}}let d=n.toolCall?.name,p=n.agentMetadata?.executionId,u=n.toolCall?.id;if(d&&Ew(d)&&p&&u&&n.agentMetadata?.awaitingLocalTool===!0){let m=`${p}:${u}`,h=this.webMcpInflightKeys.has(m),y=this.webMcpResolvedKeys.has(m),v=r.toolCall?.name,C=r.agentMetadata?.executionId===p&&r.toolCall?.id===u&&v!==void 0&&Ew(v)&&r.toolCall?.status==="complete";(h||y||C)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var uo=require("lucide");var lk={add:e=>ZC(e)},ck=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,ap={allowedTypes:xr,maxFileSize:10*1024*1024,maxFiles:4};function dk(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function pk(e){return e==="application/pdf"?uo.FileText:e.startsWith("text/")?uo.FileText:e.includes("word")?uo.FileText:e.includes("excel")||e.includes("spreadsheet")?uo.FileSpreadsheet:e==="application/json"?uo.FileCode:uo.File}var si=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??ap.allowedTypes,maxFileSize:t.maxFileSize??ap.maxFileSize,maxFiles:t.maxFiles??ap.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:lk}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:ap.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=ew(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:dk(),file:o,previewUrl:np(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=ck(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=np(t.file),o=S("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let u=S("img");u.src=t.previewUrl,u.alt=t.file.name,u.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",u.style.width="48px",u.style.height="48px",u.style.objectFit="cover",u.style.borderRadius="8px",o.appendChild(u)}else{let u=S("div");u.style.width="48px",u.style.height="48px",u.style.borderRadius="8px",u.style.backgroundColor="var(--persona-container, #f3f4f6)",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.display="flex",u.style.flexDirection="column",u.style.alignItems="center",u.style.justifyContent="center",u.style.gap="2px",u.style.overflow="hidden";let m=pk(t.file.type),h=Mt(m,20,"var(--persona-muted, #6b7280)",1.5);h&&u.appendChild(h);let y=S("span");y.textContent=tw(t.file.type,t.file.name),y.style.fontSize="8px",y.style.fontWeight="600",y.style.color="var(--persona-muted, #6b7280)",y.style.textTransform="uppercase",y.style.lineHeight="1",u.appendChild(y),o.appendChild(u)}let r=Y("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=S("div","persona-attachment-progress");s.appendChild(S("div","persona-attachment-progress__bar"));let a=Y("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=le("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?a.appendChild(l):a.textContent="\u21BB",a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,a),o.appendChild(r);let d=S("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let p=Mt(uo.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 Tw=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),uk=(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 Pw(){let e={text:"",attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=new Set,n=null,o=!1,r=!1,s=()=>e.preparing?"preparing":e.streaming?"streaming":"idle",a=()=>{let u=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(m=>Object.freeze({...m}))),mentionRefs:Object.freeze([...e.mentionRefs]),selectedModelId:e.selectedModelId,activeModeIds:Object.freeze([...e.activeModeIds]),quote:e.quote?Object.freeze({...e.quote}):void 0,pendingSubmission:e.pendingSubmission,phase:u,inputDisabled:e.inputDisabled,sendDisabled:u!=="idle"||e.sendDisabled||e.inputDisabled})},l=()=>(n||(n=a()),n),d=()=>{if(o=!1,r||t.size===0)return;let u=l();for(let m of[...t])try{m(u)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},p=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(d))};return{getState:l,subscribe:u=>(t.add(u),()=>t.delete(u)),setText:u=>{e.text!==u&&(e.text=u,p())},setAttachments:u=>{uk(e.attachments,u)||(e.attachments=[...u],p())},setMentionRefs:u=>{Tw(e.mentionRefs,u)||(e.mentionRefs=[...u],p())},setSelectedModelId:u=>{e.selectedModelId!==u&&(e.selectedModelId=u,p())},setActiveModeIds:u=>{Tw(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 On=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},kw=(e,t)=>{let n=S("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function Lw(e,t={}){let n=On(e,"[data-persona-composer-form]"),o=On(e,"[data-persona-composer-input]");if(!n||!o){let E=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||o))throw new Error(E);return typeof console<"u"&&console.warn(E),null}let r={header:On(e,"[data-persona-composer-header]"),body:On(e,"[data-persona-composer-body]"),actionsStart:On(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:On(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:On(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:On(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:On(e,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=kw("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(a,n):e.appendChild(a));let l=r.body??o.parentElement??n,d=(x,E,H,B,A)=>{if(E)return E;s.add(x);let O=kw(H,B);return A.appendChild(O),O},p=d("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),u=d("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),h=d("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),y=[],v=(x,E)=>x.target===E.target&&x.type===E.type&&x.handler===E.handler,C=On(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:a,body:l,actionsStart:p,actionsEnd:u,suggestions:m,status:h,attachmentInput:C,attachmentPreviews:On(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:On(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:On(e,"[data-persona-composer-submit]")??void 0,micButton:On(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(x,E,H,B)=>{x.addEventListener(E,H,B),y.push({target:x,type:E,handler:H,options:B})},removeListener:(x,E,H,B)=>{x.removeEventListener(E,H,B),y=y.filter(A=>!v(A,{target:x,type:E,handler:H}))},destroy:()=>{for(let x of y)x.target.removeEventListener(x.type,x.handler,x.options);y=[]}}}var _t={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},pn=1e5,fa=pn+1;var gk=8,mk=8,rf=10,Iw=200,Rw=300,Hw=0,cp=e=>Math.max(0,e);function Ww(e){e.delayMs!==void 0&&(Iw=cp(e.delayMs)),e.skipDelayMs!==void 0&&(Rw=cp(e.skipDelayMs))}var fk=()=>Date.now()<Hw,hk=e=>{Hw=e>0?Date.now()+e:0},lp=new WeakMap,af="data-persona-tooltip-suppressed",yk=e=>typeof e.closest=="function"&&e.closest(`[${af}]`)!==null;function Ow(e){lp.get(e)?.hide()}var Bw=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,bk=e=>{let t=e.getRootNode?.();return Bw(t)?t:e.ownerDocument.body},sf=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),vk=[...["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 an(e){lp.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:a=gk,viewportPadding:l=mk}=e,d=()=>t.ownerDocument,p=()=>d().defaultView??window,u=null,m=null,h=null,y=null,v,C=!1,x=!1,E=!1,H=()=>(typeof o=="function"?o():o).trim(),B=()=>(typeof r=="function"?r():r??"").trim(),A=()=>cp(e.delayMs??Iw),O=()=>cp(e.skipDelayMs??Rw),L=()=>{v!==void 0&&(p().clearTimeout(v),v=void 0)},$=()=>{L();let ge=u!==null;y?.(),y=null,u?.remove(),u=null,m=null,h=null,ge&&hk(O())},K=()=>{if(!u)return;let ge=d(),Ie=p(),Se=t.getBoundingClientRect(),ye=u.getBoundingClientRect(),dt=ge.documentElement.clientWidth||Ie.innerWidth,it=ge.documentElement.clientHeight||Ie.innerHeight,Ce=dt-l-ye.width,D=Se.left+Se.width/2-ye.width/2,Ne=sf(D,l,Ce),Fe=Se.top-l,Et=it-l-Se.bottom,Gt=ye.height+a,jt=Fe>=Gt||Fe>=Et?"top":"bottom",ke=jt==="top"?Se.top-a-ye.height:Se.bottom+a,we=it-l-ye.height,Be=sf(ke,l,we),Ee=Se.left+Se.width/2,Sn=Math.max(rf,ye.width-rf),j=sf(Ee-Ne,rf,Sn);u.dataset.placement=jt,u.style.left=`${Ne}px`,u.style.top=`${Be}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${j}px`)},ae=()=>{if(E||!s||u||!t.isConnected||yk(t))return;let ge=H(),Ie=bk(t);if(!ge||!Ie)return;let Se=d(),ye=p();u=Se.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(fa);let dt=ye.getComputedStyle?.(t);if(dt){for(let Gt of vk){let jt=dt.getPropertyValue(Gt).trim();jt&&u.style.setProperty(Gt,jt)}dt.fontFamily&&(u.style.fontFamily=dt.fontFamily)}m=Se.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ge,u.appendChild(m);let it=B();it&&(h=Se.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=it,u.appendChild(h));let Ce=Se.createElement("span");Ce.className="persona-control-tooltip__arrow",u.appendChild(Ce),Ie.appendChild(u),K(),u.dataset.state="open";let D=()=>{if(!t.isConnected){$();return}m&&(m.textContent=H()),h&&(h.textContent=B()),K()};ye.addEventListener("scroll",D,!0),ye.addEventListener("resize",D);let Ne=t.getRootNode(),Fe=Bw(Ne)?Ne:Se.documentElement,Et=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||$()});Et?.observe(Fe,{childList:!0,subtree:!0}),y=()=>{ye.removeEventListener("scroll",D,!0),ye.removeEventListener("resize",D),Et?.disconnect()}},oe=ge=>{if(!(E||u)){if(L(),ge||A()<=0||fk()){ae();return}v=p().setTimeout(()=>{v=void 0,ae()},A())}},P=()=>{C||x?oe(x):$()},k=()=>{let ge=p();(!ge.matchMedia||!ge.matchMedia("(hover: none)").matches)&&(C=!0,P())},_=()=>{C=!1,P()},I=()=>{try{x=t.matches(":focus-visible")}catch{x=!0}P()},te=()=>{x=!1,P()},U=()=>{C=!1,x=!1,$()},pe=ge=>{ge.key==="Escape"&&U()};n.addEventListener("mouseenter",k),n.addEventListener("mouseleave",_),t.addEventListener("focus",I),t.addEventListener("blur",te),t.addEventListener("keydown",pe),t.addEventListener("click",U);let ue={get isOpen(){return u!==null},show:ae,hide:$,reposition:K,destroy:()=>{E||(E=!0,$(),n.removeEventListener("mouseenter",k),n.removeEventListener("mouseleave",_),t.removeEventListener("focus",I),t.removeEventListener("blur",te),t.removeEventListener("keydown",pe),t.removeEventListener("click",U),lp.delete(t))}};return lp.set(t,ue),ue}function lf(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 dp(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function Dw(e,t){e.style.maxHeight=`${t*lf(e)}px`,e.style.overflowY="auto"}function Ol(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function _w(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Nw(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||!_w(t)}function Ck(e){return(e.submitKey??"enter")!=="enter"||_w(e)?"enter":"send"}function pp(e,t){e.setAttribute("enterkeyhint",Ck(t))}function up(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 cf(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",Ao="persona-composer-control--glyph",pf=40,vn=24,gp=(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)}},mp=(e,t)=>{let n=S("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Em,n.dir="auto",pp(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Ol(n)}),up(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=dp(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*lf(n);return r=`${d}px`,n.style.maxHeight=r,d},a=()=>{n.addEventListener("input",()=>{n.style.height="auto";let l=Math.min(n.scrollHeight,s());n.style.height=`${l}px`})};return n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.addEventListener("focus",()=>{n.style.border="none",n.style.outline="none",n.style.borderWidth="0",n.style.borderStyle="none",n.style.borderColor="transparent",n.style.boxShadow="none"}),n.addEventListener("blur",()=>{n.style.border="none",n.style.outline="none"}),{textarea:n,attachAutoResize:a}},xk="[data-persona-glyph-stack]",uf=(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},fp=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",d=e?.copy?.sendButtonLabel??"Send",p=e?.copy?.stopButtonLabel??"Stop",u=t.showTooltip??!1,m=t.size,h=parseFloat(m??"")||pf,y=t.backgroundColor,v=t.textColor,C=S("div","persona-send-button-wrapper"),x=Y("button",{className:bn("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&&!y&&"persona-bg-persona-primary",!n&&!v&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?v||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":v||void 0,backgroundColor:n&&y||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),E=null,H=null,B=null;if(n){let L=parseFloat(t.iconSize??"")||Math.round(h*.5),$=t.iconStrokeWidth??2,K=v?.trim()||"currentColor";if(r&&(E=le(r,L,K,$)),H=le(s,L,K,$),!t.iconSize)for(let ae of[E,H])ae&&(ae.style.width=`var(--persona-components-composer-sendIconSize, ${L}px)`,ae.style.height=`var(--persona-components-composer-sendIconSize, ${L}px)`);E&&H?(B=uf(E,H),x.appendChild(B)):E?x.appendChild(E):(x.textContent=o,H=null)}else x.textContent=d;x.setAttribute("aria-label",a),C.appendChild(x),an({anchor:x,trigger:C,text:()=>x.getAttribute("aria-label")??"",enabled:u});let A="send";return{button:x,wrapper:C,setMode:L=>{if(L===A)return;A=L;let $=L==="stop"?l:a;x.setAttribute("aria-label",$),x.setAttribute("data-persona-send-mode",L),n?(x.querySelector(xk)??B)?.setAttribute("data-mode",L):x.textContent=L==="stop"?p:d},glyphStack:B}},ha=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??"")||vn,u=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,h=S("div","persona-send-button-wrapper"),y=Y("button",{className:bn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Kn,!d&&Ao),attrs:{type:"button","data-persona-composer-mic":"","data-state":"idle","aria-label":t.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=le(l,p,m||"currentColor",1.5);C?y.appendChild(C):y.textContent="\u{1F3A4}",h.appendChild(y);let x=t.tooltipText??"Start voice recognition",E=t.showTooltip??!1;return an({anchor:y,trigger:h,text:()=>y.getAttribute("aria-label")??x,enabled:E}),{button:y,wrapper:h}},hp=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=S("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??xr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=S("div","persona-send-button-wrapper"),a=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Kn} ${Ao}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=le(r,vn,"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 an({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},yp=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=S("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),ei(o,t,"idle");let r=t.idleText??"Online";if(t.idleLink){let s=S("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=r;return o},bp=()=>Y("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function Sk(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function vp(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:d=2147483e3,onOpen:p,onDismiss:u}=e,m=e.container??Sk(t),h=!1,y=null,v=()=>{if(!h)return;let E=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${E.width}px`),a&&(n.style.maxWidth=`${E.width}px`);let H=n.getBoundingClientRect(),B=l?.()??null,A=B!=null?E.top+B:E.top,O=o==="top-start"||o==="top-end"?A-r-H.height:E.bottom+r,$=o==="bottom-end"||o==="top-end"?E.right-H.width:E.left,K=a?.()??null;if(K!=null){let ae=Math.max(E.left,E.right-H.width);$=Math.min(Math.max(E.left+K,E.left),ae)}n.style.top=`${O}px`,n.style.left=`${$}px`},C=()=>{h&&(h=!1,y&&(y(),y=null),n.remove())},x=()=>{if(h)return;h=!0,d!=null&&(n.style.zIndex=String(d)),m.appendChild(n),v();let E=(t.ownerDocument??document).defaultView??window,H=t.ownerDocument??document,B=()=>{if(!t.isConnected){C(),u?.("anchor-removed");return}v()},A=L=>{let $=typeof L.composedPath=="function"?L.composedPath():[];$.includes(n)||$.includes(t)||(C(),u?.("outside"))},O=E.setTimeout(()=>{H.addEventListener("pointerdown",A,!0)},0);E.addEventListener("scroll",B,!0),E.addEventListener("resize",B),y=()=>{E.clearTimeout(O),H.removeEventListener("pointerdown",A,!0),E.removeEventListener("scroll",B,!0),E.removeEventListener("resize",B)},p?.()};return{get isOpen(){return h},open:x,close:C,toggle:()=>h?C():x(),reposition:v,destroy:C}}var Ak='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',Mk=["--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"],gf="data-persona-menu-focus",Ek=new Set(["ArrowDown","ArrowUp","Home","End"]);function Fw(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(Ak)??e}var Tk=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function $w(e){let t=e.label,n=!1,o=S("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 ${Kn} ${Ao}`,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 I=e.getButtonSize?.()??"";r.style.width=I,r.style.height=I,r.style.minWidth=I,r.style.minHeight=I,r.style.lineHeight="1",r.replaceChildren();let te=le("plus",vn,"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},h=()=>{let I=m();for(let te of d){let U=!!I&&Fw(te)===I;te.toggleAttribute(gf,U&&u)}},y=()=>d.filter(I=>I.isConnected||s.contains(I)).map(Fw).filter(I=>!Tk(I)),v=(I,te)=>{I.forEach((U,pe)=>{U.setAttribute("tabindex",pe===te?"0":"-1")})},C=I=>{let te=y();if(te.length===0)return;let U=(I%te.length+te.length)%te.length;p=U,v(te,U),te[U].focus(),h()},x=()=>o.ownerDocument??document,E=null,H=null,B=null,A=()=>{E&&(x().removeEventListener("focusin",E,!0),E=null)},O=()=>{H&&(s.removeEventListener("focusin",H),H=null),B&&(s.removeEventListener("pointerdown",B,!0),B=null)},L=null,$=()=>(L||(L=vp({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),A()}})),L),K=()=>L?.isOpen===!0,ae=(I=!1)=>{if(K()){L?.close(),r.setAttribute("aria-expanded","false"),A(),O(),p=-1,u=!1;for(let te of d)te.removeAttribute(gf);I&&r.focus()}},oe=(I=0,te=!1)=>{if(n||K())return;u=te,gp(r,s,Mk),$().open(),r.setAttribute("aria-expanded","true");let U=y();v(U,-1),C(I<0?U.length-1:I),E=pe=>{let ue=typeof pe.composedPath=="function"?pe.composedPath():[];ue.includes(s)||ue.includes(o)||ae()},x().addEventListener("focusin",E,!0),H=()=>h(),s.addEventListener("focusin",H),B=()=>{u=!1},s.addEventListener("pointerdown",B,!0)},P=I=>{I.preventDefault(),I.stopPropagation(),K()?ae(!0):oe(0)},k=I=>{if(I.key==="ArrowDown"||I.key==="Enter"||I.key===" "){I.preventDefault(),u=!0,K()?C(0):oe(0,!0);return}I.key==="ArrowUp"&&(I.preventDefault(),u=!0,K()?C(-1):oe(-1,!0))},_=I=>{switch(Ek.has(I.key)&&(u=!0),I.key){case"ArrowDown":I.preventDefault(),C(p+1);return;case"ArrowUp":I.preventDefault(),C(p-1);return;case"Home":I.preventDefault(),C(0);return;case"End":I.preventDefault(),C(y().length-1);return;case"Escape":I.preventDefault(),I.stopPropagation(),ae(!0);return;case"Tab":ae(!0);return;default:}};return r.addEventListener("click",P),r.addEventListener("keydown",k),s.addEventListener("keydown",_),{trigger:o,triggerButton:r,panel:s,setItems:I=>{for(let U of d)I.includes(U)||U.removeAttribute(gf);if(d=[...I],!K())return;let te=y();v(te,Math.min(p,te.length-1)),h()},isOpen:K,open:()=>oe(0),close:ae,setLabel:I=>{I!==t&&(t=I,l())},applyButtonSize:a,destroy:()=>{n=!0,A(),O(),r.removeEventListener("click",P),r.removeEventListener("keydown",k),s.removeEventListener("keydown",_),L?.destroy(),L=null,o.remove(),s.remove(),d=[]}}}var Ko={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Uw="data-persona-composer-action",mf="data-persona-composer-disable-when-streaming",Pk="core:overflow",kk=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function Lk(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let o=S("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function ff(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 jw=(e,t)=>{!e||typeof console>"u"||console.warn(t)},Ik=(e,t)=>t.includes(":")?t:`${e}:${t}`;function Rk(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){jw(t,`[Persona] composer action "${l.id}" is already contributed by ${Vw(d)}; the ${Vw(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?Ik(p,l.id):l.id,m=l.order??Ko.custom;l.placement==="end"&&m>=Ko.send&&(jw(t,`[Persona] composer action "${u}" ordered at ${m} would render after send; clamped to ${Ko.send-1}.`),m=Ko.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 Vw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",qw=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,Hk=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function Wk(e,t){if(!e||e==="always")return!0;let n=Hk(t);return e==="when-text"?n:!n}var cs=e=>e.kind==="custom",hf=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,Ok=e=>{let t=hf(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},Bk='.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(Bk)||o.childNodes.forEach(n)};return n(e),t.trim()}var _k=e=>Dk(e).length===0;function zw(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(P,k)=>{let _=P.button;if(!_)return;_.setAttribute("role","menuitem"),_.setAttribute("tabindex","-1"),_.className="persona-composer-overflow-menu__item";for(let U of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])_.style[U]="";_.style.lineHeight="1",k.tooltipText?_.setAttribute("title",k.tooltipText):_.removeAttribute("title"),_.replaceChildren();let I=S("span","persona-composer-overflow-menu__icon");if(k.iconName){let U=le(k.iconName,16,"currentColor",1.5);U&&I.appendChild(U)}let te=S("span","persona-composer-overflow-menu__label");te.textContent=k.shortLabel??k.label,_.append(I,te)},a=(P,k)=>{let _=P.button;if(!_)return;if(_.setAttribute("aria-label",k.label),k.pressed===void 0?_.removeAttribute("aria-pressed"):_.setAttribute("aria-pressed",k.pressed?"true":"false"),_.toggleAttribute(mf,k.disableWhenStreaming===!0),P.mode==="menu"){P.tooltip?.destroy(),P.tooltip=void 0,s(P,k);return}_.removeAttribute("role"),_.removeAttribute("tabindex"),_.removeAttribute("title");let I=r(),te=!!k.shortLabel;if(_.className=bn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Kn,Ao,te&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),_.style.width=I&&!te?I:"",_.style.height=I??"",_.style.minWidth=I&&!te?I:"",_.style.minHeight=I??"",_.style.fontSize=te?"":"18px",_.style.lineHeight="1",_.style.color=k.iconColor??"",_.style.backgroundColor=k.backgroundColor??"",_.replaceChildren(),k.iconName){let U=le(k.iconName,vn,"currentColor",1.5);U&&_.appendChild(U)}if(te){let U=S("span","persona-composer-action-button__label");U.textContent=k.shortLabel,_.appendChild(U)}else _.firstChild||(_.textContent=k.label);P.tooltip?.destroy(),P.tooltip=an({anchor:_,trigger:P.element,text:()=>k.tooltipText??k.label,enabled:!!k.tooltipText})},l=(P,k)=>{let _=P.action,I=Y("button",{attrs:{type:"button"}}),te=I;if(k==="bar"){let ue=S("div","persona-send-button-wrapper");ue.appendChild(I),te=ue}te.setAttribute(Uw,P.id);let U={resolved:P,element:te,button:I,owned:!0,managed:!0,busy:!1,visible:!0,mode:k},pe=ue=>{if(ue.preventDefault(),ue.stopPropagation(),U.busy||I.disabled)return;let ge=U.resolved.action;U.mode==="menu"&&y?.close(!0);let Ie;try{Ie=ge.onSelect(e.actionContext,ue)}catch(Se){e.reportError(Se,{actionId:U.resolved.id});return}!Ie||typeof Ie.then!="function"||(U.busy=!0,I.setAttribute("aria-busy","true"),Ie.catch(Se=>{e.reportError(Se,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,I.removeAttribute("aria-busy")}))};return I.addEventListener("click",pe),U.detach=()=>I.removeEventListener("click",pe),a(U,_),U},d=P=>{let k=P.action,_;try{_=k.render({...e.actionContext,id:P.id,action:k})}catch(I){return e.reportError(I,{actionId:P.id}),null}return _?.element?(_.element.setAttribute(Uw,P.id),_.element.toggleAttribute(mf,k.disableWhenStreaming===!0),{resolved:P,element:_.element,owned:!0,managed:!0,destroy:_.destroy,busy:!1,visible:!0,mode:"bar"}):null},p=(P,k)=>{if(P.builtIn){let I=P.builtIn.element;return I?{resolved:P,element:I,owned:!1,managed:P.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let _=P.action;return _?cs(_)?d(P):l(P,k):null},u=P=>{if(P.detach?.(),P.tooltip?.destroy(),P.detachMenuSlot?.(),P.detachMenuSlot=void 0,P.menuLabel?.remove(),P.menuLabel=void 0,P.menuSlot?.remove(),P.menuSlot=void 0,P.owned){try{P.destroy?.()}catch(k){e.reportError(k,{actionId:P.resolved.id})}P.element.remove()}},m=(P,k)=>{for(let _=0;_<k.length;_++){let I=k[_];if(!I.managed)continue;let te=null;for(let U=_+1;U<k.length;U++){let pe=k[U];if(!pe.managed&&pe.element.parentElement===P){te=pe.element;break}}te?(I.element.parentElement!==P||I.element.nextSibling!==te)&&P.insertBefore(I.element,te):P.lastChild!==I.element&&P.appendChild(I.element)}},h=(P,k)=>{if(P.button){P.button.disabled=k;return}if(!P.owned)return;let _=P.element;_.toggleAttribute("data-disabled",k),_.setAttribute("aria-disabled",k?"true":"false");let I=_ instanceof HTMLButtonElement||_ instanceof HTMLSelectElement||_ instanceof HTMLInputElement||_ instanceof HTMLTextAreaElement?_:_.querySelector("button, select, input, textarea");I&&(I.disabled=k)},y=null,v=null,C=null,x=0,E=()=>{let P=e.getOverflow?.();return P?.enabled===!0?P:void 0},H=()=>(y?y.setLabel(e.getOverflowLabel?.()??"More actions"):y=$w({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),y),B=P=>{v!==P&&(C?.disconnect(),v=P,x=ff(P),!(typeof ResizeObserver>"u")&&(C=new ResizeObserver(k=>{let I=k[k.length-1]?.contentRect?.width??ff(P);I!==x&&(x=I,ae())}),C.observe(P)))},A=(P,k)=>{let _=Lk(P.collapseAutoActionsBelow,k);if(_===null)return!1;let I=x||ff(k);return I>0&&I<_},O=(P,k,_)=>{if(!k)return"bar";if(P.resolved.builtIn){let te=kk(P.resolved.id);return te&&k.includeBuiltIns?.includes(te)?"menu":"bar"}let I=P.resolved.presentation;return I==="overflow"||I==="auto"&&_?"menu":"bar"},L=P=>{let k=P.menuSlot;if(!k)return;if(!_k(P.element)){P.menuLabel?.remove(),P.menuLabel=void 0;return}let _=Ok(P.element);if(!_){P.menuLabel?.remove(),P.menuLabel=void 0;return}P.menuLabel||(P.menuLabel=S("span","persona-composer-overflow-menu__label")),P.menuLabel.textContent!==_&&(P.menuLabel.textContent=_),P.menuLabel.parentElement!==k&&k.appendChild(P.menuLabel)},$=(P,k)=>{if(P.mode===k)return P;let _=P.resolved.action;if(_&&!cs(_)){u(P),t.delete(P.resolved.id);let I=l(P.resolved,k);return t.set(P.resolved.id,I),I}if(k==="menu"){let I=Y("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[af]:""}});I.appendChild(P.element),Ow(hf(P.element)),P.menuSlot=I;let te=U=>{let pe=hf(P.element);if(pe.disabled)return;let ue=U.target===pe||pe.contains(U.target);y?.close(!0),ue||pe.click()};I.addEventListener("click",te,!0),P.detachMenuSlot=()=>I.removeEventListener("click",te,!0),P.managed=!0,L(P)}else P.detachMenuSlot?.(),P.detachMenuSlot=void 0,P.menuLabel?.remove(),P.menuLabel=void 0,P.menuSlot?.remove(),P.menuSlot=void 0;return P.mode=k,P},K=(P,k)=>{let _=k.map(I=>I.menuSlot??I.element);for(_.forEach((I,te)=>{let U=P.children[te];U!==I&&(U?P.insertBefore(I,U):P.appendChild(I))});P.children.length>_.length;)P.lastElementChild?.remove()},ae=()=>{if(o)return;let P=e.getBindings();if(!P)return;let k=e.getState(),_=k.phase==="streaming",I=E();I&&B(P.footer);let te=I?A(I,P.footer):!1,U={start:[],end:[]},pe=[];for(let ue of n){let ge=t.get(ue.id);if(!ge)continue;let Ie=ue.action,Se=Ie?qw(Ie.visible,k,!0)&&Wk(Ie.visibility,k):!0;if(ge.visible!==Se&&(ge.visible=Se,!Se&&ge.managed&&(ge.menuSlot??ge.element).remove()),!!Se){if(ge=$(ge,O(ge,I,te)),Ie){let ye=qw(Ie.disabled,k,!1)||Ie.disableWhenStreaming===!0&&_;h(ge,ye),!cs(Ie)&&Ie.pressed!==void 0&&ge.button?.setAttribute("aria-pressed",Ie.pressed?"true":"false")}ge.mode==="menu"?(L(ge),pe.push(ge)):U[ue.placement].push(ge)}}if(pe.length>0){let ue=H();K(ue.panel,pe),ue.setItems(pe.map(ye=>ye.menuSlot??ye.element)),ue.applyButtonSize();let ge=Number.isFinite(I?.order)?I?.order:Ko.overflow,Ie=U.start.findIndex(ye=>ye.resolved.order>ge),Se={resolved:{id:Pk,placement:"start",presentation:"bar",order:ge,sequence:-1,source:"core"},element:ue.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(Ie<0?U.start.length:Ie,0,Se)}else y&&(y.close(),y.trigger.remove(),y.setItems([]));m(P.actionsStart,U.start),m(P.actionsEnd,U.end)};return{resolve:()=>{if(o)return;let P=Rk(e.collect()),k=new Set(P.map(_=>_.id));for(let[_,I]of t)k.has(_)||(u(I),t.delete(_));for(let _ of P){let I=t.get(_.id);if(!I){let ue=p(_,"bar");ue&&t.set(_.id,ue);continue}let te=I.resolved.action,U=_.action;if(!!te!=!!U||te&&U&&cs(te)!==cs(U)||te&&U&&cs(te)&&cs(U)&&te.render!==U.render){u(I),t.delete(_.id);let ue=p(_,I.mode);ue&&t.set(_.id,ue);continue}I.resolved=_,_.builtIn?(I.managed=_.builtIn.managed===!0||I.mode==="menu",_.builtIn.element&&I.mode==="bar"&&(I.element=_.builtIn.element)):U&&!cs(U)?a(I,U):U&&I.element.toggleAttribute(mf,U.disableWhenStreaming===!0)}n=P,ae()},sync:ae,getResolved:()=>n,getOverflowMenu:()=>y,destroy:()=>{if(!o){o=!0,C?.disconnect(),C=null,v=null;for(let P of t.values())u(P);t.clear(),y?.destroy(),y=null,n=[]}}}}var Nk="core:model",Fk=700,Kw=16,$k=["--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"],Gw=()=>{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 Yw(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 C=e.getModels(),x=C.map(E=>`${E.id}:${E.label}`).join("|");x!==p&&(p=x,d.replaceChildren(...C.map(E=>{let H=Y("option",{attrs:{value:E.id}});return H.textContent=E.label,H}))),d.value=r(C)?.id??""};u(),o=u;let m=()=>{d.value&&e.onSelect(d.value)};d.addEventListener("change",m);let h=C=>C.stopPropagation();d.addEventListener("click",h);let{wrapper:y,chevron:v}=Gw();return y.append(d,v),{element:y,destroy:()=>{o===u&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",h)}}},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=S("span","persona-composer-model-picker-label"),u=S("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":""}}),h=new Map,y="",v=null,C=()=>v?.isOpen===!0,x=(k=!1)=>{C()&&(v?.close(),d.setAttribute("aria-expanded","false"),k&&d.focus())},E=k=>{let _=[...h.values()];if(_.length===0)return;let I=(k%_.length+_.length)%_.length;_[I].focus()},H=k=>{if(C())return;v||(v=vp({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),gp(d,m,$k),v.open(),d.setAttribute("aria-expanded","true");let I=[...h.keys()].indexOf(r(e.getModels())?.id??"");E(k??(I>=0?I:0))},B=k=>{x(!0),e.onSelect(k)},A=k=>{k.preventDefault(),k.stopPropagation();let _=k.currentTarget.getAttribute("data-persona-model-option");_&&B(_)},O=k=>{let _=Y("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":k.id}});if(k.icon){let ue=le(k.icon,Kw,"currentColor",1.5);if(ue){let ge=S("span","persona-composer-model-option-icon");ge.appendChild(ue),_.appendChild(ge)}}let I=S("span","persona-composer-model-option-body"),te=S("span","persona-composer-model-option-label");if(te.textContent=k.label,I.appendChild(te),k.description){let ue=S("span","persona-composer-model-option-description");ue.textContent=k.description,I.appendChild(ue)}_.appendChild(I);let U=S("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let pe=le("check",Kw,"currentColor",2);return pe&&U.appendChild(pe),_.appendChild(U),_.addEventListener("click",A),_},L=()=>{let k=e.getModels(),_=k.map(U=>`${U.id}:${U.label}:${U.icon??""}:${U.description??""}`).join("|");if(_!==y){y=_;for(let U of h.values())U.removeEventListener("click",A);h.clear(),m.replaceChildren(...k.map(U=>{let pe=O(U);return h.set(U.id,pe),pe}))}let I=r(k);for(let[U,pe]of h)pe.setAttribute("aria-selected",String(U===I?.id));p.textContent=I?.label??"";let te=e.getSuffix?.()??"";u.textContent=te,d.setAttribute("aria-label",[t,[I?.label,te].filter(Boolean).join(" ")].filter(Boolean).join(": "))};L(),o=L;let $=k=>{k.preventDefault(),k.stopPropagation(),C()?x(!0):H()},K=k=>{if(k.key==="ArrowDown"){k.preventDefault(),C()?E(0):H(0);return}k.key==="ArrowUp"&&(k.preventDefault(),C()?E(-1):H(-1))},ae=k=>{let _=[...h.values()],I=_.indexOf(k.target?.closest?.(".persona-composer-model-option"));switch(k.key){case"ArrowDown":k.preventDefault(),E(I+1);return;case"ArrowUp":k.preventDefault(),E(I-1);return;case"Home":k.preventDefault(),E(0);return;case"End":k.preventDefault(),E(_.length-1);return;case"Escape":k.preventDefault(),k.stopPropagation(),x(!0);return;case"Tab":x(!0);return;default:}};d.addEventListener("click",$),d.addEventListener("keydown",K),m.addEventListener("keydown",ae);let{wrapper:oe,chevron:P}=Gw();return oe.append(d,P),{element:oe,destroy:()=>{o===L&&(o=null),d.removeEventListener("click",$),d.removeEventListener("keydown",K),m.removeEventListener("keydown",ae);for(let k of h.values())k.removeEventListener("click",A);h.clear(),v?.destroy(),v=null,m.remove()}}};return{action:{id:Nk,kind:"custom",placement:"end",order:Fk,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}var yf="[data-persona-composer-chip-row]";function Cp(e){e.style.display=e.childElementCount>0?"flex":"none"}function bf(e){let t=e.querySelector(yf);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 Uk=":scope > [data-persona-composer-mode]";function Qw(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=S("span","persona-mention-chip-icon"),C=le(p.iconName,12,"currentColor",1.5);C&&v.appendChild(C),u.appendChild(v)}let m=S("span","persona-mention-chip-label");m.textContent=p.shortLabel??p.label,u.appendChild(m);let h=Y("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${p.label}`}}),y=le("x",12,"currentColor",2);return y?h.appendChild(y):h.textContent="\xD7",h.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),e.onRemove(p.id)}),u.appendChild(h),u},a=()=>Array.from(t.querySelectorAll(Uk)),l=p=>{p.setAttribute("data-persona-chip-exit",""),p.setAttribute("aria-hidden","true"),p.style.pointerEvents="none";let u=()=>{p.remove(),Cp(t)},m=t.ownerDocument.defaultView,h=typeof m?.getComputedStyle=="function"?m.getComputedStyle(p).animationName:"";if(!h||h==="none"){u();return}p.addEventListener("animationend",u,{once:!0}),p.addEventListener("animationcancel",u,{once:!0})},d=()=>{for(let p of a())p.remove()};return{element:t,render:(p,u)=>{if(o)return;let m=u.filter(C=>p.includes(C.id)),h=m.map(C=>`${C.id}:${C.shortLabel??C.label}`).join("|");if(h===n)return;n=h;let y=new Map;for(let C of a()){let x=C.getAttribute("data-persona-composer-mode");x&&m.some(H=>H.id===x)&&!C.hasAttribute("data-persona-chip-exit")?y.set(x,C):C.hasAttribute("data-persona-chip-exit")||l(C)}let v=t.firstChild;for(let C of m){let x=y.get(C.id);x||(x=s(C),r.has(C.id)||(x.setAttribute("data-persona-chip-enter",""),x.addEventListener("animationend",()=>x?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(C.id),x!==v&&t.insertBefore(x,v),v=x.nextSibling}Cp(t)},destroy:()=>{o=!0,d(),Cp(t)}}}var Xw=e=>`core:mode:${e}`;var vf=e=>Math.min(300+e,499),Jw=e=>`core:mode-group:${e}`;function wp(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function jk(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function Zw(e,t){return e?.length?e.filter(n=>!wp(n.groupId,t)&&!jk(n.groupId,t)):[]}var Vk=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function ex(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(Vk(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 xp(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function tx(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function nx(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var qk=16;function ox(e){let t=null;return{action:{id:Jw(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 h=le(p.iconName,qk,"currentColor",1.5);h&&u.appendChild(h)}let m=S("span","persona-composer-segmented-label");return m.textContent=p.shortLabel??p.label,u.appendChild(m),u.addEventListener("click",a),u},d=()=>{let p=e.getGroup();p?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",p.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let u=e.getModes(),m=u.map(y=>`${y.id}:${y.shortLabel??y.label}:${y.iconName??""}`).join("|");if(m!==s){s=m;for(let v of r.values())v.removeEventListener("click",a);r.clear();let y=u.map(v=>{let C=l(v);return r.set(v.id,C),C});o.replaceChildren(...y)}let h=e.getActiveIds();for(let[y,v]of r)v.setAttribute("aria-pressed",String(h.includes(y)))};return d(),t=d,{element:o,destroy:()=>{t===d&&(t=null);for(let p of r.values())p.removeEventListener("click",a);r.clear()}}}},repaint:()=>t?.()}}function rx(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=S("span","persona-composer-quote-bar"),l=S("div","persona-composer-quote-content");if(s.sourceLabel){let m=S("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let d=Y("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=rp(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=le("x",12,"currentColor",2);u?p.appendChild(u):p.textContent="\xD7",p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),e.onDismiss()}),t.replaceChildren(a,l,p)};return{element:t,render:s=>{if(o)return;let a=s?`${s.sourceLabel??""}\0${s.text}`:"";if(a!==n){if(n=a,!s){t.replaceChildren(),t.style.display="none";return}r(s),t.style.display="flex"}},destroy:()=>{o=!0,t.replaceChildren(),t.remove()}}}function sx(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=le(a,12,"currentColor",2);return m?u.appendChild(m):u.textContent=l,u.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),u},s=a=>{let l=rp(a.text??"",90);if(l)return l;let d=a.contentParts?.length??0;return d>0?d===1?"1 attachment":`${d} attachments`:(a.mentionRefs?.length??0)>0?a.mentionRefs.map(u=>u.label).join(", "):"Queued message"};return{element:t,render:a=>{if(o||a===n)return;if(n=a,!a){t.replaceChildren(),t.style.display="none";return}let l=S("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let d=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 ix(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=S("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",h=>{h.preventDefault(),h.stopPropagation(),u()}),m},a=()=>{let l=n.value.trim();l&&e.onSave(l)};return r.append(s(e.cancelLabel??"Cancel","persona-message-edit-cancel","data-persona-message-edit-cancel",e.onCancel),s(e.saveLabel??"Send","persona-message-edit-save","data-persona-message-edit-save",a)),n.addEventListener("keydown",l=>{if(l.key==="Escape"){l.preventDefault(),l.stopPropagation(),e.onCancel();return}l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),a())}),t.append(n,r),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let l=n.value.length;n.setSelectionRange(l,l),o()},destroy:()=>{t.replaceChildren(),t.remove()}}}function ax(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 lx(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 cx(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 dx(e){return e.wrapped||e.text.includes(`
|
|
23
|
-
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function
|
|
24
|
-
`:o===""||
|
|
25
|
-
`||a==="\uFFFC"||!r&&
|
|
22
|
+
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,d=r.contentParts.length>0;if(l){let u=[];s&&u.push(co(s)),u.push(...r.contentParts),u.push(...t.contentParts),t.contentParts=u}else if(d){let u=[];a&&u.push(co(a)),u.push(...r.contentParts),t.contentParts=u}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=ra(),a=ns();this.activeAssistantMessageId=null;let l=n?.contentParts&&pa(n.contentParts)?da:"",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 u=new AbortController;if(this.abortController=u,n?.mentions){let m=this.messages.find(h=>h.id===s)??d;if(await this.applyMentionBundle(m,o,n.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let m=this.messages.find(y=>y.id===s)??d,h=Aw({quote:n.quote,text:m.llmContent??m.content,contentParts:m.contentParts});h.contentParts&&(m.contentParts=h.contentParts),h.llmContent!==void 0&&(m.llmContent=h.llmContent),(h.contentParts||h.llmContent!==void 0)&&(m.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let p=[...this.messages];try{await this.dispatchWithDeletedRecovery(p,u,a,s,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(m){if(this.status==="resuming"||this.reconnecting)return;let h=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));if(!h){let y=rf(m,this.config.errorMessage);if(y){let v={id:a,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(v)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h||(m instanceof Error?this.callbacks.onError?.(m):this.callbacks.onError?.(new Error(String(m))))}}resubmitFrom(t,n){let o=Mw(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 u=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}},p=s?this.toComposerOptionsPayload(s.options):r.composerOptions,m=s?s.contentSegments:r.contentSegments,h=s?s.options?.quote:void 0,y=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(a??"",{...l?.length?{contentParts:[...l]}:{},...m?.length?{contentSegments:[...m]}:{},...p?{composerOptions:p}:{},...h?{quote:h}:{},...u&&Object.keys(u).length>0?{replayFields:u}:{},viaVoice:y===!0}),!0}toComposerOptionsPayload(t){if(!t)return;let n={};return t.selectedModelId&&(n.selectedModelId=t.selectedModelId),t.activeModeIds?.length&&(n.activeModeIds=[...t.activeModeIds]),Object.keys(n).length>0?n:void 0}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=ns();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=rf(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(p=>p.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,u=d&&typeof d=="object"?d.onDecision:void 0;try{let p;if(u?p=await u({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),p){let m=null;if(p instanceof Response){if(!p.ok){let h=await p.json().catch(()=>null);throw new Error(h?.error??`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);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(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}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(p=>p.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 p=t.toolCall?.args,m=Array.isArray(p?.questions)?p.questions:[];if(m.length===1){let h=typeof m[0]?.question=="string"?m[0].question:"";h&&(a={[h]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,d=t.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===0){let p=typeof n=="string"?n:Object.entries(n).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let p=a??{};u.forEach((m,h)=>{let y=typeof m?.question=="string"?m.question:"";if(!y)return;let v=p[y],C=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${h}`,role:"assistant",content:y,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${h}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let p=await this.client.resumeFlow(r,{[s]:n},{after:this.resumable?.executionId===r?this.resumable.lastEventId:void 0});if(!p.ok){let m=await p.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${p.status}`)}p.body?await this.connectStream(p.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(p){let m=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,m||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}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!==qo?!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 u=d.toolCall?.name,p=d.toolCall?.id;if(!u||!p)return null;let m=`${t}:${p}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(m),o.push(m);let h=this.markWebMcpToolRunning(d),y=d.agentMetadata?.webMcpToolCallId??u;if(u===qo)return{dedupeKey:m,resumeKey:y,output:QC(),toolMessage:d,startedAt:h,completedAt:Date.now()};let v=this.client.executeWebMcpToolCall(u,d.toolCall?.args,r.signal),C;if(!v)C={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{C=await v}catch(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));return E||this.callbacks.onError?.(x instanceof Error?x:new Error(String(x))),this.markWebMcpToolComplete(d,sf(E?"Aborted by cancel()":yk(x)),h),this.webMcpInflightKeys.delete(m),null}return r.signal.aborted?(this.markWebMcpToolComplete(d,sf("Aborted by cancel()"),h),this.webMcpInflightKeys.delete(m),null):{dedupeKey:m,resumeKey:y,output:C,toolMessage:d,startedAt:h,completedAt:Date.now()}},a;if(this.config.webmcp?.execution==="sequential"){a=[];for(let d of n)a.push(await s(d))}else a=await Promise.all(n.map(s));let l=[];try{if(l=a.filter(m=>m!==null),l.length===0)return;let d={};for(let m of l)d[m.resumeKey]=m.output;let u=await this.client.resumeFlow(t,d,{signal:r.signal,after:this.resumable?.executionId===t?this.resumable.lastEventId:void 0});if(!u.ok){let m=await u.json().catch(()=>null);throw new Error(m?.error??`Resume failed: ${u.status}`)}let p=l[0].dedupeKey;for(let m of l){this.webMcpResolvedKeys.add(m.dedupeKey);let h=m.toolMessage.toolCall?.name,y=m.toolMessage.agentMetadata?.webMcpToolCallId;this.markWebMcpToolComplete(m.toolMessage,m.output,m.startedAt,m.completedAt,{...h===qo?{suggestRepliesResolved:!0}:{},...h&&y?{clientToolAnswer:{toolCallId:y,toolName:h,args:m.toolMessage.toolCall?.args,result:m.output,batch:p}}:{}})}u.body&&await this.connectStream(u.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 p of l)this.markWebMcpToolComplete(p.toolMessage,sf("Aborted by cancel()"),p.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=Vo(this.config.features?.artifacts,t),r=Ml(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=Vo(this.config.features?.artifacts,n),s=Ml(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=Ww().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=>rf(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=ns(),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=tf(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ua(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=tf(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let l=r.agentMetadata?.clientToolAnswer;if(l&&a.agentMetadata&&!a.agentMetadata.clientToolAnswer&&(a.agentMetadata={...a.agentMetadata,clientToolAnswer:l}),r.approval&&n.approval&&r.approval.id===n.approval.id){let m=r.approval,h=n.approval;a.approval={...m,...h,executionId:h.executionId||m.executionId,toolName:h.toolName||m.toolName,description:h.description||m.description,toolType:h.toolType??m.toolType,reason:h.reason??m.reason,parameters:h.parameters??m.parameters}}let d=n.toolCall?.name,u=n.agentMetadata?.executionId,p=n.toolCall?.id;if(d&&Ow(d)&&u&&p&&n.agentMetadata?.awaitingLocalTool===!0){let m=`${u}:${p}`,h=this.webMcpInflightKeys.has(m),y=this.webMcpResolvedKeys.has(m),v=r.toolCall?.name,C=r.agentMetadata?.executionId===u&&r.toolCall?.id===p&&v!==void 0&&Ow(v)&&r.toolCall?.status==="complete";(h||y||C)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var uo=require("lucide");var bk={add:e=>lw(e)},vk=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,ap={allowedTypes:xr,maxFileSize:10*1024*1024,maxFiles:4};function Ck(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function wk(e){return e==="application/pdf"?uo.FileText:e.startsWith("text/")?uo.FileText:e.includes("word")?uo.FileText:e.includes("excel")||e.includes("spreadsheet")?uo.FileSpreadsheet:e==="application/json"?uo.FileCode:uo.File}var si=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.pendingAdds=new Map;this.destroyed=!1;this.config={allowedTypes:t.allowedTypes??ap.allowedTypes,maxFileSize:t.maxFileSize??ap.maxFileSize,maxFiles:t.maxFiles??ap.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:bk}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:ap.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=cw(o,this.config.allowedTypes,this.config.maxFileSize);if(!r.valid){let a=r.error?.includes("type")?"type":"size";this.config.onFileRejected?.(o,a);continue}let s={id:Ck(),file:o,previewUrl:np(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=vk(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=np(t.file),o=S("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let p=S("img");p.src=t.previewUrl,p.alt=t.file.name,p.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",p.style.width="48px",p.style.height="48px",p.style.objectFit="cover",p.style.borderRadius="8px",o.appendChild(p)}else{let p=S("div");p.style.width="48px",p.style.height="48px",p.style.borderRadius="8px",p.style.backgroundColor="var(--persona-container, #f3f4f6)",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.display="flex",p.style.flexDirection="column",p.style.alignItems="center",p.style.justifyContent="center",p.style.gap="2px",p.style.overflow="hidden";let m=wk(t.file.type),h=Mt(m,20,"var(--persona-muted, #6b7280)",1.5);h&&p.appendChild(h);let y=S("span");y.textContent=dw(t.file.type,t.file.name),y.style.fontSize="8px",y.style.fontWeight="600",y.style.color="var(--persona-muted, #6b7280)",y.style.textTransform="uppercase",y.style.lineHeight="1",p.appendChild(y),o.appendChild(p)}let r=Y("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=S("div","persona-attachment-progress");s.appendChild(S("div","persona-attachment-progress__bar"));let a=Y("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=le("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?a.appendChild(l):a.textContent="\u21BB",a.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,a),o.appendChild(r);let d=S("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");d.type="button",d.setAttribute("aria-label","Remove attachment"),d.style.position="absolute",d.style.top="-4px",d.style.insetInlineEnd="-4px",d.style.width="18px",d.style.height="18px",d.style.borderRadius="50%",d.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",d.style.border="none",d.style.cursor="pointer",d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="center",d.style.padding="0";let u=Mt(uo.X,10,"var(--persona-text-inverse, #ffffff)",2);u?d.appendChild(u):(d.textContent="\xD7",d.style.color="var(--persona-text-inverse, #ffffff)",d.style.fontSize="14px",d.style.lineHeight="1"),d.addEventListener("click",p=>{p.preventDefault(),p.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 Bw=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),xk=(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 Dw(){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 p=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:p,inputDisabled:e.inputDisabled,sendDisabled:p!=="idle"||e.sendDisabled||e.inputDisabled})},l=()=>(n||(n=a()),n),d=()=>{if(o=!1,r||t.size===0)return;let p=l();for(let m of[...t])try{m(p)}catch(h){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",h)}},u=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(d))};return{getState:l,subscribe:p=>(t.add(p),()=>t.delete(p)),setText:p=>{e.text!==p&&(e.text=p,u())},setAttachments:p=>{xk(e.attachments,p)||(e.attachments=[...p],u())},setMentionRefs:p=>{Bw(e.mentionRefs,p)||(e.mentionRefs=[...p],u())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,u())},setActiveModeIds:p=>{Bw(e.activeModeIds,p)||(e.activeModeIds=[...p],u())},setQuote:p=>{let m=e.quote;m?.text===p?.text&&m?.messageId===p?.messageId&&m?.sourceLabel===p?.sourceLabel||(e.quote=p?{...p}:void 0,u())},setPendingSubmission:p=>{e.pendingSubmission!==p&&(e.pendingSubmission=p,u())},setPreparing:p=>{e.preparing!==p&&(e.preparing=p,u())},setStreaming:p=>{e.streaming!==p&&(e.streaming=p,u())},setInputDisabled:p=>{e.inputDisabled!==p&&(e.inputDisabled=p,u())},setSendDisabled:p=>{e.sendDisabled!==p&&(e.sendDisabled=p,u())},flush:()=>{o&&d()},destroy:()=>{r=!0,o=!1,t.clear()}}}var On=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},_w=(e,t)=>{let n=S("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function Nw(e,t={}){let n=On(e,"[data-persona-composer-form]"),o=On(e,"[data-persona-composer-input]");if(!n||!o){let E=`[Persona] composer surface is missing required element(s): ${[!n&&"form",!o&&"input"].filter(Boolean).join(", ")}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||o))throw new Error(E);return typeof console<"u"&&console.warn(E),null}let r={header:On(e,"[data-persona-composer-header]"),body:On(e,"[data-persona-composer-body]"),actionsStart:On(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:On(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:On(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:On(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:On(e,"[data-persona-composer-status]")},s=new Set,a=r.header;a||(s.add("header"),a=_w("persona-widget-composer__header","data-persona-composer-header"),n.parentNode?n.parentNode.insertBefore(a,n):e.appendChild(a));let l=r.body??o.parentElement??n,d=(x,E,H,B,A)=>{if(E)return E;s.add(x);let O=_w(H,B);return A.appendChild(O),O},u=d("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),p=d("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),m=d("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),h=d("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),y=[],v=(x,E)=>x.target===E.target&&x.type===E.type&&x.handler===E.handler,C=On(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:a,body:l,actionsStart:u,actionsEnd:p,suggestions:m,status:h,attachmentInput:C,attachmentPreviews:On(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:On(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:On(e,"[data-persona-composer-submit]")??void 0,micButton:On(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(x,E,H,B)=>{x.addEventListener(E,H,B),y.push({target:x,type:E,handler:H,options:B})},removeListener:(x,E,H,B)=>{x.removeEventListener(E,H,B),y=y.filter(A=>!v(A,{target:x,type:E,handler:H}))},destroy:()=>{for(let x of y)x.target.removeEventListener(x.type,x.handler,x.options);y=[]}}}var _t={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},pn=1e5,fa=pn+1;var Sk=8,Ak=8,af=10,Fw=200,$w=300,Uw=0,cp=e=>Math.max(0,e);function jw(e){e.delayMs!==void 0&&(Fw=cp(e.delayMs)),e.skipDelayMs!==void 0&&($w=cp(e.skipDelayMs))}var Mk=()=>Date.now()<Uw,Ek=e=>{Uw=e>0?Date.now()+e:0},lp=new WeakMap,cf="data-persona-tooltip-suppressed",Tk=e=>typeof e.closest=="function"&&e.closest(`[${cf}]`)!==null;function Vw(e){lp.get(e)?.hide()}var qw=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Pk=e=>{let t=e.getRootNode?.();return qw(t)?t:e.ownerDocument.body},lf=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),kk=[...["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 an(e){lp.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:a=Sk,viewportPadding:l=Ak}=e,d=()=>t.ownerDocument,u=()=>d().defaultView??window,p=null,m=null,h=null,y=null,v,C=!1,x=!1,E=!1,H=()=>(typeof o=="function"?o():o).trim(),B=()=>(typeof r=="function"?r():r??"").trim(),A=()=>cp(e.delayMs??Fw),O=()=>cp(e.skipDelayMs??$w),L=()=>{v!==void 0&&(u().clearTimeout(v),v=void 0)},$=()=>{L();let ge=p!==null;y?.(),y=null,p?.remove(),p=null,m=null,h=null,ge&&Ek(O())},K=()=>{if(!p)return;let ge=d(),Ie=u(),Se=t.getBoundingClientRect(),ye=p.getBoundingClientRect(),dt=ge.documentElement.clientWidth||Ie.innerWidth,it=ge.documentElement.clientHeight||Ie.innerHeight,Ce=dt-l-ye.width,D=Se.left+Se.width/2-ye.width/2,Ne=lf(D,l,Ce),Fe=Se.top-l,Et=it-l-Se.bottom,Gt=ye.height+a,jt=Fe>=Gt||Fe>=Et?"top":"bottom",ke=jt==="top"?Se.top-a-ye.height:Se.bottom+a,we=it-l-ye.height,Be=lf(ke,l,we),Ee=Se.left+Se.width/2,An=Math.max(af,ye.width-af),j=lf(Ee-Ne,af,An);p.dataset.placement=jt,p.style.left=`${Ne}px`,p.style.top=`${Be}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${j}px`)},ae=()=>{if(E||!s||p||!t.isConnected||Tk(t))return;let ge=H(),Ie=Pk(t);if(!ge||!Ie)return;let Se=d(),ye=u();p=Se.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(fa);let dt=ye.getComputedStyle?.(t);if(dt){for(let Gt of kk){let jt=dt.getPropertyValue(Gt).trim();jt&&p.style.setProperty(Gt,jt)}dt.fontFamily&&(p.style.fontFamily=dt.fontFamily)}m=Se.createElement("span"),m.className="persona-control-tooltip__label",m.textContent=ge,p.appendChild(m);let it=B();it&&(h=Se.createElement("span"),h.className="persona-control-tooltip__hint",h.textContent=it,p.appendChild(h));let Ce=Se.createElement("span");Ce.className="persona-control-tooltip__arrow",p.appendChild(Ce),Ie.appendChild(p),K(),p.dataset.state="open";let D=()=>{if(!t.isConnected){$();return}m&&(m.textContent=H()),h&&(h.textContent=B()),K()};ye.addEventListener("scroll",D,!0),ye.addEventListener("resize",D);let Ne=t.getRootNode(),Fe=qw(Ne)?Ne:Se.documentElement,Et=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||$()});Et?.observe(Fe,{childList:!0,subtree:!0}),y=()=>{ye.removeEventListener("scroll",D,!0),ye.removeEventListener("resize",D),Et?.disconnect()}},oe=ge=>{if(!(E||p)){if(L(),ge||A()<=0||Mk()){ae();return}v=u().setTimeout(()=>{v=void 0,ae()},A())}},P=()=>{C||x?oe(x):$()},k=()=>{let ge=u();(!ge.matchMedia||!ge.matchMedia("(hover: none)").matches)&&(C=!0,P())},_=()=>{C=!1,P()},I=()=>{try{x=t.matches(":focus-visible")}catch{x=!0}P()},te=()=>{x=!1,P()},U=()=>{C=!1,x=!1,$()},pe=ge=>{ge.key==="Escape"&&U()};n.addEventListener("mouseenter",k),n.addEventListener("mouseleave",_),t.addEventListener("focus",I),t.addEventListener("blur",te),t.addEventListener("keydown",pe),t.addEventListener("click",U);let ue={get isOpen(){return p!==null},show:ae,hide:$,reposition:K,destroy:()=>{E||(E=!0,$(),n.removeEventListener("mouseenter",k),n.removeEventListener("mouseleave",_),t.removeEventListener("focus",I),t.removeEventListener("blur",te),t.removeEventListener("keydown",pe),t.removeEventListener("click",U),lp.delete(t))}};return lp.set(t,ue),ue}function df(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 dp(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function zw(e,t){e.style.maxHeight=`${t*df(e)}px`,e.style.overflowY="auto"}function Ol(e){let t=e?.ownerDocument?.defaultView??(typeof window<"u"?window:null);if(!t||typeof t.matchMedia!="function")return!1;try{return t.matchMedia("(pointer: coarse)").matches===!0}catch{return!1}}function Kw(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Gw(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||!Kw(t)}function Lk(e){return(e.submitKey??"enter")!=="enter"||Kw(e)?"enter":"send"}function pp(e,t){e.setAttribute("enterkeyhint",Lk(t))}function up(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 pf(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",Ao="persona-composer-control--glyph",gf=40,Cn=24,gp=(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)}},mp=(e,t)=>{let n=S("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Pm,n.dir="auto",pp(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Ol(n)}),up(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=dp(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 u=parseFloat(l);if(Number.isFinite(u)&&u>0)return u}let d=o*df(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}},Rk="[data-persona-glyph-stack]",mf=(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},fp=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",u=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,m=t.size,h=parseFloat(m??"")||gf,y=t.backgroundColor,v=t.textColor,C=S("div","persona-send-button-wrapper"),x=Y("button",{className:bn("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&&!y&&"persona-bg-persona-primary",!n&&!v&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?v||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":v||void 0,backgroundColor:n&&y||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),E=null,H=null,B=null;if(n){let L=parseFloat(t.iconSize??"")||Math.round(h*.5),$=t.iconStrokeWidth??2,K=v?.trim()||"currentColor";if(r&&(E=le(r,L,K,$)),H=le(s,L,K,$),!t.iconSize)for(let ae of[E,H])ae&&(ae.style.width=`var(--persona-components-composer-sendIconSize, ${L}px)`,ae.style.height=`var(--persona-components-composer-sendIconSize, ${L}px)`);E&&H?(B=mf(E,H),x.appendChild(B)):E?x.appendChild(E):(x.textContent=o,H=null)}else x.textContent=d;x.setAttribute("aria-label",a),C.appendChild(x),an({anchor:x,trigger:C,text:()=>x.getAttribute("aria-label")??"",enabled:p});let A="send";return{button:x,wrapper:C,setMode:L=>{if(L===A)return;A=L;let $=L==="stop"?l:a;x.setAttribute("aria-label",$),x.setAttribute("data-persona-send-mode",L),n?(x.querySelector(Rk)??B)?.setAttribute("data-mode",L):x.textContent=L==="stop"?u:d},glyphStack:B}},ha=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,u=parseFloat(d??"")||Cn,p=t.backgroundColor??e?.sendButton?.backgroundColor,m=t.iconColor??e?.sendButton?.textColor,h=S("div","persona-send-button-wrapper"),y=Y("button",{className:bn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Kn,!d&&Ao),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:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=le(l,u,m||"currentColor",1.5);C?y.appendChild(C):y.textContent="\u{1F3A4}",h.appendChild(y);let x=t.tooltipText??"Start voice recognition",E=t.showTooltip??!1;return an({anchor:y,trigger:h,text:()=>y.getAttribute("aria-label")??x,enabled:E}),{button:y,wrapper:h}},hp=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");n.setAttribute("data-persona-composer-attachment-previews",""),n.style.display="none";let o=S("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??xr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=S("div","persona-send-button-wrapper"),a=Y("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Kn} ${Ao}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=le(r,Cn,"currentColor",1.5);l?a.appendChild(l):a.textContent="\u{1F4CE}",a.addEventListener("click",u=>{u.preventDefault(),o.click()}),s.appendChild(a);let d=t.buttonTooltipText??"Attach file";return an({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??d}),{button:a,wrapper:s,input:o,previewsContainer:n}},yp=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=S("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),ei(o,t,"idle");let r=t.idleText??"Online";if(t.idleLink){let s=S("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=r,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=r;return o},bp=()=>Y("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});function Hk(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function vp(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:d=2147483e3,onOpen:u,onDismiss:p}=e,m=e.container??Hk(t),h=!1,y=null,v=()=>{if(!h)return;let E=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${E.width}px`),a&&(n.style.maxWidth=`${E.width}px`);let H=n.getBoundingClientRect(),B=l?.()??null,A=B!=null?E.top+B:E.top,O=o==="top-start"||o==="top-end"?A-r-H.height:E.bottom+r,$=o==="bottom-end"||o==="top-end"?E.right-H.width:E.left,K=a?.()??null;if(K!=null){let ae=Math.max(E.left,E.right-H.width);$=Math.min(Math.max(E.left+K,E.left),ae)}n.style.top=`${O}px`,n.style.left=`${$}px`},C=()=>{h&&(h=!1,y&&(y(),y=null),n.remove())},x=()=>{if(h)return;h=!0,d!=null&&(n.style.zIndex=String(d)),m.appendChild(n),v();let E=(t.ownerDocument??document).defaultView??window,H=t.ownerDocument??document,B=()=>{if(!t.isConnected){C(),p?.("anchor-removed");return}v()},A=L=>{let $=typeof L.composedPath=="function"?L.composedPath():[];$.includes(n)||$.includes(t)||(C(),p?.("outside"))},O=E.setTimeout(()=>{H.addEventListener("pointerdown",A,!0)},0);E.addEventListener("scroll",B,!0),E.addEventListener("resize",B),y=()=>{E.clearTimeout(O),H.removeEventListener("pointerdown",A,!0),E.removeEventListener("scroll",B,!0),E.removeEventListener("resize",B)},u?.()};return{get isOpen(){return h},open:x,close:C,toggle:()=>h?C():x(),reposition:v,destroy:C}}var Wk='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',Ok=["--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"],ff="data-persona-menu-focus",Bk=new Set(["ArrowDown","ArrowUp","Home","End"]);function Yw(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(Wk)??e}var Dk=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function Qw(e){let t=e.label,n=!1,o=S("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 ${Kn} ${Ao}`,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 I=e.getButtonSize?.()??"";r.style.width=I,r.style.height=I,r.style.minWidth=I,r.style.minHeight=I,r.style.lineHeight="1",r.replaceChildren();let te=le("plus",Cn,"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=[],u=-1,p=!1,m=()=>{let te=s.getRootNode().activeElement;return te instanceof HTMLElement?te:null},h=()=>{let I=m();for(let te of d){let U=!!I&&Yw(te)===I;te.toggleAttribute(ff,U&&p)}},y=()=>d.filter(I=>I.isConnected||s.contains(I)).map(Yw).filter(I=>!Dk(I)),v=(I,te)=>{I.forEach((U,pe)=>{U.setAttribute("tabindex",pe===te?"0":"-1")})},C=I=>{let te=y();if(te.length===0)return;let U=(I%te.length+te.length)%te.length;u=U,v(te,U),te[U].focus(),h()},x=()=>o.ownerDocument??document,E=null,H=null,B=null,A=()=>{E&&(x().removeEventListener("focusin",E,!0),E=null)},O=()=>{H&&(s.removeEventListener("focusin",H),H=null),B&&(s.removeEventListener("pointerdown",B,!0),B=null)},L=null,$=()=>(L||(L=vp({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),A()}})),L),K=()=>L?.isOpen===!0,ae=(I=!1)=>{if(K()){L?.close(),r.setAttribute("aria-expanded","false"),A(),O(),u=-1,p=!1;for(let te of d)te.removeAttribute(ff);I&&r.focus()}},oe=(I=0,te=!1)=>{if(n||K())return;p=te,gp(r,s,Ok),$().open(),r.setAttribute("aria-expanded","true");let U=y();v(U,-1),C(I<0?U.length-1:I),E=pe=>{let ue=typeof pe.composedPath=="function"?pe.composedPath():[];ue.includes(s)||ue.includes(o)||ae()},x().addEventListener("focusin",E,!0),H=()=>h(),s.addEventListener("focusin",H),B=()=>{p=!1},s.addEventListener("pointerdown",B,!0)},P=I=>{I.preventDefault(),I.stopPropagation(),K()?ae(!0):oe(0)},k=I=>{if(I.key==="ArrowDown"||I.key==="Enter"||I.key===" "){I.preventDefault(),p=!0,K()?C(0):oe(0,!0);return}I.key==="ArrowUp"&&(I.preventDefault(),p=!0,K()?C(-1):oe(-1,!0))},_=I=>{switch(Bk.has(I.key)&&(p=!0),I.key){case"ArrowDown":I.preventDefault(),C(u+1);return;case"ArrowUp":I.preventDefault(),C(u-1);return;case"Home":I.preventDefault(),C(0);return;case"End":I.preventDefault(),C(y().length-1);return;case"Escape":I.preventDefault(),I.stopPropagation(),ae(!0);return;case"Tab":ae(!0);return;default:}};return r.addEventListener("click",P),r.addEventListener("keydown",k),s.addEventListener("keydown",_),{trigger:o,triggerButton:r,panel:s,setItems:I=>{for(let U of d)I.includes(U)||U.removeAttribute(ff);if(d=[...I],!K())return;let te=y();v(te,Math.min(u,te.length-1)),h()},isOpen:K,open:()=>oe(0),close:ae,setLabel:I=>{I!==t&&(t=I,l())},applyButtonSize:a,destroy:()=>{n=!0,A(),O(),r.removeEventListener("click",P),r.removeEventListener("keydown",k),s.removeEventListener("keydown",_),L?.destroy(),L=null,o.remove(),s.remove(),d=[]}}}var Ko={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},Xw="data-persona-composer-action",hf="data-persona-composer-disable-when-streaming",_k="core:overflow",Nk=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function Fk(e,t){if(e===void 0)return null;if(typeof e=="number")return Number.isFinite(e)?e:null;let n=Number.parseFloat(e);if(/^\s*-?\d*\.?\d+(px)?\s*$/.test(e)&&Number.isFinite(n))return n;let o=S("div");o.style.position="absolute",o.style.visibility="hidden",o.style.pointerEvents="none",o.style.height="0",o.style.width=e,t.appendChild(o);let r=o.getBoundingClientRect().width;return o.remove(),Number.isFinite(r)&&r>0?r:Number.isFinite(n)?n:null}function yf(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 Jw=(e,t)=>{!e||typeof console>"u"||console.warn(t)},$k=(e,t)=>t.includes(":")?t:`${e}:${t}`;function Uk(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let d=o.get(l.id);if(d){Jw(t,`[Persona] composer action "${l.id}" is already contributed by ${Zw(d)}; the ${Zw(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,u)=>{let p=u?$k(u,l.id):l.id,m=l.order??Ko.custom;l.placement==="end"&&m>=Ko.send&&(Jw(t,`[Persona] composer action "${p}" ordered at ${m} would render after send; clamped to ${Ko.send-1}.`),m=Ko.send-1),s({id:p,placement:l.placement,presentation:l.presentation??"bar",order:m,sequence:r++,source:d,pluginId:u,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(u){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,u);continue}for(let u of d??[])a(u,"plugin",l.id)}return n.sort((l,d)=>l.order===d.order?l.sequence-d.sequence:l.order-d.order)}var Zw=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",ex=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,jk=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function Vk(e,t){if(!e||e==="always")return!0;let n=jk(t);return e==="when-text"?n:!n}var cs=e=>e.kind==="custom",bf=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,qk=e=>{let t=bf(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},zk='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function Kk(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(zk)||o.childNodes.forEach(n)};return n(e),t.trim()}var Gk=e=>Kk(e).length===0;function tx(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(P,k)=>{let _=P.button;if(!_)return;_.setAttribute("role","menuitem"),_.setAttribute("tabindex","-1"),_.className="persona-composer-overflow-menu__item";for(let U of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])_.style[U]="";_.style.lineHeight="1",k.tooltipText?_.setAttribute("title",k.tooltipText):_.removeAttribute("title"),_.replaceChildren();let I=S("span","persona-composer-overflow-menu__icon");if(k.iconName){let U=le(k.iconName,16,"currentColor",1.5);U&&I.appendChild(U)}let te=S("span","persona-composer-overflow-menu__label");te.textContent=k.shortLabel??k.label,_.append(I,te)},a=(P,k)=>{let _=P.button;if(!_)return;if(_.setAttribute("aria-label",k.label),k.pressed===void 0?_.removeAttribute("aria-pressed"):_.setAttribute("aria-pressed",k.pressed?"true":"false"),_.toggleAttribute(hf,k.disableWhenStreaming===!0),P.mode==="menu"){P.tooltip?.destroy(),P.tooltip=void 0,s(P,k);return}_.removeAttribute("role"),_.removeAttribute("tabindex"),_.removeAttribute("title");let I=r(),te=!!k.shortLabel;if(_.className=bn("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Kn,Ao,te&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),_.style.width=I&&!te?I:"",_.style.height=I??"",_.style.minWidth=I&&!te?I:"",_.style.minHeight=I??"",_.style.fontSize=te?"":"18px",_.style.lineHeight="1",_.style.color=k.iconColor??"",_.style.backgroundColor=k.backgroundColor??"",_.replaceChildren(),k.iconName){let U=le(k.iconName,Cn,"currentColor",1.5);U&&_.appendChild(U)}if(te){let U=S("span","persona-composer-action-button__label");U.textContent=k.shortLabel,_.appendChild(U)}else _.firstChild||(_.textContent=k.label);P.tooltip?.destroy(),P.tooltip=an({anchor:_,trigger:P.element,text:()=>k.tooltipText??k.label,enabled:!!k.tooltipText})},l=(P,k)=>{let _=P.action,I=Y("button",{attrs:{type:"button"}}),te=I;if(k==="bar"){let ue=S("div","persona-send-button-wrapper");ue.appendChild(I),te=ue}te.setAttribute(Xw,P.id);let U={resolved:P,element:te,button:I,owned:!0,managed:!0,busy:!1,visible:!0,mode:k},pe=ue=>{if(ue.preventDefault(),ue.stopPropagation(),U.busy||I.disabled)return;let ge=U.resolved.action;U.mode==="menu"&&y?.close(!0);let Ie;try{Ie=ge.onSelect(e.actionContext,ue)}catch(Se){e.reportError(Se,{actionId:U.resolved.id});return}!Ie||typeof Ie.then!="function"||(U.busy=!0,I.setAttribute("aria-busy","true"),Ie.catch(Se=>{e.reportError(Se,{actionId:U.resolved.id})}).finally(()=>{U.busy=!1,I.removeAttribute("aria-busy")}))};return I.addEventListener("click",pe),U.detach=()=>I.removeEventListener("click",pe),a(U,_),U},d=P=>{let k=P.action,_;try{_=k.render({...e.actionContext,id:P.id,action:k})}catch(I){return e.reportError(I,{actionId:P.id}),null}return _?.element?(_.element.setAttribute(Xw,P.id),_.element.toggleAttribute(hf,k.disableWhenStreaming===!0),{resolved:P,element:_.element,owned:!0,managed:!0,destroy:_.destroy,busy:!1,visible:!0,mode:"bar"}):null},u=(P,k)=>{if(P.builtIn){let I=P.builtIn.element;return I?{resolved:P,element:I,owned:!1,managed:P.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let _=P.action;return _?cs(_)?d(P):l(P,k):null},p=P=>{if(P.detach?.(),P.tooltip?.destroy(),P.detachMenuSlot?.(),P.detachMenuSlot=void 0,P.menuLabel?.remove(),P.menuLabel=void 0,P.menuSlot?.remove(),P.menuSlot=void 0,P.owned){try{P.destroy?.()}catch(k){e.reportError(k,{actionId:P.resolved.id})}P.element.remove()}},m=(P,k)=>{for(let _=0;_<k.length;_++){let I=k[_];if(!I.managed)continue;let te=null;for(let U=_+1;U<k.length;U++){let pe=k[U];if(!pe.managed&&pe.element.parentElement===P){te=pe.element;break}}te?(I.element.parentElement!==P||I.element.nextSibling!==te)&&P.insertBefore(I.element,te):P.lastChild!==I.element&&P.appendChild(I.element)}},h=(P,k)=>{if(P.button){P.button.disabled=k;return}if(!P.owned)return;let _=P.element;_.toggleAttribute("data-disabled",k),_.setAttribute("aria-disabled",k?"true":"false");let I=_ instanceof HTMLButtonElement||_ instanceof HTMLSelectElement||_ instanceof HTMLInputElement||_ instanceof HTMLTextAreaElement?_:_.querySelector("button, select, input, textarea");I&&(I.disabled=k)},y=null,v=null,C=null,x=0,E=()=>{let P=e.getOverflow?.();return P?.enabled===!0?P:void 0},H=()=>(y?y.setLabel(e.getOverflowLabel?.()??"More actions"):y=Qw({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),y),B=P=>{v!==P&&(C?.disconnect(),v=P,x=yf(P),!(typeof ResizeObserver>"u")&&(C=new ResizeObserver(k=>{let I=k[k.length-1]?.contentRect?.width??yf(P);I!==x&&(x=I,ae())}),C.observe(P)))},A=(P,k)=>{let _=Fk(P.collapseAutoActionsBelow,k);if(_===null)return!1;let I=x||yf(k);return I>0&&I<_},O=(P,k,_)=>{if(!k)return"bar";if(P.resolved.builtIn){let te=Nk(P.resolved.id);return te&&k.includeBuiltIns?.includes(te)?"menu":"bar"}let I=P.resolved.presentation;return I==="overflow"||I==="auto"&&_?"menu":"bar"},L=P=>{let k=P.menuSlot;if(!k)return;if(!Gk(P.element)){P.menuLabel?.remove(),P.menuLabel=void 0;return}let _=qk(P.element);if(!_){P.menuLabel?.remove(),P.menuLabel=void 0;return}P.menuLabel||(P.menuLabel=S("span","persona-composer-overflow-menu__label")),P.menuLabel.textContent!==_&&(P.menuLabel.textContent=_),P.menuLabel.parentElement!==k&&k.appendChild(P.menuLabel)},$=(P,k)=>{if(P.mode===k)return P;let _=P.resolved.action;if(_&&!cs(_)){p(P),t.delete(P.resolved.id);let I=l(P.resolved,k);return t.set(P.resolved.id,I),I}if(k==="menu"){let I=Y("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[cf]:""}});I.appendChild(P.element),Vw(bf(P.element)),P.menuSlot=I;let te=U=>{let pe=bf(P.element);if(pe.disabled)return;let ue=U.target===pe||pe.contains(U.target);y?.close(!0),ue||pe.click()};I.addEventListener("click",te,!0),P.detachMenuSlot=()=>I.removeEventListener("click",te,!0),P.managed=!0,L(P)}else P.detachMenuSlot?.(),P.detachMenuSlot=void 0,P.menuLabel?.remove(),P.menuLabel=void 0,P.menuSlot?.remove(),P.menuSlot=void 0;return P.mode=k,P},K=(P,k)=>{let _=k.map(I=>I.menuSlot??I.element);for(_.forEach((I,te)=>{let U=P.children[te];U!==I&&(U?P.insertBefore(I,U):P.appendChild(I))});P.children.length>_.length;)P.lastElementChild?.remove()},ae=()=>{if(o)return;let P=e.getBindings();if(!P)return;let k=e.getState(),_=k.phase==="streaming",I=E();I&&B(P.footer);let te=I?A(I,P.footer):!1,U={start:[],end:[]},pe=[];for(let ue of n){let ge=t.get(ue.id);if(!ge)continue;let Ie=ue.action,Se=Ie?ex(Ie.visible,k,!0)&&Vk(Ie.visibility,k):!0;if(ge.visible!==Se&&(ge.visible=Se,!Se&&ge.managed&&(ge.menuSlot??ge.element).remove()),!!Se){if(ge=$(ge,O(ge,I,te)),Ie){let ye=ex(Ie.disabled,k,!1)||Ie.disableWhenStreaming===!0&&_;h(ge,ye),!cs(Ie)&&Ie.pressed!==void 0&&ge.button?.setAttribute("aria-pressed",Ie.pressed?"true":"false")}ge.mode==="menu"?(L(ge),pe.push(ge)):U[ue.placement].push(ge)}}if(pe.length>0){let ue=H();K(ue.panel,pe),ue.setItems(pe.map(ye=>ye.menuSlot??ye.element)),ue.applyButtonSize();let ge=Number.isFinite(I?.order)?I?.order:Ko.overflow,Ie=U.start.findIndex(ye=>ye.resolved.order>ge),Se={resolved:{id:_k,placement:"start",presentation:"bar",order:ge,sequence:-1,source:"core"},element:ue.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};U.start.splice(Ie<0?U.start.length:Ie,0,Se)}else y&&(y.close(),y.trigger.remove(),y.setItems([]));m(P.actionsStart,U.start),m(P.actionsEnd,U.end)};return{resolve:()=>{if(o)return;let P=Uk(e.collect()),k=new Set(P.map(_=>_.id));for(let[_,I]of t)k.has(_)||(p(I),t.delete(_));for(let _ of P){let I=t.get(_.id);if(!I){let ue=u(_,"bar");ue&&t.set(_.id,ue);continue}let te=I.resolved.action,U=_.action;if(!!te!=!!U||te&&U&&cs(te)!==cs(U)||te&&U&&cs(te)&&cs(U)&&te.render!==U.render){p(I),t.delete(_.id);let ue=u(_,I.mode);ue&&t.set(_.id,ue);continue}I.resolved=_,_.builtIn?(I.managed=_.builtIn.managed===!0||I.mode==="menu",_.builtIn.element&&I.mode==="bar"&&(I.element=_.builtIn.element)):U&&!cs(U)?a(I,U):U&&I.element.toggleAttribute(hf,U.disableWhenStreaming===!0)}n=P,ae()},sync:ae,getResolved:()=>n,getOverflowMenu:()=>y,destroy:()=>{if(!o){o=!0,C?.disconnect(),C=null,v=null;for(let P of t.values())p(P);t.clear(),y?.destroy(),y=null,n=[]}}}}var Yk="core:model",Qk=700,nx=16,Xk=["--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"],ox=()=>{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 rx(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=d=>{let u=e.getSelectedModelId();return d.find(p=>p.id===u)??d[0]},s=()=>{let d=Y("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),u="",p=()=>{let C=e.getModels(),x=C.map(E=>`${E.id}:${E.label}`).join("|");x!==u&&(u=x,d.replaceChildren(...C.map(E=>{let H=Y("option",{attrs:{value:E.id}});return H.textContent=E.label,H}))),d.value=r(C)?.id??""};p(),o=p;let m=()=>{d.value&&e.onSelect(d.value)};d.addEventListener("change",m);let h=C=>C.stopPropagation();d.addEventListener("click",h);let{wrapper:y,chevron:v}=ox();return y.append(d,v),{element:y,destroy:()=>{o===p&&(o=null),d.removeEventListener("change",m),d.removeEventListener("click",h)}}},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"}}),u=S("span","persona-composer-model-picker-label"),p=S("span","persona-composer-model-picker-suffix");d.append(u,p);let m=Y("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),h=new Map,y="",v=null,C=()=>v?.isOpen===!0,x=(k=!1)=>{C()&&(v?.close(),d.setAttribute("aria-expanded","false"),k&&d.focus())},E=k=>{let _=[...h.values()];if(_.length===0)return;let I=(k%_.length+_.length)%_.length;_[I].focus()},H=k=>{if(C())return;v||(v=vp({anchor:d,content:m,placement:"top-start",offset:6,onDismiss:()=>d.setAttribute("aria-expanded","false")})),gp(d,m,Xk),v.open(),d.setAttribute("aria-expanded","true");let I=[...h.keys()].indexOf(r(e.getModels())?.id??"");E(k??(I>=0?I:0))},B=k=>{x(!0),e.onSelect(k)},A=k=>{k.preventDefault(),k.stopPropagation();let _=k.currentTarget.getAttribute("data-persona-model-option");_&&B(_)},O=k=>{let _=Y("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":k.id}});if(k.icon){let ue=le(k.icon,nx,"currentColor",1.5);if(ue){let ge=S("span","persona-composer-model-option-icon");ge.appendChild(ue),_.appendChild(ge)}}let I=S("span","persona-composer-model-option-body"),te=S("span","persona-composer-model-option-label");if(te.textContent=k.label,I.appendChild(te),k.description){let ue=S("span","persona-composer-model-option-description");ue.textContent=k.description,I.appendChild(ue)}_.appendChild(I);let U=S("span","persona-composer-model-option-check");U.setAttribute("aria-hidden","true");let pe=le("check",nx,"currentColor",2);return pe&&U.appendChild(pe),_.appendChild(U),_.addEventListener("click",A),_},L=()=>{let k=e.getModels(),_=k.map(U=>`${U.id}:${U.label}:${U.icon??""}:${U.description??""}`).join("|");if(_!==y){y=_;for(let U of h.values())U.removeEventListener("click",A);h.clear(),m.replaceChildren(...k.map(U=>{let pe=O(U);return h.set(U.id,pe),pe}))}let I=r(k);for(let[U,pe]of h)pe.setAttribute("aria-selected",String(U===I?.id));u.textContent=I?.label??"";let te=e.getSuffix?.()??"";p.textContent=te,d.setAttribute("aria-label",[t,[I?.label,te].filter(Boolean).join(" ")].filter(Boolean).join(": "))};L(),o=L;let $=k=>{k.preventDefault(),k.stopPropagation(),C()?x(!0):H()},K=k=>{if(k.key==="ArrowDown"){k.preventDefault(),C()?E(0):H(0);return}k.key==="ArrowUp"&&(k.preventDefault(),C()?E(-1):H(-1))},ae=k=>{let _=[...h.values()],I=_.indexOf(k.target?.closest?.(".persona-composer-model-option"));switch(k.key){case"ArrowDown":k.preventDefault(),E(I+1);return;case"ArrowUp":k.preventDefault(),E(I-1);return;case"Home":k.preventDefault(),E(0);return;case"End":k.preventDefault(),E(_.length-1);return;case"Escape":k.preventDefault(),k.stopPropagation(),x(!0);return;case"Tab":x(!0);return;default:}};d.addEventListener("click",$),d.addEventListener("keydown",K),m.addEventListener("keydown",ae);let{wrapper:oe,chevron:P}=ox();return oe.append(d,P),{element:oe,destroy:()=>{o===L&&(o=null),d.removeEventListener("click",$),d.removeEventListener("keydown",K),m.removeEventListener("keydown",ae);for(let k of h.values())k.removeEventListener("click",A);h.clear(),v?.destroy(),v=null,m.remove()}}};return{action:{id:Yk,kind:"custom",placement:"end",order:Qk,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?a():s()},repaint:()=>o?.()}}var vf="[data-persona-composer-chip-row]";function Cp(e){e.style.display=e.childElementCount>0?"flex":"none"}function Cf(e){let t=e.querySelector(vf);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 Jk=":scope > [data-persona-composer-mode]";function sx(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=u=>{let p=Y("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":u.id}});if(u.iconName){let v=S("span","persona-mention-chip-icon"),C=le(u.iconName,12,"currentColor",1.5);C&&v.appendChild(C),p.appendChild(v)}let m=S("span","persona-mention-chip-label");m.textContent=u.shortLabel??u.label,p.appendChild(m);let h=Y("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${u.label}`}}),y=le("x",12,"currentColor",2);return y?h.appendChild(y):h.textContent="\xD7",h.addEventListener("click",v=>{v.preventDefault(),v.stopPropagation(),e.onRemove(u.id)}),p.appendChild(h),p},a=()=>Array.from(t.querySelectorAll(Jk)),l=u=>{u.setAttribute("data-persona-chip-exit",""),u.setAttribute("aria-hidden","true"),u.style.pointerEvents="none";let p=()=>{u.remove(),Cp(t)},m=t.ownerDocument.defaultView,h=typeof m?.getComputedStyle=="function"?m.getComputedStyle(u).animationName:"";if(!h||h==="none"){p();return}u.addEventListener("animationend",p,{once:!0}),u.addEventListener("animationcancel",p,{once:!0})},d=()=>{for(let u of a())u.remove()};return{element:t,render:(u,p)=>{if(o)return;let m=p.filter(C=>u.includes(C.id)),h=m.map(C=>`${C.id}:${C.shortLabel??C.label}`).join("|");if(h===n)return;n=h;let y=new Map;for(let C of a()){let x=C.getAttribute("data-persona-composer-mode");x&&m.some(H=>H.id===x)&&!C.hasAttribute("data-persona-chip-exit")?y.set(x,C):C.hasAttribute("data-persona-chip-exit")||l(C)}let v=t.firstChild;for(let C of m){let x=y.get(C.id);x||(x=s(C),r.has(C.id)||(x.setAttribute("data-persona-chip-enter",""),x.addEventListener("animationend",()=>x?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(C.id),x!==v&&t.insertBefore(x,v),v=x.nextSibling}Cp(t)},destroy:()=>{o=!0,d(),Cp(t)}}}var ix=e=>`core:mode:${e}`;var wf=e=>Math.min(300+e,499),ax=e=>`core:mode-group:${e}`;function wp(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function Zk(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function lx(e,t){return e?.length?e.filter(n=>!wp(n.groupId,t)&&!Zk(n.groupId,t)):[]}var e0=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function cx(e,t,n,o){let r=n.find(l=>l.id===t);if(!r)return[...e];let s=e.includes(t),a=new Set(e);if(s)a.delete(t);else{if(e0(r,o)==="single"){let l=n.filter(d=>d.groupId===r.groupId).map(d=>d.id);a=new Set([...a].filter(d=>!l.includes(d)))}a.add(t)}return n.filter(l=>a.has(l.id)).map(l=>l.id)}function xp(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function dx(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function px(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var t0=16;function ux(e){let t=null;return{action:{id:ax(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=u=>{u.preventDefault(),u.stopPropagation();let m=u.currentTarget.getAttribute("data-persona-composer-mode");!m||e.getActiveIds().includes(m)&&e.getGroup()?.selection==="single"||e.onSelect(m)},l=u=>{let p=Y("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":u.id,"aria-label":u.label}});if(u.iconName){let h=le(u.iconName,t0,"currentColor",1.5);h&&p.appendChild(h)}let m=S("span","persona-composer-segmented-label");return m.textContent=u.shortLabel??u.label,p.appendChild(m),p.addEventListener("click",a),p},d=()=>{let u=e.getGroup();u?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",u.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let p=e.getModes(),m=p.map(y=>`${y.id}:${y.shortLabel??y.label}:${y.iconName??""}`).join("|");if(m!==s){s=m;for(let v of r.values())v.removeEventListener("click",a);r.clear();let y=p.map(v=>{let C=l(v);return r.set(v.id,C),C});o.replaceChildren(...y)}let h=e.getActiveIds();for(let[y,v]of r)v.setAttribute("aria-pressed",String(h.includes(y)))};return d(),t=d,{element:o,destroy:()=>{t===d&&(t=null);for(let u of r.values())u.removeEventListener("click",a);r.clear()}}}},repaint:()=>t?.()}}function gx(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=S("span","persona-composer-quote-bar"),l=S("div","persona-composer-quote-content");if(s.sourceLabel){let m=S("div","persona-composer-quote-source");m.textContent=s.sourceLabel,l.appendChild(m)}let d=Y("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});d.textContent=rp(s.text),l.appendChild(d);let u=Y("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),p=le("x",12,"currentColor",2);p?u.appendChild(p):u.textContent="\xD7",u.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),e.onDismiss()}),t.replaceChildren(a,l,u)};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 mx(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,u)=>{let p=Y("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[d]:""}}),m=le(a,12,"currentColor",2);return m?p.appendChild(m):p.textContent=l,p.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),u()}),p},s=a=>{let l=rp(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(p=>p.label).join(", "):"Queued message"};return{element:t,render:a=>{if(o||a===n)return;if(n=a,!a){t.replaceChildren(),t.style.display="none";return}let l=S("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let d=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 fx(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=S("div","persona-message-edit-actions"),s=(l,d,u,p)=>{let m=Y("button",{className:`persona-message-edit-button ${d}`,attrs:{type:"button",[u]:""},text:l});return m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),p()}),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 hx(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 yx(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 bx(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 vx(e){return e.wrapped||e.text.includes(`
|
|
23
|
+
`)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function Cx(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function wx(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 xx(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function xf(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 Ax(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var n0=e=>typeof e?.then=="function";function Sx(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 Mx(e,t,n){let o;try{o=e(xf(t),{signal:n})}catch(r){return{status:"error",error:r}}return n0(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:Sx(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):Sx(t,o)}var Ex=/\s/;function o0(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
|
|
24
|
+
`:o===""||Ex.test(o)}function r0(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let a=e[s];if(a===n)return o0(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
|
|
25
|
+
`||a==="\uFFFC"||!r&&Ex.test(a))return null;s--}return null}function Tx(e,t,n){for(let o of n){let r=r0(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Px(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function kx(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 Lx(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=S("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 ${Kn} ${Ao}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=le(o,Cn,"currentColor",1.5);return l?a.appendChild(l):a.textContent="+",a.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),n()}),s.appendChild(a),an({anchor:a,trigger:s,text:()=>a.getAttribute("aria-label")??r}),{button:a,wrapper:s}}var{setLoader:SB,load:s0}=xt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var Sf=s0;var{setLoader:EB,load:i0}=xt({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var Ix=i0;function Bl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Y("span",{className:bn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=le(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=S("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 Rx(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=kx(t).filter(A=>A.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(A=>A.sources.some(O=>typeof O.matchCommand=="function")),r=A=>o.some(O=>O.trigger?O.position==="line-start"?A.split(`
|
|
26
26
|
`).some($=>$.startsWith(O.trigger)):(O.position==="anywhere"?A:A.split(`
|
|
27
|
-
`)[0]).startsWith(O.trigger):!1),s=(A,O)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:O}))}catch{}},a=!e.chipRow,l=e.chipRow??Y("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,p=null,u=e.textarea,m=null,h=null,y=null,v=null,C=()=>{if(d)return Promise.resolve(d);if(p)return p;let A=wf().then(O=>(O.setMentionIconRenderer(le),d=O.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:l,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:B,emit:s}),d)).catch(O=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",O),p===A&&(p=null),null));return p=A,A},x=()=>{xx().then(A=>{let O=A.mountInlineComposer({textarea:e.textarea,renderToken:$=>Bl($,{render:t.renderMentionToken}),onMentionRemoved:$=>d?.untrackMention($)});m=O.input,h=O.destroy;let L=u;L.replaceWith(O.element),u=O.element,v={next:O.element,prev:L},y?.(O.element,L),d?d.rebindComposer(O.input):p&&p.then($=>$?.rebindComposer(O.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};t.display==="inline"&&x();let E=[],H=new Map;for(let A of n){if(!A.showButton)continue;let O=wx({config:{...t,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},onOpen:()=>{C().then(L=>L?.openMenu(A.trigger))}});E.push(O),H.set(A.trigger,O.button)}let B=(A,O,L)=>{let $=H.get(O);$&&($.setAttribute("aria-expanded",A?"true":"false"),A?$.setAttribute("aria-controls",L):$.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(A=>A.wrapper),contextRow:l,handleInput:A=>{if(d){d.handleInput();return}if(!vx(A))return;let O=u,L=O.selectionStart??0;bx(O.value,L,n)&&C().then($=>$?.handleInput())},handleKeydown:A=>{if(d?.isMenuOpen())return d.handleKeydown(A);if(A.key==="Backspace"&&d?.hasMentions()&&!v){let O=u,L=O.selectionStart===0&&O.selectionEnd===0;if((O.value.length===0||L)&&d.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(d??await C())?.dispatchInlineCommand(A)??null:null,clear:()=>d?.clear(),prefetch:()=>{wf().catch(()=>{})},onComposerSwap:A=>{y=A,v&&A(v.next,v.prev)},destroy:()=>{d?.destroy(),h?.();for(let A of E)A.wrapper.remove();a&&l.remove()}}}var Sp=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),Ap={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"};var Ep="16px",Tp="transparent",Xk=(()=>{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})(),Dl={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:Xk,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"}},Mp={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"}},Gn={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:Js,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ep,canvasBackground:Tp,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}},Jk=Dl.colors.gray,Zk={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},Mx={...Dl,colors:{...Dl.colors,gray:Jk}},e0={...Dl,colors:{...Dl.colors,gray:Zk},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},Ex=Mx,Tx=Mp,t0={...Mp,colors:{...Mp.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Mp.typography,fontSize:"14px",lineHeight:"1.5"}},Px=Tx,Pp=Gn,n0={...Gn,launcher:Ap,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...Gn.input,borderRadius:"palette.radius.full"},introCard:{...Gn.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...Gn.suggestion.chip,fontWeight:"400"},card:{...Gn.suggestion.card,fontWeight:"400"},list:{...Gn.suggestion.list,fontWeight:"400"}},panel:{...Gn.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...Gn.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...Gn.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...Gn.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...Gn.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...Gn.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}},kx=Pp,o0=e=>Jr({future:e}),Sf=e=>o0(e)==="v5"?{palette:e0,semantic:t0,components:n0}:{palette:Mx,semantic:Tx,components:Pp};function cn(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."))?cn(e,o):o}function kp(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=cn(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 Af(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 Lx(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]=Lx(s,r):n[o]=r}return n}function r0(e,t){return t?Lx(e,t):e}function _l(e,t={}){let n=Sf(t.future),o={palette:n.palette,semantic:n.semantic,components:n.components},r={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:r0(o.components,e?.components)},s=e?.components?.activity;for(let p of["toolBubble","reasoningBubble"])for(let u of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[u]!==void 0&&(r.components[p][u]=s[u]);let a=e?.components?.collapsibleWidget?.surface;a!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:a});let l=e?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let d=e?.components?.message;if(d?.gap!==void 0&&d.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),t.validate!==!1){let p=Af(r);if(!p.valid)throw new Error(`Theme validation failed: ${p.errors.map(u=>u.message).join(", ")}`)}if(t.plugins)for(let p of t.plugins)r=p.transform(r);return r}var xf=e=>e.trim()==="0"?"0px":e,Ax="--persona-",s0=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},i0=.179,ln=(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[Ax+s],r!==void 0)break;r!==void 0&&(e[Ax+n]=r)}};function Lp(e){let t=kp(e),n={};for(let[D,Ne]of Object.entries(t)){let Fe=D.replace(/\./g,"-");n[`--persona-${Fe}`]=Ne.value}ln(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"],ln(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"]]),ln(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"]}`,ln(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"]??Ep,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Tp,ln(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"]]),ln(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"],ln(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"],ln(n,[["header-control-size","components-header-controlSize","=32px"],["header-control-icon-size","components-header-controlIconSize","=20px"]]);let l=e.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[D,Ne]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Fe=n[`--persona-components-history-overlay-${D}`];Fe&&(n[`--persona-history-overlay-${Ne}`]=Fe)}for(let[D,Ne]of[["background","bg"],["borderRadius","radius"]]){let Fe=n[`--persona-components-history-menu-${D}`];Fe&&(n[`--persona-history-menu-${Ne}`]=Fe)}let m=e.components?.history?.motion;if(m){let D=Et=>{if(Et===void 0)return;let Gt=String(Et).trim();return/^\d+(\.\d+)?$/.test(Gt)?`${Gt}ms`:Gt},Ne=D(m.enterDurationMs);Ne!==void 0&&(n["--persona-history-enter-ms"]=Ne);let Fe=D(m.exitDurationMs);Fe!==void 0&&(n["--persona-history-exit-ms"]=Fe),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let h=n["--persona-components-history-dangerForeground"];h&&(n["--persona-history-danger-fg"]=h),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let D of["scrim","shadow"]){let Ne=n[`--persona-components-history-confirm-${D}`];Ne&&(n[`--persona-history-confirm-${D}`]=Ne)}for(let[D,Ne]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Fe=n[`--persona-components-tooltip-${D}`];Fe&&(n[`--persona-tooltip-${Ne}`]=Fe)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[D,Ne]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Fe=n[`--persona-components-messageActions-${D}`];Fe&&(n[`--persona-message-action-${Ne}`]=Fe)}ln(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let y=n["--persona-components-introCard-background"],v=n["--persona-components-introCard-shadow"],C=(!y||y==="transparent"||y==="none")&&(!v||v==="none"),x=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=C&&x==="1.5rem"?"1.5rem 0":x,ln(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"]]),ln(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let E=n["--persona-components-markdown-heading-h1-fontSize"];E&&(n["--persona-md-h1-size"]=E);let H=n["--persona-components-markdown-heading-h1-fontWeight"];H&&(n["--persona-md-h1-weight"]=H);let B=n["--persona-components-markdown-heading-h2-fontSize"];B&&(n["--persona-md-h2-size"]=B);let A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let O=n["--persona-components-markdown-prose-fontFamily"];O&&O!=="inherit"&&(n["--persona-md-prose-font-family"]=O),ln(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"]]),ln(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),ln(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),ln(n,[["md-hr-color","components-markdown-hr-color","divider"]]),ln(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]);let L=[["container","surface"],["surface","surface"],["border","border"]];for(let[D,Ne]of L){let Fe=n[`--persona-components-collapsibleWidget-${D}`]??n[`--persona-${Ne}`];Fe!==void 0&&(n[`--persona-cw-${D}`]=Fe,n[`--cw-${D}`]=Fe)}ln(n,[["message-border","components-message-border","border"]]),ln(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-border-width","components-message-assistant-borderWidth"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let $=e.components,K=$?.iconButton;K&&(K.background&&(n["--persona-icon-btn-bg"]=K.background),K.border&&(n["--persona-icon-btn-border"]=K.border),K.color&&(n["--persona-icon-btn-color"]=K.color),K.padding&&(n["--persona-icon-btn-padding"]=K.padding),K.borderRadius&&(n["--persona-icon-btn-radius"]=K.borderRadius),K.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=K.hoverBackground),K.hoverColor&&(n["--persona-icon-btn-hover-color"]=K.hoverColor),K.activeBackground&&(n["--persona-icon-btn-active-bg"]=K.activeBackground),K.activeBorder&&(n["--persona-icon-btn-active-border"]=K.activeBorder));let ae=$?.labelButton;ae&&(ae.background&&(n["--persona-label-btn-bg"]=ae.background),ae.border&&(n["--persona-label-btn-border"]=ae.border),ae.color&&(n["--persona-label-btn-color"]=ae.color),ae.padding&&(n["--persona-label-btn-padding"]=ae.padding),ae.borderRadius&&(n["--persona-label-btn-radius"]=ae.borderRadius),ae.hoverBackground&&(n["--persona-label-btn-hover-bg"]=ae.hoverBackground),ae.fontSize&&(n["--persona-label-btn-font-size"]=ae.fontSize),ae.gap&&(n["--persona-label-btn-gap"]=ae.gap));let oe=$?.toggleGroup;oe&&(oe.gap&&(n["--persona-toggle-group-gap"]=oe.gap),oe.borderRadius&&(n["--persona-toggle-group-radius"]=oe.borderRadius));let P=$?.artifact;if(P?.toolbar){let D=P.toolbar;D.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=D.iconHoverColor),D.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=D.iconHoverBackground),D.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=D.iconPadding),D.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=D.iconBorderRadius),D.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=D.iconBorder),D.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=xf(D.toggleGroupGap)),D.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=D.toggleBorderRadius),D.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=xf(D.toggleGroupPadding)),D.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=D.toggleGroupBorder),D.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=D.toggleGroupBorderRadius),D.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=cn(e,D.toggleGroupBackground)??D.toggleGroupBackground),D.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=D.copyBackground),D.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=D.copyBorder),D.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=D.copyColor),D.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=xf(D.copyBorderRadius)),D.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=D.copyPadding),D.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=D.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??D.copyMenuBackground),D.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=D.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??D.copyMenuBorder),D.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=D.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??D.copyMenuShadow),D.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=D.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??D.copyMenuBorderRadius),D.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=D.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??D.copyMenuItemHoverBackground),D.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=D.iconBackground),D.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=D.toolbarBorder)}if(P?.tab){let D=P.tab;D.background&&(n["--persona-artifact-tab-bg"]=D.background),D.activeBackground&&(n["--persona-artifact-tab-active-bg"]=D.activeBackground),D.activeBorder&&(n["--persona-artifact-tab-active-border"]=D.activeBorder),D.borderRadius&&(n["--persona-artifact-tab-radius"]=D.borderRadius),D.textColor&&(n["--persona-artifact-tab-color"]=D.textColor),D.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=D.hoverBackground),D.listBackground&&(n["--persona-artifact-tab-list-bg"]=D.listBackground),D.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=D.listBorderColor),D.listPadding&&(n["--persona-artifact-tab-list-padding"]=D.listPadding)}if(P?.pane){let D=P.pane;if(D.toolbarBackground){let Ne=cn(e,D.toolbarBackground)??D.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Ne}}if(P?.card){let D=P.card;D.background&&(n["--persona-artifact-card-bg"]=D.background),D.border&&(n["--persona-artifact-card-border"]=D.border),D.borderRadius&&(n["--persona-artifact-card-radius"]=D.borderRadius),D.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=D.hoverBackground),D.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=D.hoverBorderColor)}if(P?.inline){let D=P.inline;D.background&&(n["--persona-artifact-inline-bg"]=cn(e,D.background)??D.background),D.border&&(n["--persona-artifact-inline-border"]=D.border),D.borderRadius&&(n["--persona-artifact-inline-radius"]=D.borderRadius),D.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=cn(e,D.chromeBackground)??D.chromeBackground),D.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=cn(e,D.chromeBorder)??D.chromeBorder),D.titleColor&&(n["--persona-artifact-inline-title-color"]=cn(e,D.titleColor)??D.titleColor),D.mutedColor&&(n["--persona-artifact-inline-muted-color"]=cn(e,D.mutedColor)??D.mutedColor),D.frameHeight&&(n["--persona-artifact-inline-frame-height"]=D.frameHeight)}let k=$?.code;k&&(k.keywordColor&&(n["--persona-code-keyword-color"]=k.keywordColor),k.stringColor&&(n["--persona-code-string-color"]=k.stringColor),k.commentColor&&(n["--persona-code-comment-color"]=k.commentColor),k.numberColor&&(n["--persona-code-number-color"]=k.numberColor),k.tagColor&&(n["--persona-code-tag-color"]=k.tagColor),k.attrColor&&(n["--persona-code-attr-color"]=k.attrColor),k.propertyColor&&(n["--persona-code-property-color"]=k.propertyColor),k.lineNumberColor&&(n["--persona-code-line-number-color"]=k.lineNumberColor),k.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=k.gutterBorderColor),k.background&&(n["--persona-code-bg"]=cn(e,k.background)??k.background));let _=n["--persona-surface"],I=n["--persona-container"],te=n["--persona-palette-colors-gray-100"]??"#f3f4f6",U=n["--persona-palette-colors-gray-200"]??"#e5e7eb",pe=n["--persona-palette-colors-gray-300"]??"#d1d5db",ue=!I||I===_,ge=s0(_??n["--persona-background"]),Ie=ue&&ge!==void 0&&ge<i0,Se=Ie?"rgba(255, 255, 255, 0.08)":te,ye=Ie?"rgba(255, 255, 255, 0.12)":U,dt=Ie?"rgba(255, 255, 255, 0.16)":pe,it=ue?Se:I,Ce=ue?ye:I;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??it,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Ce,ue&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??dt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??it,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??it,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??it,n}var Ix={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 a0=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),Rx=(e,t)=>{if(!t||!a0(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(ii(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:Jr(t)==="v5"?"400px":"420px"}}}},l0={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"}}},Nl={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)"}}}},Mf=l0,c0={...Mf,colors:{...Mf.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},d0=Nl,p0={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600"}}},components:{...Nl.components,button:{...Nl.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...Nl.components?.eventStream,badge:{...Nl.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},u0=e=>Jr({future:e})==="v5"?{palette:c0,components:p0}:{palette:Mf,components:d0},Hx=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Fl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",g0=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Fl()},ii=e=>g0(e),m0=(e,t={})=>_l(e,t),f0=(e,t={})=>{let n=u0(t.future),o=xo(n.components,e??{})??{};return _l({...o,palette:{...o.palette,colors:Jr(t)==="v5"?xo(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},Mo=e=>{let t=ii(e),n=Hx(e?.theme),o=Sp(e)==="circle"?Ap:{...Pp.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=xo({components:{launcher:o}},n),s=Hx(e?.darkTheme);return Rx(t==="dark"?f0(xo(r??{},s??{}),{future:e?.future}):m0(r,{future:e?.future}),e)},h0=e=>Lp(e),ai=(e,t)=>{let n=Mo(t),o=h0(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",ii(t)),e.setAttribute("data-persona-defaults",Jr(t))},ya=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Fl())});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(Fl());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 Tr=require("lucide");var ds=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Ip="24px",Ef=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",$l=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},Wx=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var Ox=null;var Tf=()=>{if(Ox!==null)return Ox;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},y0="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Rp=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Hp=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 Rp("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Rp("unsupported",e),null):(n==="space"&&(o.key=" "),o)},b0=e=>y0.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),Bx=(e,t)=>{let n=Hp(e);if(!n)return"";let o=Tf(),r=b0(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("+")},Wp=e=>Bx(e,!1),Ul=e=>Bx(e,!0),v0=(e,t)=>t.key?.toLowerCase()===e.key&&(Tf()?t.metaKey:t.ctrlKey)===e.mod&&!(Tf()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,C0=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},Dx=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(v0(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&C0(a))){s.preventDefault();try{l.run(s)}catch(d){Rp(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=Hp(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=t.get(l);return d?(Rp(`${d.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",Ul(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}};var _x=require("idiomorph"),Op=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;_x.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 Nx=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Pf={index:-1,draft:""};function Fx(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 $x(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 Ux(){return new Map}function jx(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Vx(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function qx(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function zx(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 Kx(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Go(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function li(e,t){return Go(e)-e.scrollTop<=t}function Gx(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 Yx(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 Qx(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function kf(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 Xx(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var jl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},w0=["pre","code","a","script","style"],Bp=e=>({type:e?.type??jl.type,placeholder:e?.placeholder??jl.placeholder,speed:e?.speed??jl.speed,duration:e?.duration??jl.duration,buffer:e?.buffer??jl.buffer}),Zx=[{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"}],Vl=new Map;for(let e of Zx)Vl.set(e.name,e);var eS=["wipe","glyph-cycle"],ql=e=>{Vl.set(e.name,e)},tS=e=>{Zx.some(t=>t.name===e)||Vl.delete(e)},nS=()=>Array.from(Vl.keys()),zl=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Vl.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},x0=(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},S0=(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},Lf=/\s/,A0=(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},M0=(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(Lf.test(s[l])){let d=l;for(;d<s.length&&Lf.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&&!Lf.test(s[p]);)d.appendChild(x0(o,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,e)},E0=(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(S0(o,d,t,n.value)),n.value+=1));r.replaceChild(a,e)},Kl=(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??w0).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)A0(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=t==="char"?M0:E0;for(let m of l)u(m,n,p);return r.innerHTML},_p=(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},Gl=(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},Jx=new WeakMap,T0=(e,t)=>{if(!e.styles)return;let n=Jx.get(t);if(n||(n=new Set,Jx.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)},If=new WeakMap,P0=(e,t)=>{if(!e.onAttach)return;let n=If.get(t);if(n||(n=new Map,If.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},oS=e=>{let t=If.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Yl=(e,t)=>{T0(e,t),P0(e,t)};var{setLoader:jB,load:k0}=xt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var rS=k0;function Rf(e,t=pn){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 Ql=0,ps=null;function Hf(e=document){if(Ql++,Ql===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;ps={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,Ql=Math.max(0,Ql-1),Ql===0&&ps)){let n=e.body,o=e.defaultView??window;n.style.overflow=ps.originalOverflow,n.style.position=ps.originalPosition,n.style.top=ps.originalTop,n.style.width=ps.originalWidth,o.scrollTo(0,ps.scrollY),ps=null}}}var Xl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ct=e=>(e?.launcher?.mountMode??"floating")==="docked",us=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Bn=e=>{let t=e?.launcher?.dock,n=fr(e).dockWidth?t?.width:cn(Mo(e),"components.panel.width");return{side:t?.side??Xl.side,width:n??Xl.width,animate:t?.animate??Xl.animate,reveal:t?.reveal??Xl.reveal,maxHeight:t?.maxHeight??Xl.maxHeight}};var iS=require("lucide");var Wf=e=>e==="followUp"?"follow-up":e,Of=(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"}},sS=new WeakSet,L0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,I0=e=>{L0()||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"})})},Bf=e=>{var B,A,O;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:d,chipsConfig:p,session:u,getTextarea:m,eventTarget:h,submitPrompt:y}=e,v=o==="followUp",C=t.behavior,x=()=>{if(u.isStreaming())return;let L={suggestion:{...t},surface:o,source:r,behavior:C},$=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:L,bubbles:!0,composed:!0,cancelable:!0}));if(v&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!$)return;for(let ae of d)if(ae.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let K=m();if(C==="fill"){K.value=t.prompt,K.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),K.focus();return}if(y){y(t.prompt);return}K.value="",u.sendMessage(t.prompt)},E=()=>{let L=S("button",`persona-suggestion persona-suggestion--${s}`);if(L.type="button",L.disabled=a,L.dataset.suggestionId=t.id,L.dataset.emphasis=t.emphasis,L.dataset.behavior=C,s==="chip"&&(p?.fontWeight&&(L.style.fontWeight=p.fontWeight),p?.paddingX&&(L.style.paddingLeft=p.paddingX,L.style.paddingRight=p.paddingX),p?.paddingY&&(L.style.paddingTop=p.paddingY,L.style.paddingBottom=p.paddingY)),t.icon){let K=le(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);K&&(K.classList.add("persona-suggestion__icon"),t.iconColor&&(K.style.color=t.iconColor),L.appendChild(K))}let $=S("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})),L.appendChild($),s!=="chip"){let K=Mt(iS.ArrowRight,16,"currentColor",1.8);K&&(K.classList.add("persona-suggestion__arrow"),L.appendChild(K))}return L.addEventListener("click",x),L},H=null;for(let L of d)if(L.renderSuggestion&&(H=L.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:E,select:x}),H))break;return H??(H=E()),(B=H.dataset).suggestionId||(B.suggestionId=t.id),(A=H.dataset).behavior||(A.behavior=C),(O=H.dataset).emphasis||(O.emphasis=t.emphasis),H instanceof HTMLButtonElement||H.setAttribute("aria-disabled",a?"true":"false"),H},Jl=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,e.scrollWidth-e.clientWidth);if(u<=1){s();return}let m=getComputedStyle(e).direction==="rtl",h=Math.min(u,Math.max(0,Math.abs(e.scrollLeft))),y=4,v=h<=y,C=h>=u-y,x=m?!C:!v,E=m?!v:!C;e.toggleAttribute("data-scroll-left",x),e.toggleAttribute("data-scroll-right",E)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,m,h,y,v,C)=>{e.replaceChildren(),t.length=0,n.length=0;let x=C?.source??"config",E=C?.surface??(x==="config"?"starter":"followUp"),H=E==="followUp",B=C?.variant??"chip",A=C?.behavior??"send",O=C?.overflow??"wrap",L=C?.config??{},$=C?.plugins??[],K=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,ae=H?"followUps":"starters";!sS.has(L)&&L.debug===!0&&B!=="chip"&&L.suggestions?.[ae]?.overflow!==void 0&&(sS.add(L),console.info(`[persona] suggestions.${ae}.overflow applies to the "chip" variant only; the "${B}" variant manages its own stacking.`));let oe=U=>U.map(Of).filter(pe=>pe!==null).map(pe=>({...pe,behavior:pe.behavior??A})),P=oe(u??[]);$.forEach(U=>{U.transformSuggestions&&(P=oe(U.transformSuggestions({suggestions:P.map(pe=>({...pe})),surface:E,source:x,config:L})))});let k=K===void 0?P:P.slice(0,K);if(!k.length){e.hidden=!0,o=null,s();return}if(!H&&(y??m.getMessages()).some(pe=>pe.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Wf(E),e.dataset.variant=B,e.dataset.overflow=O;let _=document.createDocumentFragment(),I=m.isStreaming();k.forEach((U,pe)=>{let ue=Bf({item:U,index:pe,surface:E,source:x,variant:B,streaming:I,config:L,plugins:$,chipsConfig:v,session:m,getTextarea:()=>h,eventTarget:e,submitPrompt:C?.submitPrompt});_.appendChild(ue),n.push(ue),[...ue instanceof HTMLButtonElement?[ue]:[],...Array.from(ue.querySelectorAll("button"))].forEach(Ie=>{t.includes(Ie)||(Ie.disabled=I,t.push(Ie))})}),e.appendChild(_),a(),l();let te=JSON.stringify({normalized:k,surface:E,variant:B,source:x});te!==o&&(o=te,I0(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:k.map(U=>({...U})),surface:E,source:x,variant:B},bubbles:!0,composed:!0})),H&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:k.map(U=>U.prompt)},bubbles:!0,composed:!0})))}}};var Yn={"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 R0="persona-header-control",H0="persona-header-control--glyph",W0="persona-header-control--sparse",O0=20,B0={x:[1.4,1.05]},aS="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",D0="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Np=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=B0[t]??[1,1.5],l=!o;e.classList.toggle(H0,l),e.classList.toggle(W0,l&&s!==1);let d=parseFloat(o??"")||O0,p=le(t,`${Math.round(d*s)}px`,"currentColor",a);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),e.replaceChildren(p)):r&&(e.textContent=r)},ci=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=aS,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:m,borderColor:h,borderRadius:y,paddingX:v,paddingY:C,hidden:x,extraClassName:E,attrs:H}=e,B=S("div",a),A=!!(m||h),O=Y("button",{className:bn(R0,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"persona-border-none",!y&&"persona-rounded-full",E),attrs:{type:"button","aria-label":t,...H},style:{width:l,height:l,minWidth:l,minHeight:l,display:x?"none":void 0,color:p||Cn.actionIconColor,backgroundColor:u,border:A?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:y,paddingLeft:v,paddingRight:v,paddingTop:C,paddingBottom:C}});return r?Np(O,r,{iconSize:d,iconText:s}):s&&(O.textContent=s),B.appendChild(O),an({anchor:O,trigger:B,text:()=>O.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:O,wrapper:B}},ba=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=aS,buttonSize:r,iconSize:s}=t,a=e?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=ci({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}},va=(e,t={})=>{let{wrapperClassName:n=D0,buttonSize:o,iconSize:r}=t,a=(e?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=ci({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-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},Df={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)"},_0={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)"},Sr=e=>{let{config:t,showClose:n=!0}=e,o=Y("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight: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??Cl,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 O=parseFloat(s)||24,L=le(d,O*.6,"currentColor",1);L?(L.style.width=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,L.style.height=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,p.replaceChildren(L)):p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let O=S("img");O.src=t.launcher.iconUrl,O.alt="",O.className="persona-rounded-xl persona-object-cover",O.style.height=s,O.style.width=s,p.replaceChildren(O)}else p.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let u=S("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Y("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Cn.titleColor,...Df}}),h=Y("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Cn.subtitleColor,..._0}});u.append(m,h),l?o.append(u):o.append(p,u);let y=r.clearChat??{},v=y.enabled??!0,C=y.placement??"inline",x=null,E=null;if(v){let L=va(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});x=L.button,E=L.wrapper,C==="top-right"&&(E.style.right="48px"),C==="inline"&&o.appendChild(E)}let H=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:B,wrapper:A}=ba(t,{showClose:n,wrapperClassName:H});return a!=="top-right"&&o.appendChild(A),{header:o,iconHolder:p,headerTitle:m,headerSubtitle:h,closeButton:B,closeButtonWrapper:A,clearChatButton:x,clearChatButtonWrapper:E}},di=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function pi(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=e,l=S("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(fa)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let v of t){if(v.dividerBefore){let E=document.createElement("hr");l.appendChild(E)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",v.id),v.destructive&&C.setAttribute("data-destructive",""),v.icon){let E=le(v.icon,16,"currentColor",1.5);E&&C.appendChild(E)}let x=document.createElement("span");x.textContent=v.label,C.appendChild(x),C.addEventListener("click",E=>{E.stopPropagation(),m(),n(v.id)}),l.appendChild(C)}let d=null;function p(){if(!s)return;let v=o.getBoundingClientRect();l.style.top=`${v.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-v.right}px`,l.style.left="auto"):(l.style.left=`${v.left}px`,l.style.right="auto")}function u(){let v=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),v&&a?.(!0),requestAnimationFrame(()=>{let C=x=>{!l.contains(x.target)&&!o.contains(x.target)&&m()};document.addEventListener("click",C,!0),d=()=>document.removeEventListener("click",C,!0)})}function m(){let v=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,v&&a?.(!1)}function h(){l.classList.contains("persona-hidden")?u():m()}function y(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:m,toggle:h,destroy:y}}function Dn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=e,p=S("button",bn(!a&&"persona-icon-btn",s));p.type="button",p.setAttribute("aria-label",n),p.title=n;let u=le(t,o??16,"currentColor",r??2);if(u&&p.appendChild(u),l&&p.addEventListener("click",l),d)for(let[m,h]of Object.entries(d))p.setAttribute(m,h);return p}function _f(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:d}=e,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let u=S("button",p);if(u.type="button",u.setAttribute("aria-label",n),t){let h=le(t,s??14,"currentColor",2);h&&u.appendChild(h)}let m=S("span");if(m.textContent=n,u.appendChild(m),l&&u.addEventListener("click",l),d)for(let[h,y]of Object.entries(d))u.setAttribute(h,y);return u}function Zl(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=S("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function d(){for(let u of l)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of t){let m;u.icon?m=Dn({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,d(),o(u.id)}}):(m=S("button","persona-icon-btn"+(u.className?" "+u.className:"")),m.type="button",m.setAttribute("aria-label",u.label),m.title=u.label,m.textContent=u.label,m.addEventListener("click",()=>{a=u.id,d(),o(u.id)})),m.setAttribute("aria-pressed",u.id===a?"true":"false"),l.push({id:u.id,btn:m}),s.appendChild(m)}function p(u){a=u,d()}return{element:s,setSelected:p}}function lS(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:d="bottom-left",portal:p,chevronLabel:u="More options",chevronIconSize:m,className:h,primaryClassName:y,chevronClassName:v}=e,C=S("div","persona-split-btn"+(h?" "+h:"")),x={label:t,className:"persona-split-btn-primary"+(y?" "+y:""),onClick:l},E=r&&n?Dn({...x,icon:n,size:o??14}):_f({...x,icon:n,iconSize:o??14}),H=Dn({icon:"chevron-down",label:u,size:m??14,className:"persona-split-btn-chevron"+(v?" "+v:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});C.append(E,H);let B=null,A=()=>{if(B)return B;let O=(typeof p=="function"?p():p)??void 0;return B=pi({items:s,onSelect:a,anchor:C,position:d,portal:O,onOpenChange:L=>{H.setAttribute("aria-expanded",L?"true":"false")}}),O||C.appendChild(B.element),B};return C.isConnected?A():requestAnimationFrame(()=>{B||A()}),H.addEventListener("click",O=>{O.stopPropagation(),A().toggle()}),{element:C,primaryButton:E,chevronButton:H,openMenu:()=>A().show(),closeMenu:()=>B?.hide(),toggleMenu:()=>A().toggle(),destroy:()=>{B?.destroy(),C.remove()}}}function Fp(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:d}=e,p=S("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",t);let u=S("span","persona-combo-btn-label");u.textContent=t,p.appendChild(u);let m=le(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",p.appendChild(m)),d&&(p.style.borderRadius=d.borderRadius??"10px",p.style.padding=d.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=d.background??"",p.style.borderColor=d.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let h=pi({items:o,onSelect:v=>{p.setAttribute("aria-expanded","false"),r(v)},anchor:p,position:s,portal:a});a||p.appendChild(h.element);let y=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",v=>{if(v.stopPropagation(),y())return;let C=!h.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",C?"false":"true"),h.toggle()}),p.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),p.click())}),{element:p,setLabel:v=>{u.textContent=v,p.setAttribute("aria-label",v)},open:()=>{p.setAttribute("aria-expanded","true"),h.show()},close:()=>{p.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let v=!h.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",v?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),p.remove()}}}var Nf=e=>{let t=Sr({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 N0(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=ci({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Wp(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=Ul(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=pi({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 Ff=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=S("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=Cn.minHeight,l.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r?.titleMenu,p,u;if(d){let A=Fp({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:O=>{let L=K=>{K===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:O}}))},$=d.onSelect(O);$ instanceof Promise?$.then(L,()=>{}):L($)},hover:d.hover,className:""});p=A.element,p.style.color=Cn.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=S("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=S("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Cn.titleColor,Object.assign(u.style,Df),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let O=r.onTitleClick;p.addEventListener("click",L=>{L.target.closest("button")||O()}),p.addEventListener("keydown",L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),O())})}let A=r?.titleRowHover;A&&(p.style.borderRadius=A.borderRadius??"10px",p.style.padding=A.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=A.background??"",p.style.borderColor=A.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:y}=ba(t,{showClose:n,wrapperClassName:m});o&&h.addEventListener("click",o);let v=S("div","persona-flex persona-items-center persona-gap-1");d||N0(v,r?.trailingActions,r?.onAction??s);let C=a.clearChat??{},x=null,E=null;if(C.enabled??!0){let A=C.placement??"inline",O=va(t,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});x=O.button,E=O.wrapper,A==="top-right"?E.style.right="48px":v.appendChild(E)}v.appendChild(y),l.appendChild(v);let H=S("div");H.style.display="none";let B=S("span");return B.style.display="none",{header:l,iconHolder:H,headerTitle:u,headerSubtitle:B,closeButton:h,closeButtonWrapper:y,clearChatButton:x,clearChatButtonWrapper:E}},$p={default:Nf,minimal:Ff},$f=e=>$p[e]??$p.default,Ca=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=S("div");l.style.display="none";let d=S("span"),p=S("span"),u=S("button");u.style.display="none";let m=S("div");return m.style.display="none",{header:a,iconHolder:l,headerTitle:d,headerSubtitle:p,closeButton:u,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=$f(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 ui=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=bp(),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":""}}),{textarea:s,attachAutoResize:a}=mp(t);a();let l=fp(t),d=ha(t),p=hp(t),u=yp(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 h=Y("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=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&&y.append(p.wrapper),d&&v.append(d.wrapper),v.append(l.wrapper),h.append(y,v),r.append(h),r.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==d?.button&&C.target!==d?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),t?.statusIndicator?.mode==="transient"?n.append(o,u,r):n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,header:m,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:u,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:h,leftActions:y,rightActions:v,setSendButtonMode:l.setMode}};var Up=require("lucide");var cS=()=>{let e=Y("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=S("span","persona-pill-peek__icon"),n=Mt(Up.MessageSquare,16,"currentColor",1.5);n&&t.appendChild(n);let o=S("span","persona-pill-peek__text"),r=S("span","persona-pill-peek__caret"),s=Mt(Up.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},jp=e=>{let{config:t}=e,n=Y("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=bp(),r=yp(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=mp(t,{defaultMaxLines:5});a();let l=fp(t),d=ha(t),p=hp(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":""}}),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 h=Y("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&h.append(d.wrapper),h.append(l.wrapper),u.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==d?.button&&C.target!==d?.wrapper&&C.target!==p?.button&&C.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(m,s,h);let y=Y("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(y),p&&y.append(p.previewsContainer),n.append(o,u,r);let v=u;return{footer:n,suggestions:o,composerForm:u,header:y,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:v,leftActions:m,rightActions:h,setSendButtonMode:l.setMode}};var F0=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}},$0=(e,t)=>{if(!e)return null;let n=F0(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},U0=(e,t)=>{let n=S("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},j0=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},jf=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(":"))},Vf=320,mS=320,V0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),q0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),z0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),K0=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),G0=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=S("span","persona-mention-chip-icon"),s=le(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},Y0=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Bl(o.ref,{readonly:!0,render:t}))}return n},dS="\uE000",pS="\uE001",Q0=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=h=>`${dS}${r}:${h}${pS}`,a=t.map((h,y)=>h.kind==="text"?h.text:s(y)).join(""),l=n(a);if(!t.every((h,y)=>h.kind==="text"||l.includes(s(y)))){e.replaceChildren(Y0(t,o));return}e.innerHTML=l;let p=new RegExp(`${dS}${r}:(\\d+)${pS}`),u=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let h=u.nextNode();h;h=u.nextNode())m.push(h);for(let h of m){let y=h;for(let v=p.exec(y.data);v;v=p.exec(y.data)){let C=t[Number(v[1])],x=y.splitText(v.index);x.data=x.data.slice(v[0].length),C?.kind==="mention"&&x.parentNode?.insertBefore(Bl(C.ref,{readonly:!0,render:o}),x),y=x}}},X0=(e,t,n)=>{if(e.length===0)return null;try{let o=S("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,d)=>{let p=S("img");p.alt=l.alt?.trim()||`Attached image ${d+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${Vf}px`,p.style.maxHeight=`${mS}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,p.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),p.remove(),r===0&&a())}),p.addEventListener("load",()=>{u=!0}),j0(l.image)?(p.src=l.image,o.appendChild(p)):(u=!0,r=Math.max(0,r-1),p.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},J0=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!jf(o.audio))return;let r=S("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Vf}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Z0=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!jf(o.video))return;let r=S("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Vf}px`,r.style.maxHeight=`${mS}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}},eL=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!jf(o.data))return;let r=S("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},gi=()=>{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},qf=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:gi};if(t){let r=t(o);if(r!==null)return r}return gi()},tL=(e,t)=>{let n=S("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=S("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},uS=(e,t,n="div")=>{let o=S(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},ec=(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},gS={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"}},nL=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=gS[n??"bubble"]??gS.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)`)},Vp="custom:",oL=e=>`${Vp}${e}`,fS=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),zf=(e,t,n,o)=>{let r=t.showCopy??!0,s=t.showUpvote??!1,a=t.showDownvote??!1,l=t.showReadAloud??!1,d=(t.showRegenerate??!1)&&o?.canRegenerate===!0,p=(t.showEdit??!1)&&o?.canEdit===!0,u=(t.showQuote??!1)&&o?.canQuote!==!1,m=fS(t,e.role);if(!r&&!s&&!a&&!l&&!d&&!p&&!u&&m.length===0){let B=S("div");return B.style.display="none",B.id=`actions-${e.id}`,B.setAttribute("data-actions-for",e.id),B}let h=t.visibility??"hover",y=t.align??"right",v=t.layout??"pill-inside",C={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[y],x={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[v],E=S("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${C} ${x} ${h==="hover"?"persona-message-actions-hover":""}`);E.id=`actions-${e.id}`,E.setAttribute("data-actions-for",e.id);let H=(B,A,O)=>{let L=Dn({icon:B,label:A,size:14,className:"persona-message-action-btn",chromeless:!0});return L.setAttribute("data-action",O),L};r&&E.appendChild(H("copy","Copy message","copy")),l&&E.appendChild(H("volume-2","Read aloud","read-aloud")),s&&E.appendChild(H("thumbs-up","Upvote","upvote")),a&&E.appendChild(H("thumbs-down","Downvote","downvote")),d&&E.appendChild(H("refresh-cw","Regenerate response","regenerate")),p&&E.appendChild(H("pencil","Edit message","edit")),u&&E.appendChild(H("quote","Quote message","quote"));for(let B of m)E.appendChild(H(B.iconName??"ellipsis",B.label,oL(B.id)));return E},wa=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",d=a.avatar,p=a.timestamp,u=d?.show??!1,m=p?.show??!1,h=d?.position??"left",y=p?.position??"below",v=ec(e.role,l),C=S("div",v.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let x=Sf(s?.widgetConfig?.future).components.message,E=s?.widgetConfig?.theme?.components?.message;nL(C,e.role,l,e.role==="user"?{...x.user,...E?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...x.assistant,...E?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let H=V0(e),B=e.content?.trim()??"",O=H.length>0&&B===da,L=Bp(s?.widgetConfig?.features?.streamAnimation),$=s?.widgetConfig?.features?.streamAnimation?.plugins,K=e.role==="assistant"&&L.type!=="none"?zl(L.type,$):null,ae=e.role==="assistant"&&K?.isAnimating?.(e)===!0,oe=e.role==="assistant"&&K!==null&&(!!e.streaming||ae);oe&&K?.bubbleClass&&C.classList.add(K.bubbleClass);let P=document.createElement("div");P.classList.add("persona-message-content"),e.streaming&&P.classList.add("persona-content-streaming"),oe&&K&&(K.containerClass&&P.classList.add(K.containerClass),P.style.setProperty("--persona-stream-step",`${L.speed}ms`),P.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let k=oe?Dp(e.content??"",L.buffer,K,e,!!e.streaming):e.content??"",_=()=>{let Ce=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent});return oe&&K?.wrap==="char"?Kl(Ce,"char",e.id,{skipTags:K.skipTags}):oe&&K?.wrap==="word"?Kl(Ce,"word",e.id,{skipTags:K.skipTags}):Ce},I=null;if(O?(I=document.createElement("div"),I.innerHTML=_(),I.style.display="none",P.appendChild(I)):e.contentSegments?.length?Q0(P,e.contentSegments,Ce=>t({text:Ce,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):P.innerHTML=_(),oe&&K?.useCaret&&!O&&B){let Ce=_p(),D=P.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ne=D[D.length-1];if(Ne?.parentNode)Ne.parentNode.insertBefore(Ce,Ne.nextSibling);else{let Fe=P.lastElementChild;Fe?Fe.appendChild(Ce):P.appendChild(Ce)}}if(m&&y==="inline"&&e.createdAt){let Ce=uS(e,p,"span");Ce.classList.add("persona-timestamp-inline");let D=P.lastElementChild;D?D.appendChild(Ce):P.appendChild(Ce)}if(H.length>0){let Ce=X0(H,!O&&!!B,()=>{O&&I&&(I.style.display="")});Ce?C.appendChild(Ce):O&&I&&(I.style.display="")}let te=q0(e);if(te.length>0){let Ce=J0(te);Ce&&C.appendChild(Ce)}let U=z0(e);if(U.length>0){let Ce=Z0(U);Ce&&C.appendChild(Ce)}let pe=K0(e);if(pe.length>0){let Ce=eL(pe);Ce&&C.appendChild(Ce)}let ue=e.contentSegments?.length?null:G0(e.contextMentions);if(ue&&C.appendChild(ue),C.appendChild(P),m&&y==="below"&&e.createdAt){let Ce=uS(e,p);Ce.classList.add("persona-mt-1"),C.appendChild(Ce)}let ge=e.role==="assistant"?$0(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Ce=!!(k&&k.trim()),D=L.placeholder==="skeleton",Ne=D&&L.buffer==="line"&&Ce;if(Ce)Ne&&C.appendChild(Gl());else if(D)C.appendChild(Gl());else{let Fe=qf("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);Fe&&C.appendChild(Fe)}}ge&&e.stopReason&&!e.streaming&&(B||(P.style.display="none"),C.appendChild(U0(e.stopReason,ge)));let Ie=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1,Se=s?.actionEligibility,ye=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Se?.canEdit===!0||o?.showQuote===!0&&Se?.canQuote===!0||fS(o,"user").length>0);if((Ie||ye)&&o){let Ce=zf(e,ye?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Se);C.appendChild(Ce)}if(!u||e.role==="system")return C;let dt=S("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),it=tL(d,e.role);return h==="right"||h==="left"&&e.role==="user"?dt.append(C,it):dt.append(it,C),dt},hS=(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}):wa(e,t,n,o,r,s)};var rL=40,sL=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=le(t.name,rL);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},yS=(e,t,n={})=>{let o=Y("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=S("p","persona-welcome-kicker");r.hidden=!0;let s=S("h2","persona-welcome-title"),a=S("p","persona-welcome-subtitle"),l=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}},xa=(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)},zp=(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==="",sL(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-layout",t.layout??"top"),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},iL="data-persona-welcome-plugin",bS="data-persona-welcome-overlay",qp="persona-welcome-overlay-active",Kf=new WeakMap,Gf=(e,t,n)=>{n.setAttribute(iL,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(bS,""),e.classList.contains(qp)||(Kf.set(e,e.scrollTop),e.classList.add(qp),e.scrollTop=0)},Yf=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(bS),e.classList.contains(qp)&&(e.classList.remove(qp),e.scrollTop=Kf.get(e)??e.scrollTop,Kf.delete(e))},vS=()=>{let e=Y("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Kp=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Y("div",{className:ec("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},CS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,wS=(e,t)=>{if(CS()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,a=0;if(o){let v=getComputedStyle(o);r=parseFloat(v.rowGap)||0;let C=e.previousElementSibling,x=e.nextElementSibling,H=o.getBoundingClientRect().top+(parseFloat(v.borderTopWidth)||0)+(parseFloat(v.paddingTop)||0)-o.scrollTop;s=Math.max(0,C?n.top-C.getBoundingClientRect().bottom-r:n.top-H),a=Math.max(0,x?x.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let d=getComputedStyle(e),p=parseFloat(d.paddingTop)||0,u=parseFloat(d.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${u}px`,marginTop:`${s}px`,marginBottom:`${a}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),h=!1,y=()=>{h||(h=!0,e.style.overflow=l,t(m))};return m.finished.then(y).catch(y),m},xS=(e,t,n,o=260)=>{if(t<=1||CS()||typeof e.animate!="function"||!e.isConnected)return null;let r=n==="drop"?-t:t;return e.animate([{transform:`translateY(${r}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var aL="Hello \u{1F44B}",lL="I can answer questions and help you get things done here.",SS=new WeakSet,wn=(e,t)=>!!e&&e[t]!==void 0,cL=(e,t)=>{!e||e.debug!==!0||!t.length||SS.has(e)||(SS.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Sa=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!=="docked")=>{let n=e?.welcome,o=e?.copy,r=e?.future?.v5Defaults===!0,s=n?.layout??(r?"centered":"top"),a=wn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=a==="hero"&&!r&&n?.layout===void 0?"on-first-message":wn(n,"dismiss")?n.dismiss:r||a==="hero"?"on-first-message":"never",d=[];wn(n,"title")&&wn(o,"welcomeTitle")&&d.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),wn(n,"subtitle")&&wn(o,"welcomeSubtitle")&&d.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),wn(n,"variant")&&wn(o,"showWelcomeCard")&&d.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),a==="hero"&&wn(n,"message")&&d.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&a==="hero"&&wn(n,"dismiss")&&n.dismiss!=="on-first-message"&&d.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let p=n?.anchor??(s==="centered"&&t?"center":"bottom"),u=$l(n?.anchorComposerTop)!==null;return wn(n,"anchorComposerTop")&&!u&&d.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),p!=="center"&&(wn(n,"anchorComposerTop")||wn(n,"composerGap"))&&d.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),cL(e,d),{title:wn(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":aL),kicker:n?.kicker??"",subtitle:wn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":lL),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:s==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:a,dismiss:l,message:a==="hero"?void 0:n?.message,layout:s,anchor:p,anchorComposerTop:u?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||Ip}},AS=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",gs=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var dL="var(--persona-components-panel-maxWidth)",MS="var(--persona-components-panel-height)",pL="var(--persona-components-panel-maxHeight)",mi=e=>{let t=fr(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${MS})`:`max(200px, calc(${MS} - ${o}px))`;return{width:n??Qv,maxWidth:n??dL,height:r,maxHeight:pL}},ES="16px",Xf="10px",Jf="14px",TS=e=>{let t=e?.launcher?.enabled??!0,n=Ct(e);if(us(e)){let p=e?.launcher?.composerBar??{},u=S("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=p.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??pn);let m=S("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");m.style.width="100%",u.appendChild(m);let h=S("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=p.expandedSize??"anchored",h.style.zIndex=String(e?.launcher?.zIndex??pn),{wrapper:u,panel:m,pillRoot:h}}if(n){let p=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(u),{wrapper:p,panel:u}}if(!t){let p=S("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=S("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),m=fr(e),y=m.launcherWidth||m.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?mi(e).width:"100%";return p.style.width=y,u.style.width="100%",p.appendChild(u),{wrapper:p,panel:u}}let r=e?.launcher??{},s=r.position&&Yn[r.position]?Yn[r.position]:Yn["bottom-right"],a=S("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??pn);let l=S("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=mi(e);return l.style.width=d.width,l.style.maxWidth=d.maxWidth,a.appendChild(l),{wrapper:a,panel:l}},Zf=e=>{let t=Y("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Wf(e)}});return t.hidden=!0,t},PS=(e,t)=>{let n=Zf("starter"),o=yS(e,n,{flatShadow:Ct(e)}),r=Sa(e);zp(o,r),xa(t,o.host,gs(r,e?.initialMessages));let s=vS();return Kp(s,r.message,e),{welcome:o,greetingHost:s}},uL=(e,t)=>{let n=S("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=ba(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:ES,iconSize:Xf});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 $=va(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:ES,iconSize:Jf});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}=PS(e,p),{host:h,title:y,subtitle:v}=u,C=u.starterSuggestions,x=S("div","persona-widget-messages persona-flex persona-flex-col");x.style.gap="var(--persona-components-message-gap, 12px)";let E=Zf("followUp"),H=ds(e,!0);H&&(x.style.maxWidth=H,x.style.marginLeft="auto",x.style.marginRight="auto",x.style.width="100%"),p.append(h,m,x,E);let B=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"}}),A=jp({config:e}),{root:O,textNode:L}=cS();return n.append(d,r,p,B),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:x,starterSuggestions:C,transcriptSuggestions:E,composerOverlay:B,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:h,welcomeIconHolder:u.iconHolder,greetingHost:m,introKicker:u.kicker,introTitle:y,introSubtitle:v,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:S("span"),headerTitle:S("span"),headerSubtitle:S("span"),header:d,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:O,peekTextNode:L}},kS=(e,t=!0)=>{if(us(e))return uL(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?Ca(e,o,{showClose:t}):Sr({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}=PS(e,a),{host:p,title:u,subtitle:m}=l,h=l.starterSuggestions,y=S("div","persona-widget-messages persona-flex persona-flex-col");y.style.gap="var(--persona-components-message-gap, 12px)";let v=Zf("followUp"),C=ds(e,!1);C&&(y.style.maxWidth=C,y.style.marginLeft="auto",y.style.marginRight="auto",y.style.width="100%"),a.append(p,d,y,v);let x=ui({config:e}),E=e?.layout?.showFooter!==!1;r?di(n,s,e):(s.header.style.display="none",di(n,s,e)),n.append(a);let H=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 E||(x.footer.style.display="none"),n.append(x.footer),n.append(H),{container:n,body:a,messagesWrapper:y,starterSuggestions:h,transcriptSuggestions:v,composerOverlay:H,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:d,introKicker:l.kicker,introTitle:u,introSubtitle:m,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions,setSendButtonMode:x.setSendButtonMode}};var eh=(e,t)=>{let n=S("button");n.type="button",n.innerHTML=`
|
|
27
|
+
`)[0]).startsWith(O.trigger):!1),s=(A,O)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:O}))}catch{}},a=!e.chipRow,l=e.chipRow??Y("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),d=null,u=null,p=e.textarea,m=null,h=null,y=null,v=null,C=()=>{if(d)return Promise.resolve(d);if(u)return u;let A=Sf().then(O=>(O.setMentionIconRenderer(le),d=O.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:m??void 0,anchor:e.anchor,contextRow:l,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:B,emit:s}),d)).catch(O=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",O),u===A&&(u=null),null));return u=A,A},x=()=>{Ix().then(A=>{let O=A.mountInlineComposer({textarea:e.textarea,renderToken:$=>Bl($,{render:t.renderMentionToken}),onMentionRemoved:$=>d?.untrackMention($)});m=O.input,h=O.destroy;let L=p;L.replaceWith(O.element),p=O.element,v={next:O.element,prev:L},y?.(O.element,L),d?d.rebindComposer(O.input):u&&u.then($=>$?.rebindComposer(O.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};t.display==="inline"&&x();let E=[],H=new Map;for(let A of n){if(!A.showButton)continue;let O=Lx({config:{...t,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},onOpen:()=>{C().then(L=>L?.openMenu(A.trigger))}});E.push(O),H.set(A.trigger,O.button)}let B=(A,O,L)=>{let $=H.get(O);$&&($.setAttribute("aria-expanded",A?"true":"false"),A?$.setAttribute("aria-controls",L):$.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(A=>A.wrapper),contextRow:l,handleInput:A=>{if(d){d.handleInput();return}if(!Px(A))return;let O=p,L=O.selectionStart??0;Tx(O.value,L,n)&&C().then($=>$?.handleInput())},handleKeydown:A=>{if(d?.isMenuOpen())return d.handleKeydown(A);if(A.key==="Backspace"&&d?.hasMentions()&&!v){let O=p,L=O.selectionStart===0&&O.selectionEnd===0;if((O.value.length===0||L)&&d.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>d?.isMenuOpen()??!1,hasMentions:()=>d?.hasMentions()??!1,getMentionRefs:()=>d?.getMentionRefs()??[],collectForSubmit:()=>d?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(d??await C())?.dispatchInlineCommand(A)??null:null,clear:()=>d?.clear(),prefetch:()=>{Sf().catch(()=>{})},onComposerSwap:A=>{y=A,v&&A(v.next,v.prev)},destroy:()=>{d?.destroy(),h?.();for(let A of E)A.wrapper.remove();a&&l.remove()}}}var Sp=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),Ap={background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",border:"transparent",size:"48px",iconSize:"24px",borderRadius:"palette.radius.full",shadow:"0 8px 24px rgba(0,0,0,.16)",offset:"20px"};var Ep="16px",Tp="transparent",a0=(()=>{let e={};for(let t of[0,1,2,3,4,5,6,8,10,12,16,20,24,32,40,48,56,64])e[t]=t===0?"0px":`${t/4}rem`;return e})(),Dl={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},purple:{50:"#faf5ff",100:"#f3e8ff",200:"#e9d5ff",300:"#d8b4fe",400:"#c084fc",500:"#a855f7",600:"#9333ea",700:"#7e22ce",800:"#6b21a8",900:"#581c87",950:"#3b0764"},teal:{50:"#f0fdfa",100:"#ccfbf1",200:"#99f6e4",300:"#5eead4",400:"#2dd4bf",500:"#14b8a6",600:"#0d9488",700:"#0f766e",800:"#115e59",900:"#134e4a",950:"#042f2e"}},spacing:a0,typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Mp={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"}},Gn={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:Js,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ep,canvasBackground:Tp,modes:{floating:{border:"1px solid var(--persona-border)",shadow:"palette.shadows.xl",borderRadius:"palette.radius.xl"},inline:{border:"1px solid var(--persona-border)",shadow:"none",borderRadius:"palette.radius.xl"},docked:{border:"none",shadow:"none",borderRadius:"palette.radius.xl"},sidebar:{border:"none",borderRadius:"0"},mobile:{border:"none",shadow:"none",borderRadius:"0"}}},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"20px 24px",minimalPadding:"16px 24px",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{gap:"12px",user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},eventStream:{badge:{flow:{background:"palette.colors.success.100",foreground:"palette.colors.success.700"},step:{background:"palette.colors.primary.100",foreground:"palette.colors.primary.700"},reasoning:{background:"palette.colors.warning.100",foreground:"palette.colors.warning.700"},tool:{background:"palette.colors.purple.100",foreground:"palette.colors.purple.800"},agent:{background:"palette.colors.teal.100",foreground:"palette.colors.teal.800"},error:{background:"palette.colors.error.100",foreground:"palette.colors.error.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.600"}}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}},l0=Dl.colors.gray,c0={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},Wx={...Dl,colors:{...Dl.colors,gray:l0}},d0={...Dl,colors:{...Dl.colors,gray:c0},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}},Ox=Wx,Bx=Mp,p0={...Mp,colors:{...Mp.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...Mp.typography,fontSize:"14px",lineHeight:"1.5"}},Dx=Bx,Pp=Gn,u0={...Gn,launcher:Ap,activity:{rowHeight:"32px",labelSize:"13px",iconSize:"16px",indent:"0px",groupIndent:"0px",groupGap:"0px",groupPadding:"0px",transcriptGap:"0px",responseGap:"12px",bodyPadding:"4px 0",bodySize:"13px",bodyLineHeight:"1.5",bodyFontWeight:"400",sectionGap:"8px",bodySurface:"transparent"},toolBubble:{shadow:"none"},reasoningBubble:{shadow:"none"},input:{...Gn.input,borderRadius:"palette.radius.full"},introCard:{...Gn.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...Gn.suggestion.chip,fontWeight:"400"},card:{...Gn.suggestion.card,fontWeight:"400"},list:{...Gn.suggestion.list,fontWeight:"400"}},panel:{...Gn.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...Gn.header,background:"semantic.colors.container",foreground:"semantic.colors.text",padding:"8px 8px 8px 16px",minimalPadding:"8px 8px 8px 16px",minHeight:"48px",borderBottom:"none",iconBackground:"transparent",iconForeground:"semantic.colors.text",iconScale:"1",controlSize:"28px",controlIconSize:"18px",controlStrokeWidth:"1.5",actionIconForeground:"semantic.colors.textMuted",controlBorderRadius:"8px",controlHoverBackground:"color-mix(in srgb, var(--persona-text) 8%, transparent)",controlHoverForeground:"semantic.colors.text",controlFocusOutline:"2px solid color-mix(in srgb, var(--persona-text) 50%, transparent)",title:{fontSize:"14px",fontWeight:"500",lineHeight:"1.5"}},message:{...Gn.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...Gn.message.user,background:"palette.colors.gray.100",text:"semantic.colors.text",borderRadius:"palette.radius.xl",shadow:"none",padding:"8px 14px",fontSize:"14px",lineHeight:"1.5"},assistant:{...Gn.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...Gn.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}},_x=Pp,g0=e=>Jr({future:e}),Mf=e=>g0(e)==="v5"?{palette:d0,semantic:p0,components:u0}:{palette:Wx,semantic:Bx,components:Pp};function cn(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."))?cn(e,o):o}function kp(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=cn(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 Ef(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 Nx(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]=Nx(s,r):n[o]=r}return n}function m0(e,t){return t?Nx(e,t):e}function _l(e,t={}){let n=Mf(t.future),o={palette:n.palette,semantic:n.semantic,components:n.components},r={palette:{...o.palette,...e?.palette,colors:{...o.palette.colors,...e?.palette?.colors},spacing:{...o.palette.spacing,...e?.palette?.spacing},typography:{...o.palette.typography,...e?.palette?.typography},shadows:{...o.palette.shadows,...e?.palette?.shadows},borders:{...o.palette.borders,...e?.palette?.borders},radius:{...o.palette.radius,...e?.palette?.radius}},semantic:{...o.semantic,...e?.semantic,colors:{...o.semantic.colors,...e?.semantic?.colors,interactive:{...o.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...o.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...o.semantic.spacing,...e?.semantic?.spacing},typography:{...o.semantic.typography,...e?.semantic?.typography}},components:m0(o.components,e?.components)},s=e?.components?.activity;for(let u of["toolBubble","reasoningBubble"])for(let p of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[p]!==void 0&&(r.components[u][p]=s[p]);let a=e?.components?.collapsibleWidget?.surface;a!==void 0&&s?.bodySurface===void 0&&(r.components.activity={...r.components.activity,bodySurface:a});let l=e?.components?.header;l?.padding!==void 0&&l.minimalPadding===void 0&&(r.components.header.minimalPadding=r.components.header.padding);let d=e?.components?.message;if(d?.gap!==void 0&&d.fullscreenGap===void 0&&(r.components.message.fullscreenGap=r.components.message.gap),t.validate!==!1){let u=Ef(r);if(!u.valid)throw new Error(`Theme validation failed: ${u.errors.map(p=>p.message).join(", ")}`)}if(t.plugins)for(let u of t.plugins)r=u.transform(r);return r}var Af=e=>e.trim()==="0"?"0px":e,Hx="--persona-",f0=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 u=d.endsWith("%"),p=parseFloat(u?d.slice(0,-1):d);return u?p/100*255:p}))}}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},h0=.179,ln=(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[Hx+s],r!==void 0)break;r!==void 0&&(e[Hx+n]=r)}};function Lp(e){let t=kp(e),n={};for(let[D,Ne]of Object.entries(t)){let Fe=D.replace(/\./g,"-");n[`--persona-${Fe}`]=Ne.value}ln(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"],ln(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"]]),ln(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"]}`,ln(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"]??Ep,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Tp,ln(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"]]),ln(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"],ln(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"],ln(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 u=n["--persona-components-history-railHeader-border"];u&&(n["--persona-history-rail-header-border"]=u);let p=n["--persona-components-history-railHeader-minHeight"];p&&(n["--persona-history-rail-header-min-height"]=p);for(let[D,Ne]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let Fe=n[`--persona-components-history-overlay-${D}`];Fe&&(n[`--persona-history-overlay-${Ne}`]=Fe)}for(let[D,Ne]of[["background","bg"],["borderRadius","radius"]]){let Fe=n[`--persona-components-history-menu-${D}`];Fe&&(n[`--persona-history-menu-${Ne}`]=Fe)}let m=e.components?.history?.motion;if(m){let D=Et=>{if(Et===void 0)return;let Gt=String(Et).trim();return/^\d+(\.\d+)?$/.test(Gt)?`${Gt}ms`:Gt},Ne=D(m.enterDurationMs);Ne!==void 0&&(n["--persona-history-enter-ms"]=Ne);let Fe=D(m.exitDurationMs);Fe!==void 0&&(n["--persona-history-exit-ms"]=Fe),m.enterEasing&&(n["--persona-history-enter-easing"]=m.enterEasing),m.exitEasing&&(n["--persona-history-exit-easing"]=m.exitEasing)}let h=n["--persona-components-history-dangerForeground"];h&&(n["--persona-history-danger-fg"]=h),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let D of["scrim","shadow"]){let Ne=n[`--persona-components-history-confirm-${D}`];Ne&&(n[`--persona-history-confirm-${D}`]=Ne)}for(let[D,Ne]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let Fe=n[`--persona-components-tooltip-${D}`];Fe&&(n[`--persona-tooltip-${Ne}`]=Fe)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[D,Ne]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let Fe=n[`--persona-components-messageActions-${D}`];Fe&&(n[`--persona-message-action-${Ne}`]=Fe)}ln(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let y=n["--persona-components-introCard-background"],v=n["--persona-components-introCard-shadow"],C=(!y||y==="transparent"||y==="none")&&(!v||v==="none"),x=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=C&&x==="1.5rem"?"1.5rem 0":x,ln(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"]]),ln(n,[["composer-padding","components-composer-padding","=0.75rem 1rem"],["composer-gap","components-composer-gap","=0.5rem"],["composer-font-size","components-composer-fontSize","=0.875rem"],["composer-line-height","components-composer-lineHeight","=1.25rem"],["composer-control-size","components-composer-controlSize","=40px"],["composer-control-icon-size","components-composer-controlIconSize","=24px"],["motion-duration-fast","components-motion-durationFast","=120ms"],["motion-duration-base","components-motion-durationBase","=200ms"],["motion-easing","components-motion-easing","=cubic-bezier(0.2, 0, 0, 1)"],["composer-border-color","components-composer-borderColor","border","=#e5e7eb"],["composer-overlay-band","components-composer-overlayBand","=transparent"],["scrollbar-thumb","components-scrollbar-thumb","border","=#e5e7eb"],["scrollbar-track","components-scrollbar-track","=transparent"],["md-inline-code-bg","components-markdown-inlineCode-background","container"],["md-inline-code-color","components-markdown-inlineCode-foreground","text"],["md-link-color","components-markdown-link-foreground","accent","=#0f0f0f"]]);let E=n["--persona-components-markdown-heading-h1-fontSize"];E&&(n["--persona-md-h1-size"]=E);let H=n["--persona-components-markdown-heading-h1-fontWeight"];H&&(n["--persona-md-h1-weight"]=H);let B=n["--persona-components-markdown-heading-h2-fontSize"];B&&(n["--persona-md-h2-size"]=B);let A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let O=n["--persona-components-markdown-prose-fontFamily"];O&&O!=="inherit"&&(n["--persona-md-prose-font-family"]=O),ln(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"]]),ln(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),ln(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),ln(n,[["md-hr-color","components-markdown-hr-color","divider"]]),ln(n,[["md-blockquote-border-color","components-markdown-blockquote-borderColor","palette-colors-gray-900"],["md-blockquote-bg","components-markdown-blockquote-background","=transparent"],["md-blockquote-text-color","components-markdown-blockquote-textColor","palette-colors-gray-500"]]);let L=[["container","surface"],["surface","surface"],["border","border"]];for(let[D,Ne]of L){let Fe=n[`--persona-components-collapsibleWidget-${D}`]??n[`--persona-${Ne}`];Fe!==void 0&&(n[`--persona-cw-${D}`]=Fe,n[`--cw-${D}`]=Fe)}ln(n,[["message-border","components-message-border","border"]]),ln(n,[["message-user-padding","components-message-user-padding"],["message-user-max-width","components-message-user-maxWidth"],["message-user-font-size","components-message-user-fontSize"],["message-user-font-family","components-message-user-fontFamily"],["message-user-line-height","components-message-user-lineHeight"],["message-assistant-padding","components-message-assistant-padding"],["message-assistant-border-width","components-message-assistant-borderWidth"],["message-assistant-max-width","components-message-assistant-maxWidth"],["message-assistant-font-size","components-message-assistant-fontSize"],["message-assistant-font-family","components-message-assistant-fontFamily"],["message-assistant-line-height","components-message-assistant-lineHeight"]]);let $=e.components,K=$?.iconButton;K&&(K.background&&(n["--persona-icon-btn-bg"]=K.background),K.border&&(n["--persona-icon-btn-border"]=K.border),K.color&&(n["--persona-icon-btn-color"]=K.color),K.padding&&(n["--persona-icon-btn-padding"]=K.padding),K.borderRadius&&(n["--persona-icon-btn-radius"]=K.borderRadius),K.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=K.hoverBackground),K.hoverColor&&(n["--persona-icon-btn-hover-color"]=K.hoverColor),K.activeBackground&&(n["--persona-icon-btn-active-bg"]=K.activeBackground),K.activeBorder&&(n["--persona-icon-btn-active-border"]=K.activeBorder));let ae=$?.labelButton;ae&&(ae.background&&(n["--persona-label-btn-bg"]=ae.background),ae.border&&(n["--persona-label-btn-border"]=ae.border),ae.color&&(n["--persona-label-btn-color"]=ae.color),ae.padding&&(n["--persona-label-btn-padding"]=ae.padding),ae.borderRadius&&(n["--persona-label-btn-radius"]=ae.borderRadius),ae.hoverBackground&&(n["--persona-label-btn-hover-bg"]=ae.hoverBackground),ae.fontSize&&(n["--persona-label-btn-font-size"]=ae.fontSize),ae.gap&&(n["--persona-label-btn-gap"]=ae.gap));let oe=$?.toggleGroup;oe&&(oe.gap&&(n["--persona-toggle-group-gap"]=oe.gap),oe.borderRadius&&(n["--persona-toggle-group-radius"]=oe.borderRadius));let P=$?.artifact;if(P?.toolbar){let D=P.toolbar;D.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=D.iconHoverColor),D.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=D.iconHoverBackground),D.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=D.iconPadding),D.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=D.iconBorderRadius),D.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=D.iconBorder),D.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Af(D.toggleGroupGap)),D.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=D.toggleBorderRadius),D.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Af(D.toggleGroupPadding)),D.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=D.toggleGroupBorder),D.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=D.toggleGroupBorderRadius),D.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=cn(e,D.toggleGroupBackground)??D.toggleGroupBackground),D.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=D.copyBackground),D.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=D.copyBorder),D.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=D.copyColor),D.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Af(D.copyBorderRadius)),D.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=D.copyPadding),D.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=D.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??D.copyMenuBackground),D.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=D.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??D.copyMenuBorder),D.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=D.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??D.copyMenuShadow),D.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=D.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??D.copyMenuBorderRadius),D.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=D.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??D.copyMenuItemHoverBackground),D.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=D.iconBackground),D.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=D.toolbarBorder)}if(P?.tab){let D=P.tab;D.background&&(n["--persona-artifact-tab-bg"]=D.background),D.activeBackground&&(n["--persona-artifact-tab-active-bg"]=D.activeBackground),D.activeBorder&&(n["--persona-artifact-tab-active-border"]=D.activeBorder),D.borderRadius&&(n["--persona-artifact-tab-radius"]=D.borderRadius),D.textColor&&(n["--persona-artifact-tab-color"]=D.textColor),D.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=D.hoverBackground),D.listBackground&&(n["--persona-artifact-tab-list-bg"]=D.listBackground),D.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=D.listBorderColor),D.listPadding&&(n["--persona-artifact-tab-list-padding"]=D.listPadding)}if(P?.pane){let D=P.pane;if(D.toolbarBackground){let Ne=cn(e,D.toolbarBackground)??D.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Ne}}if(P?.card){let D=P.card;D.background&&(n["--persona-artifact-card-bg"]=D.background),D.border&&(n["--persona-artifact-card-border"]=D.border),D.borderRadius&&(n["--persona-artifact-card-radius"]=D.borderRadius),D.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=D.hoverBackground),D.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=D.hoverBorderColor)}if(P?.inline){let D=P.inline;D.background&&(n["--persona-artifact-inline-bg"]=cn(e,D.background)??D.background),D.border&&(n["--persona-artifact-inline-border"]=D.border),D.borderRadius&&(n["--persona-artifact-inline-radius"]=D.borderRadius),D.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=cn(e,D.chromeBackground)??D.chromeBackground),D.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=cn(e,D.chromeBorder)??D.chromeBorder),D.titleColor&&(n["--persona-artifact-inline-title-color"]=cn(e,D.titleColor)??D.titleColor),D.mutedColor&&(n["--persona-artifact-inline-muted-color"]=cn(e,D.mutedColor)??D.mutedColor),D.frameHeight&&(n["--persona-artifact-inline-frame-height"]=D.frameHeight)}let k=$?.code;k&&(k.keywordColor&&(n["--persona-code-keyword-color"]=k.keywordColor),k.stringColor&&(n["--persona-code-string-color"]=k.stringColor),k.commentColor&&(n["--persona-code-comment-color"]=k.commentColor),k.numberColor&&(n["--persona-code-number-color"]=k.numberColor),k.tagColor&&(n["--persona-code-tag-color"]=k.tagColor),k.attrColor&&(n["--persona-code-attr-color"]=k.attrColor),k.propertyColor&&(n["--persona-code-property-color"]=k.propertyColor),k.lineNumberColor&&(n["--persona-code-line-number-color"]=k.lineNumberColor),k.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=k.gutterBorderColor),k.background&&(n["--persona-code-bg"]=cn(e,k.background)??k.background));let _=n["--persona-surface"],I=n["--persona-container"],te=n["--persona-palette-colors-gray-100"]??"#f3f4f6",U=n["--persona-palette-colors-gray-200"]??"#e5e7eb",pe=n["--persona-palette-colors-gray-300"]??"#d1d5db",ue=!I||I===_,ge=f0(_??n["--persona-background"]),Ie=ue&&ge!==void 0&&ge<h0,Se=Ie?"rgba(255, 255, 255, 0.08)":te,ye=Ie?"rgba(255, 255, 255, 0.12)":U,dt=Ie?"rgba(255, 255, 255, 0.16)":pe,it=ue?Se:I,Ce=ue?ye:I;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??it,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??Ce,ue&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??dt),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??it,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??it,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??it,n}var Fx={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 y0=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),$x=(e,t)=>{if(!t||!y0(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(ii(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:Jr(t)==="v5"?"400px":"420px"}}}},b0={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"}}},Nl={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)"}}}},Tf=b0,v0={...Tf,colors:{...Tf.colors,primary:{50:"#0f0f10",100:"#27272a",200:"#3f3f46",300:"#52525b",400:"#71717a",500:"#f4f4f5",600:"#e4e4e7",700:"#d4d4d8",800:"#a1a1aa",900:"#fafafa",950:"#ffffff"},gray:{50:"#1a1a1b",100:"#27272a",200:"#2a2a2d",300:"#52525b",400:"#71717a",500:"#a1a1aa",600:"#b4b4bd",700:"#d4d4d8",800:"#e4e4e7",900:"#f4f4f5",950:"#fafafa"}}},C0=Nl,w0={semantic:{colors:{primary:"palette.colors.primary.500",accent:"palette.colors.primary.600",background:"#0f0f10",surface:"palette.colors.gray.50",container:"#1c1c20",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"#0f0f10",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600"}}},components:{...Nl.components,button:{...Nl.components?.button,primary:{background:"semantic.colors.primary",foreground:"palette.colors.primary.50"}},markdown:{inlineCode:{background:"palette.colors.gray.100",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"semantic.colors.text"},table:{headerBackground:"palette.colors.gray.100",borderColor:"semantic.colors.border"},blockquote:{background:"semantic.colors.container",borderColor:"palette.colors.gray.300",textColor:"semantic.colors.textMuted"}},eventStream:{...Nl.components?.eventStream,badge:{...Nl.components?.eventStream?.badge,step:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"},default:{background:"palette.colors.gray.100",foreground:"palette.colors.gray.700"}}}}},x0=e=>Jr({future:e})==="v5"?{palette:v0,components:w0}:{palette:Tf,components:C0},Ux=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Fl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",S0=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Fl()},ii=e=>S0(e),A0=(e,t={})=>_l(e,t),M0=(e,t={})=>{let n=x0(t.future),o=xo(n.components,e??{})??{};return _l({...o,palette:{...o.palette,colors:Jr(t)==="v5"?xo(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},Mo=e=>{let t=ii(e),n=Ux(e?.theme),o=Sp(e)==="circle"?Ap:{...Pp.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=xo({components:{launcher:o}},n),s=Ux(e?.darkTheme);return $x(t==="dark"?M0(xo(r??{},s??{}),{future:e?.future}):A0(r,{future:e?.future}),e)},E0=e=>Lp(e),ai=(e,t)=>{let n=Mo(t),o=E0(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",ii(t)),e.setAttribute("data-persona-defaults",Jr(t))},ya=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Fl())});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(Fl());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 Tr=require("lucide");var ds=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Ip="24px",Pf=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",$l=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},jx=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);var Vx=null;var kf=()=>{if(Vx!==null)return Vx;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},T0="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Rp=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Hp=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 Rp("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Rp("unsupported",e),null):(n==="space"&&(o.key=" "),o)},P0=e=>T0.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),qx=(e,t)=>{let n=Hp(e);if(!n)return"";let o=kf(),r=P0(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("+")},Wp=e=>qx(e,!1),Ul=e=>qx(e,!0),k0=(e,t)=>t.key?.toLowerCase()===e.key&&(kf()?t.metaKey:t.ctrlKey)===e.mod&&!(kf()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,L0=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},zx=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(k0(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&L0(a))){s.preventDefault();try{l.run(s)}catch(d){Rp(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=Hp(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=t.get(l);return d?(Rp(`${d.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",Ul(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}};var Kx=require("idiomorph"),Op=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Kx.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 Gx=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Lf={index:-1,draft:""};function Yx(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 Qx(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 Xx(){return new Map}function Jx(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Zx(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function eS(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function tS(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 nS(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Go(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function li(e,t){return Go(e)-e.scrollTop<=t}function oS(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:u=!1}=e,p=n-o;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&r&&(!u||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&l&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function rS(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 sS(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function If(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 iS(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var jl={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},I0=["pre","code","a","script","style"],Bp=e=>({type:e?.type??jl.type,placeholder:e?.placeholder??jl.placeholder,speed:e?.speed??jl.speed,duration:e?.duration??jl.duration,buffer:e?.buffer??jl.buffer}),lS=[{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"}],Vl=new Map;for(let e of lS)Vl.set(e.name,e);var cS=["wipe","glyph-cycle"],ql=e=>{Vl.set(e.name,e)},dS=e=>{lS.some(t=>t.name===e)||Vl.delete(e)},pS=()=>Array.from(Vl.keys()),zl=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Vl.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},R0=(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},H0=(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},Rf=/\s/,W0=(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},O0=(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(Rf.test(s[l])){let d=l;for(;d<s.length&&Rf.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 u=l;for(;u<s.length&&!Rf.test(s[u]);)d.appendChild(R0(o,s[u],t,n.value)),n.value+=1,u+=1;a.appendChild(d),l=u}r.replaceChild(a,e)},B0=(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(H0(o,d,t,n.value)),n.value+=1));r.replaceChild(a,e)},Kl=(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??I0).map(m=>m.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)W0(d,s)||l.push(d),d=a.nextNode();let u={value:o?.startIndex??0},p=t==="char"?O0:B0;for(let m of l)p(m,n,u);return r.innerHTML},_p=(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},Gl=(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},aS=new WeakMap,D0=(e,t)=>{if(!e.styles)return;let n=aS.get(t);if(n||(n=new Set,aS.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)},Hf=new WeakMap,_0=(e,t)=>{if(!e.onAttach)return;let n=Hf.get(t);if(n||(n=new Map,Hf.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},uS=e=>{let t=Hf.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Yl=(e,t)=>{D0(e,t),_0(e,t)};var{setLoader:sD,load:N0}=xt({fallbackImport:()=>import("@runtypelabs/persona/animations-extra")});var gS=N0;function Wf(e,t=pn){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 Ql=0,ps=null;function Of(e=document){if(Ql++,Ql===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;ps={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,Ql=Math.max(0,Ql-1),Ql===0&&ps)){let n=e.body,o=e.defaultView??window;n.style.overflow=ps.originalOverflow,n.style.position=ps.originalPosition,n.style.top=ps.originalTop,n.style.width=ps.originalWidth,o.scrollTo(0,ps.scrollY),ps=null}}}var Xl={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ct=e=>(e?.launcher?.mountMode??"floating")==="docked",us=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Bn=e=>{let t=e?.launcher?.dock,n=fr(e).dockWidth?t?.width:cn(Mo(e),"components.panel.width");return{side:t?.side??Xl.side,width:n??Xl.width,animate:t?.animate??Xl.animate,reveal:t?.reveal??Xl.reveal,maxHeight:t?.maxHeight??Xl.maxHeight}};var fS=require("lucide");var Bf=e=>e==="followUp"?"follow-up":e,Df=(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"}},mS=new WeakSet,F0=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,$0=e=>{F0()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},_f=e=>{var B,A,O;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:d,chipsConfig:u,session:p,getTextarea:m,eventTarget:h,submitPrompt:y}=e,v=o==="followUp",C=t.behavior,x=()=>{if(p.isStreaming())return;let L={suggestion:{...t},surface:o,source:r,behavior:C},$=h.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:L,bubbles:!0,composed:!0,cancelable:!0}));if(v&&h.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!$)return;for(let ae of d)if(ae.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let K=m();if(C==="fill"){K.value=t.prompt,K.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),K.focus();return}if(y){y(t.prompt);return}K.value="",p.sendMessage(t.prompt)},E=()=>{let L=S("button",`persona-suggestion persona-suggestion--${s}`);if(L.type="button",L.disabled=a,L.dataset.suggestionId=t.id,L.dataset.emphasis=t.emphasis,L.dataset.behavior=C,s==="chip"&&(u?.fontWeight&&(L.style.fontWeight=u.fontWeight),u?.paddingX&&(L.style.paddingLeft=u.paddingX,L.style.paddingRight=u.paddingX),u?.paddingY&&(L.style.paddingTop=u.paddingY,L.style.paddingBottom=u.paddingY)),t.icon){let K=le(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);K&&(K.classList.add("persona-suggestion__icon"),t.iconColor&&(K.style.color=t.iconColor),L.appendChild(K))}let $=S("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})),L.appendChild($),s!=="chip"){let K=Mt(fS.ArrowRight,16,"currentColor",1.8);K&&(K.classList.add("persona-suggestion__arrow"),L.appendChild(K))}return L.addEventListener("click",x),L},H=null;for(let L of d)if(L.renderSuggestion&&(H=L.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:E,select:x}),H))break;return H??(H=E()),(B=H.dataset).suggestionId||(B.suggestionId=t.id),(A=H.dataset).behavior||(A.behavior=C),(O=H.dataset).emphasis||(O.emphasis=t.emphasis),H instanceof HTMLButtonElement||H.setAttribute("aria-disabled",a?"true":"false"),H},Jl=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 p=Math.max(0,e.scrollWidth-e.clientWidth);if(p<=1){s();return}let m=getComputedStyle(e).direction==="rtl",h=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),y=4,v=h<=y,C=h>=p-y,x=m?!C:!v,E=m?!v:!C;e.toggleAttribute("data-scroll-left",x),e.toggleAttribute("data-scroll-right",E)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,m,h,y,v,C)=>{e.replaceChildren(),t.length=0,n.length=0;let x=C?.source??"config",E=C?.surface??(x==="config"?"starter":"followUp"),H=E==="followUp",B=C?.variant??"chip",A=C?.behavior??"send",O=C?.overflow??"wrap",L=C?.config??{},$=C?.plugins??[],K=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,ae=H?"followUps":"starters";!mS.has(L)&&L.debug===!0&&B!=="chip"&&L.suggestions?.[ae]?.overflow!==void 0&&(mS.add(L),console.info(`[persona] suggestions.${ae}.overflow applies to the "chip" variant only; the "${B}" variant manages its own stacking.`));let oe=U=>U.map(Df).filter(pe=>pe!==null).map(pe=>({...pe,behavior:pe.behavior??A})),P=oe(p??[]);$.forEach(U=>{U.transformSuggestions&&(P=oe(U.transformSuggestions({suggestions:P.map(pe=>({...pe})),surface:E,source:x,config:L})))});let k=K===void 0?P:P.slice(0,K);if(!k.length){e.hidden=!0,o=null,s();return}if(!H&&(y??m.getMessages()).some(pe=>pe.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Bf(E),e.dataset.variant=B,e.dataset.overflow=O;let _=document.createDocumentFragment(),I=m.isStreaming();k.forEach((U,pe)=>{let ue=_f({item:U,index:pe,surface:E,source:x,variant:B,streaming:I,config:L,plugins:$,chipsConfig:v,session:m,getTextarea:()=>h,eventTarget:e,submitPrompt:C?.submitPrompt});_.appendChild(ue),n.push(ue),[...ue instanceof HTMLButtonElement?[ue]:[],...Array.from(ue.querySelectorAll("button"))].forEach(Ie=>{t.includes(Ie)||(Ie.disabled=I,t.push(Ie))})}),e.appendChild(_),a(),l();let te=JSON.stringify({normalized:k,surface:E,variant:B,source:x});te!==o&&(o=te,$0(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:k.map(U=>({...U})),surface:E,source:x,variant:B},bubbles:!0,composed:!0})),H&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:k.map(U=>U.prompt)},bubbles:!0,composed:!0})))}}};var Yn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var U0="persona-header-control",j0="persona-header-control--glyph",V0="persona-header-control--sparse",q0=20,z0={x:[1.4,1.05]},hS="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",K0="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Np=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=z0[t]??[1,1.5],l=!o;e.classList.toggle(j0,l),e.classList.toggle(V0,l&&s!==1);let d=parseFloat(o??"")||q0,u=le(t,`${Math.round(d*s)}px`,"currentColor",a);u?(u.style.display="block",l||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),e.replaceChildren(u)):r&&(e.textContent=r)},ci=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=hS,size:l,iconSize:d,color:u,backgroundColor:p,borderWidth:m,borderColor:h,borderRadius:y,paddingX:v,paddingY:C,hidden:x,extraClassName:E,attrs:H}=e,B=S("div",a),A=!!(m||h),O=Y("button",{className:bn(U0,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"persona-border-none",!y&&"persona-rounded-full",E),attrs:{type:"button","aria-label":t,...H},style:{width:l,height:l,minWidth:l,minHeight:l,display:x?"none":void 0,color:u||wn.actionIconColor,backgroundColor:p,border:A?`${m||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:y,paddingLeft:v,paddingRight:v,paddingTop:C,paddingBottom:C}});return r?Np(O,r,{iconSize:d,iconText:s}):s&&(O.textContent=s),B.appendChild(O),an({anchor:O,trigger:B,text:()=>O.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:O,wrapper:B}},ba=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=hS,buttonSize:r,iconSize:s}=t,a=e?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:u,wrapper:p}=ci({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:u,wrapper:p}},va=(e,t={})=>{let{wrapperClassName:n=K0,buttonSize:o,iconSize:r}=t,a=(e?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:u,wrapper:p}=ci({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:u,wrapper:p}};var wn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-control-state-fg, var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af)))",minHeight:"var(--persona-header-min-height, auto)"},Nf={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},G0={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},Sr=e=>{let{config:t,showClose:n=!0}=e,o=Y("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:wn.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??Cl,a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,u=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 O=parseFloat(s)||24,L=le(d,O*.6,"currentColor",1);L?(L.style.width=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,L.style.height=`calc(${O}px * var(--persona-components-header-iconScale, 0.6))`,u.replaceChildren(L)):u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let O=S("img");O.src=t.launcher.iconUrl,O.alt="",O.className="persona-rounded-xl persona-object-cover",O.style.height=s,O.style.width=s,u.replaceChildren(O)}else u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=S("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:wn.titleColor,...Nf}}),h=Y("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:wn.subtitleColor,...G0}});p.append(m,h),l?o.append(p):o.append(u,p);let y=r.clearChat??{},v=y.enabled??!0,C=y.placement??"inline",x=null,E=null;if(v){let L=va(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});x=L.button,E=L.wrapper,C==="top-right"&&(E.style.right="48px"),C==="inline"&&o.appendChild(E)}let H=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:B,wrapper:A}=ba(t,{showClose:n,wrapperClassName:H});return a!=="top-right"&&o.appendChild(A),{header:o,iconHolder:u,headerTitle:m,headerSubtitle:h,closeButton:B,closeButtonWrapper:A,clearChatButton:x,clearChatButtonWrapper:E}},di=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function pi(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=e,l=S("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(fa)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let v of t){if(v.dividerBefore){let E=document.createElement("hr");l.appendChild(E)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",v.id),v.destructive&&C.setAttribute("data-destructive",""),v.icon){let E=le(v.icon,16,"currentColor",1.5);E&&C.appendChild(E)}let x=document.createElement("span");x.textContent=v.label,C.appendChild(x),C.addEventListener("click",E=>{E.stopPropagation(),m(),n(v.id)}),l.appendChild(C)}let d=null;function u(){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 p(){let v=l.classList.contains("persona-hidden");u(),l.classList.remove("persona-hidden"),v&&a?.(!0),requestAnimationFrame(()=>{let C=x=>{!l.contains(x.target)&&!o.contains(x.target)&&m()};document.addEventListener("click",C,!0),d=()=>document.removeEventListener("click",C,!0)})}function m(){let v=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,v&&a?.(!1)}function h(){l.classList.contains("persona-hidden")?p():m()}function y(){m(),l.remove()}return s&&s.appendChild(l),{element:l,show:p,hide:m,toggle:h,destroy:y}}function Dn(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:a,onClick:l,aria:d}=e,u=S("button",bn(!a&&"persona-icon-btn",s));u.type="button",u.setAttribute("aria-label",n),u.title=n;let p=le(t,o??16,"currentColor",r??2);if(p&&u.appendChild(p),l&&u.addEventListener("click",l),d)for(let[m,h]of Object.entries(d))u.setAttribute(m,h);return u}function Ff(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:d}=e,u="persona-label-btn";o!=="default"&&(u+=" persona-label-btn--"+o),u+=" persona-label-btn--"+r,a&&(u+=" "+a);let p=S("button",u);if(p.type="button",p.setAttribute("aria-label",n),t){let h=le(t,s??14,"currentColor",2);h&&p.appendChild(h)}let m=S("span");if(m.textContent=n,p.appendChild(m),l&&p.addEventListener("click",l),d)for(let[h,y]of Object.entries(d))p.setAttribute(h,y);return p}function Zl(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=S("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function d(){for(let p of l)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let m;p.icon?m=Dn({icon:p.icon,label:p.label,className:p.className,onClick:()=>{a=p.id,d(),o(p.id)}}):(m=S("button","persona-icon-btn"+(p.className?" "+p.className:"")),m.type="button",m.setAttribute("aria-label",p.label),m.title=p.label,m.textContent=p.label,m.addEventListener("click",()=>{a=p.id,d(),o(p.id)})),m.setAttribute("aria-pressed",p.id===a?"true":"false"),l.push({id:p.id,btn:m}),s.appendChild(m)}function u(p){a=p,d()}return{element:s,setSelected:u}}function yS(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:d="bottom-left",portal:u,chevronLabel:p="More options",chevronIconSize:m,className:h,primaryClassName:y,chevronClassName:v}=e,C=S("div","persona-split-btn"+(h?" "+h:"")),x={label:t,className:"persona-split-btn-primary"+(y?" "+y:""),onClick:l},E=r&&n?Dn({...x,icon:n,size:o??14}):Ff({...x,icon:n,iconSize:o??14}),H=Dn({icon:"chevron-down",label:p,size:m??14,className:"persona-split-btn-chevron"+(v?" "+v:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});C.append(E,H);let B=null,A=()=>{if(B)return B;let O=(typeof u=="function"?u():u)??void 0;return B=pi({items:s,onSelect:a,anchor:C,position:d,portal:O,onOpenChange:L=>{H.setAttribute("aria-expanded",L?"true":"false")}}),O||C.appendChild(B.element),B};return C.isConnected?A():requestAnimationFrame(()=>{B||A()}),H.addEventListener("click",O=>{O.stopPropagation(),A().toggle()}),{element:C,primaryButton:E,chevronButton:H,openMenu:()=>A().show(),closeMenu:()=>B?.hide(),toggleMenu:()=>A().toggle(),destroy:()=>{B?.destroy(),C.remove()}}}function Fp(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:d}=e,u=S("div","persona-combo-btn"+(l?" "+l:""));u.style.position="relative",u.style.display="inline-flex",u.style.alignItems="center",u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-haspopup","true"),u.setAttribute("aria-expanded","false"),u.setAttribute("aria-label",t);let p=S("span","persona-combo-btn-label");p.textContent=t,u.appendChild(p);let m=le(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",u.appendChild(m)),d&&(u.style.borderRadius=d.borderRadius??"10px",u.style.padding=d.padding??"6px 4px 6px 12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=d.background??"",u.style.borderColor=d.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}));let h=pi({items:o,onSelect:v=>{u.setAttribute("aria-expanded","false"),r(v)},anchor:u,position:s,portal:a});a||u.appendChild(h.element);let y=()=>u.getAttribute("data-persona-menu-locked")==="true";return u.addEventListener("click",v=>{if(v.stopPropagation(),y())return;let C=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",C?"false":"true"),h.toggle()}),u.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),u.click())}),{element:u,setLabel:v=>{p.textContent=v,u.setAttribute("aria-label",v)},open:()=>{u.setAttribute("aria-expanded","true"),h.show()},close:()=>{u.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let v=!h.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",v?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),u.remove()}}}var $f=e=>{let t=Sr({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 Y0(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=ci({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Wp(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=Ul(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=pi({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 Uf=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=S("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=wn.minHeight,l.style.padding="var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))",l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r?.titleMenu,u,p;if(d){let A=Fp({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:O=>{let L=K=>{K===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:O}}))},$=d.onSelect(O);$ instanceof Promise?$.then(L,()=>{}):L($)},hover:d.hover,className:""});u=A.element,u.style.color=wn.titleColor,p=u.querySelector(".persona-combo-btn-label")??u}else{if(u=S("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=S("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=wn.titleColor,Object.assign(p.style,Nf),p.textContent=a.title??"Chat Assistant",u.appendChild(p),r?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let O=r.onTitleClick;u.addEventListener("click",L=>{L.target.closest("button")||O()}),u.addEventListener("keydown",L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),O())})}let A=r?.titleRowHover;A&&(u.style.borderRadius=A.borderRadius??"10px",u.style.padding=A.padding??"6px 4px 6px 12px",u.style.margin="-6px 0 -6px -12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.style.width="fit-content",u.style.flex="none",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=A.background??"",u.style.borderColor=A.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}l.appendChild(u);let m="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:h,wrapper:y}=ba(t,{showClose:n,wrapperClassName:m});o&&h.addEventListener("click",o);let v=S("div","persona-flex persona-items-center persona-gap-1");d||Y0(v,r?.trailingActions,r?.onAction??s);let C=a.clearChat??{},x=null,E=null;if(C.enabled??!0){let A=C.placement??"inline",O=va(t,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":m});x=O.button,E=O.wrapper,A==="top-right"?E.style.right="48px":v.appendChild(E)}v.appendChild(y),l.appendChild(v);let H=S("div");H.style.display="none";let B=S("span");return B.style.display="none",{header:l,iconHolder:H,headerTitle:p,headerSubtitle:B,closeButton:h,closeButtonWrapper:y,clearChatButton:x,clearChatButtonWrapper:E}},$p={default:$f,minimal:Uf},jf=e=>$p[e]??$p.default,Ca=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=S("div");l.style.display="none";let d=S("span"),u=S("span"),p=S("button");p.style.display="none";let m=S("div");return m.style.display="none",{header:a,iconHolder:l,headerTitle:d,headerSubtitle:u,closeButton:p,closeButtonWrapper:m,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=jf(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 ui=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=bp(),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":""}}),{textarea:s,attachAutoResize:a}=mp(t);a();let l=fp(t),d=ha(t),u=hp(t),p=yp(t),m=Y("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(m),u&&(u.previewsContainer.style.gap="8px",m.append(u.previewsContainer),r.append(u.input)),r.append(s);let h=Y("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=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 u&&y.append(u.wrapper),d&&v.append(d.wrapper),v.append(l.wrapper),h.append(y,v),r.append(h),r.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==d?.button&&C.target!==d?.wrapper&&C.target!==u?.button&&C.target!==u?.wrapper&&s.focus()}),t?.statusIndicator?.mode==="transient"?n.append(o,p,r):n.append(o,r,p),{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:p,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:h,leftActions:y,rightActions:v,setSendButtonMode:l.setMode}};var Up=require("lucide");var bS=()=>{let e=Y("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=S("span","persona-pill-peek__icon"),n=Mt(Up.MessageSquare,16,"currentColor",1.5);n&&t.appendChild(n);let o=S("span","persona-pill-peek__text"),r=S("span","persona-pill-peek__caret"),s=Mt(Up.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},jp=e=>{let{config:t}=e,n=Y("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=bp(),r=yp(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=mp(t,{defaultMaxLines:5});a();let l=fp(t),d=ha(t),u=hp(t);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let p=Y("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),m=Y("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});u&&m.append(u.wrapper);let h=Y("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});d&&h.append(d.wrapper),h.append(l.wrapper),p.addEventListener("click",C=>{C.target!==l.button&&C.target!==l.wrapper&&C.target!==d?.button&&C.target!==d?.wrapper&&C.target!==u?.button&&C.target!==u?.wrapper&&s.focus()}),u&&p.append(u.input),p.append(m,s,h);let y=Y("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(y),u&&y.append(u.previewsContainer),n.append(o,p,r);let v=p;return{footer:n,suggestions:o,composerForm:p,header:y,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:v,leftActions:m,rightActions:h,setSendButtonMode:l.setMode}};var Q0=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}},X0=(e,t)=>{if(!e)return null;let n=Q0(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},J0=(e,t)=>{let n=S("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Z0=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},qf=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(":"))},zf=320,SS=320,eL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),tL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),nL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),oL=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),rL=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=S("span","persona-mention-chip-icon"),s=le(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},sL=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Bl(o.ref,{readonly:!0,render:t}))}return n},vS="\uE000",CS="\uE001",iL=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=h=>`${vS}${r}:${h}${CS}`,a=t.map((h,y)=>h.kind==="text"?h.text:s(y)).join(""),l=n(a);if(!t.every((h,y)=>h.kind==="text"||l.includes(s(y)))){e.replaceChildren(sL(t,o));return}e.innerHTML=l;let u=new RegExp(`${vS}${r}:(\\d+)${CS}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),m=[];for(let h=p.nextNode();h;h=p.nextNode())m.push(h);for(let h of m){let y=h;for(let v=u.exec(y.data);v;v=u.exec(y.data)){let C=t[Number(v[1])],x=y.splitText(v.index);x.data=x.data.slice(v[0].length),C?.kind==="mention"&&x.parentNode?.insertBefore(Bl(C.ref,{readonly:!0,render:o}),x),y=x}}},aL=(e,t,n)=>{if(e.length===0)return null;try{let o=S("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,d)=>{let u=S("img");u.alt=l.alt?.trim()||`Attached image ${d+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${zf}px`,u.style.maxHeight=`${SS}px`,u.style.height="auto",u.style.objectFit="contain",u.style.borderRadius="10px",u.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",u.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,u.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),u.remove(),r===0&&a())}),u.addEventListener("load",()=>{p=!0}),Z0(l.image)?(u.src=l.image,o.appendChild(u)):(p=!0,r=Math.max(0,r-1),u.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},lL=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!qf(o.audio))return;let r=S("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${zf}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},cL=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!qf(o.video))return;let r=S("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${zf}px`,r.style.maxHeight=`${SS}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}},dL=e=>{if(e.length===0)return null;try{let t=S("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!qf(o.data))return;let r=S("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},gi=()=>{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},Kf=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:gi};if(t){let r=t(o);if(r!==null)return r}return gi()},pL=(e,t)=>{let n=S("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=S("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},wS=(e,t,n="div")=>{let o=S(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},ec=(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},xS={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"}},uL=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=xS[n??"bubble"]??xS.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)`)},Vp="custom:",gL=e=>`${Vp}${e}`,AS=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),Gf=(e,t,n,o)=>{let r=t.showCopy??!0,s=t.showUpvote??!1,a=t.showDownvote??!1,l=t.showReadAloud??!1,d=(t.showRegenerate??!1)&&o?.canRegenerate===!0,u=(t.showEdit??!1)&&o?.canEdit===!0,p=(t.showQuote??!1)&&o?.canQuote!==!1,m=AS(t,e.role);if(!r&&!s&&!a&&!l&&!d&&!u&&!p&&m.length===0){let B=S("div");return B.style.display="none",B.id=`actions-${e.id}`,B.setAttribute("data-actions-for",e.id),B}let h=t.visibility??"hover",y=t.align??"right",v=t.layout??"pill-inside",C={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[y],x={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[v],E=S("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${C} ${x} ${h==="hover"?"persona-message-actions-hover":""}`);E.id=`actions-${e.id}`,E.setAttribute("data-actions-for",e.id);let H=(B,A,O)=>{let L=Dn({icon:B,label:A,size:14,className:"persona-message-action-btn",chromeless:!0});return L.setAttribute("data-action",O),L};r&&E.appendChild(H("copy","Copy message","copy")),l&&E.appendChild(H("volume-2","Read aloud","read-aloud")),s&&E.appendChild(H("thumbs-up","Upvote","upvote")),a&&E.appendChild(H("thumbs-down","Downvote","downvote")),d&&E.appendChild(H("refresh-cw","Regenerate response","regenerate")),u&&E.appendChild(H("pencil","Edit message","edit")),p&&E.appendChild(H("quote","Quote message","quote"));for(let B of m)E.appendChild(H(B.iconName??"ellipsis",B.label,gL(B.id)));return E},wa=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",d=a.avatar,u=a.timestamp,p=d?.show??!1,m=u?.show??!1,h=d?.position??"left",y=u?.position??"below",v=ec(e.role,l),C=S("div",v.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let x=Mf(s?.widgetConfig?.future).components.message,E=s?.widgetConfig?.theme?.components?.message;uL(C,e.role,l,e.role==="user"?{...x.user,...E?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...x.assistant,...E?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let H=eL(e),B=e.content?.trim()??"",O=H.length>0&&B===da,L=Bp(s?.widgetConfig?.features?.streamAnimation),$=s?.widgetConfig?.features?.streamAnimation?.plugins,K=e.role==="assistant"&&L.type!=="none"?zl(L.type,$):null,ae=e.role==="assistant"&&K?.isAnimating?.(e)===!0,oe=e.role==="assistant"&&K!==null&&(!!e.streaming||ae);oe&&K?.bubbleClass&&C.classList.add(K.bubbleClass);let P=document.createElement("div");P.classList.add("persona-message-content"),e.streaming&&P.classList.add("persona-content-streaming"),oe&&K&&(K.containerClass&&P.classList.add(K.containerClass),P.style.setProperty("--persona-stream-step",`${L.speed}ms`),P.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let k=oe?Dp(e.content??"",L.buffer,K,e,!!e.streaming):e.content??"",_=()=>{let Ce=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent});return oe&&K?.wrap==="char"?Kl(Ce,"char",e.id,{skipTags:K.skipTags}):oe&&K?.wrap==="word"?Kl(Ce,"word",e.id,{skipTags:K.skipTags}):Ce},I=null;if(O?(I=document.createElement("div"),I.innerHTML=_(),I.style.display="none",P.appendChild(I)):e.contentSegments?.length?iL(P,e.contentSegments,Ce=>t({text:Ce,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):P.innerHTML=_(),oe&&K?.useCaret&&!O&&B){let Ce=_p(),D=P.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ne=D[D.length-1];if(Ne?.parentNode)Ne.parentNode.insertBefore(Ce,Ne.nextSibling);else{let Fe=P.lastElementChild;Fe?Fe.appendChild(Ce):P.appendChild(Ce)}}if(m&&y==="inline"&&e.createdAt){let Ce=wS(e,u,"span");Ce.classList.add("persona-timestamp-inline");let D=P.lastElementChild;D?D.appendChild(Ce):P.appendChild(Ce)}if(H.length>0){let Ce=aL(H,!O&&!!B,()=>{O&&I&&(I.style.display="")});Ce?C.appendChild(Ce):O&&I&&(I.style.display="")}let te=tL(e);if(te.length>0){let Ce=lL(te);Ce&&C.appendChild(Ce)}let U=nL(e);if(U.length>0){let Ce=cL(U);Ce&&C.appendChild(Ce)}let pe=oL(e);if(pe.length>0){let Ce=dL(pe);Ce&&C.appendChild(Ce)}let ue=e.contentSegments?.length?null:rL(e.contextMentions);if(ue&&C.appendChild(ue),C.appendChild(P),m&&y==="below"&&e.createdAt){let Ce=wS(e,u);Ce.classList.add("persona-mt-1"),C.appendChild(Ce)}let ge=e.role==="assistant"?X0(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Ce=!!(k&&k.trim()),D=L.placeholder==="skeleton",Ne=D&&L.buffer==="line"&&Ce;if(Ce)Ne&&C.appendChild(Gl());else if(D)C.appendChild(Gl());else{let Fe=Kf("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);Fe&&C.appendChild(Fe)}}ge&&e.stopReason&&!e.streaming&&(B||(P.style.display="none"),C.appendChild(J0(e.stopReason,ge)));let Ie=e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1,Se=s?.actionEligibility,ye=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&Se?.canEdit===!0||o?.showQuote===!0&&Se?.canQuote===!0||AS(o,"user").length>0);if((Ie||ye)&&o){let Ce=Gf(e,ye?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,Se);C.appendChild(Ce)}if(!p||e.role==="system")return C;let dt=S("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),it=pL(d,e.role);return h==="right"||h==="left"&&e.role==="user"?dt.append(C,it):dt.append(it,C),dt},MS=(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}):wa(e,t,n,o,r,s)};var mL=40,fL=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=le(t.name,mL);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},ES=(e,t,n={})=>{let o=Y("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=S("p","persona-welcome-kicker");r.hidden=!0;let s=S("h2","persona-welcome-title"),a=S("p","persona-welcome-subtitle"),l=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}},xa=(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)},zp=(e,t)=>{e.title.textContent=t.title,e.kicker.textContent=t.kicker??"",e.kicker.hidden=!t.kicker,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",fL(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss),e.host.setAttribute("data-persona-welcome-layout",t.layout??"top"),e.host.setAttribute("data-persona-welcome-anchor",t.anchor??"bottom"),t.iconPlacement==="inline"?e.host.setAttribute("data-persona-welcome-icon-placement","inline"):e.host.removeAttribute("data-persona-welcome-icon-placement"),t.align?e.host.setAttribute("data-persona-welcome-align",t.align):e.host.removeAttribute("data-persona-welcome-align")},hL="data-persona-welcome-plugin",TS="data-persona-welcome-overlay",qp="persona-welcome-overlay-active",Yf=new WeakMap,Qf=(e,t,n)=>{n.setAttribute(hL,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(TS,""),e.classList.contains(qp)||(Yf.set(e,e.scrollTop),e.classList.add(qp),e.scrollTop=0)},Xf=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(TS),e.classList.contains(qp)&&(e.classList.remove(qp),e.scrollTop=Yf.get(e)??e.scrollTop,Yf.delete(e))},PS=()=>{let e=Y("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Kp=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Y("div",{className:ec("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},kS=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,LS=(e,t)=>{if(kS()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,a=0;if(o){let v=getComputedStyle(o);r=parseFloat(v.rowGap)||0;let C=e.previousElementSibling,x=e.nextElementSibling,H=o.getBoundingClientRect().top+(parseFloat(v.borderTopWidth)||0)+(parseFloat(v.paddingTop)||0)-o.scrollTop;s=Math.max(0,C?n.top-C.getBoundingClientRect().bottom-r:n.top-H),a=Math.max(0,x?x.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let d=getComputedStyle(e),u=parseFloat(d.paddingTop)||0,p=parseFloat(d.paddingBottom)||0,m=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${p}px`,marginTop:`${s}px`,marginBottom:`${a}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),h=!1,y=()=>{h||(h=!0,e.style.overflow=l,t(m))};return m.finished.then(y).catch(y),m},IS=(e,t,n,o=260)=>{if(t<=1||kS()||typeof e.animate!="function"||!e.isConnected)return null;let r=n==="drop"?-t:t;return e.animate([{transform:`translateY(${r}px)`},{transform:"none"}],{duration:o,easing:"cubic-bezier(0.2, 0, 0, 1)",fill:"none"})};var yL="Hello \u{1F44B}",bL="I can answer questions and help you get things done here.",RS=new WeakSet,xn=(e,t)=>!!e&&e[t]!==void 0,vL=(e,t)=>{!e||e.debug!==!0||!t.length||RS.has(e)||(RS.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Sa=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!=="docked")=>{let n=e?.welcome,o=e?.copy,r=e?.future?.v5Defaults===!0,s=n?.layout??(r?"centered":"top"),a=xn(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=a==="hero"&&!r&&n?.layout===void 0?"on-first-message":xn(n,"dismiss")?n.dismiss:r||a==="hero"?"on-first-message":"never",d=[];xn(n,"title")&&xn(o,"welcomeTitle")&&d.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),xn(n,"subtitle")&&xn(o,"welcomeSubtitle")&&d.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),xn(n,"variant")&&xn(o,"showWelcomeCard")&&d.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),a==="hero"&&xn(n,"message")&&d.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),!r&&n?.layout===void 0&&a==="hero"&&xn(n,"dismiss")&&n.dismiss!=="on-first-message"&&d.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let u=n?.anchor??(s==="centered"&&t?"center":"bottom"),p=$l(n?.anchorComposerTop)!==null;return xn(n,"anchorComposerTop")&&!p&&d.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),u!=="center"&&(xn(n,"anchorComposerTop")||xn(n,"composerGap"))&&d.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),vL(e,d),{title:xn(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":yL),kicker:n?.kicker??"",subtitle:xn(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":bL),icon:n?.icon,align:n?.align==="start"||n?.align==="center"?n.align:s==="centered"?"center":void 0,iconPlacement:n?.icon&&typeof n.icon!="function"&&n.icon.placement==="inline"?"inline":"above",variant:a,dismiss:l,message:a==="hero"?void 0:n?.message,layout:s,anchor:u,anchorComposerTop:p?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||Ip}},HS=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",gs=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var CL="var(--persona-components-panel-maxWidth)",WS="var(--persona-components-panel-height)",wL="var(--persona-components-panel-maxHeight)",mi=e=>{let t=fr(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${WS})`:`max(200px, calc(${WS} - ${o}px))`;return{width:n??sC,maxWidth:n??CL,height:r,maxHeight:wL}},OS="16px",Zf="10px",eh="14px",BS=e=>{let t=e?.launcher?.enabled??!0,n=Ct(e);if(us(e)){let u=e?.launcher?.composerBar??{},p=S("div","persona-widget-wrapper persona-fixed persona-transition");p.setAttribute("data-persona-composer-bar",""),p.dataset.state="collapsed",p.dataset.expandedSize=u.expandedSize??"anchored",p.style.zIndex=String(e?.launcher?.zIndex??pn);let m=S("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");m.style.width="100%",p.appendChild(m);let h=S("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??pn),{wrapper:p,panel:m,pillRoot:h}}if(n){let u=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),p=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return u.appendChild(p),{wrapper:u,panel:p}}if(!t){let u=S("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),p=S("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),m=fr(e),y=m.launcherWidth||m.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?mi(e).width:"100%";return u.style.width=y,p.style.width="100%",u.appendChild(p),{wrapper:u,panel:p}}let r=e?.launcher??{},s=r.position&&Yn[r.position]?Yn[r.position]:Yn["bottom-right"],a=S("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??pn);let l=S("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=mi(e);return l.style.width=d.width,l.style.maxWidth=d.maxWidth,a.appendChild(l),{wrapper:a,panel:l}},th=e=>{let t=Y("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Bf(e)}});return t.hidden=!0,t},DS=(e,t)=>{let n=th("starter"),o=ES(e,n,{flatShadow:Ct(e)}),r=Sa(e);zp(o,r),xa(t,o.host,gs(r,e?.initialMessages));let s=PS();return Kp(s,r.message,e),{welcome:o,greetingHost:s}},xL=(e,t)=>{let n=S("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=ba(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:OS,iconSize:Zf});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 $=va(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:OS,iconSize:eh});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"}}),u=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"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:m}=DS(e,u),{host:h,title:y,subtitle:v}=p,C=p.starterSuggestions,x=S("div","persona-widget-messages persona-flex persona-flex-col");x.style.gap="var(--persona-components-message-gap, 12px)";let E=th("followUp"),H=ds(e,!0);H&&(x.style.maxWidth=H,x.style.marginLeft="auto",x.style.marginRight="auto",x.style.width="100%"),u.append(h,m,x,E);let B=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"}}),A=jp({config:e}),{root:O,textNode:L}=bS();return n.append(d,r,u,B),l&&n.appendChild(l),{container:n,body:u,messagesWrapper:x,starterSuggestions:C,transcriptSuggestions:E,composerOverlay:B,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:h,welcomeIconHolder:p.iconHolder,greetingHost:m,introKicker:p.kicker,introTitle:y,introSubtitle:v,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:S("span"),headerTitle:S("span"),headerSubtitle:S("span"),header:d,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:O,peekTextNode:L}},_S=(e,t=!0)=>{if(us(e))return xL(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?Ca(e,o,{showClose:t}):Sr({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}=DS(e,a),{host:u,title:p,subtitle:m}=l,h=l.starterSuggestions,y=S("div","persona-widget-messages persona-flex persona-flex-col");y.style.gap="var(--persona-components-message-gap, 12px)";let v=th("followUp"),C=ds(e,!1);C&&(y.style.maxWidth=C,y.style.marginLeft="auto",y.style.marginRight="auto",y.style.width="100%"),a.append(u,d,y,v);let x=ui({config:e}),E=e?.layout?.showFooter!==!1;r?di(n,s,e):(s.header.style.display="none",di(n,s,e)),n.append(a);let H=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 E||(x.footer.style.display="none"),n.append(x.footer),n.append(H),{container:n,body:a,messagesWrapper:y,starterSuggestions:h,transcriptSuggestions:v,composerOverlay:H,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.statusText,welcomeHost:u,welcomeIconHolder:l.iconHolder,greetingHost:d,introKicker:l.kicker,introTitle:p,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 nh=(e,t)=>{let n=S("button");n.type="button",n.innerHTML=`
|
|
29
29
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
30
30
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
31
31
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -33,15 +33,15 @@ _Details: ${n.message}_`:o}var of=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=Ct(s),d=Sp(s)==="circle";d?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",a.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let
|
|
37
|
-
`):""},
|
|
38
|
-
`).length>7?{tabindex:"0","aria-label":`${l} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),y=Y("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),v=le("copy",14,"currentColor",1.7);v&&y.appendChild(v),
|
|
36
|
+
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=Ct(s),d=Sp(s)==="circle";d?(n.dataset.personaLauncherVariant="circle",n.setAttribute("aria-label",a.title??"Open chat")):(n.removeAttribute("data-persona-launcher-variant"),n.removeAttribute("aria-label"));let u=n.querySelector("[data-role='launcher-title']");if(u){let A=a.title??"Chat Assistant";u.textContent=A,u.setAttribute("title",A)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let A=a.subtitle??"Here to help you get answers fast";p.textContent=A,p.setAttribute("title",A)}let m=n.querySelector(".persona-flex-col");m&&(a.textHidden||l||d?m.style.display="none":m.style.display="");let h=n.querySelector("[data-role='launcher-icon']");if(h)if(a.agentIconHidden)h.style.display="none";else{let A=a.agentIconSize??"40px";if(h.style.height=A,h.style.width=A,a.agentIconBackgroundColor?(h.style.backgroundColor=a.agentIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),h.innerHTML="",a.agentIconName){let O=parseFloat(A)||24,L=le(a.agentIconName,O*.6,"var(--persona-text-inverse, #ffffff)",1.5);L?(h.appendChild(L),h.style.display=""):(h.textContent=a.agentIconText??"\u{1F4AC}",h.style.display="")}else a.iconUrl?h.style.display="none":(h.textContent=a.agentIconText??"\u{1F4AC}",h.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let A=a.agentIconSize??"40px";y.style.height=A,y.style.width=A,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let v=n.querySelector("[data-role='launcher-call-to-action-icon']");if(v){let A=a.callToActionIconSize??"32px";v.style.height=A,v.style.width=A,a.callToActionIconBackgroundColor?(v.style.backgroundColor=a.callToActionIconBackgroundColor,v.classList.remove("persona-bg-persona-primary")):(v.style.backgroundColor="",v.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(v.style.color=a.callToActionIconColor,v.classList.remove("persona-text-persona-call-to-action")):(v.style.color="",v.classList.add("persona-text-persona-call-to-action"));let O=0;if(a.callToActionIconPadding?(v.style.boxSizing="border-box",v.style.padding=a.callToActionIconPadding,O=(parseFloat(a.callToActionIconPadding)||0)*2):(v.style.boxSizing="",v.style.padding=""),a.callToActionIconHidden||d)v.style.display="none";else if(v.style.display=l?"none":"",v.innerHTML="",a.callToActionIconName){let L=parseFloat(A)||24,$=Math.max(L-O,8),K=le(a.callToActionIconName,$,"currentColor",1.5);K?v.appendChild(K):v.textContent=a.callToActionIconText??"\u2197"}else v.textContent=a.callToActionIconText??"\u2197"}let C=a.position&&Yn[a.position]?Yn[a.position]:Yn["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?E:`${x} ${C}`,l||(n.style.zIndex=String(a.zIndex??pn));let H="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",B="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??H,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:B,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},SL="teaser-dismissed",FS=new Set,NS=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${SL}`},AL=(e,t)=>{if(FS.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},ML=(e,t)=>{if(FS.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},EL=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,TL=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Ct(e??{})?null:t},$S=(e,t)=>{let n=S("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,a=null,l=null,d=null,u=!1,p=!1,m=!1,h=!1,y=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,v=()=>{d!==null&&(clearTimeout(d),d=null)},C=()=>{!s||!u||(u=!1,s.hidden=!0)},x=te=>{v(),m=!0,C(),ML(NS(o),te&&y())},E=te=>{!r||m||x(te==="user"&&u)},H=()=>{d=null,!(!s||m||h)&&(p=!0,u=!0,s.hidden=!1,!(EL()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},B=()=>{!r||!s||m||p||h||AL(NS(o),y())||(v(),d=setTimeout(H,Math.max(0,r.delayMs??0)))},A=()=>{x(y()),t()},O=te=>{te.stopPropagation(),x(y())},$=nh(e,()=>{E("user"),t()}),K=()=>{v(),l?.removeEventListener("click",A),a?.removeEventListener("click",O),s?.remove(),s=null,l=null,a=null,u=!1},ae=()=>{l=Y("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",A),a=Y("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",O),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)},oe=()=>{let te=o.launcher?.position??"bottom-right",U=Yn[te]??Yn["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",$.element.style.position="";return}n.className=bn("persona-launcher-surface",U),n.setAttribute("data-teaser",te),n.style.zIndex=String(o.launcher?.zIndex??pn),$.element.style.position="static"},P=te=>{let U=TL(te);if(r=U,!U){K();return}s||ae(),l.textContent=U.text,a.hidden=U.dismissible===!1,a.setAttribute("aria-label",U.dismissLabel??"Dismiss message"),B()},k=te=>{o=te,$.update(te),P(te),oe()},_=(te,U="user")=>{h=te,te&&E(U)},I=()=>{K(),$.destroy(),n.remove()};return n.appendChild($.element),e&&(P(e),oe()),{element:n,launcher:$,get teaser(){return s?{element:s,show:H,dismiss:x}:null},setPanelOpen:_,update:k,destroy:I}};var US=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=BS(e),s=_S(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},u={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:u,replaceHeader:h=>(d.element.replaceWith(h.header),d.element=h.header,d.iconHolder=h.iconHolder,d.headerTitle=h.headerTitle,d.headerSubtitle=h.headerSubtitle,d.closeButton=h.closeButton,d.closeButtonWrapper=h.closeButtonWrapper,d.clearChatButton=h.clearChatButton,d.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{u.footer.replaceWith(h),u.footer=h}}},oh=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>nh(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=$S(e,n);return{instance:r,element:r.element}};var PL=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},kL=(e,t,n)=>`${PL(e)}plugin:${t}:${n}`,jS=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=>kL(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),u=o();if(u)try{u.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 Aa=(e,t,n)=>{let o=n;for(let r of t){let s=S("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};var LL=(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
|
+
`):""},rh=(e,t,n)=>{Od(e,t,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},sh=(e,t,n=new Set)=>{t=Dd(t,"reasoning");let o=e.reasoning,r=Id("persona-reasoning-bubble",e.id);if(!o)return yr(r,e,t,"reasoning");let s=t?.features?.reasoningDisplay??{},a=s.expandable??Zs.expandable,l=a&&n.has(e.id),d=o.status!=="complete",u=LL(e,s.previewMaxLines??Zs.previewMaxLines),p=Rd({expandable:a,expanded:l,bubbleType:"reasoning"}),m=S("div","persona-flex persona-flex-col persona-text-left"),h=S("span","persona-text-xs persona-text-persona-primary"),y=Zr(t,"reasoning")==="row",v=y&&!d?`Thought for ${wl(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",C=t?.reasoning??{},x=String(o.startedAt??Date.now()),E=()=>{let U=S("span","");return U.setAttribute("data-tool-elapsed",x),U.textContent=Gd(o),U},H=C.renderCollapsedSummary?.({message:e,reasoning:o,defaultSummary:v,previewText:u,isActive:d,config:t??{},elapsed:Gd(o),createElapsedElement:E});typeof H=="string"&&H.trim()?(h.textContent=H,m.appendChild(h)):H instanceof HTMLElement?m.appendChild(H):(h.textContent=v,m.appendChild(h));let B=S("span","persona-text-xs persona-text-persona-primary");B.textContent=XC(o),y||m.appendChild(B);let A=s.loadingAnimation??Zs.loadingAnimation,O=C.activeTextTemplate,L=C.completeTextTemplate,$=d?O:L,K=H instanceof HTMLElement,ae=(U,pe)=>{h.textContent="";let ue=Yd(U,""),ge=0;for(let Ie of ue){let Se=Ie.styles.length>0?(()=>{let ye=S("span",Ie.styles.map(dt=>`persona-tool-text-${dt}`).join(" "));return h.appendChild(ye),ye})():h;if(Ie.isDuration&&d)Se.appendChild(E());else{let ye=Ie.isDuration?Gd(o):Ie.text;pe?ge=Aa(Se,ye,ge):Se.appendChild(document.createTextNode(ye))}}};if(!K&&$)if(B.style.display="none",h.style.display="",d&&A!=="none"){let U=C.loadingAnimationDuration??2e3;h.setAttribute("data-preserve-animation","true"),A==="pulse"?(h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${U}ms`),ae($,!1)):(h.classList.add(`persona-tool-loading-${A}`),h.style.setProperty("--persona-tool-anim-duration",`${U}ms`),A==="shimmer-color"&&(C.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",C.loadingAnimationColor),C.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",C.loadingAnimationSecondaryColor)),ae($,!0))}else ae($,!1);else if(!K&&d&&A!=="none"){h.style.display="";let U=C.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),A==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${U}ms`);else{h.classList.add(`persona-tool-loading-${A}`),h.style.setProperty("--persona-tool-anim-duration",`${U}ms`),A==="shimmer-color"&&(C.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",C.loadingAnimationColor),C.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",C.loadingAnimationSecondaryColor));let pe=h.textContent||v;h.textContent="",Aa(h,pe,0)}o.status==="complete"&&!y&&(h.style.display="none")}else K||(o.status==="complete"&&!y?h.style.display="none":h.style.display="");if(s.iconName&&!K){let U=S("span","persona-reasoning-header-icon"),pe=le(s.iconName,16,"currentColor",2);pe&&(U.appendChild(pe),p.appendChild(U))}let oe="currentColor",P=na(p,m,{expandable:a,expanded:l,iconColor:oe,metaGap:!1}),k=Hd({bubble:r,previewKind:"reasoning",expanded:l,isActive:d,previewText:u,activePreview:s.activePreview,activeMinHeight:s.activeMinHeight,renderPreview:()=>t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:o,defaultPreview:u,isActive:d,config:t??{}})});if(!a)return r.append(p,k),yr(r,e,t,"reasoning");let _=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=l?"":"none";let I=o.chunks.join(""),te=S("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return te.textContent=I||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(te),Wd({expanded:l,header:p,toggleIcon:P,content:_,collapsedPreview:k,iconColor:oe}),r.append(p,k,_),yr(r,e,t,"reasoning")};var VS=e=>{if(e==null)return!0;if(typeof e=="string"){if(!e.trim())return!0;try{return VS(JSON.parse(e))}catch{return!1}}return typeof e=="object"&&Object.keys(e).length===0},IL=e=>{if(e!==null&&typeof e=="object")return!0;if(typeof e!="string")return!1;try{let t=JSON.parse(e);return t!==null&&typeof t=="object"}catch{return!1}};function qS(e,t,n){let o=t.toolCall;if(!o)return;let r=n.toolCall??{},s=(l,d)=>{let u=Y("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":l.toLowerCase()},style:{backgroundColor:r.codeBlockBackgroundColor,borderColor:r.codeBlockBorderColor,borderWidth:r.codeBlockBorderColor?"1px":void 0}}),p=Y("div",{className:"persona-tool-detail-label",text:l,style:{color:r.labelTextColor}}),m=ca(d),h=Y("pre",{className:`persona-tool-detail-value${IL(d)?" persona-tool-detail-code":""}`,text:m,attrs:m.length>420||m.split(`
|
|
38
|
+
`).length>7?{tabindex:"0","aria-label":`${l} content`}:{},style:{color:r.codeBlockTextColor??r.contentTextColor}}),y=Y("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${l.toLowerCase()}`,title:`Copy ${l.toLowerCase()}`}}),v=le("copy",14,"currentColor",1.7);v&&y.appendChild(v),u.append(p,h,y),e.appendChild(u)};VS(o.args)||s("Request",o.args);let a=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");a!==void 0&&(typeof a!="string"||a.trim())&&s("Response",a),o.success===!1&&e.appendChild(Y("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var ih=new WeakMap;async function zS(e){let t=e.closest("[data-persona-tool-detail]"),n=t?.querySelector("pre");if(!n)return;let o=`Copy ${t?.getAttribute("data-persona-tool-detail")}`;clearTimeout(ih.get(e));try{await navigator.clipboard.writeText(n.textContent??""),e.dataset.copied="true",e.setAttribute("aria-label","Copied"),e.title="Copied";let r=le("check",14,"currentColor",2);r&&e.replaceChildren(r)}catch{e.setAttribute("aria-label","Copy failed \u2014 try again"),e.title="Copy failed \u2014 try again"}ih.set(e,setTimeout(()=>{delete e.dataset.copied,e.setAttribute("aria-label",o),e.title=o;let r=le("copy",14,"currentColor",1.7);r&&e.replaceChildren(r),ih.delete(e)},1800))}var KS=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?"currentColor":"var(--persona-primary, #171717)"),RL=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
|
|
39
39
|
`);let r=ca(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
40
|
-
`):""},sh=(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)"},SL=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??hr.collapsedMode,s=n?.success===!1?n.error||"Tool failed":xL(e,o?.previewMaxLines??hr.previewMaxLines),a=n?Zr(t,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:VC(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=qm(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=qm(n,d.completeTextTemplate,p)),n.success===!1&&(p+=" \xB7 Failed"),{summary:p,previewText:s,isActive:l}},ih=(e,t,n,o)=>{Od(e,t,{stateSet:n,previewKind:"tool",iconColor:_S(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},ah=(e,t,n=new Set)=>{t=Dd(t,"tool");let o=e.toolCall,r=t?.toolCall??{},s=Id("persona-tool-bubble",e.id);if(r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow)",!o)return yr(s,e,t,"tool");let a=t?.features?.toolCallDisplay??{},l=a.expandable??hr.expandable,d=l&&n.has(e.id),{summary:p,previewText:u,isActive:m}=SL(e,t),h=Rd({expandable:l,expanded:d,bubbleType:"tool"});r.headerBackgroundColor&&(h.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(h.style.paddingLeft=r.headerPaddingX,h.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(h.style.paddingTop=r.headerPaddingY,h.style.paddingBottom=r.headerPaddingY);let y=S("div","persona-flex persona-flex-col persona-text-left"),v=S("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(v.style.color=r.headerTextColor);let C=String(o.startedAt??Date.now()),x=()=>{let k=S("span","");return k.setAttribute("data-tool-elapsed",C),k.textContent=Ll(o),k},E=r.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:p,previewText:u,collapsedMode:a.collapsedMode??hr.collapsedMode,isActive:m,config:t??{},elapsed:Ll(o),createElapsedElement:x});typeof E=="string"&&E.trim()?(v.textContent=E,y.appendChild(v)):E instanceof HTMLElement?y.appendChild(E):(v.textContent=p,y.appendChild(v));let H=a.loadingAnimation??hr.loadingAnimation,B=r.activeTextTemplate,A=r.completeTextTemplate,O=m?B:A,L=E instanceof HTMLElement,$=(k,_)=>{v.textContent="";let I=o.name?.trim()||"tool",te=Yd(k,I),U=0;for(let pe of te){let ue=pe.styles.length>0?(()=>{let ge=S("span",pe.styles.map(Ie=>`persona-tool-text-${Ie}`).join(" "));return v.appendChild(ge),ge})():v;if(pe.isDuration&&m)ue.appendChild(x());else{let ge=pe.isDuration?Ll(o):pe.text;_?U=Aa(ue,ge,U):ue.appendChild(document.createTextNode(ge))}}};if(!L)if(m&&H!=="none"){let k=r.loadingAnimationDuration??2e3;if(v.setAttribute("data-preserve-animation","true"),H==="pulse")v.classList.add("persona-tool-loading-pulse"),v.style.setProperty("--persona-tool-anim-duration",`${k}ms`),O&&$(O,!1);else if(v.classList.add(`persona-tool-loading-${H}`),v.style.setProperty("--persona-tool-anim-duration",`${k}ms`),H==="shimmer-color"&&(r.loadingAnimationColor&&v.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&v.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),O)$(O,!0);else{let _=v.textContent||p;v.textContent="",Aa(v,_,0)}}else O&&$(O,!1);let K=_S(r,Zr(t,"tool")==="row"),ae=na(h,y,{expandable:l,expanded:d,iconColor:K,metaGap:!0}),oe=Hd({bubble:s,previewKind:"tool",expanded:d,isActive:m,previewText:u,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:u,isActive:m,config:t??{}})});if(!l)return s.append(h,oe),yr(s,e,t,"tool");let P=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(P.style.display=d?"":"none",r.contentBackgroundColor&&(P.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(P.style.color=r.contentTextColor),r.contentPaddingX&&(P.style.paddingLeft=r.contentPaddingX,P.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(P.style.paddingTop=r.contentPaddingY,P.style.paddingBottom=r.contentPaddingY),t.future?.v5Defaults===!0)BS(P,e,t);else{if(o.name){let k=S("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?k.style.color=r.contentTextColor:r.headerTextColor&&(k.style.color=r.headerTextColor),k.textContent=o.name,P.appendChild(k)}if(o.args!==void 0){let k=S("div","persona-space-y-1"),_=S("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Arguments";let I=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",sh(I,r),I.textContent=ca(o.args),k.append(_,I),P.appendChild(k)}if(o.chunks&&o.chunks.length){let k=S("div","persona-space-y-1"),_=S("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Activity";let I=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",sh(I,r),I.textContent=o.chunks.join(""),k.append(_,I),P.appendChild(k)}if(o.success===!1&&P.appendChild(Y("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let k=S("div","persona-space-y-1"),_=S("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Result";let I=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",sh(I,r),I.textContent=ca(o.result),k.append(_,I),P.appendChild(k)}if(o.status==="complete"&&typeof o.duration=="number"){let k=S("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(k.style.color=r.contentTextColor),k.textContent=`Duration: ${o.duration}ms`,P.appendChild(k)}}return Wd({expanded:d,header:h,toggleIcon:ae,content:P,collapsedPreview:oe,iconColor:K}),s.append(h,oe,P),yr(s,e,t,"tool")};var{setLoader:J_,load:AL,provide:Z_,getSync:ML}=xt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var NS=AL;var FS=ML;var{setLoader:nN,load:EL}=xt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var lh=EL;var ch=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)})}},Eo=new ch;var dh=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:cN,load:TL,provide:dN,getSync:PL}=xt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),Ma=null,Gp=new Set,$S=e=>{if(Ma)return Ma;Ma=e,e.initArtifactsUi({componentRegistry:Eo});for(let o of dh)Eo.has(o)||Eo.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=jo();t?e.__provideMarkdownParsers(t):Ji(()=>{let o=jo();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>Ed());let n=[...Gp];Gp.clear();for(let o of n)try{o()}catch{}return e};var Yp=()=>TL().then($S);var Ar=()=>{if(Ma)return Ma;let e=PL();return e?$S(e):null},ph=e=>Ma?()=>{}:(Gp.add(e),()=>{Gp.delete(e)});function xn(e){return e?.features?.artifacts?.enabled===!0}function US(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 kL(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 jS=["panel","seamless","detached"];function uh(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&jS.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function gh(e){return!e||!xn(e)?!1:uh(e)==="detached"}function tc(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"),kL(e),US(e,t);return}let n=t.features?.artifacts?.layout,o=uh(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)}US(e,t)}function nc(e,t){for(let l of jS)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=uh(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 VS(e,t){return!t||!xn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var LL=new Set(["__proto__","prototype","constructor"]),IL=new Set(["collapsed","card","panel","inline"]),qS=new Set(["markdown","component"]),RL=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,fi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xp=e=>!LL.has(e),mh=e=>typeof e=="string"&&IL.has(e),hi=e=>Object.keys(e).length>0;function Yo(e,t,n,o){e.push({path:t,code:n,message:o})}var HL="Ignored because this key is not part of the persisted preference schema.",Qp="Ignored an unsupported value.",WL="Expected collapsed, panel, or inline.",OL='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',zS={kind:"mode",message:Qp},Ea={kind:"string",message:"Expected a CSS length string."},Mr={kind:"boolean"},BL={paneWidth:Ea,paneMaxWidth:Ea,paneMinWidth:Ea,expandedPanelWidth:Ea,resizableMinWidth:Ea,resizableMaxWidth:Ea,expandLauncherPanelWhenOpen:Mr,resizable:Mr},DL={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Mr,showReasoning:Mr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Qp},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Qp},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Qp},expandable:Mr,grouped:Mr}},reasoningDisplay:{kind:"object",children:{expandable:Mr,activePreview:Mr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:zS,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:zS,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:qS,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:qS}}},filePreview:{kind:"object",children:{enabled:Mr}},layout:{kind:"object",children:BL}}}}};function KS(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Yo(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Yo(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Yo(o,n,"invalid_value",t.message);case"mode":return mh(e)?Wn(e):Yo(o,n,"invalid_value",t.message);case"modeMap":{if(!fi(e))return Yo(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:ts(a);Xp(a)&&(r?r.has(a):RL.test(d))?mh(l)?s[d]=Wn(l):Yo(o,`${n}.${a}`,"invalid_value",WL):Yo(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":OL)}return hi(s)?s:void 0}case"object":{if(t.bareMode&&mh(e))return Wn(e);if(!fi(e))return Yo(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))(!Xp(l)||!r.includes(l))&&Yo(o,s(l),"unknown_key",HL);let a={};for(let l of r){let d=t.children[l],p=KS(e[l],d,s(l),o);if(d.deprecated&&e[l]!==void 0&&Yo(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,m=a[u];a[u]=fi(m)&&fi(p)?{...m,...p}:p}return hi(a)?a:void 0}}}function fh(e){let t=[];return{preferences:(e===null?void 0:KS(e,DL,"",t))??{},issues:t}}function Ta(e){if(Array.isArray(e))return e.map(Ta);if(!fi(e))return e;let t={};for(let[n,o]of Object.entries(e))Xp(n)&&o!==void 0&&(t[n]=Ta(o));return t}function GS(e,t){let n=Ta(e);for(let[o,r]of Object.entries(t)){if(!Xp(o)||r===void 0)continue;let s=n[o];n[o]=fi(s)&&fi(r)?GS(s,r):Ta(r)}return n}function _L(e){let t={},n;for(let r of e){let s=fh(r).preferences;n=YS(n,s.artifacts?.display),t=GS(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function NL(e,t){if(t===void 0)return e===void 0?void 0:Ta(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}:{},...hi(r)?{byMediaType:r}:{}};return hi(s)?s:void 0}function YS(e,t){if(t===void 0)return e===void 0?void 0:Ta(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=NL(n.files,t.files),a={...o?{default:o}:{},...hi(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return hi(a)?a:void 0}function hh(e={},t){let n=_L(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=YS(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 oc(e){let t=e.preferences;return!t||!hi(t)?e:{...e,features:hh(e.features??{},[t])}}function FL(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 $L(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 UL(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function jL(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function yh(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 QS(e,t,n,o,r,s,a=200){let l=FL(r,200),d=jL(t,n,o,a);d=Math.max(l,d);let p=$L(s);return p!==null&&(d=Math.min(d,p)),UL(e,l,d)}var{setLoader:yN,load:VL,provide:bN,getSync:qL}=xt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var XS=VL;var JS=qL;var bh=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()}},rc=new bh;var ZS=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zL=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),eA=(e,t,n)=>{if(!ZS(e)||!ZS(t)||zL.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]=eA(e[r],t[r],s)}return o};function Jp(e,t){let n=Pd(Xs),o=Gv(e,t,n),r=wm(Yv(eA(e,t,""),n,o),o);return Am(ta(r),Xv(e,t))}var tA=()=>{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 KL=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},GL=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},sc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=KL(e),n=GL(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}},vh=e=>typeof e=="string"?e:e==null?"":String(e),yi={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:vh(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=vh(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:vh(n.text)}}},nA=e=>Array.isArray(e)?e.map(t=>String(t)):[],ic=e=>{let t=new Set(nA(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(nA(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?e.parsers.reduce((p,u)=>p||u?.({text:a,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let d={action:l,message:s.message};e.emit("action:detected",d);for(let p of e.handlers)if(p)try{let u=()=>{e.emit("action:resubmit",d)},m=p(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!m)continue;if(m.handled){let h=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:h,resubmit:m.resubmit}}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var YL=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}},QL=e=>e.map(t=>({...t,streaming:!1})),XL=e=>e.map(t=>({...t,status:"complete"})),Zp=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?YL(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?QL(n.messages):void 0,artifacts:n.artifacts?XL(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 JL=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")},oA=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 JL(e)},ZL=async(e,t)=>{let n=await oA(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await oA(`${e}\0${t}`)}`}};var rA=(e,t,n)=>{let o="",r="",s="",a=!1,l=!1,d=0,p=null,u=null,m=new Set,h=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},y=()=>{let L=h();if(!L)return p;try{return L.getItem(o)}catch{return a=!0,p}},v=(L,$)=>{if(l||L===p)return;let K=p;p=L,d+=1;let ae={previousToken:K,token:L,source:$,revision:d};for(let oe of m)oe(ae)},C=L=>{l||L.key!==null&&L.key!==o||v(L.key===null?null:L.newValue??null,"external")},x=(async()=>{let L=await ZL(e,t);o=L.storageKey,r=L.leaseKey,s=L.lockName,p=y(),!n&&typeof window<"u"&&window.addEventListener("storage",C)})(),E=L=>new Promise($=>setTimeout($,L)),H=()=>{let L=h();if(!L)return null;try{let $=L.getItem(r);if(!$)return null;let K=JSON.parse($);return typeof K?.expiresAt=="number"&&typeof K?.ownerNonce=="string"?K:null}catch{return null}},B=L=>{let $=h();if($)try{H()?.ownerNonce===L&&$.removeItem(r)}catch{}},A=L=>new Promise($=>{let K=setTimeout(ae,L);function ae(){clearTimeout(K),window.removeEventListener("storage",oe),$()}function oe(P){(P.key===null||P.key===r)&&ae()}window.addEventListener("storage",oe)}),O=async L=>{let $=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,K=Date.now()+15e3;for(;Date.now()<K;){let ae=h();if(!ae)break;let oe=Date.now(),P=H();if(P&&P.expiresAt>oe&&P.ownerNonce!==$){await A(Math.min(P.expiresAt-oe,500));continue}try{ae.setItem(r,JSON.stringify({ownerNonce:$,expiresAt:oe+1e4}))}catch{a=!0;break}if(await E(20+Math.random()*40),H()?.ownerNonce!==$){await A(500);continue}u=$;try{return await L()}finally{u=null,B($)}}return L()};return{ready:x,async get(){return await x,v(y(),"external"),p},async set(L){await x;let $=h();if($)try{$.setItem(o,L)}catch{a=!0}v(L,"local")},async clear(){await x;let L=h();if(L)try{L.removeItem(o)}catch{a=!0}v(null,"local")},revision(){return d},subscribe(L){return m.add(L),()=>{m.delete(L)}},async withFirstInitLock(L){await x;let $=globalThis.navigator?.locks;return $?.request?$.request(s,()=>L()):h()?O(L):L()},matches(L,$,K){return L===e&&$===t&&K===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",C),u&&B(u)}}};var{setLoader:LN,load:eI}=xt({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var Ch=eI;var wh=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Er=e=>Object.freeze({...e}),sA=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),iA=e=>e?Er(e):null;function aA(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,a=!1,l=null,d=[],p=()=>{for(let A of d.splice(0))try{A()}catch(O){wh("renderHistoryView cleanup",O)}},u=(A,O)=>{for(let L of t){let $=L[A];if($)try{let K=$(O);if(K)return K}catch(K){wh(A,K)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),h={header:A=>a?u("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:Er(A.identityStatus),pendingAction:iA(A.pendingAction),copy:Er(A.copy),actions:Object.freeze({close:C.close,startNewConversation:C.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>a?u("renderHistoryConversation",Object.freeze({...m(),conversation:sA(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>a?u("renderHistoryState",Object.freeze({...m(),state:Er(A.state),identityStatus:Er(A.identityStatus),copy:Er(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},y=t.flatMap(A=>(A.railSections??[]).map(O=>({...O,placement:O.placement??"above-conversations",items:[],render:L=>O.render(Object.freeze({collapsed:L,presentation:e.getPresentation(),actions:C}))}))),v=e.createView({slots:h,renderDom:!1,onModelChange:()=>B(),railSections:y}),C=Object.freeze({...v.operations,close:e.close}),x=()=>(a=!0,v.setDomRenderEnabled(!0),v.element),E=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(sA)),activeConversationId:A.activeConversationId,state:Er(A.state),pendingAction:iA(A.pendingAction),identityStatus:Er(A.identityStatus),nextCursor:A.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Er(v.copy),actions:C,defaultRenderer:x,requestRender:()=>B(),onCleanup:O=>{d.push(O)}}),H=()=>{a=!1;let A=null;for(let L of t)if(L.renderHistoryView){try{A=L.renderHistoryView(E(v.getModel()))}catch($){wh("renderHistoryView",$),A=null}if(A)break}let O=!A||A.contains(v.element);return a=O,v.setDomRenderEnabled(O),A??v.element};function B(){if(!(!s||o||r)){r=!0;try{p();let A=H();if(A===l)return;let O=l;l=A,e.onElementChanged(A,O)}finally{r=!1}}}return s=!0,B(),{view:v,get element(){return l??v.element},requestRender:B,dispose:()=>{o=!0,p()}}}var tI=null;function lA(){return tI}var nI=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),oI=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),xh=e=>oI.get(e)??"Conversation history is unavailable right now.";function rI(e){if(e instanceof po)return e;if(e instanceof je){let t=nI.get(e.code)??"unavailable";return new po(t,xh(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new po("unavailable",xh("unavailable"))}function cA(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 po("unsupported_scope",xh("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw rI(p)}},a=l=>{let d=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){d||(d=!0,l.commit(),await e.onActivationCommitted(l.session))},discard(){d||(d=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return t().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return t().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let d=await t().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(l,d){return s(d.context.scope,async()=>{let p=await t().getConversation(l,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),u=ow(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 sI=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],dA={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 Sh(e){if(!e)return dA;let t={...dA};for(let n of sI){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var iI="button:not([disabled])";function eu(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=y=>{u||(u=!0,d.removeEventListener("keydown",h,!0),d.remove(),t?.focus(),p(y))};function h(y){if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),m(!1);return}if(y.key!=="Tab")return;let v=Array.from(l.querySelectorAll(iI));if(v.length===0)return;let C=v[0],x=v[v.length-1],E=document.activeElement;y.shiftKey&&(E===C||!l.contains(E))?(y.preventDefault(),x.focus()):!y.shiftKey&&E===x&&(y.preventDefault(),C.focus())}d.addEventListener("keydown",h,!0),d.addEventListener("pointerdown",y=>{y.target===d&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),e.host.appendChild(d),s.focus()})}var Pa=require("partial-json");function aI(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function lI(e,t){if(!aI(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 tu(){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,Pa.parse)(n,Pa.STR|Pa.OBJ),s=lI(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function pA(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function nu(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Eo.get(e.component);if(!s){if(dh.includes(e.component)){Yp().catch(()=>{});let l=S("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function uA(){let e=tu();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function gA(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 ac(e){let t=gA(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 ou(e){let t=gA(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var cI=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ru(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:p=cI}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,y.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,y.appendChild(C),h.appendChild(y);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-csat",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let L=1;L<=5;L++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-star-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`${L} star${L>1?"s":""}: ${p[L-1]}`),$.title=p[L-1],$.dataset.rating=String(L),$.innerHTML=`
|
|
40
|
+
`):""},ah=(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)"},HL=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??hr.collapsedMode,s=n?.success===!1?n.error||"Tool failed":RL(e,o?.previewMaxLines??hr.previewMaxLines),a=n?Zr(t,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:ZC(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",d=t?.toolCall??{},u=a;return r==="tool-name"?u=n.name?.trim()||a:r==="tool-preview"&&s&&(u=s),l&&d.activeTextTemplate?u=Km(n,d.activeTextTemplate,u):!l&&d.completeTextTemplate&&(u=Km(n,d.completeTextTemplate,u)),n.success===!1&&(u+=" \xB7 Failed"),{summary:u,previewText:s,isActive:l}},lh=(e,t,n,o)=>{Od(e,t,{stateSet:n,previewKind:"tool",iconColor:KS(o?.toolCall??{},t.classList.contains("persona-activity-row"))})},ch=(e,t,n=new Set)=>{t=Dd(t,"tool");let o=e.toolCall,r=t?.toolCall??{},s=Id("persona-tool-bubble",e.id);if(r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),s.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow)",!o)return yr(s,e,t,"tool");let a=t?.features?.toolCallDisplay??{},l=a.expandable??hr.expandable,d=l&&n.has(e.id),{summary:u,previewText:p,isActive:m}=HL(e,t),h=Rd({expandable:l,expanded:d,bubbleType:"tool"});r.headerBackgroundColor&&(h.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(h.style.paddingLeft=r.headerPaddingX,h.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(h.style.paddingTop=r.headerPaddingY,h.style.paddingBottom=r.headerPaddingY);let y=S("div","persona-flex persona-flex-col persona-text-left"),v=S("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(v.style.color=r.headerTextColor);let C=String(o.startedAt??Date.now()),x=()=>{let k=S("span","");return k.setAttribute("data-tool-elapsed",C),k.textContent=Ll(o),k},E=r.renderCollapsedSummary?.({message:e,toolCall:o,defaultSummary:u,previewText:p,collapsedMode:a.collapsedMode??hr.collapsedMode,isActive:m,config:t??{},elapsed:Ll(o),createElapsedElement:x});typeof E=="string"&&E.trim()?(v.textContent=E,y.appendChild(v)):E instanceof HTMLElement?y.appendChild(E):(v.textContent=u,y.appendChild(v));let H=a.loadingAnimation??hr.loadingAnimation,B=r.activeTextTemplate,A=r.completeTextTemplate,O=m?B:A,L=E instanceof HTMLElement,$=(k,_)=>{v.textContent="";let I=o.name?.trim()||"tool",te=Yd(k,I),U=0;for(let pe of te){let ue=pe.styles.length>0?(()=>{let ge=S("span",pe.styles.map(Ie=>`persona-tool-text-${Ie}`).join(" "));return v.appendChild(ge),ge})():v;if(pe.isDuration&&m)ue.appendChild(x());else{let ge=pe.isDuration?Ll(o):pe.text;_?U=Aa(ue,ge,U):ue.appendChild(document.createTextNode(ge))}}};if(!L)if(m&&H!=="none"){let k=r.loadingAnimationDuration??2e3;if(v.setAttribute("data-preserve-animation","true"),H==="pulse")v.classList.add("persona-tool-loading-pulse"),v.style.setProperty("--persona-tool-anim-duration",`${k}ms`),O&&$(O,!1);else if(v.classList.add(`persona-tool-loading-${H}`),v.style.setProperty("--persona-tool-anim-duration",`${k}ms`),H==="shimmer-color"&&(r.loadingAnimationColor&&v.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&v.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),O)$(O,!0);else{let _=v.textContent||u;v.textContent="",Aa(v,_,0)}}else O&&$(O,!1);let K=KS(r,Zr(t,"tool")==="row"),ae=na(h,y,{expandable:l,expanded:d,iconColor:K,metaGap:!0}),oe=Hd({bubble:s,previewKind:"tool",expanded:d,isActive:m,previewText:p,activePreview:a.activePreview,activeMinHeight:a.activeMinHeight,renderPreview:()=>r.renderCollapsedPreview?.({message:e,toolCall:o,defaultPreview:p,isActive:m,config:t??{}})});if(!l)return s.append(h,oe),yr(s,e,t,"tool");let P=S("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(P.style.display=d?"":"none",r.contentBackgroundColor&&(P.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(P.style.color=r.contentTextColor),r.contentPaddingX&&(P.style.paddingLeft=r.contentPaddingX,P.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(P.style.paddingTop=r.contentPaddingY,P.style.paddingBottom=r.contentPaddingY),t.future?.v5Defaults===!0)qS(P,e,t);else{if(o.name){let k=S("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?k.style.color=r.contentTextColor:r.headerTextColor&&(k.style.color=r.headerTextColor),k.textContent=o.name,P.appendChild(k)}if(o.args!==void 0){let k=S("div","persona-space-y-1"),_=S("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Arguments";let I=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",ah(I,r),I.textContent=ca(o.args),k.append(_,I),P.appendChild(k)}if(o.chunks&&o.chunks.length){let k=S("div","persona-space-y-1"),_=S("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Activity";let I=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",ah(I,r),I.textContent=o.chunks.join(""),k.append(_,I),P.appendChild(k)}if(o.success===!1&&P.appendChild(Y("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":""}})),o.status==="complete"&&o.result!==void 0){let k=S("div","persona-space-y-1"),_=S("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(_.style.color=r.labelTextColor),_.textContent="Result";let I=S("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",ah(I,r),I.textContent=ca(o.result),k.append(_,I),P.appendChild(k)}if(o.status==="complete"&&typeof o.duration=="number"){let k=S("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(k.style.color=r.contentTextColor),k.textContent=`Duration: ${o.duration}ms`,P.appendChild(k)}}return Wd({expanded:d,header:h,toggleIcon:ae,content:P,collapsedPreview:oe,iconColor:K}),s.append(h,oe,P),yr(s,e,t,"tool")};var{setLoader:mN,load:WL,provide:fN,getSync:OL}=xt({fallbackImport:()=>import("@runtypelabs/persona/approval-ui")});var GS=WL;var YS=OL;var{setLoader:bN,load:BL}=xt({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var dh=BL;var ph=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)})}},Eo=new ph;var uh=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:MN,load:DL,provide:EN,getSync:_L}=xt({fallbackImport:()=>import("@runtypelabs/persona/artifacts-ui")}),Ma=null,Gp=new Set,QS=e=>{if(Ma)return Ma;Ma=e,e.initArtifactsUi({componentRegistry:Eo});for(let o of uh)Eo.has(o)||Eo.register(o,o==="PersonaArtifactCard"?e.PersonaArtifactCard:e.PersonaArtifactInline,{bubbleChrome:!1});let t=jo();t?e.__provideMarkdownParsers(t):Ji(()=>{let o=jo();o&&e.__provideMarkdownParsers(o)}),e.__setIconsExtraLoader(()=>Ed());let n=[...Gp];Gp.clear();for(let o of n)try{o()}catch{}return e};var Yp=()=>DL().then(QS);var Ar=()=>{if(Ma)return Ma;let e=_L();return e?QS(e):null},gh=e=>Ma?()=>{}:(Gp.add(e),()=>{Gp.delete(e)});function Sn(e){return e?.features?.artifacts?.enabled===!0}function XS(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"),!Sn(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 NL(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 JS=["panel","seamless","detached"];function mh(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&JS.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function fh(e){return!e||!Sn(e)?!1:mh(e)==="detached"}function tc(e,t){if(!Sn(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"),NL(e),XS(e,t);return}let n=t.features?.artifacts?.layout,o=mh(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 u=l?.trim();u?e.style.setProperty(d,u):e.style.removeProperty(d)}XS(e,t)}function nc(e,t){for(let l of JS)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"),!Sn(t))return;let n=t.features?.artifacts?.layout,o=mh(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 ZS(e,t){return!t||!Sn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var FL=new Set(["__proto__","prototype","constructor"]),$L=new Set(["collapsed","card","panel","inline"]),eA=new Set(["markdown","component"]),UL=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,fi=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xp=e=>!FL.has(e),hh=e=>typeof e=="string"&&$L.has(e),hi=e=>Object.keys(e).length>0;function Yo(e,t,n,o){e.push({path:t,code:n,message:o})}var jL="Ignored because this key is not part of the persisted preference schema.",Qp="Ignored an unsupported value.",VL="Expected collapsed, panel, or inline.",qL='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',tA={kind:"mode",message:Qp},Ea={kind:"string",message:"Expected a CSS length string."},Mr={kind:"boolean"},zL={paneWidth:Ea,paneMaxWidth:Ea,paneMinWidth:Ea,expandedPanelWidth:Ea,resizableMinWidth:Ea,resizableMaxWidth:Ea,expandLauncherPanelWhenOpen:Mr,resizable:Mr},KL={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Mr,showReasoning:Mr,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Qp},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Qp},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Qp},expandable:Mr,grouped:Mr}},reasoningDisplay:{kind:"object",children:{expandable:Mr,activePreview:Mr}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:tA,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:tA,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:eA,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:eA}}},filePreview:{kind:"object",children:{enabled:Mr}},layout:{kind:"object",children:zL}}}}};function nA(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Yo(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Yo(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Yo(o,n,"invalid_value",t.message);case"mode":return hh(e)?Wn(e):Yo(o,n,"invalid_value",t.message);case"modeMap":{if(!fi(e))return Yo(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:ts(a);Xp(a)&&(r?r.has(a):UL.test(d))?hh(l)?s[d]=Wn(l):Yo(o,`${n}.${a}`,"invalid_value",VL):Yo(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":qL)}return hi(s)?s:void 0}case"object":{if(t.bareMode&&hh(e))return Wn(e);if(!fi(e))return Yo(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))(!Xp(l)||!r.includes(l))&&Yo(o,s(l),"unknown_key",jL);let a={};for(let l of r){let d=t.children[l],u=nA(e[l],d,s(l),o);if(d.deprecated&&e[l]!==void 0&&Yo(o,s(l),"deprecated_key",d.deprecated),u===void 0)continue;let p=d.alias??l,m=a[p];a[p]=fi(m)&&fi(u)?{...m,...u}:u}return hi(a)?a:void 0}}}function yh(e){let t=[];return{preferences:(e===null?void 0:nA(e,KL,"",t))??{},issues:t}}function Ta(e){if(Array.isArray(e))return e.map(Ta);if(!fi(e))return e;let t={};for(let[n,o]of Object.entries(e))Xp(n)&&o!==void 0&&(t[n]=Ta(o));return t}function oA(e,t){let n=Ta(e);for(let[o,r]of Object.entries(t)){if(!Xp(o)||r===void 0)continue;let s=n[o];n[o]=fi(s)&&fi(r)?oA(s,r):Ta(r)}return n}function GL(e){let t={},n;for(let r of e){let s=yh(r).preferences;n=rA(n,s.artifacts?.display),t=oA(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function YL(e,t){if(t===void 0)return e===void 0?void 0:Ta(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}:{},...hi(r)?{byMediaType:r}:{}};return hi(s)?s:void 0}function rA(e,t){if(t===void 0)return e===void 0?void 0:Ta(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=YL(n.files,t.files),a={...o?{default:o}:{},...hi(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return hi(a)?a:void 0}function bh(e={},t){let n=GL(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=rA(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 oc(e){let t=e.preferences;return!t||!hi(t)?e:{...e,features:bh(e.features??{},[t])}}function QL(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 XL(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 JL(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ZL(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function vh(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 sA(e,t,n,o,r,s,a=200){let l=QL(r,200),d=ZL(t,n,o,a);d=Math.max(l,d);let u=XL(s);return u!==null&&(d=Math.min(d,u)),JL(e,l,d)}var{setLoader:HN,load:eI,provide:WN,getSync:tI}=xt({fallbackImport:()=>import("@runtypelabs/persona/forms-ui")});var iA=eI;var aA=tI;var Ch=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()}},rc=new Ch;var lA=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nI=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),cA=(e,t,n)=>{if(!lA(e)||!lA(t)||nI.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]=cA(e[r],t[r],s)}return o};function Jp(e,t){let n=Pd(Xs),o=oC(e,t,n),r=Sm(rC(cA(e,t,""),n,o),o);return Em(ta(r),iC(e,t))}var dA=()=>{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 oI=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},rI=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},sc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=oI(e),n=rI(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}},wh=e=>typeof e=="string"?e:e==null?"":String(e),yi={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:wh(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=wh(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:wh(n.text)}}},pA=e=>Array.isArray(e)?e.map(t=>String(t)):[],ic=e=>{let t=new Set(pA(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(pA(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((u,p)=>u||p?.({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 u of e.handlers)if(u)try{let p=()=>{e.emit("action:resubmit",d)},m=u(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!m)continue;if(m.handled){let h=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:h,resubmit:m.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var sI=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}},iI=e=>e.map(t=>({...t,streaming:!1})),aI=e=>e.map(t=>({...t,status:"complete"})),Zp=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?sI(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?iI(n.messages):void 0,artifacts:n.artifacts?aI(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 lI=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")},uA=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 lI(e)},cI=async(e,t)=>{let n=await uA(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await uA(`${e}\0${t}`)}`}};var gA=(e,t,n)=>{let o="",r="",s="",a=!1,l=!1,d=0,u=null,p=null,m=new Set,h=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},y=()=>{let L=h();if(!L)return u;try{return L.getItem(o)}catch{return a=!0,u}},v=(L,$)=>{if(l||L===u)return;let K=u;u=L,d+=1;let ae={previousToken:K,token:L,source:$,revision:d};for(let oe of m)oe(ae)},C=L=>{l||L.key!==null&&L.key!==o||v(L.key===null?null:L.newValue??null,"external")},x=(async()=>{let L=await cI(e,t);o=L.storageKey,r=L.leaseKey,s=L.lockName,u=y(),!n&&typeof window<"u"&&window.addEventListener("storage",C)})(),E=L=>new Promise($=>setTimeout($,L)),H=()=>{let L=h();if(!L)return null;try{let $=L.getItem(r);if(!$)return null;let K=JSON.parse($);return typeof K?.expiresAt=="number"&&typeof K?.ownerNonce=="string"?K:null}catch{return null}},B=L=>{let $=h();if($)try{H()?.ownerNonce===L&&$.removeItem(r)}catch{}},A=L=>new Promise($=>{let K=setTimeout(ae,L);function ae(){clearTimeout(K),window.removeEventListener("storage",oe),$()}function oe(P){(P.key===null||P.key===r)&&ae()}window.addEventListener("storage",oe)}),O=async L=>{let $=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,K=Date.now()+15e3;for(;Date.now()<K;){let ae=h();if(!ae)break;let oe=Date.now(),P=H();if(P&&P.expiresAt>oe&&P.ownerNonce!==$){await A(Math.min(P.expiresAt-oe,500));continue}try{ae.setItem(r,JSON.stringify({ownerNonce:$,expiresAt:oe+1e4}))}catch{a=!0;break}if(await E(20+Math.random()*40),H()?.ownerNonce!==$){await A(500);continue}p=$;try{return await L()}finally{p=null,B($)}}return L()};return{ready:x,async get(){return await x,v(y(),"external"),u},async set(L){await x;let $=h();if($)try{$.setItem(o,L)}catch{a=!0}v(L,"local")},async clear(){await x;let L=h();if(L)try{L.removeItem(o)}catch{a=!0}v(null,"local")},revision(){return d},subscribe(L){return m.add(L),()=>{m.delete(L)}},async withFirstInitLock(L){await x;let $=globalThis.navigator?.locks;return $?.request?$.request(s,()=>L()):h()?O(L):L()},matches(L,$,K){return L===e&&$===t&&K===n},destroy(){l=!0,m.clear(),typeof window<"u"&&window.removeEventListener("storage",C),p&&B(p)}}};var{setLoader:zN,load:dI}=xt({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var xh=dI;var Sh=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Er=e=>Object.freeze({...e}),mA=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),fA=e=>e?Er(e):null;function hA(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,a=!1,l=null,d=[],u=()=>{for(let A of d.splice(0))try{A()}catch(O){Sh("renderHistoryView cleanup",O)}},p=(A,O)=>{for(let L of t){let $=L[A];if($)try{let K=$(O);if(K)return K}catch(K){Sh(A,K)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),h={header:A=>a?p("renderHistoryHeader",Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:Er(A.identityStatus),pendingAction:fA(A.pendingAction),copy:Er(A.copy),actions:Object.freeze({close:C.close,startNewConversation:C.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>a?p("renderHistoryConversation",Object.freeze({...m(),conversation:mA(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>a?p("renderHistoryState",Object.freeze({...m(),state:Er(A.state),identityStatus:Er(A.identityStatus),copy:Er(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},y=t.flatMap(A=>(A.railSections??[]).map(O=>({...O,placement:O.placement??"above-conversations",items:[],render:L=>O.render(Object.freeze({collapsed:L,presentation:e.getPresentation(),actions:C}))}))),v=e.createView({slots:h,renderDom:!1,onModelChange:()=>B(),railSections:y}),C=Object.freeze({...v.operations,close:e.close}),x=()=>(a=!0,v.setDomRenderEnabled(!0),v.element),E=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(mA)),activeConversationId:A.activeConversationId,state:Er(A.state),pendingAction:fA(A.pendingAction),identityStatus:Er(A.identityStatus),nextCursor:A.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Er(v.copy),actions:C,defaultRenderer:x,requestRender:()=>B(),onCleanup:O=>{d.push(O)}}),H=()=>{a=!1;let A=null;for(let L of t)if(L.renderHistoryView){try{A=L.renderHistoryView(E(v.getModel()))}catch($){Sh("renderHistoryView",$),A=null}if(A)break}let O=!A||A.contains(v.element);return a=O,v.setDomRenderEnabled(O),A??v.element};function B(){if(!(!s||o||r)){r=!0;try{u();let A=H();if(A===l)return;let O=l;l=A,e.onElementChanged(A,O)}finally{r=!1}}}return s=!0,B(),{view:v,get element(){return l??v.element},requestRender:B,dispose:()=>{o=!0,u()}}}var pI=null;function yA(){return pI}var uI=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"]]),gI=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."]]),Ah=e=>gI.get(e)??"Conversation history is unavailable right now.";function mI(e){if(e instanceof po)return e;if(e instanceof je){let t=uI.get(e.code)??"unavailable";return new po(t,Ah(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new po("unavailable",Ah("unavailable"))}function bA(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 po("unsupported_scope",Ah("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(u){throw mI(u)}},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 u=await t().getConversation(l,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),p=uw(u.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:u.summary,messages:Hl([],p),conversationRevision:u.conversationRevision??"",nextCursor:u.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 fI=["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"],vA={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 Mh(e){if(!e)return vA;let t={...vA};for(let n of fI){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var hI="button:not([disabled])";function eu(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 u of[s,a])u.style.minHeight="44px",u.style.minWidth="88px",u.style.padding="0 16px",u.style.borderRadius="var(--persona-radius-md, 0.5rem)",u.style.cursor="pointer",u.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(u=>{let p=!1,m=y=>{p||(p=!0,d.removeEventListener("keydown",h,!0),d.remove(),t?.focus(),u(y))};function h(y){if(y.key==="Escape"){y.preventDefault(),y.stopPropagation(),m(!1);return}if(y.key!=="Tab")return;let v=Array.from(l.querySelectorAll(hI));if(v.length===0)return;let C=v[0],x=v[v.length-1],E=document.activeElement;y.shiftKey&&(E===C||!l.contains(E))?(y.preventDefault(),x.focus()):!y.shiftKey&&E===x&&(y.preventDefault(),C.focus())}d.addEventListener("keydown",h,!0),d.addEventListener("pointerdown",y=>{y.target===d&&m(!1)}),s.addEventListener("click",()=>m(!1)),a.addEventListener("click",()=>m(!0)),e.host.appendChild(d),s.focus()})}var Pa=require("partial-json");function yI(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function bI(e,t){if(!yI(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 tu(){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,Pa.parse)(n,Pa.STR|Pa.OBJ),s=bI(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function CA(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function nu(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Eo.get(e.component);if(!s){if(uh.includes(e.component)){Yp().catch(()=>{});let l=S("div","persona-w-full");return l.setAttribute("data-persona-artifact-pending","true"),l}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function wA(){let e=tu();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function xA(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 ac(e){let t=xA(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 ou(e){let t=xA(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 vI=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ru(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:u=vI}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let m=null,h=document.createElement("div");h.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,y.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,y.appendChild(C),h.appendChild(y);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-csat",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let L=1;L<=5;L++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-star-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`${L} star${L>1?"s":""}: ${u[L-1]}`),$.title=u[L-1],$.dataset.rating=String(L),$.innerHTML=`
|
|
41
41
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
42
42
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
43
43
|
</svg>
|
|
44
|
-
`,$.addEventListener("click",()=>{m=L,E.forEach((K,ae)=>{let oe=ae<L;K.classList.toggle("selected",oe),K.setAttribute("aria-checked",ae===L-1?"true":"false")})}),E.push($),x.appendChild($)}h.appendChild(x);let H=null;if(d){let L=document.createElement("div");L.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=s,H.rows=3,H.setAttribute("aria-label","Additional comments"),L.appendChild(H),h.appendChild(L)}let B=document.createElement("div");B.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=l,A.addEventListener("click",()=>{n?.(),u.remove()});let O=document.createElement("button");return O.type="button",O.className="persona-feedback-btn persona-feedback-btn-submit",O.textContent=a,O.addEventListener("click",async()=>{if(m===null){x.classList.add("persona-feedback-shake"),setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let L=H?.value.trim()||void 0;await t(m,L),u.remove()}catch(L){O.disabled=!1,O.textContent=a,console.error("[CSAT Feedback] Failed to submit:",L)}}),B.appendChild(A),B.appendChild(O),h.appendChild(B),u.appendChild(h),u}function su(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:p="Not likely",highLabel:u="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let h=null,y=document.createElement("div");y.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,v.appendChild(C);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,v.appendChild(x),y.appendChild(v);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let H=document.createElement("div");H.className="persona-feedback-labels";let B=document.createElement("span");B.className="persona-feedback-label-low",B.textContent=p;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=u,H.appendChild(B),H.appendChild(A);let O=document.createElement("div");O.className="persona-feedback-numbers";let L=[];for(let P=0;P<=10;P++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-number-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`Rating ${P} out of 10`),k.textContent=String(P),k.dataset.rating=String(P),P<=6?k.classList.add("persona-feedback-detractor"):P<=8?k.classList.add("persona-feedback-passive"):k.classList.add("persona-feedback-promoter"),k.addEventListener("click",()=>{h=P,L.forEach((_,I)=>{_.classList.toggle("selected",I===P),_.setAttribute("aria-checked",I===P?"true":"false")})}),L.push(k),O.appendChild(k)}E.appendChild(H),E.appendChild(O),y.appendChild(E);let $=null;if(d){let P=document.createElement("div");P.className="persona-feedback-comment-container",$=document.createElement("textarea"),$.className="persona-feedback-comment",$.placeholder=s,$.rows=3,$.setAttribute("aria-label","Additional comments"),P.appendChild($),y.appendChild(P)}let K=document.createElement("div");K.className="persona-feedback-actions";let ae=document.createElement("button");ae.type="button",ae.className="persona-feedback-btn persona-feedback-btn-skip",ae.textContent=l,ae.addEventListener("click",()=>{n?.(),m.remove()});let oe=document.createElement("button");return oe.type="button",oe.className="persona-feedback-btn persona-feedback-btn-submit",oe.textContent=a,oe.addEventListener("click",async()=>{if(h===null){O.classList.add("persona-feedback-shake"),setTimeout(()=>O.classList.remove("persona-feedback-shake"),500);return}oe.disabled=!0,oe.textContent="Submitting...";try{let P=$?.value.trim()||void 0;await t(h,P),m.remove()}catch(P){oe.disabled=!1,oe.textContent=a,console.error("[NPS Feedback] Failed to submit:",P)}}),K.appendChild(ae),K.appendChild(oe),y.appendChild(K),m.appendChild(y),m}var ka="persona-chat-history",uI=30*1e3,gI=641,La="data-persona-composer-reason",mI={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function fI(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=mI[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function iu(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 hI(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 yI(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ah=e=>!e||typeof e!="object"?{}:{...e},mA=e=>e.map(t=>({...t,streaming:!1})),fA=(e,t,n)=>{let o=e?.markdown?Sl(e.markdown):null,r=_d(e?.sanitize);e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function.");let s=!1,a=l=>{let d=l.text??"",p=l.message.rawContent??null;if(t){let h=t.process({text:d,raw:p??d,message:l.message,streaming:l.streaming});h!==null&&(d=h.text,h.persist||(l.message.__skipPersist=!0),h.resubmit&&!l.streaming&&n&&n())}let u=jo()!==null,m;if(e?.postprocessMessage){let h=e.postprocessMessage({...l,text:d,raw:p??l.text??""});m=r?r(h):h}else if(o){let h=l.streaming?mC(d):d,y=o(h);m=r&&u?r(y):y}else m=br(d);return m};return l=>{try{return a(l)}catch(d){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",d)),br(l.text??"")}}};function hA(e){let t=S("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=le(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=S("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var bI=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},vI=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:bI(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),au=(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=ta(t),r=new Set,s=new Set,a=nC((i,c)=>{$t.delete(i);let g=Array.from(be.querySelectorAll("[data-message-id]")).find(f=>f.dataset.messageId===i);g&&(c==="tool"?ih(i,g,r,o):nh(i,g,s))}),l=new Map,d=()=>{Ww({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};d();let p=o.features;o=oc(o);let u=rc.getForInstance(o.plugins),m=Dx(e),h=[],y=!1,v=WS(()=>o),C=null,x=null,E=null,H=!1,B=null,A=i=>{C=i,i.initApprovalUi({webMcpToolTitle:oa});let c=i.createBuiltInApprovalPlugin(l);x=c.plugin,E=c.teardown},O=()=>{if(C)return C;let i=FS();return i?(A(i),i):(NS().then(c=>{H||C||(A(c),B?.())}).catch(()=>{}),null)},L=!1,$=!1,K=null,ae=(i,c,g,f)=>{if(!i.querySelector("[data-tv-form]"))return;let b=JS();if(b){b.enhanceWithForms(i,c,g,f);return}XS().then(()=>{L||$||!K||($=!0,K())}).catch(()=>{})};o.components&&Eo.registerAll(o.components);let oe=tA(),k=o.persistState===!1?null:o.storageAdapter??Zp(),_=!!o.clientToken&&typeof o.reconnectStream!="function",I={},te=null,U,pe=new Promise(i=>{U=i}),ue,ge=!1,Ie=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&&(ge=!0),g}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(k?.load)try{let i=k.load();if(i&&typeof i.then=="function")te=i.then(c=>Ie(c??{messages:[],metadata:{}}));else{let g=Ie(i??{messages:[],metadata:{}});g.metadata&&(I=Ah(g.metadata)),g.messages?.length&&(o={...o,initialMessages:g.messages}),g.artifacts?.length&&(o={...o,initialArtifacts:g.artifacts,initialSelectedArtifactId:g.selectedArtifactId??null}),ue=g.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=Ie({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}te||U();let Se=()=>I,ye=i=>{I=i({...I})??{},Ii()},dt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[sc],it=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[yi.message,yi.messageAndClick],Ce=ic({parsers:dt,handlers:it,getSessionMetadata:Se,updateSessionMetadata:ye,emit:oe.emit,documentRef:typeof document<"u"?document:null});Ce.syncFromMetadata();let D=o.launcher?.enabled??!0,Ne=o.launcher?.autoExpand??!1,Fe=o.autoFocusInput??!1,Et=Ne,Gt=D,jt=o.layout?.header?.layout,ke=!1,we=()=>us(o),Be=()=>D||we(),Ee=we()?!1:D?Ne:!0,Sn=!1,j=null,M=()=>{Sn=!0,j&&clearTimeout(j),j=setTimeout(()=>{Sn&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Sn=!1)},1e4)},N=fA(o,Ce,M),z=o.features?.showReasoning??!0,J=o.features?.showToolCalls??!0,X=o.features?.showEventStreamToggle??!1,fe=o.features?.scrollToBottom??{},Ae=o.features?.scrollBehavior??{},Me=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Nt=`${Me()}event-stream`,et=null,ze=o.features?.eventStream?.maxEvents??2e3,ft=null,Zt=null,It=null,gn=!1,ht=null,go=!1,kr=null,Au=0,jh=(i,c)=>{ft?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},Mu=(i,c)=>{Zt?.processEvent(i,c),ft?jh(i,c):It&&(It.length>=ze&&It.shift(),It.push({type:i,payload:c}))},pc=()=>{ft||!X||(It??(It=[]),lh().then(i=>{if(gn||ft||!X)return;et=new i.EventStreamStore(Nt),ft=new i.EventStreamBuffer(ze,et),Zt=Zt??new i.ThroughputTracker,et.open().then(()=>ft?.restore()).catch(g=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",g)});let c=It??[];It=null;for(let g of c)Zt?.processEvent(g.type,g.payload),jh(g.type,g.payload)}).catch(()=>{}))};X&&pc();let Rt=!1,Vt=null,Eu=()=>{},Xo=()=>{},Vh=()=>{},qh=()=>{},Tu=()=>{},dM=()=>go||Rt&&Vt==="panel",vi={onCopy:i=>{oe.emit("message:copy",i),T?.isClientTokenMode()&&T.submitMessageFeedback(i.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{oe.emit("message:feedback",i),T?.isClientTokenMode()&&T.submitMessageFeedback(i.messageId,i.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(i)}},PR=o.statusIndicator??{},Pu=(i,c=o.statusIndicator??{})=>i==="idle"?c.idleText??_t.idle:i==="connecting"?c.connectingText??_t.connecting:i==="connected"?c.connectedText??_t.connected:i==="error"?c.errorText??_t.error:i==="paused"?c.pausedText??_t.paused:i==="resuming"?c.resumingText??_t.resuming:_t[i];function Ra(i,c,g,f){if(!we()&&(g.mode==="transient"||i.classList.contains("persona-mb-2"))&&(Pm(i,An,g),ei(i,g,f)),!i.hasAttribute(La))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 _n=HS({config:o,showClose:Be()}),{wrapper:Qe,panel:xe,pillRoot:en}=_n.shell,$e=_n.panelElements,{container:de,body:ne,messagesWrapper:be,starterSuggestions:ku,transcriptSuggestions:Ha,suggestions:Lr,textarea:ce,sendButton:Te,composerForm:An,statusText:Je,welcomeHost:tn,welcomeIconHolder:pM,greetingHost:Nn,introKicker:uM,introTitle:gM,introSubtitle:mM,closeButton:qe,iconHolder:Ht,headerTitle:Ir,headerSubtitle:fs,header:Pe,footer:He,actionsRow:fM}=$e,Lu=$e.leftActions,uc=$e.rightActions,Po=$e.sendButtonWrapper,zh=$e.setSendButtonMode,ie=$e.micButton,Fn=$e.micButtonWrapper,kt=$e.attachmentButton,Mn=$e.attachmentButtonWrapper,St=$e.attachmentInput,En=$e.attachmentPreviewsContainer;de.classList.add("persona-relative"),ne.classList.add("persona-relative");let hM=12,Wa=()=>fe.label??"",yM=()=>fe.iconName??"arrow-down",bM=()=>fe.enabled!==!1,$n=()=>Ae.mode??"anchor-top",Rr=()=>$n()==="follow"||$n()==="anchor-top"&&qa,Oa=()=>Ae.anchorTopOffset??16,vM=()=>Ae.restorePosition??"bottom",Kh=()=>Ae.pauseOnInteraction===!0,Gh=()=>Ae.showActivityWhilePinned!==!1,Yh=()=>Ae.announce===!0,Iu=()=>Ae.scrollbar??"on-scroll",qt=S("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");qt.type="button",qt.style.display="none",qt.setAttribute("data-persona-scroll-to-bottom","true");let Ba=S("span","persona-flex persona-items-center"),Ru=S("span",""),hs=S("span","");hs.setAttribute("data-persona-scroll-to-bottom-count",""),hs.style.display="none",qt.append(Ba,Ru,hs),de.appendChild(qt);let Qn=S("div","persona-stream-anchor-spacer");Qn.setAttribute("aria-hidden","true"),Qn.setAttribute("data-persona-anchor-spacer",""),Qn.style.flexShrink="0",Qn.style.pointerEvents="none",Qn.style.height="0px",Qn.style.display="none",ne.appendChild(Qn);let Jo=S("div","persona-sr-only");Jo.setAttribute("aria-live","polite"),Jo.setAttribute("aria-atomic","true"),Jo.setAttribute("role","status"),Jo.setAttribute("data-persona-live-region",""),Object.assign(Jo.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),de.appendChild(Jo);let Da=null,gc=null,mc=i=>{!Yh()||!i||(gc=i,Da===null&&(Da=setTimeout(()=>{Da=null,gc&&Yh()&&(Jo.textContent=gc),gc=null},400)))},_a=()=>{let i=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&i.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(D||Ct(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!Ct(o)},ys=()=>Sa(o,_a()),fc="empty",hc=0,Hu=()=>hc||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,bs=()=>{let c=He.style.display==="none"?0:He.offsetHeight;qt.style.bottom=`${c+Hu()+hM}px`};bs();let Wu=()=>{Ai||(He.style.marginBottom=hc>0?`${hc}px`:"")},yc=()=>{let i=Ef(o,we()),c=ys();e.setAttribute("data-persona-welcome-fullscreen",String(_a())),e.setAttribute("data-persona-welcome-layout",c.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom");let f=He.style.display==="none"?0:He.offsetHeight,b=c.anchor==="center"&&fc==="empty"?$l(c.anchorComposerTop)??$l("44%"):null,w=b!==null&&c.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,W=w?getComputedStyle(ne):null,V=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,F=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,q=Math.max(0,(parseFloat(W?.paddingBottom??"")||0)-(i==="overlay"?V+F:0)),Q=w?ne.getBoundingClientRect().top-de.getBoundingClientRect().top:0,se=!w||tn.hidden?0:(tn.querySelector("[data-persona-welcome-plugin]")??tn).offsetHeight,me=b===null||we()?0:w?Math.max(0,Math.round((de.clientHeight-Q-se-q-f)/2)):Wx({columnHeight:de.clientHeight,footerHeight:f,fraction:b});e.style.setProperty("--persona-composer-overlay-height",`${f}px`),e.style.setProperty("--persona-composer-lift",`${i==="overlay"?me:0}px`),hc=i==="block"?me:0,Wu(),bs()},Qh=()=>{let i=!!Wa();qt.setAttribute("aria-label",Wa()||"Jump to latest"),qt.title=Wa(),qt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Ba.innerHTML="";let c=le(yM(),"14px","currentColor",2);c?(Ba.appendChild(c),Ba.style.display=""):Ba.style.display="none",Ru.textContent=Wa(),Ru.style.display=i?"":"none"};Qh();let rt=null,Ft=null,ve=Pw(),CM=i=>{try{de.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};ve.subscribe(CM);let ko=()=>{ve.setText(ce?.value??"")},vs=()=>{ve.setMentionRefs(Ft?.getMentionRefs()??[])},wM=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}),Xh=i=>{let c=Object.freeze(i.map(wM));ve.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(g){console.error("[AgentWidget] attachments.onChange failed:",g)}cg()};ve.setSelectedModelId(o.composer?.selectedModelId);let Na=()=>o.composer?.modes??[],Ci=()=>Zw(Na(),o.composer?.modeGroups);{let i=xp(o.composer?.defaultActiveModeIds??[],Na());i.length&&ve.setActiveModeIds(i)}function Jh(i){if(ve.getState().selectedModelId!==i){ve.setSelectedModelId(i),Hr?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function bc(i){ve.setActiveModeIds(i),Zo?.render(i,Ci()),wi.forEach(c=>c.repaint()),Io?.resolve(),jc(),mo()}function Ou(i){bc(ex(ve.getState().activeModeIds,i,Na(),o.composer?.modeGroups))}let Hr=null,Bu=null,Zo=null,wi=new Map,Wr=null;function Lo(i){ve.setQuote(i),Wr?.render(ve.getState().quote),mo(),jy()}let Zh=!1;function Du(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!Zh&&o.debug===!0&&(Zh=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Or=null;function xi(i){ve.setPendingSubmission(i),Or?.render(ve.getState().pendingSubmission),mo()}let xM=i=>{let c=wi.get(i);if(c)return c;let g=ox({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===i),getModes:()=>Na().filter(f=>f.groupId===i),getActiveIds:()=>ve.getState().activeModeIds,onSelect:f=>Ou(f)});return wi.set(i,g),g},SM=()=>{let i=[],c=ve.getState().activeModeIds,g=new Set;if(Na().forEach((f,b)=>{if(wp(f.groupId,o.composer?.modeGroups)){let w=f.groupId;if(g.has(w))return;g.add(w);let W=xM(w);W.action.order=vf(b),W.action.label=o.composer?.modeGroups?.find(V=>V.id===w)?.label??w,i.push(W.action);return}i.push({id:Xw(f.id),kind:"button",placement:"start",order:vf(b),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:c.includes(f.id),onSelect:()=>Ou(f.id)})}),o.composer?.models?.length&&!u.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!Hr||Bu!==f)&&(Bu=f,Hr=Yw({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>ve.getState().selectedModelId,onSelect:b=>Jh(b),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Hr.action)}return i},_u=null,ey=u.find(i=>i.renderHeader);if(ey?.renderHeader){let i=ey.renderHeader({config:o,defaultRenderer:()=>{let c=Sr({config:o,showClose:Be()});return di(de,c,o),c.header},onClose:()=>yt(!1,"user")});if(i){let c=Pe;c&&(c.replaceWith(i),Pe=i,_n.header.element=i)}}let ty=()=>{ht&&(ne.style.display="none",He.parentNode?.insertBefore(ht.element,He),ht.update())},Nu=()=>{if(!ft){pc();return}if(go=!0,ht?ty():lh().then(c=>{ht||!go||!ft||(ht=c.createEventStreamView({buffer:ft,getFullHistory:()=>ft.getAllFromStore(),onClose:()=>Si(),config:o,plugins:u,getThroughput:()=>Zt?.getMetric()??{status:"idle"},renderIconByName:le}),ty())}).catch(()=>{Si()}),at){at.style.boxShadow=`inset 0 0 0 1.5px ${Cn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(g=>g&&at.classList.add(g))}let i=()=>{if(!go)return;let c=Date.now();c-Au>=200&&(ht?.update(),Au=c),kr=requestAnimationFrame(i)};Au=0,kr=requestAnimationFrame(i),Qt(),oe.emit("eventStream:opened",{timestamp:Date.now()})},Si=()=>{if(go){if(go=!1,ht&&ht.element.remove(),ne.style.display="",at){at.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&at.classList.remove(c))}kr!==null&&(cancelAnimationFrame(kr),kr=null),Qt(),oe.emit("eventStream:closed",{timestamp:Date.now()})}},at=null;if(X){let i=o.features?.eventStream?.classNames,c="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");at=S("button",c),at.style.width="28px",at.style.height="28px",at.style.color=Cn.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let g=Mt(Tr.Activity,"18px","currentColor",1.5);g&&at.appendChild(g);let f=$e.clearChatButtonWrapper,b=$e.closeButtonWrapper,w=f||b;w&&w.parentNode===Pe?Pe.insertBefore(at,w):Pe.appendChild(at),at.addEventListener("click",()=>{go?Si():Nu()})}let ny=i=>{let c=o.attachments;if(!c?.enabled)return;let g=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!g){g=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),g.setAttribute("data-persona-composer-attachment-previews",""),g.style.display="none";let b=i.querySelector("[data-persona-composer-form]");b?.parentNode?b.parentNode.insertBefore(g,b):i.insertBefore(g,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let b=S("input");b.type="file",b.setAttribute("data-persona-composer-attachment-input",""),b.accept=(c.allowedTypes??xr).join(","),b.multiple=(c.maxFiles??4)>1,b.style.display="none",b.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(b)}},Ai=!1,oy=i=>{let c=u.find(b=>b.renderComposer);if(!c?.renderComposer)return null;let g=o.composer,f=y?T.isStreaming():!1;return c.renderComposer({config:o,defaultRenderer:i,requestRender:()=>wv(),storage:v(c.id),onSubmit:b=>{!T||T.isStreaming()||hd(b.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{Oo()||St?.click()},models:g?.models,selectedModelId:ve.getState().selectedModelId??g?.selectedModelId,onModelChange:b=>Jh(b),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{_u?.()}:void 0})},ry=oy(()=>ui({config:o}).footer);ry&&(_n.replaceComposer(ry),He=_n.composer.footer,Ai=!0);let tt=null,AM=i=>{An=i.form,ce=i.input,Po=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Te=i.sendButton),i.micButton&&(ie=i.micButton,Fn=i.micButton.parentElement),i.found.status&&(Je=i.found.status),i.found.suggestions&&(Lr=i.found.suggestions),i.attachmentButton&&(kt=i.attachmentButton,Mn=i.attachmentButton.parentElement),St=i.attachmentInput??null,En=i.attachmentPreviews??null,i.found.actionsRow&&(fM=i.found.actionsRow),Lu=i.found.actionsStart,uc=i.found.actionsEnd};function Fu(){let i=ce;if(!i)return;let c=o.composer?.inputAttributes,g=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;up(i,c),g&&i.setAttribute("aria-label",g),pp(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Ol(i)}),Dw(i,dp(o.composer?.maxLines,we()?5:3))}let sy=i=>{tt=Lw(i,{debug:o.debug===!0}),tt&&AM(tt),Fu()};ny(He),sy(He),ko();let Fa=ds(o,we());Fa&&(be.style.maxWidth=Fa,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%",Nn.style.maxWidth=Fa,Nn.style.marginLeft="auto",Nn.style.marginRight="auto",Nn.style.width="100%",ku.style.maxWidth=Fa,Ha.style.maxWidth=Fa,Ha.style.marginLeft="auto",Ha.style.marginRight="auto",Ha.style.width="100%");let iy=()=>{let i=ds(o,we());if(!(!i||we()))for(let c of[An,Lr,En,Je])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};iy();let ay=()=>{!o.attachments?.enabled||!St||!En||(rt?rt.remountPreviews(En):(rt=si.fromConfig(o.attachments,Xh),rt.setPreviewsContainer(En)),tt?.addListener(St,"change",i=>{let c=i.target;rt?.handleFileSelect(c.files),c.value=""}),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(hA(o.attachments.dropOverlay)))};ay();let MM=()=>Ft?.prefetch(),ly=()=>{if(!o.contextMentions?.enabled||!ce)return;let i=tt?.header??null,c=i?bf(i):void 0;if(Ft=Sx({config:o,textarea:ce,anchor:An??ce,getMessages:()=>T.getMessages(),liveRegionHost:de,chipRow:c}),Ft&&!c){let g=ce;g.parentElement?.insertBefore(Ft.contextRow,g)}};ly();let Io=null,EM={getState:()=>ve.getState(),getValue:()=>ce?.value??"",setValue:i=>{ce&&(ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),ko())},submit:()=>{gx(tt?.form??null)},openAttachmentPicker:()=>{Oo()||St?.click()},toggleVoice:()=>{_u?.()},requestRender:()=>Io?.resolve()},TM=()=>{let i=[];return(Ft?.affordanceButtons??[]).forEach((g,f)=>{i.push({id:`core:mention-${f}`,placement:"start",order:Ko.mention+f,element:g,managed:!0})}),Mn&&i.push({id:"core:attachment",placement:"start",order:Ko.attachment,element:Mn}),Fn&&i.push({id:"core:mic",placement:"end",order:Ko.mic,element:Fn}),Po&&i.push({id:"core:send",placement:"end",order:Ko.send,element:Po}),i},cy=()=>{Io?.destroy(),Io=zw({getBindings:()=>tt,collect:()=>({builtIns:TM(),configActions:[...SM(),...o.composer?.actions??[]],plugins:u,contributionContext:{config:o,getState:()=>ve.getState(),requestRender:()=>Io?.resolve()},debug:o.debug===!0}),actionContext:EM,getState:()=>ve.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),Io.resolve()};cy();let $u=()=>{if(Zo?.destroy(),Zo=null,!Ci().length)return;let i=tt?.header;i&&(Zo=Qw({row:bf(i),onRemove:c=>Ou(c),initialIds:ve.getState().activeModeIds}),Zo.render(ve.getState().activeModeIds,Ci()))};$u();let dy=()=>{Wr?.destroy(),Wr=null,Or?.destroy(),Or=null;let i=tt?.header;i&&(Wr=rx({onDismiss:()=>Lo(void 0)}),i.appendChild(Wr.element),Wr.render(ve.getState().quote),Du()==="defer-one"&&(Or=sx({onEdit:()=>eT(),onRemove:()=>xi(void 0)}),i.appendChild(Or.element),Or.render(ve.getState().pendingSubmission)))};dy();let Uu=px(),PM=()=>{let i=tt?.header?.querySelector(yf);if(i)return i.childElementCount>0;let c=ve.getState();return c.mentionRefs.length>0||xp(c.activeModeIds,Ci()).length>0};function mo(){let i=ve.getState(),c=Uu.observe(ux(ce),i.text);He.toggleAttribute("data-persona-composer-compact",dx({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:PM(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0}))}function py(){o.composer?.layout==="single-row"&&!we()?He.setAttribute("data-persona-composer-layout","single-row"):He.removeAttribute("data-persona-composer-layout")}py(),ve.subscribe(()=>{Io?.sync(),cg(),$c(),mo(),jy()}),$c();let uy=!1,kM=i=>{if(uy||o.debug!==!0)return;let c=["messages","composer"].filter(g=>i[g]);c.length&&(uy=!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??{};kM(i);let c=f=>{switch(f){case"body-top":return ne.querySelector("[data-persona-intro-card]");case"messages":return be;case"footer-top":return Lr;case"composer":return An;case"footer-bottom":return Je;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 w=Pe.querySelector(".persona-flex-col");w?w.parentNode?.insertBefore(b,w.nextSibling):Pe.appendChild(b)}break;case"body-top":{let w=ne.querySelector("[data-persona-intro-card]");w?w.replaceWith(b):ne.insertBefore(b,ne.firstChild);break}case"body-bottom":ne.appendChild(b);break;case"footer-top":Lr.replaceWith(b);break;case"footer-bottom":Je.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)}})(),be.addEventListener("click",i=>{let c=i.target;if(!(c instanceof Element))return;let g=c.closest("button[data-persona-copy-tool-detail]");g&&(i.preventDefault(),i.stopPropagation(),DS(g))});let ju=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;Fr(),Wi();let w=g.getAttribute("data-bubble-type");if(f.classList.contains("persona-activity-row")){a.manual(b);let W=f.parentElement?.closest("[data-persona-tool-group]");W?.dataset.messageId&&a.manual(W.dataset.messageId)}if(w==="reasoning")s.has(b)?s.delete(b):s.add(b),nh(b,f,s);else if(w==="tool")r.has(b)?r.delete(b):r.add(b),ih(b,f,r,o);else if(w==="approval"&&C){let V=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",F=l.get(b)??V;l.set(b,!F),C.updateApprovalDetailsUI(b,f,o,l)}$t.delete(b)};be.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ju(i))}),be.addEventListener("click",i=>{i.detail===0&&i.target.closest(".persona-activity-row")&&ju(i)}),be.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ju(i))}),be.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let g=be.getRootNode(),f=typeof g.getSelection=="function"?g.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let b=f.toString(),w=Nx(b);!w||w===b||(c.setData("text/plain",w),i.preventDefault())});let Vu=new Map,gy=null,my="idle",LM={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},IM=(i,c)=>{let{icon:g,label:f}=LM[c];i.setAttribute("aria-label",f),i.title=f,i.setAttribute("aria-pressed",c==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",c!=="idle"),i.classList.toggle("persona-message-action-loading",c==="loading");let b=le(g,14,"currentColor",2);b&&(i.innerHTML="",i.appendChild(b))},fy=()=>{be.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let f=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;IM(c,f&&f===gy?my:"idle")})};be.addEventListener("click",i=>{let g=i.target.closest(".persona-message-action-btn[data-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest("[data-actions-for]");if(!f)return;let b=f.getAttribute("data-actions-for");if(!b)return;let w=g.getAttribute("data-action");if(w==="copy"){let V=T.getMessages().find(F=>F.id===b);if(V&&vi.onCopy){let F=V.content||"";navigator.clipboard.writeText(F).then(()=>{g.classList.add("persona-message-action-success");let q=Mt(Tr.Check,14,"currentColor",2);q&&(g.innerHTML="",g.appendChild(q)),setTimeout(()=>{g.classList.remove("persona-message-action-success");let Q=Mt(Tr.Copy,14,"currentColor",2);Q&&(g.innerHTML="",g.appendChild(Q))},2e3)}).catch(q=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",q)}),vi.onCopy(V)}}else if(w==="read-aloud")T.toggleReadAloud(b);else if(w==="upvote"||w==="downvote"){let V=(Vu.get(b)??null)===w,F=w==="upvote"?"thumbs-up":"thumbs-down";if(V){Vu.delete(b),g.classList.remove("persona-message-action-active");let q=le(F,14,"currentColor",2);q&&(g.innerHTML="",g.appendChild(q))}else{let q=w==="upvote"?"downvote":"upvote",Q=f.querySelector(`[data-action="${q}"]`);if(Q){Q.classList.remove("persona-message-action-active");let nt=le(q==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(Q.innerHTML="",Q.appendChild(nt))}Vu.set(b,w),g.classList.add("persona-message-action-active");let se=le(F,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 Ve=T.getMessages().find(st=>st.id===b);Ve&&vi.onFeedback&&vi.onFeedback({type:w,messageId:Ve.id,message:Ve})}}else if(w==="regenerate")vc?.regenerate(b);else if(w==="edit")vc?.edit(b);else if(w==="quote")vc?.quote(b);else if(w?.startsWith(Vp)){let W=w.slice(Vp.length),V=o.messageActions?.custom?.find(q=>q.id===W),F=T.getMessages().find(q=>q.id===b);if(!V||!F)return;try{V.onSelect(F)}catch(q){console.error(`[AgentWidget] messageActions.custom "${W}" onSelect failed:`,q)}}});let vc=null;be.addEventListener("click",i=>{let g=i.target.closest("button[data-approval-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest(".persona-approval-bubble");if(!f)return;let b=f.getAttribute("data-message-id");if(!b)return;let w=g.getAttribute("data-approval-action");if(!w)return;let W=w==="approve"?"approved":"denied",F=T.getMessages().find(Q=>Q.id===b);if(!F?.approval)return;let q=f.querySelector("[data-approval-buttons]");q&&q.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?T.resolveWebMcpApproval(b,W):T.resolveApproval(F.approval,W)});let Ke=null,hy=!1,$a=null,Cs=()=>{},Ua="none",Cc=null,Xn={artifacts:[],selectedId:null},er=!1,fo=!1,ja=!1,Mi=!1,yy=()=>Mi||Xn.artifacts.some(i=>Vo(o.features?.artifacts,i)==="panel"),wc=()=>Xn.artifacts.length>0&&!er&&yy(),ct={current:null},qu=(i,c)=>{let g=T.getArtifactById(c),f=g?.markdown,b=g?.title||"artifact",w=g?.file,W=g?.artifactType??"markdown";if(!f){let q=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(q){let se=T.getMessages().find(me=>me.id===q);if(se?.rawContent)try{let me=JSON.parse(se.rawContent);f=me?.props?.markdown,b=me?.props?.title||b,me?.props?.file&&typeof me.props.file=="object"&&(w=me.props.file),!g&&typeof me?.props?.artifactType=="string"&&(W=me.props.artifactType)}catch{}}}return{markdown:f,title:b,file:w,artifactType:W}};be.addEventListener("click",i=>{let g=i.target.closest("[data-download-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-download-artifact");if(!f||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:f})===!0)return;let{markdown:w,title:W,file:V}=qu(g,f);if(!w)return;let F=Ar();F&&F.triggerArtifactDownload(F.downloadInfoFor({title:W,markdown:w,file:V}))}),be.addEventListener("click",i=>{let g=i.target.closest("[data-artifact-custom-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-artifact-custom-action");if(!f)return;let b=g.closest("[data-artifact-inline]"),w=b?null:g.closest("[data-open-artifact]"),W=b?b.getAttribute("data-artifact-inline"):w?.getAttribute("data-open-artifact")??null,F=(b?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(st=>st.id===f);if(!F)return;let{markdown:q,title:Q,file:se,artifactType:me}=qu(g,W??""),Ve={artifactId:W,title:Q,artifactType:me,markdown:q,file:se};try{Promise.resolve(F.onClick(Ve)).catch(()=>{})}catch{}}),be.addEventListener("click",i=>{let g=i.target.closest("[data-copy-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-copy-artifact");if(!f)return;let b=T.getArtifactById(f),w=Ar();if(!w)return;let W="";if(b)W=w.artifactCopyText(b);else{let{markdown:V,file:F,artifactType:q}=qu(g,f);q==="markdown"&&(W=w.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:V??"",...F?{file:F}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let V=Mt(Tr.Check,16,"currentColor",2);V&&(g.replaceChildren(V),setTimeout(()=>{let F=Mt(Tr.Copy,16,"currentColor",2);F&&g.replaceChildren(F)},1500))}).catch(()=>{})}),be.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||(er=!1,Mi=!0,fo=!0,ja=!0,T.selectArtifact(f),ho())}),be.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(),er=!1,Mi=!0,T.selectArtifact(f),ho())}),be.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 Ei=$e.composerOverlay,Ti=(i,c,g)=>{let f=c.trim();if(!f||!ct.current)return;let b=i.getAttribute("data-tool-call-id")??"",w=g.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:b,answer:f,answers:g.structured,values:g.values??(g.source==="multi"?f.split(", "):[f]),isFreeText:w,source:g.source},bubbles:!0,composed:!0})),ss(Ei,b);let W=ct.current.getMessages().find(V=>V.toolCall?.id===b);W?.agentMetadata?.awaitingLocalTool?ct.current.resolveAskUserQuestion(W,g.structured??f):ct.current.sendMessage(f)},ws=i=>{let c=ct.current;if(!c)return;let g=i.getAttribute("data-tool-call-id")??"",f=c.getMessages().find(b=>b.toolCall?.id===g);f&&c.persistAskUserQuestionProgress(f,{answers:Ud(i,f),currentIndex:lo(i)})},by=i=>Object.entries(i).map(([c,g])=>`${c}: ${Array.isArray(g)?g.join(", "):g}`).join(" | "),zu=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=lo(i),g=ia(i);if(c>=g-1)return;let f=ct.current?.getMessages().find(b=>b.toolCall?.id===i.getAttribute("data-tool-call-id"));f&&(jd(i,f,o,c+1),ws(i))};Ei.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})),ss(Ei,w);let W=ct.current?.getMessages().find(V=>V.toolCall?.id===w);W?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(W),ct.current?.resolveAskUserQuestion(W,"(dismissed)"));return}if(b==="pick"){let w=g.getAttribute("data-option-label");if(!w)return;let W=f.getAttribute("data-multi-select")==="true",V=rs(f);if(V&&W){let F=ti(f)[lo(f)],q=new Set(Array.isArray(F)?F:[]);q.has(w)?q.delete(w):q.add(w),is(f,Array.from(q)),ws(f);return}if(V){is(f,w),ws(f),zu(f);return}if(W){let F=g.getAttribute("aria-pressed")==="true";g.setAttribute("aria-pressed",F?"false":"true"),g.classList.toggle("persona-ask-pill-selected",!F);let q=f.querySelector('[data-ask-user-action="submit-multi"]');q&&(q.disabled=Nm(f).length===0);return}Ti(f,w,{source:"pick",values:[w]});return}if(b==="submit-multi"){let w=Nm(f);if(w.length===0)return;Ti(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(rs(f)){is(f,W.trim()),ws(f),zu(f);return}Ti(f,W,{source:"free-text"});return}if(b==="next"||b==="back"){if(!ct.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=ct.current.getMessages().find(se=>se.toolCall?.id===w);if(!W)return;let F=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(F){let se=ti(f)[lo(f)];(typeof se!="string"||se!==F)&&is(f,F)}let q=b==="next"?1:-1,Q=lo(f)+q;jd(f,W,o,Q),ws(f);return}if(b==="submit-all"){if(!ct.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=ct.current.getMessages().find(se=>se.toolCall?.id===w);if(!W)return;let F=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";F&&is(f,F);let q=Ud(f,W);ct.current.persistAskUserQuestionProgress(W,{answers:q,currentIndex:lo(f)});let Q=by(q);Ti(f,Q||"(submitted)",{source:"submit-all",structured:q});return}if(b==="skip"){if(!ct.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=ct.current.getMessages().find(me=>me.toolCall?.id===w);if(!W)return;let V=rs(f),F=lo(f),q=ia(f),Q=F>=q-1;if(!V){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:w},bubbles:!0,composed:!0})),ss(Ei,w),W.agentMetadata?.awaitingLocalTool&&(ct.current.markAskUserQuestionResolved(W),ct.current.resolveAskUserQuestion(W,"(dismissed)"));return}is(f,"");let se=f.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),Q){let me=Ud(f,W),Ve=by(me);Ti(f,Ve||"(skipped)",{source:"submit-all",structured:me});return}jd(f,W,o,F+1),ws(f);return}}),Ei.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(rs(f)){is(f,b.trim()),ws(f),zu(f);return}Ti(f,b,{source:"free-text"})}});let vy=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=Ei.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",vy);let Ro=null,Tt=null,Va=null,xc=null,Sc=()=>{},Cy=!1,Ac="",Mc="";function Ku(){xc?.(),xc=null}let RM=()=>{let i=$i&&$s?.isConnected?$s:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},wy=()=>{if(!Ro||!Tt)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){Tt.style.removeProperty("position"),Tt.style.removeProperty("left"),Tt.style.removeProperty("top"),Tt.style.removeProperty("bottom"),Tt.style.removeProperty("width"),Tt.style.removeProperty("z-index");return}let f=Ro.firstElementChild;if(!f||f===Tt)return;let b=10;Tt.style.position="absolute",Tt.style.top="0",Tt.style.bottom="0",Tt.style.width=`${b}px`,Tt.style.zIndex="5";let w=yh(Ro,c),W=f.offsetWidth+w/2-b/2;Tt.style.left=`${Math.max(0,W)}px`},Ec=()=>{},xy=()=>{let i=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,g=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>g?!1:D||Ct(o)},Tc=()=>!xn(o)||!wc()||e.classList.contains("persona-artifact-narrow-host")||xy()||(e.ownerDocument.defaultView??window).innerWidth<gI?"none":gh(o)?"detached":"welded",ho=()=>{if(!Ke||!xn(o))return;tc(e,o),nc(e,o),Ec();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=xe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let g=wc();Ke.setVisible(g),Ke.update(Xn),er?(Ke.setMobileOpen(!1),Ke.element.classList.add("persona-hidden"),Ke.backdrop?.classList.add("persona-hidden"),fo=!1,ja=!1):Xn.artifacts.length>0&&yy()?(Ke.element.classList.remove("persona-hidden"),Ke.setMobileOpen(!0)):(Ke.setMobileOpen(!1),Ke.element.classList.add("persona-hidden"),Ke.backdrop?.classList.add("persona-hidden"),fo=!1,ja=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ke.setExpandToggleVisible(f),Ke.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ke.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Ke.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ke.setTabFade(o.features?.artifacts?.layout?.tabFade),Ke.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!ja&&(fo=!1),fo!==Cy){let w=Ke.element;fo?(Ac=w.style.width,Mc=w.style.maxWidth,w.style.removeProperty("width"),w.style.removeProperty("max-width")):(Ac&&(w.style.width=Ac),Mc&&(w.style.maxWidth=Mc),Ac="",Mc=""),Cy=fo}e.classList.toggle("persona-artifact-expanded",fo),Ke.setExpanded(fo);let b=Tc();b!==Ua&&(Ua=b,Cs()),Sc()};if(xn(o)){xe.style.position="relative";let i=S("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=S("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(de),Ro=c,c.appendChild(i),xe.appendChild(c);let g=b=>{hy||Ke||(Ke=b.createArtifactPane(o,{onSelect:w=>ct.current?.selectArtifact(w),onDismiss:()=>{er=!0,ho()},onToggleExpand:()=>{let w=!fo,W=Xn.selectedId??Xn.artifacts[Xn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:W,expanded:w})!==!0&&(fo=w,w||(ja=!1),ho())}}),Ke.element.classList.add("persona-hidden"),c.appendChild(Ke.element),Ke.backdrop&&xe.appendChild(Ke.backdrop),Sc(),ho())},f=Ar();f?g(f):(ph(()=>{let b=Ar();b&&g(b)}),Yp().catch(()=>{})),Sc=()=>{if(!Ro||!Ke)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Va?.(),Va=null,Ku(),Tt&&(Tt.remove(),Tt=null),Ke.element.style.removeProperty("width"),Ke.element.style.removeProperty("maxWidth");return}if(!Tt){let w=S("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");w.setAttribute("role","separator"),w.setAttribute("aria-orientation","vertical"),w.setAttribute("aria-label","Resize artifacts panel"),w.tabIndex=0;let W=e.ownerDocument,V=W.defaultView??window,F=q=>{if(!Ke||q.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||V.innerWidth<=640)return;q.preventDefault(),Ku();let Q=q.clientX,se=Ke.element.getBoundingClientRect().width,me=o.features?.artifacts?.layout,Ve=nt=>{let In=Ro.getBoundingClientRect().width,At=e.classList.contains("persona-artifact-welded-split"),Lt=yh(Ro,V),hn=At?0:w.getBoundingClientRect().width||6,Bt=se-(nt.clientX-Q),pt=QS(Bt,In,Lt,hn,me?.resizableMinWidth,me?.resizableMaxWidth,RM());Ke.element.style.width=`${pt}px`,Ke.element.style.maxWidth="none",wy()},st=()=>{W.removeEventListener("pointermove",Ve),W.removeEventListener("pointerup",st),W.removeEventListener("pointercancel",st),xc=null;try{w.releasePointerCapture(q.pointerId)}catch{}};xc=st,W.addEventListener("pointermove",Ve),W.addEventListener("pointerup",st),W.addEventListener("pointercancel",st);try{w.setPointerCapture(q.pointerId)}catch{}};w.addEventListener("pointerdown",F),Tt=w,Ro.insertBefore(w,Ke.element),Va=()=>{w.removeEventListener("pointerdown",F)}}if(Tt){let w=wc();Tt.classList.toggle("persona-hidden",!w),wy()}},Ec=()=>{if(!D||!Ke||(o.launcher?.sidebarMode??!1)||Ct(o)&&Bn(o).reveal==="emerge")return;let w=e.ownerDocument.defaultView??window,W=o.launcher?.mobileFullscreen??!0,V=o.launcher?.mobileBreakpoint??640;if(W&&w.innerWidth<=V||!VS(o,D))return;let F=mi(o).width,q=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";wc()?(xe.style.width=q,xe.style.maxWidth=q):(xe.style.width=F,xe.style.maxWidth=F)},typeof ResizeObserver<"u"&&($a=new ResizeObserver(()=>{ho()}),$a.observe(xe))}else xe.appendChild(de);we()&&en&&($e.peekBanner&&en.appendChild($e.peekBanner),en.appendChild(He)),e.appendChild(Qe),en&&e.appendChild(en);let Gu=()=>{let i=xy()||we()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!Ct(o);if(be.style.gap=i?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",be.style.setProperty("--persona-transcript-gap",be.style.gap),we()){xe.style.width="100%",xe.style.maxWidth="100%";let Re=o.launcher?.composerBar??{},Ue=Qe.dataset.state==="expanded",_e=Re.expandedSize??"anchored";if(!(Ue&&_e!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let Kt=o.theme?.components?.panel,Rn=Mo(o),gr=(mr,Gs)=>mr==null||mr===""?Gs:cn(Rn,mr)??mr,um="1px solid var(--persona-border)",Ks="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",gm="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=gr(Kt?.border,um),de.style.borderRadius=gr(Kt?.borderRadius,gm),de.style.boxShadow=gr(Kt?.shadow,Ks),de.style.overflow="hidden";return}let c=Ct(o),g=o.launcher?.sidebarMode??!1,f=c||g||(o.launcher?.fullHeight??!1),b=o.launcher?.enabled===!1,w=o.launcher?.detachedPanel===!0,W=o.theme?.components?.panel,V=o.darkTheme?.components?.panel,F=ii(o)==="dark"?xo(W??{},V??{}):W,q=Mo(o),Q=(Re,Ue)=>Re==null||Re===""?Ue:cn(q,Re)??Re,se=e.ownerDocument.defaultView??window,me=o.launcher?.mobileFullscreen??!0,Ve=o.launcher?.mobileBreakpoint??640,st=se.innerWidth<=Ve,nt=me&&st&&D,In=c&&me&&st,At=o.launcher?.position??"bottom-left",Lt=At==="bottom-left"||At==="top-left",hn=o.launcher?.zIndex??pn,Bt=(Re,Ue,_e)=>`var(--persona-components-panel-modes-${Re}-${Ue}, ${_e})`,pt=F?.modes?.floating,No=Q(pt?.border??F?.border,Bt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),Fo=Q(pt?.shadow??F?.shadow,Bt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),so=Q(pt?.borderRadius??F?.borderRadius,Bt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),io=w&&!nt&&!In,Yr=nt||In?"mobile":io?"floating":c?"docked":g?"sidebar":b?"inline":"floating",$o=F?.modes?.[Yr];io?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let vo=io?No:g||nt?"none":No,Qr=io?Fo:nt?"none":g?Lt?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":b?"none":Fo;c&&!nt&&!io&&(Qr="none",vo="none");let hl=io?so:g||nt?"0":so,zs=Q($o?.border??F?.border,Bt(Yr,"border",vo)),R=Q($o?.shadow??F?.shadow,Bt(Yr,"shadow",Qr)),We=Q($o?.borderRadius??F?.borderRadius,Bt(Yr,"borderRadius",hl)),Oe=Tc(),re=Oe==="detached",ut=Oe==="welded";e.classList.toggle("persona-artifact-detached-split",re),e.classList.toggle("persona-artifact-welded-split",ut);let Ut="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)))))",bt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&xn(o)&&gh(o)&&b&&!c;e.classList.toggle("persona-artifact-chat-flush",bt);let Dt=re||bt?"none":R,Xt=re?No:ut?"none":zs,Le=re?so:We;bt&&(Xt="none",Le="0");let vt=$o?.borderRadius!=null&&$o.borderRadius!==""||F?.borderRadius!=null&&F.borderRadius!=="",De=bt&&!vt?"0":We,Jt=ne.scrollTop;e.style.cssText="",Qe.style.cssText="",xe.style.cssText="",de.style.cssText="",ne.style.cssText="",Ai||(He.style.cssText=""),go&&(ne.style.display="none"),(f||b)&&(e.style.minWidth="0");let ao=()=>{if(Jt<=0)return;(ne.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ne.scrollTop===Jt)return;let Ue=ne.scrollHeight-ne.clientHeight;Ue<=0||(ne.scrollTop=Math.min(Jt,Ue))})};if(nt){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
|
+
`,$.addEventListener("click",()=>{m=L,E.forEach((K,ae)=>{let oe=ae<L;K.classList.toggle("selected",oe),K.setAttribute("aria-checked",ae===L-1?"true":"false")})}),E.push($),x.appendChild($)}h.appendChild(x);let H=null;if(d){let L=document.createElement("div");L.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=s,H.rows=3,H.setAttribute("aria-label","Additional comments"),L.appendChild(H),h.appendChild(L)}let B=document.createElement("div");B.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=l,A.addEventListener("click",()=>{n?.(),p.remove()});let O=document.createElement("button");return O.type="button",O.className="persona-feedback-btn persona-feedback-btn-submit",O.textContent=a,O.addEventListener("click",async()=>{if(m===null){x.classList.add("persona-feedback-shake"),setTimeout(()=>x.classList.remove("persona-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let L=H?.value.trim()||void 0;await t(m,L),p.remove()}catch(L){O.disabled=!1,O.textContent=a,console.error("[CSAT Feedback] Failed to submit:",L)}}),B.appendChild(A),B.appendChild(O),h.appendChild(B),p.appendChild(h),p}function su(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:u="Not likely",highLabel:p="Very likely"}=e,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let h=null,y=document.createElement("div");y.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,v.appendChild(C);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,v.appendChild(x),y.appendChild(v);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-nps",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Likelihood rating from 0 to 10");let H=document.createElement("div");H.className="persona-feedback-labels";let B=document.createElement("span");B.className="persona-feedback-label-low",B.textContent=u;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=p,H.appendChild(B),H.appendChild(A);let O=document.createElement("div");O.className="persona-feedback-numbers";let L=[];for(let P=0;P<=10;P++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-number-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`Rating ${P} out of 10`),k.textContent=String(P),k.dataset.rating=String(P),P<=6?k.classList.add("persona-feedback-detractor"):P<=8?k.classList.add("persona-feedback-passive"):k.classList.add("persona-feedback-promoter"),k.addEventListener("click",()=>{h=P,L.forEach((_,I)=>{_.classList.toggle("selected",I===P),_.setAttribute("aria-checked",I===P?"true":"false")})}),L.push(k),O.appendChild(k)}E.appendChild(H),E.appendChild(O),y.appendChild(E);let $=null;if(d){let P=document.createElement("div");P.className="persona-feedback-comment-container",$=document.createElement("textarea"),$.className="persona-feedback-comment",$.placeholder=s,$.rows=3,$.setAttribute("aria-label","Additional comments"),P.appendChild($),y.appendChild(P)}let K=document.createElement("div");K.className="persona-feedback-actions";let ae=document.createElement("button");ae.type="button",ae.className="persona-feedback-btn persona-feedback-btn-skip",ae.textContent=l,ae.addEventListener("click",()=>{n?.(),m.remove()});let oe=document.createElement("button");return oe.type="button",oe.className="persona-feedback-btn persona-feedback-btn-submit",oe.textContent=a,oe.addEventListener("click",async()=>{if(h===null){O.classList.add("persona-feedback-shake"),setTimeout(()=>O.classList.remove("persona-feedback-shake"),500);return}oe.disabled=!0,oe.textContent="Submitting...";try{let P=$?.value.trim()||void 0;await t(h,P),m.remove()}catch(P){oe.disabled=!1,oe.textContent=a,console.error("[NPS Feedback] Failed to submit:",P)}}),K.appendChild(ae),K.appendChild(oe),y.appendChild(K),m.appendChild(y),m}var ka="persona-chat-history",xI=30*1e3,SI=641,La="data-persona-composer-reason",AI={"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 MI(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=AI[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 iu(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 EI(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 TI(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Eh=e=>!e||typeof e!="object"?{}:{...e},SA=e=>e.map(t=>({...t,streaming:!1})),AA=(e,t,n)=>{let o=e?.markdown?Sl(e.markdown):null,r=_d(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??"",u=l.message.rawContent??null;if(t){let h=t.process({text:d,raw:u??d,message:l.message,streaming:l.streaming});h!==null&&(d=h.text,h.persist||(l.message.__skipPersist=!0),h.resubmit&&!l.streaming&&n&&n())}let p=jo()!==null,m;if(e?.postprocessMessage){let h=e.postprocessMessage({...l,text:d,raw:u??l.text??""});m=r?r(h):h}else if(o){let h=l.streaming?SC(d):d,y=o(h);m=r&&p?r(y):y}else m=br(d);return m};return l=>{try{return a(l)}catch(d){return s||(s=!0,console.error("[Persona] markdown rendering failed; falling back to plain text:",d)),br(l.text??"")}}};function MA(e){let t=S("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=le(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=S("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var PI=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},kI=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:PI(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),au=(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=ta(t),r=new Set,s=new Set,a=pC((i,c)=>{$t.delete(i);let g=Array.from(be.querySelectorAll("[data-message-id]")).find(f=>f.dataset.messageId===i);g&&(c==="tool"?lh(i,g,r,o):rh(i,g,s))}),l=new Map,d=()=>{jw({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};d();let u=o.features;o=oc(o);let p=rc.getForInstance(o.plugins),m=zx(e),h=[],y=!1,v=jS(()=>o),C=null,x=null,E=null,H=!1,B=null,A=i=>{C=i,i.initApprovalUi({webMcpToolTitle:oa});let c=i.createBuiltInApprovalPlugin(l);x=c.plugin,E=c.teardown},O=()=>{if(C)return C;let i=YS();return i?(A(i),i):(GS().then(c=>{H||C||(A(c),B?.())}).catch(()=>{}),null)},L=!1,$=!1,K=null,ae=(i,c,g,f)=>{if(!i.querySelector("[data-tv-form]"))return;let b=aA();if(b){b.enhanceWithForms(i,c,g,f);return}iA().then(()=>{L||$||!K||($=!0,K())}).catch(()=>{})};o.components&&Eo.registerAll(o.components);let oe=dA(),k=o.persistState===!1?null:o.storageAdapter??Zp(),_=!!o.clientToken&&typeof o.reconnectStream!="function",I={},te=null,U,pe=new Promise(i=>{U=i}),ue,ge=!1,Ie=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&&(ge=!0),g}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(k?.load)try{let i=k.load();if(i&&typeof i.then=="function")te=i.then(c=>Ie(c??{messages:[],metadata:{}}));else{let g=Ie(i??{messages:[],metadata:{}});g.metadata&&(I=Eh(g.metadata)),g.messages?.length&&(o={...o,initialMessages:g.messages}),g.artifacts?.length&&(o={...o,initialArtifacts:g.artifacts,initialSelectedArtifactId:g.selectedArtifactId??null}),ue=g.draft}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=Ie({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}te||U();let Se=()=>I,ye=i=>{I=i({...I})??{},Ii()},dt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[sc],it=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[yi.message,yi.messageAndClick],Ce=ic({parsers:dt,handlers:it,getSessionMetadata:Se,updateSessionMetadata:ye,emit:oe.emit,documentRef:typeof document<"u"?document:null});Ce.syncFromMetadata();let D=o.launcher?.enabled??!0,Ne=o.launcher?.autoExpand??!1,Fe=o.autoFocusInput??!1,Et=Ne,Gt=D,jt=o.layout?.header?.layout,ke=!1,we=()=>us(o),Be=()=>D||we(),Ee=we()?!1:D?Ne:!0,An=!1,j=null,M=()=>{An=!0,j&&clearTimeout(j),j=setTimeout(()=>{An&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),An=!1)},1e4)},N=AA(o,Ce,M),z=o.features?.showReasoning??!0,J=o.features?.showToolCalls??!0,X=o.features?.showEventStreamToggle??!1,fe=o.features?.scrollToBottom??{},Ae=o.features?.scrollBehavior??{},Me=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",Nt=`${Me()}event-stream`,et=null,ze=o.features?.eventStream?.maxEvents??2e3,ft=null,Zt=null,It=null,gn=!1,ht=null,go=!1,kr=null,Au=0,qh=(i,c)=>{ft?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})},Mu=(i,c)=>{Zt?.processEvent(i,c),ft?qh(i,c):It&&(It.length>=ze&&It.shift(),It.push({type:i,payload:c}))},pc=()=>{ft||!X||(It??(It=[]),dh().then(i=>{if(gn||ft||!X)return;et=new i.EventStreamStore(Nt),ft=new i.EventStreamBuffer(ze,et),Zt=Zt??new i.ThroughputTracker,et.open().then(()=>ft?.restore()).catch(g=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",g)});let c=It??[];It=null;for(let g of c)Zt?.processEvent(g.type,g.payload),qh(g.type,g.payload)}).catch(()=>{}))};X&&pc();let Rt=!1,Vt=null,Eu=()=>{},Xo=()=>{},zh=()=>{},Kh=()=>{},Tu=()=>{},CM=()=>go||Rt&&Vt==="panel",vi={onCopy:i=>{oe.emit("message:copy",i),T?.isClientTokenMode()&&T.submitMessageFeedback(i.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{oe.emit("message:feedback",i),T?.isClientTokenMode()&&T.submitMessageFeedback(i.messageId,i.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(i)}},VR=o.statusIndicator??{},Pu=(i,c=o.statusIndicator??{})=>i==="idle"?c.idleText??_t.idle:i==="connecting"?c.connectingText??_t.connecting:i==="connected"?c.connectedText??_t.connected:i==="error"?c.errorText??_t.error:i==="paused"?c.pausedText??_t.paused:i==="resuming"?c.resumingText??_t.resuming:_t[i];function Ra(i,c,g,f){if(!we()&&(g.mode==="transient"||i.classList.contains("persona-mb-2"))&&(Lm(i,Mn,g),ei(i,g,f)),!i.hasAttribute(La))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 _n=US({config:o,showClose:Be()}),{wrapper:Qe,panel:xe,pillRoot:en}=_n.shell,$e=_n.panelElements,{container:de,body:ne,messagesWrapper:be,starterSuggestions:ku,transcriptSuggestions:Ha,suggestions:Lr,textarea:ce,sendButton:Te,composerForm:Mn,statusText:Je,welcomeHost:tn,welcomeIconHolder:wM,greetingHost:Nn,introKicker:xM,introTitle:SM,introSubtitle:AM,closeButton:qe,iconHolder:Ht,headerTitle:Ir,headerSubtitle:fs,header:Pe,footer:He,actionsRow:MM}=$e,Lu=$e.leftActions,uc=$e.rightActions,Po=$e.sendButtonWrapper,Gh=$e.setSendButtonMode,se=$e.micButton,Fn=$e.micButtonWrapper,kt=$e.attachmentButton,En=$e.attachmentButtonWrapper,St=$e.attachmentInput,Tn=$e.attachmentPreviewsContainer;de.classList.add("persona-relative"),ne.classList.add("persona-relative");let EM=12,Wa=()=>fe.label??"",TM=()=>fe.iconName??"arrow-down",PM=()=>fe.enabled!==!1,$n=()=>Ae.mode??"anchor-top",Rr=()=>$n()==="follow"||$n()==="anchor-top"&&qa,Oa=()=>Ae.anchorTopOffset??16,kM=()=>Ae.restorePosition??"bottom",Yh=()=>Ae.pauseOnInteraction===!0,Qh=()=>Ae.showActivityWhilePinned!==!1,Xh=()=>Ae.announce===!0,Iu=()=>Ae.scrollbar??"on-scroll",qt=S("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");qt.type="button",qt.style.display="none",qt.setAttribute("data-persona-scroll-to-bottom","true");let Ba=S("span","persona-flex persona-items-center"),Ru=S("span",""),hs=S("span","");hs.setAttribute("data-persona-scroll-to-bottom-count",""),hs.style.display="none",qt.append(Ba,Ru,hs),de.appendChild(qt);let Qn=S("div","persona-stream-anchor-spacer");Qn.setAttribute("aria-hidden","true"),Qn.setAttribute("data-persona-anchor-spacer",""),Qn.style.flexShrink="0",Qn.style.pointerEvents="none",Qn.style.height="0px",Qn.style.display="none",ne.appendChild(Qn);let Jo=S("div","persona-sr-only");Jo.setAttribute("aria-live","polite"),Jo.setAttribute("aria-atomic","true"),Jo.setAttribute("role","status"),Jo.setAttribute("data-persona-live-region",""),Object.assign(Jo.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),de.appendChild(Jo);let Da=null,gc=null,mc=i=>{!Xh()||!i||(gc=i,Da===null&&(Da=setTimeout(()=>{Da=null,gc&&Xh()&&(Jo.textContent=gc),gc=null},400)))},_a=()=>{let i=e.ownerDocument.defaultView??window;return(o.launcher?.mobileFullscreen??!0)&&i.innerWidth<=(o.launcher?.mobileBreakpoint??640)&&(D||Ct(o))||o.launcher?.fullHeight===!0&&!o.launcher.sidebarMode&&!Ct(o)},ys=()=>Sa(o,_a()),fc="empty",hc=0,Hu=()=>hc||parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,bs=()=>{let c=He.style.display==="none"?0:He.offsetHeight;qt.style.bottom=`${c+Hu()+EM}px`};bs();let Wu=()=>{Ai||(He.style.marginBottom=hc>0?`${hc}px`:"")},yc=()=>{let i=Pf(o,we()),c=ys();e.setAttribute("data-persona-welcome-fullscreen",String(_a())),e.setAttribute("data-persona-welcome-layout",c.layout??"top"),e.setAttribute("data-persona-welcome-layout-explicit",o.welcome?.layout??""),e.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom");let f=He.style.display==="none"?0:He.offsetHeight,b=c.anchor==="center"&&fc==="empty"?$l(c.anchorComposerTop)??$l("44%"):null,w=b!==null&&c.layout==="centered"&&o.welcome?.anchor===void 0&&o.welcome?.anchorComposerTop===void 0,W=w?getComputedStyle(ne):null,V=parseFloat(e.style.getPropertyValue("--persona-composer-overlay-height"))||0,F=parseFloat(e.style.getPropertyValue("--persona-composer-lift"))||0,q=Math.max(0,(parseFloat(W?.paddingBottom??"")||0)-(i==="overlay"?V+F:0)),Q=w?ne.getBoundingClientRect().top-de.getBoundingClientRect().top:0,ie=!w||tn.hidden?0:(tn.querySelector("[data-persona-welcome-plugin]")??tn).offsetHeight,me=b===null||we()?0:w?Math.max(0,Math.round((de.clientHeight-Q-ie-q-f)/2)):jx({columnHeight:de.clientHeight,footerHeight:f,fraction:b});e.style.setProperty("--persona-composer-overlay-height",`${f}px`),e.style.setProperty("--persona-composer-lift",`${i==="overlay"?me:0}px`),hc=i==="block"?me:0,Wu(),bs()},Jh=()=>{let i=!!Wa();qt.setAttribute("aria-label",Wa()||"Jump to latest"),qt.title=Wa(),qt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Ba.innerHTML="";let c=le(TM(),"14px","currentColor",2);c?(Ba.appendChild(c),Ba.style.display=""):Ba.style.display="none",Ru.textContent=Wa(),Ru.style.display=i?"":"none"};Jh();let rt=null,Ft=null,ve=Dw(),LM=i=>{try{de.dispatchEvent(new CustomEvent("persona:composer:state",{detail:i,bubbles:!0,composed:!0}))}catch{}};ve.subscribe(LM);let ko=()=>{ve.setText(ce?.value??"")},vs=()=>{ve.setMentionRefs(Ft?.getMentionRefs()??[])},IM=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}),Zh=i=>{let c=Object.freeze(i.map(IM));ve.setAttachments(c);try{o.attachments?.onChange?.(c)}catch(g){console.error("[AgentWidget] attachments.onChange failed:",g)}cg()};ve.setSelectedModelId(o.composer?.selectedModelId);let Na=()=>o.composer?.modes??[],Ci=()=>lx(Na(),o.composer?.modeGroups);{let i=xp(o.composer?.defaultActiveModeIds??[],Na());i.length&&ve.setActiveModeIds(i)}function ey(i){if(ve.getState().selectedModelId!==i){ve.setSelectedModelId(i),Hr?.repaint();try{o.composer?.onModelChange?.(i)}catch(c){console.error("[AgentWidget] composer.onModelChange failed:",c)}}}function bc(i){ve.setActiveModeIds(i),Zo?.render(i,Ci()),wi.forEach(c=>c.repaint()),Io?.resolve(),jc(),mo()}function Ou(i){bc(cx(ve.getState().activeModeIds,i,Na(),o.composer?.modeGroups))}let Hr=null,Bu=null,Zo=null,wi=new Map,Wr=null;function Lo(i){ve.setQuote(i),Wr?.render(ve.getState().quote),mo(),qy()}let ty=!1;function Du(){let i=o.composer?.streamingSubmitBehavior??"block";return i!=="interrupt"?i:o.clientToken?"interrupt":(!ty&&o.debug===!0&&(ty=!0,typeof console<"u"&&console.warn('[persona] composer.streamingSubmitBehavior "interrupt" requires the client-token transport; falling back to "block".')),"block")}let Or=null;function xi(i){ve.setPendingSubmission(i),Or?.render(ve.getState().pendingSubmission),mo()}let RM=i=>{let c=wi.get(i);if(c)return c;let g=ux({groupId:i,getGroup:()=>o.composer?.modeGroups?.find(f=>f.id===i),getModes:()=>Na().filter(f=>f.groupId===i),getActiveIds:()=>ve.getState().activeModeIds,onSelect:f=>Ou(f)});return wi.set(i,g),g},HM=()=>{let i=[],c=ve.getState().activeModeIds,g=new Set;if(Na().forEach((f,b)=>{if(wp(f.groupId,o.composer?.modeGroups)){let w=f.groupId;if(g.has(w))return;g.add(w);let W=RM(w);W.action.order=wf(b),W.action.label=o.composer?.modeGroups?.find(V=>V.id===w)?.label??w,i.push(W.action);return}i.push({id:ix(f.id),kind:"button",placement:"start",order:wf(b),presentation:f.presentation??"auto",label:f.label,shortLabel:f.shortLabel,iconName:f.iconName,pressed:c.includes(f.id),onSelect:()=>Ou(f.id)})}),o.composer?.models?.length&&!p.some(f=>f.renderComposer)){let f=o.composer?.modelPicker?.presentation??"native";(!Hr||Bu!==f)&&(Bu=f,Hr=rx({getModels:()=>o.composer?.models??[],getSelectedModelId:()=>ve.getState().selectedModelId,onSelect:b=>ey(b),presentation:f,getSuffix:()=>o.composer?.modelPicker?.suffix})),i.push(Hr.action)}return i},_u=null,ny=p.find(i=>i.renderHeader);if(ny?.renderHeader){let i=ny.renderHeader({config:o,defaultRenderer:()=>{let c=Sr({config:o,showClose:Be()});return di(de,c,o),c.header},onClose:()=>yt(!1,"user")});if(i){let c=Pe;c&&(c.replaceWith(i),Pe=i,_n.header.element=i)}}let oy=()=>{ht&&(ne.style.display="none",He.parentNode?.insertBefore(ht.element,He),ht.update())},Nu=()=>{if(!ft){pc();return}if(go=!0,ht?oy():dh().then(c=>{ht||!go||!ft||(ht=c.createEventStreamView({buffer:ft,getFullHistory:()=>ft.getAllFromStore(),onClose:()=>Si(),config:o,plugins:p,getThroughput:()=>Zt?.getMetric()??{status:"idle"},renderIconByName:le}),oy())}).catch(()=>{Si()}),at){at.style.boxShadow=`inset 0 0 0 1.5px ${wn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(g=>g&&at.classList.add(g))}let i=()=>{if(!go)return;let c=Date.now();c-Au>=200&&(ht?.update(),Au=c),kr=requestAnimationFrame(i)};Au=0,kr=requestAnimationFrame(i),Qt(),oe.emit("eventStream:opened",{timestamp:Date.now()})},Si=()=>{if(go){if(go=!1,ht&&ht.element.remove(),ne.style.display="",at){at.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&at.classList.remove(c))}kr!==null&&(cancelAnimationFrame(kr),kr=null),Qt(),oe.emit("eventStream:closed",{timestamp:Date.now()})}},at=null;if(X){let i=o.features?.eventStream?.classNames,c="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");at=S("button",c),at.style.width="28px",at.style.height="28px",at.style.color=wn.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let g=Mt(Tr.Activity,"18px","currentColor",1.5);g&&at.appendChild(g);let f=$e.clearChatButtonWrapper,b=$e.closeButtonWrapper,w=f||b;w&&w.parentNode===Pe?Pe.insertBefore(at,w):Pe.appendChild(at),at.addEventListener("click",()=>{go?Si():Nu()})}let ry=i=>{let c=o.attachments;if(!c?.enabled)return;let g=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!g){g=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),g.setAttribute("data-persona-composer-attachment-previews",""),g.style.display="none";let b=i.querySelector("[data-persona-composer-form]");b?.parentNode?b.parentNode.insertBefore(g,b):i.insertBefore(g,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let b=S("input");b.type="file",b.setAttribute("data-persona-composer-attachment-input",""),b.accept=(c.allowedTypes??xr).join(","),b.multiple=(c.maxFiles??4)>1,b.style.display="none",b.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(b)}},Ai=!1,sy=i=>{let c=p.find(b=>b.renderComposer);if(!c?.renderComposer)return null;let g=o.composer,f=y?T.isStreaming():!1;return c.renderComposer({config:o,defaultRenderer:i,requestRender:()=>Lv(),storage:v(c.id),onSubmit:b=>{!T||T.isStreaming()||hd(b.trim(),{consumeDraft:!1})},streaming:f,disabled:f,openAttachmentPicker:()=>{Oo()||St?.click()},models:g?.models,selectedModelId:ve.getState().selectedModelId??g?.selectedModelId,onModelChange:b=>ey(b),onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{_u?.()}:void 0})},iy=sy(()=>ui({config:o}).footer);iy&&(_n.replaceComposer(iy),He=_n.composer.footer,Ai=!0);let tt=null,WM=i=>{Mn=i.form,ce=i.input,Po=i.sendButton?i.sendButton.parentElement:null,i.sendButton&&(Te=i.sendButton),i.micButton&&(se=i.micButton,Fn=i.micButton.parentElement),i.found.status&&(Je=i.found.status),i.found.suggestions&&(Lr=i.found.suggestions),i.attachmentButton&&(kt=i.attachmentButton,En=i.attachmentButton.parentElement),St=i.attachmentInput??null,Tn=i.attachmentPreviews??null,i.found.actionsRow&&(MM=i.found.actionsRow),Lu=i.found.actionsStart,uc=i.found.actionsEnd};function Fu(){let i=ce;if(!i)return;let c=o.composer?.inputAttributes,g=!c?.ariaLabel&&!(i instanceof HTMLTextAreaElement)?i.getAttribute("aria-label"):null;up(i,c),g&&i.setAttribute("aria-label",g),pp(i,{submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Ol(i)}),zw(i,dp(o.composer?.maxLines,we()?5:3))}let ay=i=>{tt=Nw(i,{debug:o.debug===!0}),tt&&WM(tt),Fu()};ry(He),ay(He),ko();let Fa=ds(o,we());Fa&&(be.style.maxWidth=Fa,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%",Nn.style.maxWidth=Fa,Nn.style.marginLeft="auto",Nn.style.marginRight="auto",Nn.style.width="100%",ku.style.maxWidth=Fa,Ha.style.maxWidth=Fa,Ha.style.marginLeft="auto",Ha.style.marginRight="auto",Ha.style.width="100%");let ly=()=>{let i=ds(o,we());if(!(!i||we()))for(let c of[Mn,Lr,Tn,Je])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};ly();let cy=()=>{!o.attachments?.enabled||!St||!Tn||(rt?rt.remountPreviews(Tn):(rt=si.fromConfig(o.attachments,Zh),rt.setPreviewsContainer(Tn)),tt?.addListener(St,"change",i=>{let c=i.target;rt?.handleFileSelect(c.files),c.value=""}),de.querySelector(".persona-attachment-drop-overlay")||de.appendChild(MA(o.attachments.dropOverlay)))};cy();let OM=()=>Ft?.prefetch(),dy=()=>{if(!o.contextMentions?.enabled||!ce)return;let i=tt?.header??null,c=i?Cf(i):void 0;if(Ft=Rx({config:o,textarea:ce,anchor:Mn??ce,getMessages:()=>T.getMessages(),liveRegionHost:de,chipRow:c}),Ft&&!c){let g=ce;g.parentElement?.insertBefore(Ft.contextRow,g)}};dy();let Io=null,BM={getState:()=>ve.getState(),getValue:()=>ce?.value??"",setValue:i=>{ce&&(ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),ko())},submit:()=>{xx(tt?.form??null)},openAttachmentPicker:()=>{Oo()||St?.click()},toggleVoice:()=>{_u?.()},requestRender:()=>Io?.resolve()},DM=()=>{let i=[];return(Ft?.affordanceButtons??[]).forEach((g,f)=>{i.push({id:`core:mention-${f}`,placement:"start",order:Ko.mention+f,element:g,managed:!0})}),En&&i.push({id:"core:attachment",placement:"start",order:Ko.attachment,element:En}),Fn&&i.push({id:"core:mic",placement:"end",order:Ko.mic,element:Fn}),Po&&i.push({id:"core:send",placement:"end",order:Ko.send,element:Po}),i},py=()=>{Io?.destroy(),Io=tx({getBindings:()=>tt,collect:()=>({builtIns:DM(),configActions:[...HM(),...o.composer?.actions??[]],plugins:p,contributionContext:{config:o,getState:()=>ve.getState(),requestRender:()=>Io?.resolve()},debug:o.debug===!0}),actionContext:BM,getState:()=>ve.getState(),getOverflow:()=>o.composer?.actionOverflow,reportError:(i,c)=>{typeof console<"u"&&console.error(`[AgentWidget] composer action "${c.actionId}" failed:`,i)}}),Io.resolve()};py();let $u=()=>{if(Zo?.destroy(),Zo=null,!Ci().length)return;let i=tt?.header;i&&(Zo=sx({row:Cf(i),onRemove:c=>Ou(c),initialIds:ve.getState().activeModeIds}),Zo.render(ve.getState().activeModeIds,Ci()))};$u();let uy=()=>{Wr?.destroy(),Wr=null,Or?.destroy(),Or=null;let i=tt?.header;i&&(Wr=gx({onDismiss:()=>Lo(void 0)}),i.appendChild(Wr.element),Wr.render(ve.getState().quote),Du()==="defer-one"&&(Or=mx({onEdit:()=>dT(),onRemove:()=>xi(void 0)}),i.appendChild(Or.element),Or.render(ve.getState().pendingSubmission)))};uy();let Uu=Cx(),_M=()=>{let i=tt?.header?.querySelector(vf);if(i)return i.childElementCount>0;let c=ve.getState();return c.mentionRefs.length>0||xp(c.activeModeIds,Ci()).length>0};function mo(){let i=ve.getState(),c=Uu.observe(wx(ce),i.text);He.toggleAttribute("data-persona-composer-compact",vx({text:i.text,wrapped:c,hasAttachments:i.attachments.length>0,hasChips:_M(),hasQuote:i.quote!==void 0,hasPendingSubmission:i.pendingSubmission!==void 0}))}function gy(){o.composer?.layout==="single-row"&&!we()?He.setAttribute("data-persona-composer-layout","single-row"):He.removeAttribute("data-persona-composer-layout")}gy(),ve.subscribe(()=>{Io?.sync(),cg(),$c(),mo(),qy()}),$c();let my=!1,NM=i=>{if(my||o.debug!==!0)return;let c=["messages","composer"].filter(g=>i[g]);c.length&&(my=!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??{};NM(i);let c=f=>{switch(f){case"body-top":return ne.querySelector("[data-persona-intro-card]");case"messages":return be;case"footer-top":return Lr;case"composer":return Mn;case"footer-bottom":return Je;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 w=Pe.querySelector(".persona-flex-col");w?w.parentNode?.insertBefore(b,w.nextSibling):Pe.appendChild(b)}break;case"body-top":{let w=ne.querySelector("[data-persona-intro-card]");w?w.replaceWith(b):ne.insertBefore(b,ne.firstChild);break}case"body-bottom":ne.appendChild(b);break;case"footer-top":Lr.replaceWith(b);break;case"footer-bottom":Je.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)}})(),be.addEventListener("click",i=>{let c=i.target;if(!(c instanceof Element))return;let g=c.closest("button[data-persona-copy-tool-detail]");g&&(i.preventDefault(),i.stopPropagation(),zS(g))});let ju=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;Fr(),Wi();let w=g.getAttribute("data-bubble-type");if(f.classList.contains("persona-activity-row")){a.manual(b);let W=f.parentElement?.closest("[data-persona-tool-group]");W?.dataset.messageId&&a.manual(W.dataset.messageId)}if(w==="reasoning")s.has(b)?s.delete(b):s.add(b),rh(b,f,s);else if(w==="tool")r.has(b)?r.delete(b):r.add(b),lh(b,f,r,o);else if(w==="approval"&&C){let V=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",F=l.get(b)??V;l.set(b,!F),C.updateApprovalDetailsUI(b,f,o,l)}$t.delete(b)};be.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ju(i))}),be.addEventListener("click",i=>{i.detail===0&&i.target.closest(".persona-activity-row")&&ju(i)}),be.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ju(i))}),be.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let g=be.getRootNode(),f=typeof g.getSelection=="function"?g.getSelection():window.getSelection();if(!f||f.isCollapsed)return;let b=f.toString(),w=Gx(b);!w||w===b||(c.setData("text/plain",w),i.preventDefault())});let Vu=new Map,fy=null,hy="idle",FM={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},$M=(i,c)=>{let{icon:g,label:f}=FM[c];i.setAttribute("aria-label",f),i.title=f,i.setAttribute("aria-pressed",c==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",c!=="idle"),i.classList.toggle("persona-message-action-loading",c==="loading");let b=le(g,14,"currentColor",2);b&&(i.innerHTML="",i.appendChild(b))},yy=()=>{be.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let f=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;$M(c,f&&f===fy?hy:"idle")})};be.addEventListener("click",i=>{let g=i.target.closest(".persona-message-action-btn[data-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest("[data-actions-for]");if(!f)return;let b=f.getAttribute("data-actions-for");if(!b)return;let w=g.getAttribute("data-action");if(w==="copy"){let V=T.getMessages().find(F=>F.id===b);if(V&&vi.onCopy){let F=V.content||"";navigator.clipboard.writeText(F).then(()=>{g.classList.add("persona-message-action-success");let q=Mt(Tr.Check,14,"currentColor",2);q&&(g.innerHTML="",g.appendChild(q)),setTimeout(()=>{g.classList.remove("persona-message-action-success");let Q=Mt(Tr.Copy,14,"currentColor",2);Q&&(g.innerHTML="",g.appendChild(Q))},2e3)}).catch(q=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",q)}),vi.onCopy(V)}}else if(w==="read-aloud")T.toggleReadAloud(b);else if(w==="upvote"||w==="downvote"){let V=(Vu.get(b)??null)===w,F=w==="upvote"?"thumbs-up":"thumbs-down";if(V){Vu.delete(b),g.classList.remove("persona-message-action-active");let q=le(F,14,"currentColor",2);q&&(g.innerHTML="",g.appendChild(q))}else{let q=w==="upvote"?"downvote":"upvote",Q=f.querySelector(`[data-action="${q}"]`);if(Q){Q.classList.remove("persona-message-action-active");let nt=le(q==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(Q.innerHTML="",Q.appendChild(nt))}Vu.set(b,w),g.classList.add("persona-message-action-active");let ie=le(F,14,"currentColor",2);ie&&(ie.setAttribute("fill","currentColor"),g.innerHTML="",g.appendChild(ie)),g.classList.remove("persona-message-action-pop"),g.offsetWidth,g.classList.add("persona-message-action-pop");let Ve=T.getMessages().find(st=>st.id===b);Ve&&vi.onFeedback&&vi.onFeedback({type:w,messageId:Ve.id,message:Ve})}}else if(w==="regenerate")vc?.regenerate(b);else if(w==="edit")vc?.edit(b);else if(w==="quote")vc?.quote(b);else if(w?.startsWith(Vp)){let W=w.slice(Vp.length),V=o.messageActions?.custom?.find(q=>q.id===W),F=T.getMessages().find(q=>q.id===b);if(!V||!F)return;try{V.onSelect(F)}catch(q){console.error(`[AgentWidget] messageActions.custom "${W}" onSelect failed:`,q)}}});let vc=null;be.addEventListener("click",i=>{let g=i.target.closest("button[data-approval-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.closest(".persona-approval-bubble");if(!f)return;let b=f.getAttribute("data-message-id");if(!b)return;let w=g.getAttribute("data-approval-action");if(!w)return;let W=w==="approve"?"approved":"denied",F=T.getMessages().find(Q=>Q.id===b);if(!F?.approval)return;let q=f.querySelector("[data-approval-buttons]");q&&q.querySelectorAll("button").forEach(ie=>{ie.disabled=!0,ie.style.opacity="0.5",ie.style.cursor="not-allowed"}),F.approval.toolType==="webmcp"?T.resolveWebMcpApproval(b,W):T.resolveApproval(F.approval,W)});let Ke=null,by=!1,$a=null,Cs=()=>{},Ua="none",Cc=null,Xn={artifacts:[],selectedId:null},er=!1,fo=!1,ja=!1,Mi=!1,vy=()=>Mi||Xn.artifacts.some(i=>Vo(o.features?.artifacts,i)==="panel"),wc=()=>Xn.artifacts.length>0&&!er&&vy(),ct={current:null},qu=(i,c)=>{let g=T.getArtifactById(c),f=g?.markdown,b=g?.title||"artifact",w=g?.file,W=g?.artifactType??"markdown";if(!f){let q=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(q){let ie=T.getMessages().find(me=>me.id===q);if(ie?.rawContent)try{let me=JSON.parse(ie.rawContent);f=me?.props?.markdown,b=me?.props?.title||b,me?.props?.file&&typeof me.props.file=="object"&&(w=me.props.file),!g&&typeof me?.props?.artifactType=="string"&&(W=me.props.artifactType)}catch{}}}return{markdown:f,title:b,file:w,artifactType:W}};be.addEventListener("click",i=>{let g=i.target.closest("[data-download-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-download-artifact");if(!f||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:f})===!0)return;let{markdown:w,title:W,file:V}=qu(g,f);if(!w)return;let F=Ar();F&&F.triggerArtifactDownload(F.downloadInfoFor({title:W,markdown:w,file:V}))}),be.addEventListener("click",i=>{let g=i.target.closest("[data-artifact-custom-action]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-artifact-custom-action");if(!f)return;let b=g.closest("[data-artifact-inline]"),w=b?null:g.closest("[data-open-artifact]"),W=b?b.getAttribute("data-artifact-inline"):w?.getAttribute("data-open-artifact")??null,F=(b?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(st=>st.id===f);if(!F)return;let{markdown:q,title:Q,file:ie,artifactType:me}=qu(g,W??""),Ve={artifactId:W,title:Q,artifactType:me,markdown:q,file:ie};try{Promise.resolve(F.onClick(Ve)).catch(()=>{})}catch{}}),be.addEventListener("click",i=>{let g=i.target.closest("[data-copy-artifact]");if(!g)return;i.preventDefault(),i.stopPropagation();let f=g.getAttribute("data-copy-artifact");if(!f)return;let b=T.getArtifactById(f),w=Ar();if(!w)return;let W="";if(b)W=w.artifactCopyText(b);else{let{markdown:V,file:F,artifactType:q}=qu(g,f);q==="markdown"&&(W=w.artifactCopyText({id:f,artifactType:"markdown",status:"complete",markdown:V??"",...F?{file:F}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let V=Mt(Tr.Check,16,"currentColor",2);V&&(g.replaceChildren(V),setTimeout(()=>{let F=Mt(Tr.Copy,16,"currentColor",2);F&&g.replaceChildren(F)},1500))}).catch(()=>{})}),be.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||(er=!1,Mi=!0,fo=!0,ja=!0,T.selectArtifact(f),ho())}),be.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(),er=!1,Mi=!0,T.selectArtifact(f),ho())}),be.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 Ei=$e.composerOverlay,Ti=(i,c,g)=>{let f=c.trim();if(!f||!ct.current)return;let b=i.getAttribute("data-tool-call-id")??"",w=g.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:b,answer:f,answers:g.structured,values:g.values??(g.source==="multi"?f.split(", "):[f]),isFreeText:w,source:g.source},bubbles:!0,composed:!0})),ss(Ei,b);let W=ct.current.getMessages().find(V=>V.toolCall?.id===b);W?.agentMetadata?.awaitingLocalTool?ct.current.resolveAskUserQuestion(W,g.structured??f):ct.current.sendMessage(f)},ws=i=>{let c=ct.current;if(!c)return;let g=i.getAttribute("data-tool-call-id")??"",f=c.getMessages().find(b=>b.toolCall?.id===g);f&&c.persistAskUserQuestionProgress(f,{answers:Ud(i,f),currentIndex:lo(i)})},Cy=i=>Object.entries(i).map(([c,g])=>`${c}: ${Array.isArray(g)?g.join(", "):g}`).join(" | "),zu=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=lo(i),g=ia(i);if(c>=g-1)return;let f=ct.current?.getMessages().find(b=>b.toolCall?.id===i.getAttribute("data-tool-call-id"));f&&(jd(i,f,o,c+1),ws(i))};Ei.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})),ss(Ei,w);let W=ct.current?.getMessages().find(V=>V.toolCall?.id===w);W?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(W),ct.current?.resolveAskUserQuestion(W,"(dismissed)"));return}if(b==="pick"){let w=g.getAttribute("data-option-label");if(!w)return;let W=f.getAttribute("data-multi-select")==="true",V=rs(f);if(V&&W){let F=ti(f)[lo(f)],q=new Set(Array.isArray(F)?F:[]);q.has(w)?q.delete(w):q.add(w),is(f,Array.from(q)),ws(f);return}if(V){is(f,w),ws(f),zu(f);return}if(W){let F=g.getAttribute("aria-pressed")==="true";g.setAttribute("aria-pressed",F?"false":"true"),g.classList.toggle("persona-ask-pill-selected",!F);let q=f.querySelector('[data-ask-user-action="submit-multi"]');q&&(q.disabled=$m(f).length===0);return}Ti(f,w,{source:"pick",values:[w]});return}if(b==="submit-multi"){let w=$m(f);if(w.length===0)return;Ti(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(rs(f)){is(f,W.trim()),ws(f),zu(f);return}Ti(f,W,{source:"free-text"});return}if(b==="next"||b==="back"){if(!ct.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=ct.current.getMessages().find(ie=>ie.toolCall?.id===w);if(!W)return;let F=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(F){let ie=ti(f)[lo(f)];(typeof ie!="string"||ie!==F)&&is(f,F)}let q=b==="next"?1:-1,Q=lo(f)+q;jd(f,W,o,Q),ws(f);return}if(b==="submit-all"){if(!ct.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=ct.current.getMessages().find(ie=>ie.toolCall?.id===w);if(!W)return;let F=f.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";F&&is(f,F);let q=Ud(f,W);ct.current.persistAskUserQuestionProgress(W,{answers:q,currentIndex:lo(f)});let Q=Cy(q);Ti(f,Q||"(submitted)",{source:"submit-all",structured:q});return}if(b==="skip"){if(!ct.current)return;let w=f.getAttribute("data-tool-call-id")??"",W=ct.current.getMessages().find(me=>me.toolCall?.id===w);if(!W)return;let V=rs(f),F=lo(f),q=ia(f),Q=F>=q-1;if(!V){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:w},bubbles:!0,composed:!0})),ss(Ei,w),W.agentMetadata?.awaitingLocalTool&&(ct.current.markAskUserQuestionResolved(W),ct.current.resolveAskUserQuestion(W,"(dismissed)"));return}is(f,"");let ie=f.querySelector('[data-ask-free-text-input="true"]');if(ie&&(ie.value=""),Q){let me=Ud(f,W),Ve=Cy(me);Ti(f,Ve||"(skipped)",{source:"submit-all",structured:me});return}jd(f,W,o,F+1),ws(f);return}}),Ei.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(rs(f)){is(f,b.trim()),ws(f),zu(f);return}Ti(f,b,{source:"free-text"})}});let wy=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=Ei.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",wy);let Ro=null,Tt=null,Va=null,xc=null,Sc=()=>{},xy=!1,Ac="",Mc="";function Ku(){xc?.(),xc=null}let UM=()=>{let i=$i&&$s?.isConnected?$s:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},Sy=()=>{if(!Ro||!Tt)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){Tt.style.removeProperty("position"),Tt.style.removeProperty("left"),Tt.style.removeProperty("top"),Tt.style.removeProperty("bottom"),Tt.style.removeProperty("width"),Tt.style.removeProperty("z-index");return}let f=Ro.firstElementChild;if(!f||f===Tt)return;let b=10;Tt.style.position="absolute",Tt.style.top="0",Tt.style.bottom="0",Tt.style.width=`${b}px`,Tt.style.zIndex="5";let w=vh(Ro,c),W=f.offsetWidth+w/2-b/2;Tt.style.left=`${Math.max(0,W)}px`},Ec=()=>{},Ay=()=>{let i=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,g=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>g?!1:D||Ct(o)},Tc=()=>!Sn(o)||!wc()||e.classList.contains("persona-artifact-narrow-host")||Ay()||(e.ownerDocument.defaultView??window).innerWidth<SI?"none":fh(o)?"detached":"welded",ho=()=>{if(!Ke||!Sn(o))return;tc(e,o),nc(e,o),Ec();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=xe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let g=wc();Ke.setVisible(g),Ke.update(Xn),er?(Ke.setMobileOpen(!1),Ke.element.classList.add("persona-hidden"),Ke.backdrop?.classList.add("persona-hidden"),fo=!1,ja=!1):Xn.artifacts.length>0&&vy()?(Ke.element.classList.remove("persona-hidden"),Ke.setMobileOpen(!0)):(Ke.setMobileOpen(!1),Ke.element.classList.add("persona-hidden"),Ke.backdrop?.classList.add("persona-hidden"),fo=!1,ja=!1);let f=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ke.setExpandToggleVisible(f),Ke.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ke.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Ke.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ke.setTabFade(o.features?.artifacts?.layout?.tabFade),Ke.setRenderTabBar(o.features?.artifacts?.renderTabBar),!f&&!ja&&(fo=!1),fo!==xy){let w=Ke.element;fo?(Ac=w.style.width,Mc=w.style.maxWidth,w.style.removeProperty("width"),w.style.removeProperty("max-width")):(Ac&&(w.style.width=Ac),Mc&&(w.style.maxWidth=Mc),Ac="",Mc=""),xy=fo}e.classList.toggle("persona-artifact-expanded",fo),Ke.setExpanded(fo);let b=Tc();b!==Ua&&(Ua=b,Cs()),Sc()};if(Sn(o)){xe.style.position="relative";let i=S("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=S("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(de),Ro=c,c.appendChild(i),xe.appendChild(c);let g=b=>{by||Ke||(Ke=b.createArtifactPane(o,{onSelect:w=>ct.current?.selectArtifact(w),onDismiss:()=>{er=!0,ho()},onToggleExpand:()=>{let w=!fo,W=Xn.selectedId??Xn.artifacts[Xn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:W,expanded:w})!==!0&&(fo=w,w||(ja=!1),ho())}}),Ke.element.classList.add("persona-hidden"),c.appendChild(Ke.element),Ke.backdrop&&xe.appendChild(Ke.backdrop),Sc(),ho())},f=Ar();f?g(f):(gh(()=>{let b=Ar();b&&g(b)}),Yp().catch(()=>{})),Sc=()=>{if(!Ro||!Ke)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Va?.(),Va=null,Ku(),Tt&&(Tt.remove(),Tt=null),Ke.element.style.removeProperty("width"),Ke.element.style.removeProperty("maxWidth");return}if(!Tt){let w=S("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");w.setAttribute("role","separator"),w.setAttribute("aria-orientation","vertical"),w.setAttribute("aria-label","Resize artifacts panel"),w.tabIndex=0;let W=e.ownerDocument,V=W.defaultView??window,F=q=>{if(!Ke||q.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||V.innerWidth<=640)return;q.preventDefault(),Ku();let Q=q.clientX,ie=Ke.element.getBoundingClientRect().width,me=o.features?.artifacts?.layout,Ve=nt=>{let Rn=Ro.getBoundingClientRect().width,At=e.classList.contains("persona-artifact-welded-split"),Lt=vh(Ro,V),hn=At?0:w.getBoundingClientRect().width||6,Bt=ie-(nt.clientX-Q),pt=sA(Bt,Rn,Lt,hn,me?.resizableMinWidth,me?.resizableMaxWidth,UM());Ke.element.style.width=`${pt}px`,Ke.element.style.maxWidth="none",Sy()},st=()=>{W.removeEventListener("pointermove",Ve),W.removeEventListener("pointerup",st),W.removeEventListener("pointercancel",st),xc=null;try{w.releasePointerCapture(q.pointerId)}catch{}};xc=st,W.addEventListener("pointermove",Ve),W.addEventListener("pointerup",st),W.addEventListener("pointercancel",st);try{w.setPointerCapture(q.pointerId)}catch{}};w.addEventListener("pointerdown",F),Tt=w,Ro.insertBefore(w,Ke.element),Va=()=>{w.removeEventListener("pointerdown",F)}}if(Tt){let w=wc();Tt.classList.toggle("persona-hidden",!w),Sy()}},Ec=()=>{if(!D||!Ke||(o.launcher?.sidebarMode??!1)||Ct(o)&&Bn(o).reveal==="emerge")return;let w=e.ownerDocument.defaultView??window,W=o.launcher?.mobileFullscreen??!0,V=o.launcher?.mobileBreakpoint??640;if(W&&w.innerWidth<=V||!ZS(o,D))return;let F=mi(o).width,q=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";wc()?(xe.style.width=q,xe.style.maxWidth=q):(xe.style.width=F,xe.style.maxWidth=F)},typeof ResizeObserver<"u"&&($a=new ResizeObserver(()=>{ho()}),$a.observe(xe))}else xe.appendChild(de);we()&&en&&($e.peekBanner&&en.appendChild($e.peekBanner),en.appendChild(He)),e.appendChild(Qe),en&&e.appendChild(en);let Gu=()=>{let i=Ay()||we()&&o.launcher?.composerBar?.expandedSize==="fullscreen"||o.launcher?.fullHeight===!0&&!o.launcher?.sidebarMode&&!Ct(o);if(be.style.gap=i?"var(--persona-components-message-fullscreenGap, var(--persona-components-message-gap, 12px))":"var(--persona-components-message-gap, 12px)",be.style.setProperty("--persona-transcript-gap",be.style.gap),we()){xe.style.width="100%",xe.style.maxWidth="100%";let Re=o.launcher?.composerBar??{},Ue=Qe.dataset.state==="expanded",_e=Re.expandedSize??"anchored";if(!(Ue&&_e!=="fullscreen")){de.style.background="",de.style.border="",de.style.borderRadius="",de.style.overflow="",de.style.boxShadow="";return}let Kt=o.theme?.components?.panel,Hn=Mo(o),gr=(mr,Gs)=>mr==null||mr===""?Gs:cn(Hn,mr)??mr,mm="1px solid var(--persona-border)",Ks="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",fm="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";de.style.background="var(--persona-surface, #ffffff)",de.style.border=gr(Kt?.border,mm),de.style.borderRadius=gr(Kt?.borderRadius,fm),de.style.boxShadow=gr(Kt?.shadow,Ks),de.style.overflow="hidden";return}let c=Ct(o),g=o.launcher?.sidebarMode??!1,f=c||g||(o.launcher?.fullHeight??!1),b=o.launcher?.enabled===!1,w=o.launcher?.detachedPanel===!0,W=o.theme?.components?.panel,V=o.darkTheme?.components?.panel,F=ii(o)==="dark"?xo(W??{},V??{}):W,q=Mo(o),Q=(Re,Ue)=>Re==null||Re===""?Ue:cn(q,Re)??Re,ie=e.ownerDocument.defaultView??window,me=o.launcher?.mobileFullscreen??!0,Ve=o.launcher?.mobileBreakpoint??640,st=ie.innerWidth<=Ve,nt=me&&st&&D,Rn=c&&me&&st,At=o.launcher?.position??"bottom-left",Lt=At==="bottom-left"||At==="top-left",hn=o.launcher?.zIndex??pn,Bt=(Re,Ue,_e)=>`var(--persona-components-panel-modes-${Re}-${Ue}, ${_e})`,pt=F?.modes?.floating,No=Q(pt?.border??F?.border,Bt("floating","border","var(--persona-panel-border, 1px solid var(--persona-border))")),Fo=Q(pt?.shadow??F?.shadow,Bt("floating","shadow","var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))")),so=Q(pt?.borderRadius??F?.borderRadius,Bt("floating","borderRadius","var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))")),io=w&&!nt&&!Rn,Yr=nt||Rn?"mobile":io?"floating":c?"docked":g?"sidebar":b?"inline":"floating",$o=F?.modes?.[Yr];io?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let vo=io?No:g||nt?"none":No,Qr=io?Fo:nt?"none":g?Lt?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":b?"none":Fo;c&&!nt&&!io&&(Qr="none",vo="none");let hl=io?so:g||nt?"0":so,zs=Q($o?.border??F?.border,Bt(Yr,"border",vo)),R=Q($o?.shadow??F?.shadow,Bt(Yr,"shadow",Qr)),We=Q($o?.borderRadius??F?.borderRadius,Bt(Yr,"borderRadius",hl)),Oe=Tc(),re=Oe==="detached",ut=Oe==="welded";e.classList.toggle("persona-artifact-detached-split",re),e.classList.toggle("persona-artifact-welded-split",ut);let Ut="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)))))",bt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Sn(o)&&fh(o)&&b&&!c;e.classList.toggle("persona-artifact-chat-flush",bt);let Dt=re||bt?"none":R,Xt=re?No:ut?"none":zs,Le=re?so:We;bt&&(Xt="none",Le="0");let vt=$o?.borderRadius!=null&&$o.borderRadius!==""||F?.borderRadius!=null&&F.borderRadius!=="",De=bt&&!vt?"0":We,Jt=ne.scrollTop;e.style.cssText="",Qe.style.cssText="",xe.style.cssText="",de.style.cssText="",ne.style.cssText="",Ai||(He.style.cssText=""),go&&(ne.style.display="none"),(f||b)&&(e.style.minWidth="0");let ao=()=>{if(Jt<=0)return;(ne.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ne.scrollTop===Jt)return;let Ue=ne.scrollHeight-ne.clientHeight;Ue<=0||(ne.scrollTop=Math.min(Jt,Ue))})};if(nt){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=`
|
|
45
45
|
position: fixed !important;
|
|
46
46
|
inset: 0 !important;
|
|
47
47
|
width: 100% !important;
|
|
@@ -135,9 +135,9 @@ _Details: ${n.message}_`:o}var of=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
135
135
|
border-top: none !important;
|
|
136
136
|
padding: 8px 16px 12px 16px !important;
|
|
137
137
|
${bt?"background: transparent !important;":""}
|
|
138
|
-
`)}if(!b&&!c){let Re="max-height: -moz-available !important; max-height: stretch !important;",Ue=g?"":"padding-top: 1.25em !important;",_e=g?"":`z-index: ${o.launcher?.zIndex??pn} !important;`;Qe.style.cssText+=Re+Ue+_e}Wu(),ao()},Yu=()=>{e.style.setProperty("--persona-content-max-width",ds(o,we()))},Sy=!1;function Ay(){o.layout?.topFade&&ne.scrollTop>1?ne.setAttribute("data-persona-top-fade","true"):ne.removeAttribute("data-persona-top-fade")}let Qu=()=>{Ay();let i=Ef(o,we());we()&&o.composer?.placement&&o.debug===!0&&!Sy&&(Sy=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=ys();e.setAttribute("data-persona-composer-placement",i),e.setAttribute("data-persona-conversation-state",fc),e.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",c.composerGap??Ip),yc()},My=()=>{if(we())return;let i=Ct(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!D)return;let f=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640;if(b&&f.innerWidth<=w)return;let W=mi(o);xe.style.height=W.height,xe.style.maxHeight=W.maxHeight};Gu(),ai(e,o),tc(e,o),nc(e,o),Yu(),Qu(),Cs=()=>{Gu(),My(),ai(e,o),tc(e,o),nc(e,o),Yu(),Qu(),Cc?e.style.setProperty("--persona-artifact-welded-outer-radius",Cc):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Xo(),Eu()};let he=[];he.push(()=>{hy=!0}),he.push(()=>{h.forEach(i=>i()),m.destroy()}),he.push(()=>{document.removeEventListener("keydown",vy)}),he.push(()=>{Da!==null&&clearTimeout(Da)});let Ho=null,Wo=null;he.push(()=>{Ho?.(),Ho=null,Wo?.(),Wo=null}),$a&&he.push(()=>{$a?.disconnect(),$a=null}),he.push(()=>{Va?.(),Va=null,Ku(),Tt&&(Tt.remove(),Tt=null),Ke?.element.style.removeProperty("width"),Ke?.element.style.removeProperty("maxWidth"),Ke?.destroy()}),X&&he.push(()=>{gn=!0,It=null,kr!==null&&(cancelAnimationFrame(kr),kr=null),ht?.destroy(),ht=null,ft?.destroy(),ft=null,et=null});let xs=null,Ey=()=>{xs&&(xs(),xs=null),o.colorScheme==="auto"&&(xs=ya(()=>{ai(e,o)}))};Ey(),he.push(()=>{xs&&(xs(),xs=null)}),he.push(()=>{H=!0,E?.()}),he.push(()=>{L=!0});let Ty=!1;he.push(()=>{Ty=!0});let Xu=(i,c)=>{let g=zl(i,c);return g||!eS.includes(i)?g:(rS().then(f=>{if(Ty)return;ql(f.wipe),ql(f.glyphCycle);let b=zl(i,c);b&&Yl(b,e)}).catch(()=>{}),null)},Pc=o.features?.streamAnimation;if(Pc?.type&&Pc.type!=="none"){let i=Xu(Pc.type,Pc.plugins);i&&Yl(i,e),he.push(()=>oS(e))}let tr=Jl(Lr),Py=Jl(ku),ky=Jl(Ha),Ss=[tr,Py,ky];he.push(()=>{Ss.forEach(i=>i.destroy())});let As=null,T,Ms=null,Ly=!1,Iy=0,Ry=null,Hy=i=>i.reduce((c,g)=>g.role==="user"?c+1:c,0),Wy=i=>{for(let c=i.length-1;c>=0;c--)if(ni(i[c]))return i[c].id??null;return null},Oy=!1,HM=()=>{Oy||o.debug!==!0||(Oy=!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".'))},By=!1,Dy=!1,_y=(i,c)=>{By||o.debug!==!0||!c.enabled||c.expose||Ly||Dy&&(T.isStreaming()||i.some(ni)||(By=!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.")))},Es=i=>{if(!T)return;let c=i??T.getMessages(),g=se=>{se.render([],T,ce,c)},f=se=>{Ss.forEach(me=>{me!==se&&g(me)})};Ms&&(Hy(c)>Iy||Wy(c)!==Ry)&&(Ms=null);let b=as(o);_y(c,b);let w=b.enabled?qd(c):null,W=Ms??w,V=Ms?"host":"agent";if(W){let se=o.suggestions?.followUps,me=se?.placement??(se?"auto":"composer"),st=(me==="auto"?we()?"composer":"after-message":me)==="after-message"?ky:tr;f(st),st.render(W,T,ce,c,o.suggestionChipsConfig,{source:V,surface:"followUp",variant:se?.variant??"chip",behavior:se?.behavior??"send",overflow:se?.overflow??"wrap",maxItems:se?.maxItems??4,config:o,plugins:u,submitPrompt:fd});return}if(c.some(se=>se.role==="user")){Ss.forEach(g);return}let F=o.future?.v5Defaults===!0,q=_a(),Q=o.suggestions?.starters??(F?{}:void 0);if(Q){let se=gs(ys(),c),me=Q.placement??"auto",Ve=me==="auto"?se?"welcome":"composer":me;if(Ve==="welcome"&&!se){HM(),Ss.forEach(g);return}let st=Ve==="welcome"?Py:tr;f(st),st.render(Q.items??o.suggestionChips,T,ce,c,o.suggestionChipsConfig,{surface:"starter",variant:Q.variant??(F&&!q?"chip":"card"),behavior:Q.behavior??"send",overflow:Q.overflow??"wrap",maxItems:Q.maxItems??(F&&!q?3:4),config:o,plugins:u,submitPrompt:fd});return}f(tr),tr.render(o.suggestionChips,T,ce,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:u,submitPrompt:fd})},Ny=()=>{Ms&&(Ms=null,Es())},WM=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){Ny();return}let g=T?T.getMessages():[];Ms=c,Ly=!0,Iy=Hy(g),Ry=Wy(g),Es(g)},Un=!1,$t=Ux(),Pi=new Map,Ts=new Map,Br=new Map,Ps=null,Dr=null;function ks(){if(!Ps)return;let i=Ps;Ps=null,Dr?.destroy(),Dr=null,$t.delete(i),de.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),T&&Jn(be,T.getMessages(),N)}let Ls=0,OM=jo()!==null,jn=Kx(),Vn=0,_r=null,Tn=!1,kc=!1,Nr=0,Yt=null,Is=null,Ju=!1,ki=!1,Rs=null,qa=!0,Lc=!1,Li=null,Ic=!1,Fr=()=>{Ic=!0,NM()},Zu=null,BM=4,nr=24,DM=80,_M=1e3,or=null,Fy=()=>{e.setAttribute("data-persona-scrollbar",Iu()),Iu()!=="on-scroll"&&(or!==null&&clearTimeout(or),or=null,ne.removeAttribute("data-persona-scrollbar-visible"))},NM=()=>{Iu()==="on-scroll"&&(ne.setAttribute("data-persona-scrollbar-visible",""),or!==null&&clearTimeout(or),or=setTimeout(()=>{or=null,li(ne,nr)&&ne.removeAttribute("data-persona-scrollbar-visible")},_M))};Fy(),he.push(()=>{or!==null&&clearTimeout(or)});let eg=new Map,Xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};mo();let $y=o.voiceRecognition?.autoResume??!1,rr=i=>{oe.emit("voice:state",{active:Xe.active,source:i,timestamp:Date.now()})},yo=()=>{ye(i=>({...i,voiceState:{active:Xe.active,timestamp:Date.now(),manuallyDeactivated:Xe.manuallyDeactivated}}))},FM=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Ah(I.voiceState),c=!!i.active,g=Number(i.timestamp??0);Xe.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-g<uI&&setTimeout(()=>{Xe.active||(Xe.manuallyDeactivated=!1,Hn(o.voiceRecognition?.provider)?T.toggleVoice().then(()=>{Xe.active=T.isVoiceActive(),rr("restore"),T.isVoiceActive()&&Qi()}):bd("restore"))},1e3)},$M=()=>T?mA(T.getMessages()).filter(i=>!i.__skipPersist):[],Rc=null,Uy=(i,c)=>{typeof console<"u"&&console.error(i,c)},Hc=(i,c)=>{let g=()=>{try{let W=i();return!W||typeof W.then!="function"?null:Promise.resolve(W).catch(V=>{Uy(c,V)})}catch(W){return Uy(c,W),null}},f=Rc,b=f?f.then(()=>g()??void 0):g();if(!b)return;let w=b.finally(()=>{Rc===w&&(Rc=null)});Rc=w};function Ii(i){if(!k?.save)return;let c=i?mA(i):T?$M():[],g=_&&T?.getResumableHandle();g&&(I={...I,durableResume:{executionId:g.executionId,after:g.lastEventId}});let f={messages:c,metadata:I,artifacts:Xn.artifacts,selectedArtifactId:Xn.selectedId,...Hs?{draft:Hs}:{}};Hc(()=>k.save(f),"[AgentWidget] Failed to persist state:")}let Hs,Wc=()=>!k?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,za=cx({write:()=>{if(!Wc())return;let i=ve.getState(),c=ax({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Jg(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(Hs)&&(Hs=c,Ii())}});function jy(){Wc()&&za.schedule()}function tg(){za.flush()}function Vy(i){if(!Wc())return;let c=lx(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(g=>g.id),modelIds:(o.composer?.models??[]).map(g=>g.id),modes:o.composer?.modes??[]});c&&(Hs=i,ce&&!ce.value&&(ce.value=c.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),ko()),c.selectedModelId&&(ve.setSelectedModelId(c.selectedModelId),Hr?.repaint()),bc(c.activeModeIds??[]),c.quote&&Lo(c.quote),za.cancel())}function Oc(){za.cancel(),Hs&&(Hs=void 0,Wc()&&Ii())}let Ri=null,qy=()=>Qe.querySelector("#persona-scroll-container")||ne,Hi=()=>{Ri!==null&&(cancelAnimationFrame(Ri),Ri=null),Tn=!1},zy=()=>{_r!==null&&(cancelAnimationFrame(_r),_r=null),kc=!1,Hi()},UM=()=>Un&&og()&&($n()!=="anchor-top"||Gh()),ng=()=>{let i=Wa()||"Jump to latest",c=UM();qt.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Nr>0?(hs.textContent=String(Nr),hs.style.display="",qt.setAttribute("aria-label",`${i} (${Nr} new)`)):(hs.textContent="",hs.style.display="none",qt.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},Ky=()=>{Nr!==0&&(Nr=0,ng())},jM=()=>{let i=Yt?.spacerHeight??0;return i<=0?li(ne,nr):Nc(i)-ne.scrollTop-ne.clientHeight<=nr},og=()=>Rr()?!jn.isFollowing():!jM(),rg=()=>!!T&&T.getMessages().length>0,Qt=()=>{if(!bM()||dM()){qt.parentNode&&qt.remove(),qt.style.display="none";return}qt.parentNode!==de&&de.appendChild(qt),bs();let c=Go(ne)>0&&og()&&rg();c?ng():Ky(),qt.style.display=c?"":"none"},Wi=()=>{jn.pause()&&(zy(),Qt())},Pn=()=>{jn.resume(),Ky(),Qt()},$r=(i=!1)=>{Rr()&&rg()&&jn.isFollowing()&&(!i&&!Un||(_r!==null&&(cancelAnimationFrame(_r),_r=null),kc=!0,_r=requestAnimationFrame(()=>{_r=null,kc=!1,jn.isFollowing()&&VM(qy(),i?220:140)})))},Gy=(i,c,g,f=()=>!0)=>{let b=i.scrollTop,w=c(),W=w-b;if(Hi(),Math.abs(W)<1){Tn=!0,i.scrollTop=w,Vn=i.scrollTop,Tn=!1;return}let V=performance.now();Tn=!0;let F=Q=>1-Math.pow(1-Q,3),q=Q=>{if(!f()){Hi();return}let se=c();se!==w&&(w=se,W=w-b);let me=Q-V,Ve=Math.min(me/g,1),st=F(Ve),nt=b+W*st;i.scrollTop=nt,Vn=i.scrollTop,Ve<1?Ri=requestAnimationFrame(q):(i.scrollTop=w,Vn=i.scrollTop,Ri=null,Tn=!1)};Ri=requestAnimationFrame(q)},VM=(i,c=500)=>{let g=Go(i)-i.scrollTop;if(Math.abs(g)<1){Vn=i.scrollTop;return}if(Math.abs(g)>=DM){Hi(),Tn=!0,i.scrollTop=Go(i),Vn=i.scrollTop,Tn=!1;return}Gy(i,()=>Go(i),c,()=>jn.isFollowing())},Bc=()=>{if(!rg()){Qt();return}let i=qy();Tn=!0,i.scrollTop=Go(i),Vn=i.scrollTop,Tn=!1,Qt()},Ws=i=>{let c=0,g=i;for(;g&&g!==ne;)c+=g.offsetTop,g=g.offsetParent;return c},qM=()=>{let i=ne.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ne.ownerDocument.getSelection()},Dc=()=>Qx(qM(),ne),sg=()=>{if(vM()!=="last-user-turn")return!1;let i=T?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(w=>w.role==="user");if(!c)return!1;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=ne.querySelector(`[data-message-id="${g}"]`);if(!f)return!1;let b=Math.min(Math.max(0,Ws(f)-Oa()),Go(ne));return Tn=!0,ne.scrollTop=b,Vn=ne.scrollTop,Tn=!1,$n()==="follow"&&!li(ne,nr)&&jn.pause(),Qt(),!0},_c=i=>{let c=Math.max(0,Math.round(i));Qn.style.height=`${c}px`,Qn.style.display=c>0?"":"none",Yt&&(Yt.spacerHeight=Math.max(0,i))},Nc=i=>{let c=parseFloat(getComputedStyle(ne).paddingBottom)||0,g=0;for(let b of Array.from(ne.children)){if(b===Qn||b.offsetHeight===0)continue;let w=Ws(b)+b.offsetHeight;w>g&&(g=w)}let f=ne.scrollHeight-i;return g>0?Math.min(g+c,f):f},zM=()=>{if(!Yt||Yt.spacerHeight<=0)return;let i=Nc(Yt.spacerHeight),c=Math.max(0,Math.round(ne.scrollTop)+ne.clientHeight-i+nr);c<Yt.spacerHeight&&(_c(c),Qt())},bo=()=>{Is!==null&&(cancelAnimationFrame(Is),Is=null),Hi(),Yt=null,Qn.style.height="0px",Qn.style.display="none"},Yy=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),ig=i=>ne.querySelector(`[data-message-id="${Yy(i)}"]`),Qy=i=>{Is!==null&&cancelAnimationFrame(Is),Is=requestAnimationFrame(()=>{Is=null;let c=Yy(i),g=ne.querySelector(`[data-message-id="${c}"]`);if(!g)return;let f=Ws(g),b=Yt?.spacerHeight??0,w=Nc(b),{targetScrollTop:W,spacerHeight:V}=kf({anchorOffsetTop:f,topOffset:Oa(),viewportHeight:ne.clientHeight,contentHeight:w,slack:nr});Yt={initialSpacerHeight:V,contentHeightAtAnchor:w,spacerHeight:V},_c(V),Gy(ne,()=>g.isConnected?Math.max(0,Ws(g)-Oa()):W,220)})},kn=()=>{if($n()!=="anchor-top"||!Yt||!Li)return;let i=ig(Li);if(!i)return;Hi();let c=Yt.spacerHeight,g=Nc(c),{targetScrollTop:f,spacerHeight:b}=kf({anchorOffsetTop:Ws(i),topOffset:Oa(),viewportHeight:ne.clientHeight,contentHeight:g,slack:nr});Yt={initialSpacerHeight:b,contentHeightAtAnchor:g,spacerHeight:b},_c(b),Tn=!0,ne.scrollTop=f,Vn=ne.scrollTop,Tn=!1,Qt()},KM=()=>{if(Rr()){if(!jn.isFollowing()||li(ne,1))return;$r(!Un);return}if(Yt&&Yt.initialSpacerHeight>0){let i=ne.scrollHeight-Yt.spacerHeight,c=Xx({initialSpacerHeight:Yt.initialSpacerHeight,contentHeightAtAnchor:Yt.contentHeightAtAnchor,currentContentHeight:i});c!==Yt.spacerHeight&&_c(c)}Qt()},GM=i=>{let c=$n();c==="follow"?(Pn(),$r(!0)):c==="anchor-top"&&(qa=!1,Lc=!0,Ic=!1,Li=i,Qy(i))},YM=()=>{if($n()==="anchor-top"){if(Lc){qa=!1;return}qa=!0,bo(),Pn(),$r(!0)}},QM=96,XM=i=>{if(Rs===null)return!0;let c=ig(Rs),g=ig(i);if(!c||!g)return!0;let f=Ws(g)-Ws(c);return Oa()+f>ne.clientHeight-QM},JM=i=>{if($n()!=="anchor-top"||!Lc||Ic||Dc())return;let c=Rs===null;for(let g of i){if(!c){g.id===Rs&&(c=!0);continue}if(zx(g)){if(g.id===Li||!XM(g.id))return;Li=g.id,Qy(g.id);return}}},ZM=i=>{let c=new Map;i.forEach(g=>{let f=eg.get(g.id);c.set(g.id,{streaming:g.streaming,role:g.role}),!f&&g.role==="assistant"&&(oe.emit("assistant:message",g),!ki&&($n()!=="anchor-top"||Gh())&&og()&&(Nr+=1,ng(),Qt(),mc(Nr===1?"1 new message below.":`${Nr} new messages below.`))),g.role==="assistant"&&f?.streaming&&g.streaming===!1&&oe.emit("assistant:complete",g),g.variant==="approval"&&g.approval&&(f?g.approval.status!=="pending"&&oe.emit("approval:resolved",{approval:g.approval,decision:g.approval.status}):oe.emit("approval:requested",{approval:g.approval,message:g}))}),eg.clear(),c.forEach((g,f)=>{eg.set(f,g)})},Ka=(i,c)=>{let g=c==="user"?"user":"assistant",f=o.layout?.messages?.[g],b=f?.width??"content",w=f?.maxWidth??(b==="full"?`var(--persona-message-${g}-max-width, 100%)`:void 0);i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${c}`,`persona-message-width-${b}`),i.classList.toggle("persona-justify-end",c==="user"),i.setAttribute("data-message-role",c),i.setAttribute("data-message-width",b),w?i.style.setProperty("--persona-message-row-max-width",w):i.style.removeProperty("--persona-message-row-max-width")},sr=(i,c)=>{let g=document.createElement("div");return g.className="persona-flex",g.id=`wrapper-${i}`,g.setAttribute("data-wrapper-id",i),Ka(g,c),g},eE=(i,c,g)=>{let f=new Set;for(let R of c){let We=R.variant==="tool"?"tool":R.variant==="reasoning"?"reasoning":null;if(!We||Zr(o,We)!=="row")continue;let Oe=We==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;Oe?.expandable!==!1&&(f.add(R.id),a.observe(R,We,We==="tool"?r:s,Oe))}let b=document.createElement("div"),W=(()=>{let R=u.find(We=>We.renderLoadingIndicator);if(R?.renderLoadingIndicator)return R.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),V=(R,We)=>We==null?!1:typeof We=="string"?(R.textContent=We,!0):(R.appendChild(We),!0),F=new Set,q=new Map,Q=new Set,se=u.some(R=>R.renderAskUserQuestion),me=[],Ve=[],st=o.enableComponentStreaming!==!1,nt=o.approval!==!1,In=[],At=o.messageActions,Lt=At?.showRegenerate===!0&&At.enabled!==!1&&ct.current?.isStreaming()!==!0?yw(c):null,hn=At?.showEdit===!0&&At.enabled!==!1,Bt=At?.showQuote===!0&&At.enabled!==!1,pt=null,No=o.features?.reasoningDisplay?.completedVisibility,Fo=R=>No==="removed"?!0:No==="removed-when-short"?jC(R,o.features?.reasoningDisplay?.shortThinkThreshold):!1,so=o.features?.toolCallDisplay?.completedVisibility==="removed",io=R=>R.variant==="reasoning"&&R.reasoning?.status==="complete"?Fo(R.reasoning):so&&R.variant==="tool"&&R.toolCall?.status==="complete";if(c.forEach(R=>{if(io(R))return;if(F.add(R.id),q.set(R.id,R.role),Ps===R.id&&Dr){let De=sr(R.id,R.role);De.setAttribute("data-persona-message-edit-stub","true"),De.setAttribute("data-preserve-runtime","true"),b.appendChild(De),pt={messageId:R.id,element:Dr.element};return}let We=se&&vr(R),Oe=nt&&R.variant==="approval"&&!!R.approval,re=!We&&R.role==="assistant"&&!R.variant&&st&&ac(R);!Oe&&Br.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),Br.delete(R.id)),!re&&Ts.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),Ts.delete(R.id));let ut=vr(R)?`:${R.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${R.agentMetadata?.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ut={canRegenerate:Lt===R.id,canEdit:hn&&Xm(R),canQuote:Bt&&!R.variant&&(R.content?.trim().length??0)>0},un=`${Ut.canRegenerate?"r":""}${Ut.canEdit?"e":""}${Ut.canQuote?"q":""}`,nn=$x(R,Ls)+ut+`:${un}`,bt=We||Oe||re?null:jx($t,R.id,nn);if(bt){b.appendChild(bt.cloneNode(!0)),vr(R)&&R.toolCall?.id&&R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(Q.add(R.toolCall.id),aa(R,o,$e.composerOverlay));return}let Dt=null,Xt=u.find(De=>!!(R.variant==="reasoning"&&De.renderReasoning||R.variant==="tool"&&De.renderToolCall||!R.variant&&De.renderMessage)),Le=o.layout?.messages;if(vr(R)&&R.agentMetadata?.askUserQuestionAnswered===!0){Pi.delete(R.id),i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime");return}if(ni(R)&&as(o).enabled)return;if(vr(R)&&o.features?.askUserQuestion?.enabled!==!1){let De=u.find(Jt=>typeof Jt.renderAskUserQuestion=="function");if(De&&ct.current){let Jt=Pi.get(R.id),ao=Jt!==nn,on=null;if(ao){let{payload:Ue,complete:_e}=Cr(R),Xr=R.id,Kt=()=>ct.current?.getMessages().find(Rn=>Rn.id===Xr);on=De.renderAskUserQuestion({message:R,payload:Ue,complete:_e,resolve:Rn=>{let gr=Kt();gr&&ct.current?.resolveAskUserQuestion(gr,Rn)},dismiss:()=>{let Rn=Kt();Rn?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(Rn),ct.current?.resolveAskUserQuestion(Rn,"(dismissed)"))},config:o})}let gt=Jt!=null;if(ao&&on===null&&!gt){R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(Q.add(R.toolCall.id),aa(R,o,$e.composerOverlay));return}let Re=sr(R.id,R.role);Re.setAttribute("data-ask-plugin-stub","true"),Re.setAttribute("data-preserve-runtime","true"),b.appendChild(Re),me.push({messageId:R.id,fingerprint:nn,bubble:on});return}else{R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(Q.add(R.toolCall.id),aa(R,o,$e.composerOverlay));return}}else if(Oe){let De=O();if(!De){b.appendChild(sr(R.id,R.role));return}let Jt=u.find(Re=>typeof Re.renderApproval=="function")??x,on=Br.get(R.id)!==nn,gt=null;if(on&&Jt?.renderApproval){let Re=R.id,Ue=(_e,Xr)=>{let Kt=ct.current?.getMessages().find(Rn=>Rn.id===Re);Kt?.approval&&(Kt.approval.toolType==="webmcp"?ct.current?.resolveWebMcpApproval(Kt.id,_e):ct.current?.resolveApproval(Kt.approval,_e,Xr))};gt=Jt.renderApproval({message:R,defaultRenderer:()=>De.createApprovalBubble(R,o,l),config:o,approve:_e=>Ue("approved",_e),deny:_e=>Ue("denied",_e)})}if(on&>===null)i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),Br.delete(R.id),Dt=De.createApprovalBubble(R,o,l);else{let Re=sr(R.id,R.role);Re.setAttribute("data-approval-plugin-stub","true"),Re.setAttribute("data-preserve-runtime","true"),b.appendChild(Re),In.push({messageId:R.id,fingerprint:nn,bubble:gt});return}}else if(Xt)if(R.variant==="reasoning"&&R.reasoning&&Xt.renderReasoning){if(!z)return;Dt=Xt.renderReasoning({message:R,defaultRenderer:()=>oh(R,o,s),config:o})}else if(R.variant==="tool"&&R.toolCall&&Xt.renderToolCall){if(!J)return;Dt=Xt.renderToolCall({message:R,defaultRenderer:()=>ah(R,o,r),config:o})}else Xt.renderMessage&&(Dt=Xt.renderMessage({message:R,defaultRenderer:()=>{let De=wa(R,g,Le,o.messageActions,vi,{loadingIndicatorRenderer:W,widgetConfig:o,actionEligibility:Ut});return R.role!=="user"&&ae(De,R,o,T),De},config:o}));if(!Dt&&re){let De=ou(R);if(De){let Jt=Ts.get(R.id),ao=Jt!==nn,on=o.wrapComponentDirectiveInBubble!==!1&&Eo.getOptions(De.component)?.bubbleChrome!==!1,gt=null;if(ao){let Re=nu(De,{config:o,message:R,transform:g});if(Re&&De.component==="PersonaArtifactInline"){let Ue=Re.hasAttribute("data-artifact-inline")?Re:Re.querySelector("[data-artifact-inline]"),_e=Ue?.getAttribute("data-artifact-inline")??"",Xr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(_e):_e,Kt=_e?i.querySelector(`#wrapper-${R.id}`)?.querySelector(`[data-artifact-inline="${Xr}"]`)??null:null;Ue&&Kt&&Kt!==Ue&&Ar()?.hasLiveInlineArtifactBlock(Kt)&&(Ue===Re?Re=Kt:Ue.replaceWith(Kt))}if(Re)if(on){let Ue=document.createElement("div");if(Ue.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ue.id=`bubble-${R.id}`,Ue.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let _e=document.createElement("div");_e.className="persona-mb-3 persona-text-sm persona-leading-relaxed",_e.innerHTML=g({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ue.appendChild(_e)}Ue.appendChild(Re),gt=Ue}else{let Ue=document.createElement("div");if(Ue.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ue.id=`bubble-${R.id}`,Ue.setAttribute("data-message-id",R.id),Ue.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let _e=document.createElement("div");_e.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",_e.innerHTML=g({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ue.appendChild(_e)}Ue.appendChild(Re),gt=Ue}}if(gt||Jt!=null){let Re=sr(R.id,R.role);Re.setAttribute("data-component-directive-stub","true"),Re.setAttribute("data-preserve-runtime","true"),b.appendChild(Re),Ve.push({messageId:R.id,fingerprint:nn,bubble:gt});return}}}if(!Dt)if(R.variant==="reasoning"&&R.reasoning){if(!z)return;Dt=oh(R,o,s)}else if(R.variant==="tool"&&R.toolCall){if(!J)return;Dt=ah(R,o,r)}else if(R.variant==="approval"&&R.approval){if(o.approval===!1)return;let De=O();if(!De)return;Dt=De.createApprovalBubble(R,o,l)}else{let De=o.layout?.messages;De?.renderUserMessage&&R.role==="user"?Dt=De.renderUserMessage({message:R,config:o,streaming:!!R.streaming}):De?.renderAssistantMessage&&R.role==="assistant"?Dt=De.renderAssistantMessage({message:R,config:o,streaming:!!R.streaming}):Dt=wa(R,g,De,o.messageActions,vi,{loadingIndicatorRenderer:W,widgetConfig:o,actionEligibility:Ut}),R.role!=="user"&&Dt&&ae(Dt,R,o,T)}let vt=sr(R.id,R.role);vt.appendChild(Dt),Vx($t,R.id,nn,vt),b.appendChild(vt)}),$e.composerOverlay&&$e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(We=>{let Oe=We.getAttribute("data-persona-ask-sheet-for");Oe&&!Q.has(Oe)&&ss($e.composerOverlay,Oe)}),o.features?.toolCallDisplay?.grouped){let R=[],We=[],Oe=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(re=>{if(re.variant==="tool"&&re.toolCall&&J){if(so&&re.toolCall.status==="complete")return;We.push(re);return}re.variant==="reasoning"&&(!z||re.reasoning?.status==="complete"&&Fo(re.reasoning))||((We.length>1||Oe&&We.length>0)&&R.push(We),We=[])}),(We.length>1||Oe&&We.length>0)&&R.push(We),R.forEach(re=>{let ut=re.map(Le=>Array.from(b.children).find(vt=>vt instanceof HTMLElement&&vt.getAttribute("data-wrapper-id")===Le.id)).filter(Le=>!!Le);if(ut.length<(Oe?1:2))return;let Ut=sr(`tool-group-${re[0].id}`,"assistant");if(Ut.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let Le=`tool-group-${re[0].id}`,vt=re.some(gt=>gt.toolCall?.status!=="complete"),De={...re[0],id:Le,toolCall:{id:Le,name:`${re.length} tools`,status:vt?"running":"complete",chunks:re.flatMap(gt=>gt.toolCall?.chunks??[]),success:!re.some(gt=>gt.toolCall?.success===!1)}};f.add(Le),a.observe(De,"tool",r,o.features.toolCallDisplay);let Jt=`${vt?"Using":"Used"} ${re.length} tools`,ao=o.toolCall?.renderGroupedSummary?.({messages:re,toolCalls:re.map(gt=>gt.toolCall),defaultSummary:Jt,config:o}),on=oC(De,o,r.has(Le),ao??Jt);on.bubble.classList.add("persona-tool-group"),on.body.dataset.personaToolGroupStack="true",ut[0].before(Ut),Ut.appendChild(on.bubble),ut.forEach((gt,Re)=>{gt.style.setProperty("--persona-message-row-max-width","100%"),gt.style.setProperty("--persona-activity-stagger",`${Re*40}ms`),gt.classList.add("persona-activity-group-child"),on.body.appendChild(gt)});return}let un=document.createElement("div");un.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",un.setAttribute("data-persona-tool-group","true");let nn=document.createElement("div");nn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",nn.id=`tool-group-summary-${re[0].id}`;let bt=`Called ${re.length} ${re.length===1?"tool":"tools"}`,Dt=o.toolCall?.renderGroupedSummary?.({messages:re,toolCalls:re.map(Le=>Le.toolCall).filter(Le=>!!Le),defaultSummary:bt,config:o});V(nn,Dt)||(nn.textContent=bt);let Xt=document.createElement("div");Xt.className="persona-tool-group-stack persona-flex persona-flex-col",Xt.id=`tool-group-stack-${re[0].id}`,Xt.setAttribute("data-persona-tool-group-stack","true"),un.appendChild(nn),Oe||un.appendChild(Xt),Ut.appendChild(un),ut[0].before(Ut),ut.forEach((Le,vt)=>{if(Oe){Le.remove();return}Le.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"),vt<ut.length-1&&De.setAttribute("data-persona-tool-group-connector","true"),De.appendChild(Le),Xt.appendChild(De)})})}a.prune(f),qx($t,F);let Yr=R=>R.variant==="tool"&&!J||R.variant==="reasoning"&&!z||io(R),$o=c.some(R=>R.role==="assistant"&&R.streaming&&!Yr(R)),vo=c.length-1;for(;vo>=0&&Yr(c[vo]);)vo--;let Qr=vo>=0?c[vo]:void 0,hl=vo<c.length-1,zs=Qr?.role==="assistant"&&!Qr.streaming&&Qr.variant!=="approval"&&!hl;if(Un&&c.some(R=>R.role==="user")&&!$o&&!zs){let R={config:o,streaming:!0,location:"standalone",defaultRenderer:gi},We=u.find(re=>re.renderLoadingIndicator),Oe=null;if(We?.renderLoadingIndicator&&(Oe=We.renderLoadingIndicator(R)),Oe===null&&o.loadingIndicator?.render&&(Oe=o.loadingIndicator.render(R)),Oe===null&&(Oe=gi()),Oe){let re=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1,Ut=o.layout?.messages?.layout??"bubble";re.className=ut?ec("assistant",Ut).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),re.setAttribute("data-typing-indicator","true"),ut&&(re.style.color="var(--persona-message-assistant-text, var(--persona-text))",Ut!=="flat"&&(re.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",re.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),re.appendChild(Oe);let un=sr("typing-indicator","assistant");un.appendChild(re),b.appendChild(un)}}if(!Un&&c.length>0){let R=c[c.length-1],We={config:o,lastMessage:R,messageCount:c.length},Oe=u.find(ut=>ut.renderIdleIndicator),re=null;if(Oe?.renderIdleIndicator&&(re=Oe.renderIdleIndicator(We)),re===null&&o.loadingIndicator?.renderIdle&&(re=o.loadingIndicator.renderIdle(We)),re){let ut=document.createElement("div"),Ut=o.loadingIndicator?.showBubble!==!1;ut.className=Ut?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ut.setAttribute("data-idle-indicator","true"),ut.appendChild(re);let un=sr("idle-indicator","assistant");un.appendChild(ut),b.appendChild(un)}}if(bC(b),Op(i,b),Im(i),pt){let{messageId:R,element:We}=pt,Oe=i.querySelector(`#wrapper-${R}`);Oe&&We.parentElement!==Oe&&(Ka(Oe,q.get(R)??"user"),Oe.replaceChildren(We))}if(me.length>0)for(let{messageId:R,fingerprint:We,bubble:Oe}of me){let re=i.querySelector(`#wrapper-${R}`);re&&(Ka(re,q.get(R)??"assistant"),Oe!==null&&(re.replaceChildren(Oe),re.setAttribute("data-bubble-fp",We),Pi.set(R,We)))}if(Pi.size>0)for(let R of Pi.keys())F.has(R)||Pi.delete(R);if(Ve.length>0)for(let{messageId:R,fingerprint:We,bubble:Oe}of Ve){let re=i.querySelector(`#wrapper-${R}`);re&&(Ka(re,q.get(R)??"assistant"),Oe!==null&&(re.replaceChildren(Oe),re.setAttribute("data-bubble-fp",We),Ts.set(R,We)))}if(Ts.size>0)for(let R of Ts.keys())F.has(R)||Ts.delete(R);if(In.length>0)for(let{messageId:R,fingerprint:We,bubble:Oe}of In){let re=i.querySelector(`#wrapper-${R}`);re&&(Ka(re,q.get(R)??"assistant"),Oe!==null&&(re.replaceChildren(Oe),re.setAttribute("data-bubble-fp",We),Br.set(R,We)))}if(Br.size>0)for(let R of Br.keys())F.has(R)||Br.delete(R)},ag=!1,Fc=()=>{ag||(ag=!0,Md().catch(()=>{ag=!1}))},Jn=(i,c,g)=>{c.length>0&&Fc(),eE(i,c,g),fy()},Ga=null,tE=()=>{if(Ga)return;let i=g=>{let f=g.composedPath();f.includes(Qe)||en&&f.includes(en)||yt(!1,"user")};Ga=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},Xy=()=>{if(!Ga)return;(e.ownerDocument??document).removeEventListener("pointerdown",Ga,!0),Ga=null};he.push(()=>Xy());let Ya=null,nE=()=>{if(Ya)return;let i=g=>{g.key==="Escape"&&(g.isComposing||yt(!1,"user"))};Ya=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Jy=()=>{if(!Ya)return;(e.ownerDocument??document).removeEventListener("keydown",Ya,!0),Ya=null};he.push(()=>Jy());let Qa=!1,Zy=new Set,oE=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Oi=()=>{if(!we())return;let i=$e.peekBanner,c=$e.peekTextNode;if(!i||!c)return;if(Ee){i.classList.remove("persona-pill-peek--visible");return}let g=T?.getMessages()??[],f;for(let At=g.length-1;At>=0;At--){let Lt=g[At];if(Lt.role==="assistant"&&Lt.content){f=Lt;break}}if(!f){i.classList.remove("persona-pill-peek--visible");return}let b=f.content,w=!!f.streaming,W=oE(),V=Bp(W),F=V.type!=="none"?Xu(V.type,W?.plugins):null,q=F?.isAnimating?.(f)===!0,Q=F!==null&&(w||q);Q&&F&&!Zy.has(F.name)&&(Yl(F,e),Zy.add(F.name));let se=Q&&F?.containerClass?F.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),Q?(c.style.setProperty("--persona-stream-step",`${V.speed}ms`),c.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let Ve=Q?Dp(b,V.buffer,F,f,w):b;if(Q&&V.placeholder==="skeleton"&&w&&(!Ve||!Ve.trim())){let At=document.createElement("div"),Lt=Gl();Lt.classList.add("persona-pill-peek__skeleton"),At.appendChild(Lt),Op(c,At)}else{let At=Math.max(0,Ve.length-100),Lt=Ve.length>100?Ve.slice(-100):Ve,hn=br(Lt);if(!Q||!F){let Bt=Ve.length>100?`\u2026${Lt}`:Lt;c.textContent!==Bt&&(c.textContent=Bt)}else{let Bt=hn;(F.wrap==="char"||F.wrap==="word")&&(Bt=Kl(hn,F.wrap,`peek-${f.id}`,{skipTags:F.skipTags,startIndex:At}));let pt=document.createElement("div");if(pt.innerHTML=Bt,F.useCaret&&Lt.length>0){let No=_p(),Fo=pt.querySelectorAll(".persona-stream-char, .persona-stream-word"),so=Fo[Fo.length-1];so?.parentNode?so.parentNode.insertBefore(No,so.nextSibling):pt.appendChild(No)}Op(c,pt),F.onAfterRender?.({container:c,bubble:i,messageId:f.id,message:f,speed:V.speed,duration:V.duration})}}let In=Un||Qa;i.classList.toggle("persona-pill-peek--visible",In)};if(we()){let i=$e.peekBanner;if(i){let f=b=>{b.preventDefault(),b.stopPropagation(),yt(!0,"user")};i.addEventListener("pointerdown",f),he.push(()=>{i.removeEventListener("pointerdown",f)})}let c=()=>{Qa||(Qa=!0,Oi())},g=()=>{Qa&&(Qa=!1,Oi())};xe.addEventListener("pointerenter",c),xe.addEventListener("pointerleave",g),he.push(()=>{xe.removeEventListener("pointerenter",c),xe.removeEventListener("pointerleave",g)}),en&&(en.addEventListener("pointerenter",c),en.addEventListener("pointerleave",g),he.push(()=>{en.removeEventListener("pointerenter",c),en.removeEventListener("pointerleave",g)}))}let rE=i=>{let c=o.launcher?.composerBar??{},g=c.expandedSize??"anchored",f=c.bottomOffset??"16px",b=c.collapsedMaxWidth,w=c.expandedMaxWidth??"880px",W=c.expandedTopOffset??"5vh",V=c.modalMaxWidth??"880px",F=c.modalMaxHeight??"min(90vh, 800px)",q="calc(100vw - 32px)",Q="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="",en){let me=en.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=V,se.maxWidth=q,se.maxHeight=F,se.height=F;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${f} + ${Q})`,se.top=W,se.width=w,se.maxWidth=q}},Xa=()=>{if(Ee&&Fc(),!Be())return;if(we()){let q=(o.launcher?.composerBar??{}).expandedSize??"anchored",Q=Ee?"expanded":"collapsed";Qe.dataset.state=Q,Qe.dataset.expandedSize=q,en&&(en.dataset.state=Q,en.dataset.expandedSize=q),Qe.style.removeProperty("display"),Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),rE(Ee),de.style.display=Ee?"flex":"none",Cs(),Ee?(tE(),nE()):(Xy(),Jy()),Oi();return}let i=Ct(o),c=e.ownerDocument.defaultView??window,g=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,b=c.innerWidth<=g,w=f&&b&&D,W=Bn(o).reveal;Ee?(Qe.style.removeProperty("display"),Qe.style.display=i?"flex":"",Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-95","persona-opacity-0"),xe.classList.add("persona-scale-100","persona-opacity-100"),Wt?(Wt.setPanelOpen(!0),Wt.element.style.display="none"):fn&&(fn.style.display="none")):(i?i&&(W==="overlay"||W==="push")&&!w?(Qe.style.removeProperty("display"),Qe.style.display="flex",Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.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"),xe.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"),xe.classList.remove("persona-scale-100","persona-opacity-100"),xe.classList.add("persona-scale-95","persona-opacity-0")),Wt?(Wt.setPanelOpen(!1),Wt.element.style.display=i?"none":""):fn&&(fn.style.display=i?"none":""))},yt=(i,c="user")=>{if(!Be()||Ee===i)return;let g=Ee;Ee=i,Xa();let f=(()=>{let w=o.launcher?.sidebarMode??!1,W=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,F=o.launcher?.mobileBreakpoint??640,q=W.innerWidth<=F,Q=Ct(o)&&V&&q,se=we()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return w||V&&q&&D||Q||se})();if(Ee&&f){if(!Ho){let w=e.getRootNode(),W=w instanceof ShadowRoot?w.host:e.closest(".persona-host");W&&(Ho=Rf(W,o.launcher?.zIndex??pn))}Wo||(Wo=Hf(e.ownerDocument))}else Ee||(Ho?.(),Ho=null,Wo?.(),Wo=null);Ee&&(gl(),sg()||($n()==="follow"?$r(!0):Bc()));let b={open:Ee,source:c,timestamp:Date.now()};Ee&&!g?oe.emit("widget:opened",b):!Ee&&g&&oe.emit("widget:closed",b),oe.emit("widget:state",{open:Ee,launcherEnabled:D,voiceActive:Xe.active,streaming:T.isStreaming()})},Ur={inputDisabled:!1,sendDisabled:!1},Oo=()=>Ur.inputDisabled,lg=()=>Hn(o.voiceRecognition?.provider)&&!!T&&(T.isBargeInActive()||["listening","processing","speaking"].includes(T.getVoiceStatus())),Os=()=>Ur.inputDisabled||Ur.sendDisabled,sE=()=>(Ur.inputDisabled?Ur.inputReason:void 0)??(Ur.sendDisabled?Ur.sendReason:void 0);function cg(){if(!Te)return;if(ve.getState().phase==="streaming"){Te.disabled=!1;return}let i=rt?!rt.isReady():!1;Te.disabled=Os()||i}function $c(){if(!Po)return;let i=ve.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;Po.toggleAttribute("data-persona-send-hidden",c)}function iE(){let i=sE();if(we()){let c=An??He;i?c.setAttribute("title",i):c.removeAttribute("title"),He.toggleAttribute(La,!!i);return}if(i){Je.setAttribute("role","status"),Je.setAttribute("aria-live","polite"),Je.setAttribute(La,""),Je.textContent=i,ei(Je,o.statusIndicator??{},"idle");return}if(Je.hasAttribute(La)&&(Je.removeAttribute("role"),Je.removeAttribute("aria-live"),Je.removeAttribute(La),y)){let c=T.getStatus();Ra(Je,Pu(c),o.statusIndicator??{},c)}}function dg(){let i=cf(o.composer?.inputDisabled),c=cf(o.composer?.sendDisabled);Ur={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},ve.setInputDisabled(i.disabled),ve.setSendDisabled(c.disabled);let g=ve.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")),kt&&(kt.disabled=f),St&&(St.disabled=f);for(let w of Ft?.affordanceButtons??[])w.querySelectorAll("button").forEach(W=>{W.disabled=f});ie&&(ie.disabled=f||g&&!lg()),Ss.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})}),fg.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=Os()?"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)}),cg(),iE()}let Ja=i=>{ve.setStreaming(i),zh(i?"stop":"send"),dg()},Bs=()=>{Xe.active||ce&&ce.focus()};oe.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Bs(),200)});let Ds=null,Za=!1,pg=!tn.hidden,jr=null,ug=!te,Uc=null;he.push(()=>{Uc?.cancel(),Uc=null});let aE=i=>{let c=AS(i);if(c===fc)return;fc=c,e.setAttribute("data-persona-conversation-state",c);let g=Hu();yc(),ug&&(Uc?.cancel(),Uc=xS(He,c==="active"?g:Hu(),c==="active"?"drop":"rise",ys().layout==="centered"?320:260)),kn()},eb=null,tb,nb=null,Bi=null,gg=!1,Di=i=>{let c=ys(),g=`${c.variant}|${c.layout}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(g!==eb||c.icon!==tb)&&(eb=g,tb=c.icon,zp({host:tn,iconHolder:pM,kicker:uM,title:gM,subtitle:mM,starterSuggestions:ku},c));let f=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;f!==nb&&(nb=f,Kp(Nn,c.message,o));let b=i??(T?T.getMessages():o.initialMessages);aE(b);let w=Za,W=!w&&gs(c,b),V=W!==pg;if(pg=W,Bi){jr?.cancel(),jr=null,w!==gg&&(gg=w,w?Yf(ne,tn,null):Gf(ne,tn,Bi)),xa(ne,tn,!w);return}if(V&&!W&&!w&&c.dismiss==="on-first-message"&&ug){jr=wS(tn,q=>{jr===q&&(jr=null),!pg&&!Bi&&(xa(ne,tn,!1),kn()),q?.cancel()});return}if(jr){if(!W&&!w)return;jr.cancel(),jr=null}let F=!tn.hidden;xa(ne,tn,W),!W&&F&&kn()},mg=[],fg=[],hg=!1,ob=null,rb,sb=()=>{fg.length=0;let i=mg.splice(0,mg.length);for(let c of i)try{c()}catch(g){console.warn("[persona] renderWelcome cleanup threw",g)}};he.push(sb);let lE=(i,c)=>{let g=Of(i,c);if(!g)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),S("span");let f=o.suggestions?.starters,b=Bf({item:{...g,behavior:g.behavior??f?.behavior??"send"},index:c,surface:"starter",source:"config",variant:f?.variant??"card",streaming:y?T.isStreaming():!1,config:o,plugins:u,chipsConfig:o.suggestionChipsConfig,session:T,getTextarea:()=>ce,eventTarget:tn,submitPrompt:fd});return fg.push(b),b},yg=()=>{if(hg)return;hg=!0;let i=ys();ob=`${i.variant}|${i.layout}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,rb=i.icon;try{sb(),Yf(ne,tn,Bi),Bi=null,gg=!1;let c=T?T.getMessages():o.initialMessages,g=gs(i,c),f=0,b=null;for(let w of u)if(w.renderWelcome&&(b=w.renderWelcome({config:i,variant:i.variant,visible:g,defaultRenderer:()=>tn,sendMessage:W=>{if(!T||T.isStreaming())return;let V=W.trim();V&&T.sendMessage(V)},requestRender:()=>yg(),renderStarter:W=>lE(W,f++),storage:v(w.id),onCleanup:W=>{mg.push(W)}}),b))break;b&&b!==tn&&(Bi=b,Gf(ne,tn,b))}finally{hg=!1}Di()},cE=()=>{let i=ys();`${i.variant}|${i.layout}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===ob&&i.icon===rb||yg()},jc=()=>{Di(),Ai||(ce.placeholder=nx(ve.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!T?.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))"},dE=!!o.setStoredConversationId,_i=i=>ye(c=>{let g={...c};return delete g[i],g}),Vc=i=>{let c=I[i];return typeof c=="string"?c:null},ib=()=>{let i=I.durableResume;if(!i||typeof i!="object")return null;let c=i;return typeof c.executionId=="string"&&c.executionId.length>0&&typeof c.after=="string"&&c.after.length>0?{executionId:c.executionId,after:c.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Vc("sessionId"),setStoredSessionId:i=>{ye(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>_i("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Vc("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{ye(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>_i("conversationId"))});let ab=()=>o.clientToken??null,lb=i=>rA(i,Me(),o.persistState===!1),cb=ab(),Zn=cb?lb(cb):null,ir={...Zn?{visitorStore:Zn}:{},historyBootstrapReady:pe,getStoredMessageCursor:()=>Vc("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){_i("historyMessageCursor");return}ye(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=I.pendingDisplayProjections;if(!i||typeof i!="object")return null;let c=i;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(g=>typeof g=="string")}},setPendingDisplayProjections:i=>{if(!i){_i("pendingDisplayProjections");return}ye(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:ib,setStoredResumableHandle:i=>{if(!i){_i("durableResume");return}ye(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>_&&ib()!==null,...dE?{}:{getStoredConversationRevision:()=>Vc("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){_i("conversationRevision");return}ye(c=>({...c,conversationRevision:i}))}}};if(_){let i=o.onExecutionState,c=e.ownerDocument.defaultView,g=!1,f=()=>g=!0,b=()=>g=!1;c?.addEventListener("pagehide",f),c?.addEventListener("pageshow",b),he.push(()=>{c?.removeEventListener("pagehide",f),c?.removeEventListener("pageshow",b)}),o={...o,reconnectStream:o.reconnectStream??(w=>T.getClient().reconnectClientTokenStream(w)),onExecutionState:w=>{(w||!g)&&ir.setStoredResumableHandle?.(w?{executionId:w.executionId,after:w.lastEventId}:null),i?.(w)}}}let pE=()=>{let i=ab();if(i&&Zn?.matches(i,Me(),o.persistState===!1)||!i&&!Zn)return;Zn?.destroy(),Zn=i?lb(i):null;let c={...ir};Zn?c.visitorStore=Zn:delete c.visitorStore,ir=c,T.setHistoryInternals(ir)},_s=null,uE=()=>{_s==null&&(_s=setInterval(()=>{let i=be.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(_s),_s=null;return}let c=Date.now();i.forEach(g=>{let f=Number(g.getAttribute("data-tool-elapsed"));f&&(g.textContent=g.closest(".persona-activity-row")?wl(c-f):Kd(c-f))})},100))},bg=(i,c)=>{if(Object.is(i,c))return!0;if(i===null||c===null||typeof i!="object"||typeof c!="object")return!1;if(Array.isArray(i)||Array.isArray(c))return!Array.isArray(i)||!Array.isArray(c)||i.length!==c.length?!1:i.every((W,V)=>bg(W,c[V]));let g=i,f=c,b=Object.keys(g),w=Object.keys(f);return b.length===w.length&&b.every(W=>Object.prototype.hasOwnProperty.call(f,W)&&bg(g[W],f[W]))},db=i=>{let{content:c,rawContent:g,llmContent:f,...b}=i;return b},vg=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!ac(i),gE=(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))&&vg(f)&&vg(b)&&bg(db(f),db(b))},Cg=null,Ni=null,Ns=null,ar=null,wg=null,mE=i=>{if(!_)return Ii(i);wg=i,queueMicrotask(()=>{wg===i&&(wg=null,Ii(i))})},qc=i=>{Cg=i;let c,g;Ni=null;for(let b=i.length-1;b>=0;b-=1){let w=i[b];if(!c&&w.role==="user"&&(c=w),!g&&w.role==="assistant"&&(g=w),!Ni&&vg(w)&&(Ni={index:b,id:w.id}),c&&g&&Ni)break}Jn(be,i,N),Ar()?.updateInlineArtifactBlocks(be,Xn.artifacts,{suppressTransition:Un}),uE(),Di(i),Es(i),$r(!Un),ZM(i),i.length===0&&(bo(),qa=!0,Lc=!1,Li=null,Ic=!1),!Ju||ki?(Ju=!0,Rs=c?.id??null,Zu=g?.id??null):c&&c.id!==Rs?(Rs=c.id,GM(c.id)):g&&g.id!==Zu&&YM(),g&&(Zu=g.id),JM(i);let f=Xe.lastUserMessageId;c&&c.id!==f&&(Xe.lastUserMessageId=c.id,oe.emit("user:message",c)),Xe.lastUserMessageWasVoice=!!c?.viaVoice,mE(i),Oi()},xg=()=>{ar!==null&&(cancelAnimationFrame(ar),ar=null);let i=Ns;Ns=null,i&&qc(i)},pb=()=>{ar!==null&&cancelAnimationFrame(ar),ar=null,Ns=null},fE=i=>{let c=Ns??Cg;if(Un&&c&&Ni&&gE(c,i,Ni)){Ns=i,ar===null&&(ar=requestAnimationFrame(()=>{ar=null;let g=Ns;Ns=null,g&&qc(g)}));return}if(i.length===0){pb(),qc(i);return}xg(),qc(i)};T=new ma(o,{onMessagesChanged(i){fE(i)},onStatusChanged(i){let c=o.statusIndicator??{};Ra(Je,(f=>f==="idle"?c.idleText??_t.idle:f==="connecting"?c.connectingText??_t.connecting:f==="connected"?c.connectedText??_t.connected:f==="error"?c.errorText??_t.error:f==="paused"?c.pausedText??_t.paused:f==="resuming"?c.resumingText??_t.resuming:_t[f])(i),c,i),Tu()},onStreamingChanged(i){i||(T?.getMessages().length===0?pb():xg()),Un=i,Ja(i),Tu(),T&&Jn(be,T.getMessages(),N),i||($r(!0),zM(),Dy=!0,T&&_y(T.getMessages(),as(o))),Qt(),mc(i?"Responding\u2026":"Response complete."),Oi()},onVoiceStatusChanged(i){if(oe.emit("voice:status",{status:i,timestamp:Date.now()}),!(i!=="disconnected"&&!Hn(o.voiceRecognition?.provider)))switch(i){case"listening":ur(),Qi();break;case"processing":ur(),yT();break;case"speaking":ur(),bT();break;default:i==="idle"&&T.isBargeInActive()?(ur(),Qi(),ie?.setAttribute("aria-label","End voice session")):(Xe.active=!1,ur(),rr("system"),yo());break}},onArtifactsState(i){Xn=i,i.artifacts.length===0&&(Mi=!1),Ar()?.updateInlineArtifactBlocks(be,i.artifacts,{suppressTransition:Un}),ho(),Ii()},onHistoryStateChanged(i){Vh(i)},onHistoryNotice(i){qh(i)},onReconnect(i){let{executionId:c,lastEventId:g}=i.handle;i.phase==="paused"?oe.emit("stream:paused",{executionId:c,after:g}):i.phase==="resuming"?oe.emit("stream:resuming",{executionId:c,after:g,attempt:i.attempt??1}):oe.emit("stream:resumed",{executionId:c,after:g})}},ir),ct.current=T,he.push(()=>T.cancel()),he.push(()=>{T.destroy(),Zn?.destroy(),Zn=null});let Sg=null;if(T.onReadAloudChange((i,c)=>{gy=i,my=c,fy();let g=i??Sg;i&&(Sg=i);let f=g?T.getMessages().find(b=>b.id===g)??null:null;oe.emit("message:read-aloud",{messageId:g,message:f,state:c,timestamp:Date.now()}),c==="idle"&&(Sg=null)}),y=!0,Ju=!0,o.voiceRecognition?.enabled===!0&&Hn(o.voiceRecognition.provider))try{T.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let hE=720,yE=250,Ze=Sh(o.features?.history?.copy),qn=null,Ag=!1,lt=null,zc=null,Kc="conversation",Mg=null,mn=null,Bo=null,Gc=T.getHistoryState(),Eg=null,el=0,Tg=null,Yc=null,Qc=null,Pg=`persona-history-${Math.random().toString(36).slice(2,8)}`,kg=()=>o.features?.history?.enabled===!0,Do=()=>kg()&&!!qn&&!Ag,ub=()=>{let i=T.getStatus();return Un||i==="paused"||i==="resuming"},Lg=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",g=qn?.capabilities.scopes;return!g||g.includes(c)?c:g[0]??c},Fi=()=>zc?.scope??Lg(),gb=()=>T.getClientSession()?.targetId??null,mb=i=>`${i.state}:${"reason"in i?i.reason:""}`,bE=i=>{let c=mb(i);c!==Eg&&(Eg=c,oe.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},Xc=i=>{i&&(Jo.textContent="",Jo.textContent=i)},fb=null,hb=null,vE=()=>{if(!kg())return null;let i=lA();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(fb!==c&&(fb=c,hb=c()),hb):T.isClientTokenMode()?cA({client:T.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:g=>T.bindActivatedSession(g),getClient:()=>T.getClient()}):null},yb=()=>{Yc?.(),Yc=null,Qc?.(),Qc=null,Ag=!1,qn=vE();let i={...ir};qn?i.historyProvider=qn:delete i.historyProvider,ir=i,T.setHistoryInternals(ir),qn&&(Yc=qn.subscribeAvailability?.(c=>{Ag=!c,c||Ln({restoreFocus:!1}),qr()})??null,Qc=qn.subscribeIdentityStatus(c=>bE(c)),Eg=mb(qn.getIdentityStatus()))},Ig=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!D||Ct(o)))return"panel";let c=Ro??de;return(c.getBoundingClientRect().width||c.clientWidth)>=hE?"rail":"panel"},eo=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},Jc="data-persona-history-suppressed",zn=null,Vr=null,Fs=null,tl=null,Rg=null,bb="",vb=()=>Pe===Rg?bb:o.layout?.showHeader===!1?"none":"",CE=()=>Vt==="panel"&&!!Fs&&tl===Fs.element&&o.layout?.showHeader!==!1&&vb()!=="none",wE=()=>{for(let i of Array.from(Pe.children))i!==zn&&i.setAttribute(Jc,"")},xE=()=>{for(let i of Array.from(de.querySelectorAll(`[${Jc}]`)))i.removeAttribute(Jc)},SE=()=>{let i=Fs;if(!i)return;if(Array.from(Pe.children).some(f=>f!==zn&&!f.hasAttribute(Jc))){Vr&&Vr!==Pe&&(Vr.style.removeProperty("min-height"),Vr=null);let f=Pe.offsetHeight;f>0&&(Pe.style.minHeight=`${f}px`,Vr=Pe)}zn||(zn=S("div","persona-history-header-host")),i.setHeaderPlacement("external");let g=i.getHeaderElement();g.parentNode!==zn&&zn.replaceChildren(g),zn.parentNode!==Pe&&Pe.appendChild(zn),wE()},Cb=()=>{Vr&&(Vr.style.removeProperty("min-height"),Vr=null),zn&&(Fs?.setHeaderPlacement("inline"),zn.remove(),zn=null,xE())},Zc=null,Hg=()=>{if(Zc){if(ne.style.display="none",eo(ne,!0),He.hidden=!0,eo(He,!0),CE()){SE(),Pe.style.display=vb(),eo(Pe,!1);return}Cb(),Pe.style.display="none",eo(Pe,!0)}};Eu=Hg;let AE=i=>{let c=ne.style.display,g=He.hidden,f=He,b=Pe,w=Pe.style.display;Rg=b,bb=w,Zc=()=>{Zc=null,Cb(),Rg=null,ne.style.display=c,eo(ne,!1),f.hidden=g,eo(f,!1),He!==f&&(He.hidden=!1,eo(He,!1)),b.style.display=w,eo(b,!1),Pe!==b&&(Pe.style.display=o.layout?.showHeader===!1?"none":"",eo(Pe,!1))},He.parentNode?.insertBefore(i,He),Hg()},$i=null,$s=null,nl=null,Ui=null,wb=()=>[Pe,$e.closeButtonWrapper,$e.clearChatButtonWrapper,ne,He],ME=52,ed=()=>o.features?.history?.rail?.collapsible!==!1,ji=()=>o.features?.history?.rail?.side==="right"?"right":"left",Wg=200,Og=400,Bg=i=>Math.min(Og,Math.max(Wg,Math.round(i))),EE=()=>o.features?.history?.rail?.resizable===!0,ol,TE=()=>{if(ol===void 0&&(ol=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Me()}rail-width`));i&&(ol=i)}catch{}return ol},rl=()=>Bg(TE()??o.features?.history?.rail?.width??260),PE=i=>{if(ol=i,o.persistState!==!1)try{window.localStorage.setItem(`${Me()}rail-width`,String(i))}catch{}},td=()=>ed()&&o.features?.history?.rail?.collapsedBehavior==="overlay",zt=!1,xb=i=>{let c=S("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},kE=()=>{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=xb(i.iconUrl):g=i.icon?le(i.icon,20):null),g?g.cloneNode(!0):null}},LE=()=>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=xb(f.iconUrl):b=f.icon?le(f.icon,20):null}catch(w){g(w),b=null}return b},onSelect:()=>{try{f.onSelect()}catch(w){g(w)}}}})}})??[],IE=i=>{let c=LE();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},sl=null,Sb=()=>`${Me()}rail-collapsed`,Dg=()=>{if(sl===null&&(sl=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(Sb());i&&(sl=i==="1")}catch{}return sl},_g=i=>{if(sl=i,o.persistState!==!1)try{window.localStorage.setItem(Sb(),i?"1":"0")}catch{}},il=()=>Vt==="rail"&&ed()&&!td()&&Dg(),Ng=()=>{},Ab=()=>{if(td()){Ng();return}_g(!Dg()),lt?.view.setCollapsed(il()),Xo(),kn()},Fg=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!Hp(i)?null:{combo:i,hint:Wp(i),aria:Ul(i)}},Mb=()=>{h.forEach(c=>c()),h=[];let i=Fg();i&&h.push(m.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Rt&&Vt==="rail"&&ed()||qi(),run:()=>td()?Ng():Ab()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&h.push(m.register({id:`header-action-${c.id}`,combo:c.shortcut,run:()=>{let g=e.querySelector(`[data-persona-header-action="${c.id}"]`);g?g.click():o.layout?.header?.onAction?.(c.id)}}));for(let c of u)for(let g of c.shortcuts??[])h.push(m.register({...g,id:`${c.id}:${g.id}`}))};Mb();let RE=300,nd="var(--persona-history-overlay-margin,8px)",to=null,lr=null,od=0,cr=null,Vi=null,Us=!1,$g=0,Eb=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,qi=()=>Do()&&td()&&(Vt??Ig())==="rail",HE=()=>Rt&&!zt,al=()=>{Vi!==null&&clearTimeout(Vi),Vi=null},WE=()=>{Ch().catch(()=>{})},Tb=()=>{al(),zt&&(Vi=setTimeout(()=>{Vi=null,!(Us||!zt)&&(cr?.contains(document.activeElement)||Ln({restoreFocus:!1}))},RE))},OE=(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},Ug=i=>{zt&&(Us=OE(i.clientX,i.clientY),Us?al():Vi===null&&Tb())},Pb=i=>{Rt||!qi()||(zt=!0,cl({invoker:to,keyboard:i?.keyboard===!0}).then(()=>{Rt?!Us&&document.activeElement!==to&&Ln():zt=!1}))},kb=()=>{let i=tl?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",zt?Ze.expandLabel:Ze.collapseLabel),i.setAttribute("aria-expanded",zt?"false":"true"))},Lb=()=>{_g(!1);let i=lt;if(!zt||!i){cl({invoker:to});return}let c=document.activeElement===to;zt=!1,rd(),i.element.remove(),Vg(i.element),kb(),c&&id(),kn(),qr()},BE=()=>{_g(!0),Ln()};Ng=()=>{!Rt||zt?Lb():BE()};let DE=()=>{let i=Fg(),c=ci({ariaLabel:Ze.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":Pg,...i?{"aria-keyshortcuts":i.aria}:{}}}),g=c.button;g.addEventListener("mouseenter",()=>{Us=!0,al(),!(Eb()||Date.now()<$g)&&Pb()}),g.addEventListener("mouseleave",()=>{Us=!1,$g=0,Tb()}),g.addEventListener("focus",()=>{Rt||WE()}),g.addEventListener("click",f=>{Do()&&(f.detail!==0&&Eb()&&!Rt?Pb():Lb())}),to=g,lr=c.wrapper},ll=()=>{if(lr&&!lr.isConnected&&(lr=null,to=null),!qi()){lr?.remove(),lr=null,to=null;return}to||DE();let i=lr,c=to;if(!i||!c)return;let g=ji()!=="right"?Pe.firstChild:null;(g??Pe.lastChild)!==i&&Pe.insertBefore(i,g),i.style.display=HE()||od>0?"none":"",c.setAttribute("aria-label",Ze.expandLabel),c.setAttribute("aria-expanded",Rt?"true":"false"),cr&&Xo()},Ib=i=>{if(!zt)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",Ib,!0),he.push(()=>{document.removeEventListener("pointerdown",Ib,!0),document.removeEventListener("pointermove",Ug),zi?.(),al()});let jg=null,zi=null,Rb=16,Hb=i=>{PE(Bg(i)),Xo(),kn()},_E=()=>{let i=S("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(Wg)),i.setAttribute("aria-valuemax",String(Og)),i.addEventListener("pointerdown",c=>{let g=$s;if(!g||c.button!==0)return;c.preventDefault(),zi?.();let f=c.clientX,b=g.getBoundingClientRect().width||rl(),w=ji()==="right"?-1:1,W=b,V=e.ownerDocument;g.style.transition="none";let F=Q=>{W=Bg(b+w*(Q.clientX-f)),g.style.flex=`0 0 ${W}px`,i.setAttribute("aria-valuenow",String(W))},q=()=>{zi=null,V.removeEventListener("pointermove",F),V.removeEventListener("pointerup",q),V.removeEventListener("pointercancel",q),g.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}Hb(W)};zi=q,V.addEventListener("pointermove",F),V.addEventListener("pointerup",q),V.addEventListener("pointercancel",q);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let g=ji()==="right"?-Rb:Rb,f=rl(),b=c.key==="ArrowRight"?f+g:c.key==="ArrowLeft"?f-g:c.key==="Home"?Wg:c.key==="End"?Og:null;b!==null&&(c.preventDefault(),Hb(b))}),i},NE=(i,c)=>{if(!EE()||il()){zi?.(),jg?.remove();return}let g=jg??_E();jg=g,g.setAttribute("aria-label",Ze.resizeLabel),g.setAttribute("aria-valuenow",String(rl())),g.nextElementSibling!==c&&i.insertBefore(g,c)};Xo=()=>{lt?.view.setRailSide(ji());let i=ji()==="right",c=cr;if(c){let V=to?to.getBoundingClientRect().bottom-de.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(V))}px + ${nd})`,c.style.width=`${rl()}px`,c.style.left=i?"":nd,c.style.right=i?nd:""}let g=$s,f=$i,b=nl;if(!g||!f||!b)return;g.style.flex=`0 0 ${il()?ME:rl()}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),NE(f,i?g:b)};let Wb=i=>{if(Ui&&$s){Ui.replaceWith(i),Ui=null,Xo();return}let c=S("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let g=S("div","persona-history-rail-conversation");g.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let f=S("div","persona-history-rail-host");f.style.cssText="display:flex;min-height:0;overflow:hidden",de.insertBefore(c,Pe.parentNode===de?Pe:ne);for(let b of wb())b?.parentNode===de&&g.appendChild(b);c.append(f,g),f.appendChild(i),$i=c,$s=f,nl=g,Xo()},FE=()=>{if($i)return;let i=S("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",Ui=i,Wb(i),kn()},Ob=()=>{Ui&&(rd(),kn())},$E=i=>{let c=S("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${nd};display:flex;overflow:hidden;z-index:${fa-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,de.style.position="relative",de.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",Ug),cr=c,Xo(),kb()},rd=()=>{Zc?.(),cr&&(Us&&($g=Date.now()+150),document.removeEventListener("pointermove",Ug),cr.remove(),cr=null);let i=$i;if(i){zi?.();for(let c of wb())c&&i.contains(c)&&de.insertBefore(c,i);i.remove(),$i=null,$s=null,nl=null,Ui=null}},Bb=i=>{tl=i,i.id=Pg,i.style.flex="1 1 auto",i.style.minHeight="0"},Vg=i=>{Bb(i),(Vt!=="rail"||zt)&&Ob(),Vt!=="rail"?AE(i):zt?$E(i):Wb(i)},sd=()=>{if(ll(),Kb(),!Rt||!lt)return;let i=Ig();if(i===Vt)return;let c=document.activeElement,g=c instanceof HTMLElement&&(lt.element.contains(c)||zn?.contains(c)===!0)?c:null;rd(),lt.element.remove(),lt.view.setHeaderPlacement("inline"),Vt=i,lt.view.setPresentation(i),lt.view.setCollapsed(il()),lt.requestRender(),lt.element.isConnected||Vg(lt.element),g?.isConnected?g.focus():id(),Qt(),kn(),qr()},Db=(i,c)=>zn?.querySelector(c)??i.querySelector(c),id=()=>{let i=lt?.element??tl;if(!i)return;let c=Db(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let g=Db(i,".persona-history-title")??i;g.tabIndex=-1,g.focus()},cl=async i=>{if(!Do()||Rt)return;let c=qn;if(!c)return;if(!zt&&qi()&&Dg()){ll();return}ad();let g=++el;Kc=i?.returnSurface??"conversation",Mg=i?.invoker??mn;let f=qi()&&!zt;f&&(od+=1,ll(),FE());let b;try{b=await Ch()}catch{Xc(Ze.openHistoryLabel),f&&(od-=1,g===el&&(Ob(),ll()));return}if(f&&(od-=1),g!==el||Rt)return;zc={scope:Lg()},Vt=Ig(),Rt=!0;let w=Vt==="panel"&&o.layout?.showHeader!==!1&&Pe.style.display!=="none"?"external":"inline",W=o.features?.history?.rowAvatar,V=Fg(),F=V?{hint:V.hint,aria:V.aria}:null,q={provider:c,context:zc,targetId:gb(),presentation:Vt,collapsible:ed(),collapsed:il(),railSide:ji(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:kE(),onToggleCollapse:Ab,...F?{collapseShortcut:F}:{},headerPlacement:w,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:W===!1?!1:typeof W=="string"?W:o.launcher?.iconUrl,activeConversationId:T.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:Q=>zg(Q,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Q=>js(Q),attachTooltip:an,onStartNew:()=>Kg({focusComposer:!0}),onClose:()=>Ln(),onRequestDeleteConversation:Q=>zb(Q),onRequestClearHistory:()=>KE(),...c.resetDevice?{onRequestResetIdentity:()=>GE()}:{}};lt=aA({plugins:u,config:o,getPresentation:()=>Vt??"panel",getReturnSurface:()=>Kc,close:()=>Ln(),createView:({slots:Q,renderDom:se,onModelChange:me,railSections:Ve})=>(Fs=b.createHistoryView({...q,railSections:IE(Ve),slots:Q,renderDom:se,onModelChange:me,onAnnounce:Xc}),Fs),onElementChanged:(Q,se)=>{if(!se?.isConnected)return Vg(Q);Bb(Q),se.replaceWith(Q),Hg()}}),lt.view.setNewConversationRequired(Gc.recovery==="new_conversation_required"),i?.focus!==!1&&(Vt!=="rail"||i?.keyboard===!0)&&id(),Qt(),kn(),qr(),oe.emit("history:opened",{presentation:Vt,returnSurface:Kc,timestamp:Date.now()})},ad=()=>{},Ln=i=>{if(!Rt)return;el+=1;let c=Kc,g=Mg,f=lt,b=i?.restoreFocus!==!1;Rt=!1;let w=!1,W=null,V=()=>{if(!w){if(w=!0,ad=()=>{},W!==null&&clearTimeout(W),zt=!1,al(),rd(),f?.dispose(),f?.view.destroy(),f?.element.remove(),lt===f&&(lt=null,Fs=null,tl=null,Vt=null,zc=null,Mg=null),Qt(),kn(),qr(),b){let q=g??mn;q?.isConnected?q.focus():Bs()}oe.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},F=f&&f.element===f.view.element?f.view.playExit():null;if(!F){V();return}ad=V,W=setTimeout(V,yE),F.then(V)},_b=i=>{if(!(i.key!=="Escape"||!Rt||!lt)){if(Vt==="rail"){let c=i.target;if(!(c instanceof Node)||!(lt.element.contains(c)||zt&&lr?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Ln()}};de.addEventListener("keydown",_b),he.push(()=>de.removeEventListener("keydown",_b));let ld=null,Nb=!1,dl=()=>{if(!Ir)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&ld?.trim()||null;Ir.textContent=c??o.launcher?.title??"Chat Assistant";let g=Ir.closest(".persona-combo-btn");if(!g)return;let f=!i||T.getActiveConversationId()!==null;g.setAttribute("data-persona-menu-locked",f?"false":"true"),g.setAttribute("aria-haspopup",f?"true":"false"),f||g.setAttribute("aria-expanded","false"),g.style.cursor=f?"pointer":"default";let b=g.querySelector("svg");b&&(b.style.display=f?"":"none")},UE=i=>{i!==ld&&(ld=i,dl())},js=i=>{Nb=i?.starred===!0,UE(i&&i.title.trim()||null),dl()};dl(),de.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,g=T.getActiveConversationId();g&&(c==="delete"?zb(g):c==="star"&&T.canUpdateConversations()&&Gg(g,{starred:!Nb}).catch(()=>{}))});let cd=0,jE=250,dd=null,pd=()=>{dd&&clearTimeout(dd),dd=null};he.push(pd);let Fb=()=>{pd();let i=Ds;i&&(Za=!0,i.hidden=!1,be.style.display="none",Di())},ud=()=>{cd+=1,pd(),Ds&&(Ds.remove(),Ds=null,Za=!1,be.style.removeProperty("display"),eo(He,!1),Di())},VE=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;be.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},qg=(i,c)=>Y("div",{className:bn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),$b=()=>Y("div",{className:"persona-conversation-loading-body"},qg("58%",!1),qg("72%",!0),qg("44%",!1)),Ub=i=>{Ds?.remove(),Ds=i,i.hidden=!Za,ne.insertBefore(i,be),pd(),Za||(dd=setTimeout(Fb,jE)),eo(He,!0)},qE=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:$b},c=null,g=u.find(f=>f.renderLoadingIndicator);g?.renderLoadingIndicator&&(c=g.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),Ub(Y("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ze.openConversationLoadingLabel}},c??$b()))},zE=i=>{let c=()=>{zg(i,{focusComposer:!0}).catch(()=>{})},g=Do()?()=>{ud(),cl()}:void 0,f=(V,F)=>{let q=Y("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:V});return q.addEventListener("click",F),q},b=()=>Y("div",{className:"persona-conversation-loading-error-body"},Y("p",{className:"persona-conversation-loading-error-title",text:Ze.openConversationErrorTitle}),Y("div",{className:"persona-conversation-loading-error-actions"},f(Ze.openConversationRetryLabel,c),g?f(Ze.openConversationBackLabel,g):null)),w=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Ze.openConversationErrorTitle,retryLabel:Ze.openConversationRetryLabel,backLabel:Ze.openConversationBackLabel}),retry:c,...g?{back:g}:{},defaultRenderer:b}),W=null;for(let V of u)if(V.renderHistoryOpenError){try{W=V.renderHistoryOpenError(w)}catch(F){console.warn("[persona] renderHistoryOpenError threw",F),W=null}if(W)break}Ub(Y("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},W??b())),Fb()};oe.on("history:closed",()=>{Ds&&eo(He,!0)});let zg=async(i,{focusComposer:c=!1}={})=>{let g=Fi(),f=!!lt;lt?.view.setActiveConversationId(i),ud();let b=cd;qE(),Rt&&(Vt==="panel"||zt)&&Ln({restoreFocus:!1}),ki=!0;try{await T.openConversation(i,{scope:g})}catch(w){throw b===cd&&zE(i),w}finally{ki=!1}b===cd&&(ud(),$t.clear(),bo(),Pn(),sg()||Bc(),VE(),dr(),f||js(null),oe.emit("history:conversationOpened",{conversationId:i,title:ld,scope:g,timestamp:Date.now()}),c&&Bs())},Kg=async({focusComposer:i=!1}={})=>{ud(),await T.startNewConversation({scope:Fi()}),js(null),$t.clear(),bo(),Pn(),Bc(),dr();let c=T.getActiveConversationId();lt?.view.setActiveConversationId(c),oe.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),Rt&&(Vt==="panel"||zt)&&Ln({restoreFocus:!1}),i&&Bs()},Gg=async(i,c)=>{let g=await T.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return lt?.view.applyConversationSummary(g),!lt&&i===T.getActiveConversationId()&&js(g),g},jb=async i=>{let c=Fi(),g=T.getActiveConversationId()===i;await T.deleteConversation(i,{scope:c}),lt?.view.removeConversationSummary(i),g&&(js(null),$t.clear(),bo(),Pn(),dr()),oe.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:g,timestamp:Date.now()})},Vb=async i=>{let c=i?.scope??Fi(),g=i?.allTargets?null:i?.targetId??gb(),f=await T.clearConversationHistory({...g?{targetId:g}:{},scope:c});return js(null),$t.clear(),bo(),Pn(),dr(),oe.emit("history:cleared",{deleted:f.deleted,scope:c,targetId:g,timestamp:Date.now()}),f},qb=async()=>{if(!qn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await T.resetHistoryDevice()).remoteRevocationConfirmed}finally{js(null),T.clearArtifacts(),$t.clear(),Cg=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),I={},Ce.syncFromMetadata(),k?.clear&&Hc(()=>k.clear(),"[AgentWidget] Failed to clear storage adapter:"),bo(),Pn(),dr(),Ln({restoreFocus:!1}),Bs(),Ee||Wt?.launcher.element.focus()}return Xc(i?Ze.identityResetNotice:Ze.identityResetUnconfirmedNotice),oe.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},Yg=()=>Ro?xe:de,zb=async i=>await eu({host:Yg(),title:Ze.deleteConversationConfirmTitle,description:Ze.deleteConversationConfirm,confirmLabel:Ze.deleteConversationConfirmLabel,cancelLabel:Ze.confirmCancelLabel})?(await jb(i),"deleted"):"cancelled",KE=async()=>{let i=Fi()==="verified-user";return await eu({host:Yg(),title:Ze.clearHistoryConfirmTitle,description:i?Ze.clearHistoryVerifiedConfirm:Ze.clearHistoryConfirm,confirmLabel:Ze.clearHistoryConfirmLabel,cancelLabel:Ze.confirmCancelLabel})?(await Vb(),"cleared"):"cancelled"},GE=async()=>{if(!await eu({host:Yg(),title:Ze.resetIdentityConfirmTitle,description:Ze.resetIdentityConfirm,confirmLabel:Ze.resetIdentityConfirmLabel,cancelLabel:Ze.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await qb();return{outcome:"reset",remoteRevocationConfirmed:c}},no=S("button","persona-history-earlier");no.type="button",no.textContent=Ze.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(!(Do()&&!!Gc.nextMessageCursor&&!!T.getActiveConversationId())){no.remove();return}no.textContent=Ze.showEarlierMessagesLabel,no.parentNode!==ne&&ne.insertBefore(no,ne.firstChild)};no.addEventListener("click",()=>{let i=T.getActiveConversationId(),c=Gc.nextMessageCursor;if(!i||!c||no.disabled)return;no.disabled=!0;let g=ne.scrollHeight,f=ne.scrollTop;T.loadOlderMessages(i,c,{scope:Fi()}).then(()=>{ne.scrollTop=f+(ne.scrollHeight-g),kn()}).catch(()=>{}).finally(()=>{no.disabled=!1,dr()})});let YE=()=>{let i=ci({ariaLabel:Ze.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(!(!Do()||ub())){if(Rt){Ln();return}cl({invoker:i.button,keyboard:c.detail===0})}}),i},Kb=()=>{if(!Do()){Bo?.remove(),mn=null,Bo=null;return}if(Bo&&!Bo.isConnected&&(mn=null,Bo=null),!mn&&Pe){let f=YE();mn=f.button,Bo=f.wrapper;let b=$e.clearChatButtonWrapper||$e.closeButtonWrapper;b?.parentNode&&Pe.contains(b)?b.parentNode.insertBefore(Bo,b):Pe.appendChild(Bo)}if(!mn||!Bo)return;let i=qi()||Rt&&Vt==="rail";if(Bo.style.display=i?"none":"",i){document.activeElement===mn&&id();return}let c=ub();mn.disabled=c,mn.setAttribute("aria-disabled",c?"true":"false");let g=c?Ze.openHistoryBusyLabel:Ze.openHistoryLabel;mn.setAttribute("aria-label",g),(o.features?.history?.presentation??"panel")==="panel"?(mn.removeAttribute("aria-expanded"),mn.removeAttribute("aria-controls")):(mn.setAttribute("aria-expanded",Rt?"true":"false"),mn.setAttribute("aria-controls",Pg))},gd=!1,QE=()=>{let i=$e.clearChatButton;if(i){if(Do()){gd||(Tg=i.getAttribute("aria-label")??"",gd=!0),i.setAttribute("aria-label",Ze.newConversationLabel),i.removeAttribute("title");return}gd&&(gd=!1,Tg&&i.setAttribute("aria-label",Tg))}},qr=()=>{Ze=Sh(o.features?.history?.copy),Kb(),ll(),QE(),dr()};Tu=qr,Vh=i=>{Gc=i,lt?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),Ja(i.sendBlocked||Un),dr()},qh=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&($t.clear(),bo(),Pn()),Xc(i.message),lt?.view.refresh()},yb(),qr(),he.push(()=>{Yc?.(),Qc?.(),el+=1,ad(),lt?.dispose(),lt?.view.destroy(),lt=null}),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&T.initClientSession().then(()=>{if(Do())return T.reconcileBootConversation({scope:Lg()})}).then(()=>{dr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)});let Qg=()=>T.warmClientSession(),Gb=i=>{let c=o.sessionInit??"input",g=tt?.input??ce,f=i.target;g&&(i.type==="input"?(c==="input"||c==="focus")&&f===g&&i.inputType&&g.value.trim():c==="focus"&&(i.type==="keyup"?f===g&&i.key==="Tab":(tt?.form??An)?.contains(f)))&&Qg()},Yb=["input","pointerdown","keyup"];Yb.forEach(i=>e.addEventListener(i,Gb));let Qb,Xg,Xb=()=>{let i=Xg;Xg=void 0;try{typeof i=="function"&&i()}catch{}},Jb=()=>{let i=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(i!==Qb){Xb(),Qb=i;try{Xg=i?.({warm:Qg,mount:e})}catch{}}};Jb(),he.push(()=>{Yb.forEach(i=>e.removeEventListener(i,Gb)),Xb()}),(X||o.onSSEEvent)&&T.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),Mu(i,c)});let Zb=()=>{let i=o.resume??(_?ir.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&T.resumeFromHandle(i)};te?te.then(i=>{if(i){if(i.metadata&&(I=Ah(i.metadata),Ce.syncFromMetadata()),i.messages?.length){ki=!0;try{T.hydrateMessages(i.messages)}finally{ki=!1}Fc()}i.artifacts?.length&&T.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),Vy(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{ug=!0,U(),Zb()}):(Vy(ue),Zb());let XE=()=>{!we()||Ee||!(o.launcher?.composerBar?.expandOnSubmit??!0)||yt(!0,"auto")},JE=(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),vI(b)}}:i:c,Jg=()=>{let c=ce.getInlineMessageFields?.();return c&&c.contentSegments.some(f=>f.kind==="mention")?c.contentSegments:void 0},pr=!1,Vs=null,md=()=>{ce.value="",ce.style.height="auto",ko(),ul()},Zg="data-persona-composer-notice",Ki=null;function ZE(i){mc(i),!(we()||!Je)&&(Je.hasAttribute(La)||(Je.setAttribute(Zg,""),Je.setAttribute("role","status"),Je.setAttribute("aria-live","polite"),Je.textContent=i,ei(Je,o.statusIndicator??{},"idle"),Ki&&clearTimeout(Ki),Ki=setTimeout(()=>{if(Ki=null,!!Je?.hasAttribute(Zg)&&(Je.removeAttribute(Zg),Je.removeAttribute("role"),Je.removeAttribute("aria-live"),y)){let c=T.getStatus();Ra(Je,Pu(c),o.statusIndicator??{},c)}},4e3)))}function eT(){let i=ve.getState().pendingSubmission;i&&(xi(void 0),ce&&(ce.value=i.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),ko()),i.options.selectedModelId&&(ve.setSelectedModelId(i.options.selectedModelId),Hr?.repaint()),i.options.activeModeIds?.length&&bc(i.options.activeModeIds),i.options.quote&&Lo(i.options.quote),ce?.focus())}let tT=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},ev=(i={})=>{let c=(i.overrideText??ce?.value??"").trim();return i.resolveInlineCommand&&c?(Ft?.takeInlineCommand(c)??Promise.resolve(null)).then(g=>tv(i,c,g)):tv(i,c,null)},tv=(i,c,g)=>{if(g?.kind==="action"){md(),Ft?.clear(),vs();return}let f=g?.kind==="server"?g.mentions:null,b=g?.kind==="prompt"?g.sendText:c,w=i.pending?.contentParts,W=(rt?.hasAttachments()??!1)||(w?.length??0)>0;if(!fx({text:b,hasAttachments:W,attachmentsReady:rt?.isReady()??!0,hasMentions:Ft?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:Oo(),sendDisabled:Os()}))return;let V=T.isStreaming()?Du():"block";if(V==="defer-one"&&!i.pending){if(ve.getState().pendingSubmission){ZE("One message is already queued. Edit or remove it first.");return}nT({intent:i,sendText:b,serverMentions:f});return}let F={text:b,mentionRefs:[...Ft?.getMentionRefs()??[],...f?.refs??[]],contentSegments:g?.kind==="prompt"?void 0:Jg(),options:{...ve.getState().selectedModelId&&{selectedModelId:ve.getState().selectedModelId},...ve.getState().activeModeIds.length>0&&{activeModeIds:[...ve.getState().activeModeIds]},...ve.getState().quote&&{quote:{...ve.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(F.options={...i.pending.options},F.contentSegments=i.pending.contentSegments,F.mentionRefs=[...i.pending.mentionRefs],F.viaVoice=i.pending.viaVoice);let q=()=>{if(w?.length)return[...w];if(!rt?.hasAttachments())return;let nt=[...rt.getContentParts()];return F.text&&nt.push(co(F.text)),nt};F.contentParts=q();let Q=()=>{ks(),XE();let nt=Ft?.collectForSubmit()??null,In=JE(nt,f),At=q();i.consumeDraft!==!1&&md();let Lt={selectedModelId:F.options.selectedModelId,activeModeIds:F.options.activeModeIds},hn=V==="interrupt";hn&&T.cancel(),T.sendMessage(F.text,{contentParts:At,mentions:In??void 0,contentSegments:F.contentSegments,viaVoice:F.viaVoice,composerOptions:Lt,...F.options.quote&&{quote:F.options.quote},...hn&&{interrupt:!0}}),rt?.hasAttachments()&&rt.clearAttachments(),nt&&Ft?.clear(),vs();let Bt=ve.getState().activeModeIds,pt=tx(Bt,o.composer?.modes);pt.length!==Bt.length&&bc(pt),ve.getState().quote&&Lo(void 0),Oc(),Uu.release(),mo()},se=o.composer?.onBeforeSend;if(!se){Q();return}let me=new AbortController;Vs=me;let Ve=nt=>{if(Vs=null,nt.status==="error"){tT(nt.error);return}nt.status==="proceed"&&Q()},st=hx(se,F,me.signal);if(!(st instanceof Promise)){Ve(st);return}return ve.setPreparing(!0),st.then(Ve).finally(()=>ve.setPreparing(!1))};function nT(i){let c=ve.getState(),g=rt?.hasAttachments()??!1,f=g?[...rt.getContentParts()]:[];g&&i.sendText&&f.push(co(i.sendText));let b=Cf({text:i.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Ft?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Jg(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});xi(b),i.intent.consumeDraft!==!1&&md(),g&&rt.clearAttachments(),Ft?.clear(),vs(),c.quote&&Lo(void 0),Oc(),Uu.release(),mo(),mc("Message queued. It sends when the response finishes.")}function oT(){let i=ve.getState().pendingSubmission;i&&(xi(void 0),hd(i.text,{consumeDraft:!1,pending:i}))}function rT(i){if(o.messageActions?.showEdit!==!0)return;let c=T.getMessages().find(g=>g.id===i);!c||!Xm(c)||Ps!==i&&(ks(),Ps=i,Dr=ix({messageId:i,initialText:c.content,onSave:g=>sT(i,g),onCancel:()=>ks()}),$t.delete(i),Jn(be,T.getMessages(),N),Dr.focus())}function sT(i,c){let g=Dr;if(Ps=null,Dr=null,g?.destroy(),$t.delete(i),!T.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){Jn(be,T.getMessages(),N);return}kn()}function iT(i){if(T.isStreaming())return;let c=Qm(T.getMessages(),i);c&&(ks(),T.resubmitFrom(c,{reason:"retry"})&&kn())}vc={regenerate:iT,edit:rT,quote:i=>{let g=T.getMessages().find(f=>f.id===i)?.content?.trim();g&&(Lo({text:g,messageId:i}),ce?.focus())}};let pl=async i=>{if(!pr){pr=!0;try{await ev({resolveInlineCommand:!0,...i})}finally{pr=!1}}};function fd(i){Os()||(md(),hd(i,{consumeDraft:!1}))}let hd=(i,c)=>{if(pr)return;pr=!0;let g=()=>{pr=!1};try{let f=ev({...c,overrideText:i});f instanceof Promise?f.finally(g):g()}catch(f){throw g(),f}},aT=i=>{if(i.preventDefault(),T.isStreaming()){T.cancel(),Zt?.reset(),ht?.update();return}pr||pl()},lT=()=>o.features?.composerHistory!==!1,em={...Pf},tm=!1,ul=()=>{em={...Pf}},cT=()=>T.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),dT=i=>{if(!ce)return;tm=!0,ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),tm=!1;let c=ce.value.length;ce.setSelectionRange(c,c)},pT=i=>{tm||(i.isComposing||Ft?.handleInput(i.inputType??void 0),ul())},uT=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Ol(ce)}),gT=i=>{if(ce&&!Oo()&&!(!i.isComposing&&Ft?.handleKeydown(i))){if(lT()&&(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=Fx({direction:i.key==="ArrowUp"?"up":"down",history:cT(),currentValue:ce.value,atStart:c,state:em});if(em=g.state,g.handled){i.preventDefault(),g.value!==void 0&&dT(g.value);return}}if(Nw(i,uT())){if(T.isStreaming()){if(i.preventDefault(),Du()==="block"||pr||Os())return;ul(),pl();return}if(pr){i.preventDefault();return}if(Os()){i.preventDefault();return}ul(),i.preventDefault(),Te.click()}}},nv=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(de)){if(Vs){Vs.abort(),Vs=null,i.preventDefault(),i.stopImmediatePropagation();return}T.isStreaming()&&(T.cancel(),Zt?.reset(),ht?.update(),ul(),i.preventDefault(),i.stopImmediatePropagation())}},mT=async i=>{if(o.attachments?.enabled!==!0||!rt||Oo())return;let c=fI(i.clipboardData);c.length!==0&&(i.preventDefault(),await rt.handleFiles(c))},oo=null,_o=!1,Gi=null,Pt=null,nm=()=>o.voiceRecognition?.completionBehavior==="review";function qs(i){ie?.setAttribute("data-state",i),i==="recording"?hT():im()}let ov="--persona-voice-level",om=.5,Yi=null,rm=-1,yd=0,rv=()=>{let i=[],c=Fn??ie?.parentElement??null;return c&&i.push(c),He&&i.push(He),i},sm=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==rm){rm=c;for(let g of rv())g.style.setProperty(ov,String(c))}},fT=()=>{rm=-1,yd=0;for(let i of rv())i.style.removeProperty(ov)};function hT(){if(Yi!==null)return;if(typeof requestAnimationFrame!="function"){sm(y?T.getVoiceLevel()??om:om);return}let i=()=>{Yi=requestAnimationFrame(i);let c=y?T.getVoiceLevel():null;if(c===null){sm(om);return}yd+=(c-yd)*.3,sm(yd)};Yi=requestAnimationFrame(i)}function im(){Yi!==null&&(cancelAnimationFrame(Yi),Yi=null),fT()}let sv=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,bd=(i="user")=>{if(_o||T.isStreaming())return;let c=sv();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=w=>{let W="",V="";for(let q=0;q<w.results.length;q++){let Q=w.results[q],se=Q[0].transcript;Q.isFinal?W+=se+" ":V=se}let F=b+W+V;ce.value=F,ko(),Gi&&clearTimeout(Gi),(W||V)&&(Gi=window.setTimeout(()=>{if(ce.value.trim()&&oo&&_o){if(zr(),nm())return;pl({viaVoice:!0})}},f))},oo.onerror=w=>{w.error!=="no-speech"&&zr()},oo.onend=()=>{if(_o){let w=ce.value.trim();!nm()&&w&&w!==b.trim()&&pl({viaVoice:!0}),zr()}};try{if(oo.start(),_o=!0,Xe.active=!0,i!=="system"&&(Xe.manuallyDeactivated=!1),rr(i),yo(),mo(),ie){let w=o.voiceRecognition??{};Pt={backgroundColor:ie.style.backgroundColor,color:ie.style.color,borderColor:ie.style.borderColor,iconName:w.iconName??"mic",iconSize:parseFloat(w.iconSize??"")||vn};let W=w.recordingBackgroundColor,V=w.recordingIconColor,F=w.recordingBorderColor;if(ie.classList.add("persona-voice-recording"),qs("recording"),ie.style.backgroundColor=W??"var(--persona-voice-recording-bg, #ef4444)",ie.style.color=V??"var(--persona-voice-recording-indicator, #ffffff)",V){let q=ie.querySelector("svg");q&&q.setAttribute("stroke",V)}F&&(ie.style.borderColor=F),ie.setAttribute("aria-label","Stop voice recognition")}}catch{zr("system")}},zr=(i="user")=>{if(_o){if(_o=!1,Gi&&(clearTimeout(Gi),Gi=null),oo){try{oo.stop()}catch{}oo=null}if(Xe.active=!1,rr(i),yo(),mo(),ie){if(ie.classList.remove("persona-voice-recording"),qs("idle"),Pt){ie.style.backgroundColor=Pt.backgroundColor,ie.style.color=Pt.color,ie.style.borderColor=Pt.borderColor;let c=ie.querySelector("svg");c&&c.setAttribute("stroke",Pt.color||"currentColor"),Pt=null}ie.setAttribute("aria-label","Start voice recognition")}}},am=()=>{if(!ie||Pt)return;let i=o.voiceRecognition??{};Pt={backgroundColor:ie.style.backgroundColor,color:ie.style.color,borderColor:ie.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||vn}},lm=(i,c)=>{if(!ie)return;let g=ie.querySelector("svg");g&&g.remove();let f=Pt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||vn),b=le(i,f,c,1.5);b&&ie.appendChild(b)},vd=()=>{ie&&ie.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Qi=()=>{if(!ie)return;am();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,g=i.recordingIconColor,f=i.recordingBorderColor;if(vd(),ie.classList.add("persona-voice-recording"),qs("recording"),ie.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",ie.style.color=g??"var(--persona-voice-recording-indicator, #ffffff)",g){let b=ie.querySelector("svg");b&&b.setAttribute("stroke",g)}f&&(ie.style.borderColor=f),ie.setAttribute("aria-label","Stop voice recognition")},yT=()=>{if(!ie)return;am();let i=o.voiceRecognition??{},c=T.getVoiceInterruptionMode(),g=i.processingIconName??"loader",f=i.processingIconColor??Pt?.color??"",b=i.processingBackgroundColor??Pt?.backgroundColor??"",w=i.processingBorderColor??Pt?.borderColor??"";vd(),ie.classList.add("persona-voice-processing"),qs("processing"),ie.style.backgroundColor=b,ie.style.borderColor=w;let W=f||"currentColor";ie.style.color=W,lm(g,W),ie.setAttribute("aria-label","Processing voice input"),c==="none"&&(ie.style.cursor="default")},bT=()=>{if(!ie)return;am();let i=o.voiceRecognition??{},c=T.getVoiceInterruptionMode(),g=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",f=i.speakingIconName??g,b=i.speakingIconColor??(c==="barge-in"?i.recordingIconColor??Pt?.color??"":Pt?.color??""),w=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Pt?.backgroundColor??""),W=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":Pt?.borderColor??"");vd(),ie.classList.add("persona-voice-speaking"),qs("speaking"),ie.style.backgroundColor=w,ie.style.borderColor=W;let V=b||"currentColor";ie.style.color=V,lm(f,V);let F=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";ie.setAttribute("aria-label",F),c==="none"&&(ie.style.cursor="default"),c==="barge-in"&&ie.classList.add("persona-voice-recording")},ur=()=>{ie&&(vd(),qs("idle"),Pt&&(ie.style.backgroundColor=Pt.backgroundColor??"",ie.style.color=Pt.color??"",ie.style.borderColor=Pt.borderColor??"",lm(Pt.iconName,Pt.color||"currentColor"),Pt=null),ie.style.cursor="",ie.setAttribute("aria-label","Start voice recognition"))},cm=()=>{if(!Oo()){if(Hn(o.voiceRecognition?.provider)){let i=T.getVoiceStatus(),c=T.getVoiceInterruptionMode();if(c==="none"&&(i==="processing"||i==="speaking"))return;if(c==="cancel"&&(i==="processing"||i==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,yo(),rr("user"),ur()});return}T.toggleVoice().then(()=>{Xe.active=T.isVoiceActive(),Xe.manuallyDeactivated=!T.isVoiceActive(),yo(),rr("user"),T.isVoiceActive()?Qi():ur()});return}if(_o){let i=ce.value.trim();Xe.manuallyDeactivated=!0,yo(),zr("user"),i&&!nm()&&pl()}else Xe.manuallyDeactivated=!1,yo(),bd("user")}};_u=cm,ie&&he.push(()=>{Hn(o.voiceRecognition?.provider)?(T.isVoiceActive()&&T.toggleVoice(),ur()):zr("system")});let vT=oe.on("assistant:complete",()=>{ve.getState().pendingSubmission&&setTimeout(()=>{T.isStreaming()||oT()},0)});he.push(vT);let CT=oe.on("assistant:complete",()=>{$y&&(Xe.active||Xe.manuallyDeactivated||$y==="assistant"&&!Xe.lastUserMessageWasVoice||setTimeout(()=>{!Xe.active&&!Xe.manuallyDeactivated&&(Hn(o.voiceRecognition?.provider)?T.toggleVoice().then(()=>{Xe.active=T.isVoiceActive(),rr("auto"),T.isVoiceActive()&&Qi()}):bd("auto"))},600))});he.push(CT);let wT=oe.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});he.push(wT);let iv=()=>{yt(!Ee,"user")},Wt=null,fn=null;if(D&&!we()){let{instance:i,element:c}=th({config:o,plugins:u,onToggle:iv});Wt=i,i||(fn=c)}Wt?e.appendChild(Wt.element):fn&&e.appendChild(fn),Xa(),Es(),jc(),yg(),Ja(T.isStreaming()),sg()||($n()==="follow"?$r(!0):Bc()),FM(),Fe&&(!D||we()?setTimeout(()=>Bs(),0):Ee&&setTimeout(()=>Bs(),200));let Kr=null,av=()=>{Kr&&(Kr.disconnect(),Kr.observe(He),Kr.observe(de),Kr.observe(tn))},lv=_a(),gl=()=>{if(we()){bs(),Xa();return}let i=Ct(o),c=o.launcher?.sidebarMode??!1,g=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640,w=g.innerWidth<=b,W=f&&w&&D;try{if(W){Cs(),Ua=Tc();return}let V=!1;ke&&(ke=!1,Cs(),V=!0);let F=Tc();if(!V&&F!==Ua&&(Cs(),V=!0),Ua=F,V&&Sc(),!D&&!i){xe.style.height="",xe.style.width="";return}if(!c&&!i){let q=mi(o);xe.style.width=q.width,xe.style.maxWidth=q.maxWidth}Ec(),My()}finally{bs(),yc();let V=_a();if(V!==lv&&(lv=V,Di(),Es()),Xa(),Ee&&D){let q=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),Q=o.launcher?.sidebarMode??!1,se=o.launcher?.mobileFullscreen??!0,me=Ct(o)&&se&&q,Ve=Q||se&&q&&D||me;if(Ve&&!Wo){let st=e.getRootNode(),nt=st instanceof ShadowRoot?st.host:e.closest(".persona-host");nt&&!Ho&&(Ho=Rf(nt,o.launcher?.zIndex??pn)),Wo=Hf(e.ownerDocument)}else Ve||(Ho?.(),Ho=null,Wo?.(),Wo=null)}}};gl();let Cd=e.ownerDocument.defaultView??window;if(Cd.addEventListener("resize",gl),he.push(()=>Cd.removeEventListener("resize",gl)),typeof ResizeObserver<"u"){Kr=new ResizeObserver(()=>{yc()}),av(),he.push(()=>{Kr?.disconnect(),Kr=null});let i=new ResizeObserver(()=>{sd()});i.observe(de),he.push(()=>i.disconnect())}Cd.addEventListener("resize",sd),he.push(()=>Cd.removeEventListener("resize",sd)),Vn=ne.scrollTop;let cv=Go(ne),dv=()=>{Ay();let i=ne.scrollTop,c=Go(ne),g=c<cv;if(cv=c,!Rr()){Vn=i,Qt();return}let{action:f,nextLastScrollTop:b}=Gx({following:jn.isFollowing(),currentScrollTop:i,lastScrollTop:Vn,nearBottom:li(ne,nr),userScrollThreshold:BM,isAutoScrolling:Tn||kc||g,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Vn=b,f==="resume"){Dc()||Pn();return}f==="pause"&&Wi()};if(ne.addEventListener("scroll",dv,{passive:!0}),he.push(()=>ne.removeEventListener("scroll",dv)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{KM(),Im(be)});i.observe(be),i.observe(ne),he.push(()=>i.disconnect())}let pv=()=>{Rr()&&jn.isFollowing()&&Dc()&&Wi()},uv=ne.ownerDocument;uv.addEventListener("selectionchange",pv),he.push(()=>{uv.removeEventListener("selectionchange",pv)});let xT=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),gv=i=>{xT.has(i.key)&&(Fr(),Kh()&&Rr()&&jn.isFollowing()&&Wi())},mv=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Fr(),Kh()&&Rr()&&jn.isFollowing()&&Wi())};ne.addEventListener("keydown",gv),ne.addEventListener("focusin",mv),he.push(()=>{ne.removeEventListener("keydown",gv),ne.removeEventListener("focusin",mv)});let fv=i=>{if(i.deltaY!==0&&Fr(),!Rr())return;let c=Yx({following:jn.isFollowing(),deltaY:i.deltaY,nearBottom:li(ne,nr),resumeWhenNearBottom:!0});c==="pause"?Wi():c==="resume"&&!Dc()&&Pn()};ne.addEventListener("wheel",fv,{passive:!0}),ne.addEventListener("touchmove",Fr,{passive:!0}),ne.addEventListener("pointerdown",Fr,{passive:!0}),he.push(()=>{ne.removeEventListener("touchmove",Fr),ne.removeEventListener("pointerdown",Fr)}),he.push(()=>ne.removeEventListener("wheel",fv)),qt.addEventListener("click",()=>{bo(),ne.scrollTop=ne.scrollHeight,Vn=ne.scrollTop,Pn(),$r(!0),Qt()}),he.push(()=>qt.remove()),he.push(()=>{zy(),bo()});let hv=()=>{qe&&(As&&(qe.removeEventListener("click",As),As=null),Be()?(qe.style.display="",As=()=>{yt(!1,"user")},qe.addEventListener("click",As)):qe.style.display="none")};hv(),(()=>{let{clearChatButton:i}=$e;i&&i.addEventListener("click",()=>{if(Do()){Kg({focusComposer:!0}).catch(g=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",g)});return}T.clearMessages(),o.layout?.topFade&&(ne.scrollTop=0),ne.removeAttribute("data-persona-top-fade"),$t.clear(),Pn(),ss($e.composerOverlay);try{localStorage.removeItem(ka),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ka}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ka)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),k?.clear&&Hc(()=>k.clear(),"[AgentWidget] Failed to clear storage adapter:"),I={},Ce.syncFromMetadata(),rt?.clearAttachments(),Oc(),xi(void 0),Lo(void 0),ks(),ft?.clear(),Zt?.reset(),ht?.update()})})();let yv=[["keydown",gT],["input",pT],["input",ko],["input",vs],["keyup",vs],["paste",mT],["focus",MM]],bv=i=>{if(i)for(let[c,g]of yv)tt?.addListener(i,c,g)},ST=i=>{if(i)for(let[c,g]of yv)tt?.removeListener(i,c,g)},vv=()=>{tt&&(tt.addListener(tt.form,"submit",aT),tt.addListener(tt.footer,"click",vs),bv(ce),ie&&tt.addListener(ie,"click",cm))};vv();let Cv=()=>{Ft?.onComposerSwap((i,c)=>{ST(c),ce=i,tt&&(tt.input=i),bv(i),Fu(),dg(),ko()})};Cv();let dm=!1;function wv(){if(!dm){dm=!0;try{let i=ce?.value??"",c=He.ownerDocument??document,g=ce?c.activeElement===ce:!1;im(),tt?.destroy(),tt=null,Ft?.destroy(),Ft=null;let f=null,b=()=>(f=we()?jp({config:o}):ui({config:o}),f.footer),w=oy(b)??b();_n.replaceComposer(w),He=_n.composer.footer;let W=f!==null&&w===f.footer;Ai=!W,zh=W?f.setSendButtonMode:()=>{},ny(He),sy(He),iy(),ay(),ly(),Cv(),cy(),$u(),dy(),vv();let V=Ss.indexOf(tr);if(tr.destroy(),tr=Jl(Lr),V>=0&&(Ss[V]=tr),ce&&(ce.value=i),ko(),vs(),jc(),Es(),Ja(T.isStreaming()),o.statusIndicator?.mode==="transient"&&!we()){let F=T.getStatus();Ra(Je,Pu(F),o.statusIndicator,F)}Xe.active&&qs("recording"),Cs(),av(),bs(),mo(),$c(),g&&ce?.focus()}finally{dm=!1}}}let ml=e.ownerDocument??document;ml.addEventListener("keydown",nv,!0);let xv=()=>{tg()},Sv=()=>{ml.visibilityState==="hidden"&&tg()};typeof window<"u"&&(window.addEventListener("pagehide",xv),ml.addEventListener("visibilitychange",Sv),he.push(()=>{window.removeEventListener("pagehide",xv),ml.removeEventListener("visibilitychange",Sv)}));let Av="persona-attachment-drop-active",fl=0,pm=()=>{fl=0,de.classList.remove(Av)},Xi=()=>o.attachments?.enabled===!0&&rt!==null&&!Oo(),Mv=i=>{!iu(i.dataTransfer)||!Xi()||(fl++,fl===1&&de.classList.add(Av))},Ev=i=>{!iu(i.dataTransfer)||!Xi()||(fl--,fl<=0&&pm())},Tv=i=>{!iu(i.dataTransfer)||!Xi()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Pv=i=>{if(!iu(i.dataTransfer)||!Xi())return;i.preventDefault(),i.stopPropagation(),pm();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&rt.handleFiles(c)},Gr=!0;de.addEventListener("dragenter",Mv,Gr),de.addEventListener("dragleave",Ev,Gr),e.addEventListener("dragover",Tv,Gr),e.addEventListener("drop",Pv,Gr);let wd=e.ownerDocument,kv=i=>{Xi()&&i.preventDefault()},Lv=i=>{Xi()&&i.preventDefault()};wd.addEventListener("dragover",kv),wd.addEventListener("drop",Lv),he.push(()=>{tt?.destroy(),tt=null,im(),Io?.destroy(),Io=null,Zo?.destroy(),Zo=null,Wr?.destroy(),Wr=null,Or?.destroy(),Or=null,Hr=null,Bu=null,tg(),za.destroy(),Ki&&clearTimeout(Ki),ks(),Vs?.abort(),Vs=null,rt?.destroy(),rt=null,ve.destroy(),ml.removeEventListener("keydown",nv,!0),Ft?.destroy()}),he.push(()=>{de.removeEventListener("dragenter",Mv,Gr),de.removeEventListener("dragleave",Ev,Gr),e.removeEventListener("dragover",Tv,Gr),e.removeEventListener("drop",Pv,Gr),wd.removeEventListener("dragover",kv),wd.removeEventListener("drop",Lv),pm()}),he.push(()=>{T.cancel()}),Wt?he.push(()=>{Wt?.destroy()}):fn&&he.push(()=>{fn?.remove()});let Ot={update(i){let c=o.future?.v5Defaults===!0,g=o.toolCall,f=o.messageActions,b=o.layout?.messages,w=o.colorScheme,W=o.loadingIndicator,V=o.iterationDisplay,F=o.features?.showReasoning,q=o.features?.showToolCalls,Q=o.features?.toolCallDisplay,se=o.features?.reasoningDisplay,me=o.features?.streamAnimation?.type,Ve=o.features?.history?.enabled===!0,st=o.features?.history?.provider,nt=o.getIdentityProof,In=o.clientToken,At=o.contextMentions;o=Jp({...o,features:p},i),p=o.features,o=oc(o),d(),Gu(),ai(e,o),tc(e,o),nc(e,o),Xo(),ho(),o.colorScheme!==w&&Ey();let Lt=rc.getForInstance(o.plugins);u.length=0,u.push(...Lt),Mb(),D=o.launcher?.enabled??!0,Ne=o.launcher?.autoExpand??!1,z=o.features?.showReasoning??!0,J=o.features?.showToolCalls??!0,fe=o.features?.scrollToBottom??{};let hn=$n();Ae=o.features?.scrollBehavior??{},hn!==$n()&&(bo(),Pn()),Fy(),Qh(),Qt();let Bt=X;if(X=o.features?.showEventStreamToggle??!1,X&&!Bt){if(ft||(pc(),T.setSSEEventCallback((Z,Ge)=>{o.onSSEEvent?.(Z,Ge),Mu(Z,Ge)})),!at&&Pe){let Z=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"+(Z?.toggleButton?" "+Z.toggleButton:"");at=S("button",Ge),at.style.width="28px",at.style.height="28px",at.style.color=Cn.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let Ye=Mt(Tr.Activity,"18px","currentColor",1.5);Ye&&at.appendChild(Ye);let ot=$e.clearChatButtonWrapper,wt=$e.closeButtonWrapper,dn=ot||wt;dn&&dn.parentNode===Pe?Pe.insertBefore(at,dn):Pe.appendChild(at),at.addEventListener("click",()=>{go?Si():Nu()})}}else!X&&Bt&&(Si(),at&&(at.remove(),at=null),ft?.clear(),et?.destroy(),ft=null,et=null,Zt?.reset(),Zt=null,It=null);if(o.launcher?.enabled===!1&&Wt&&(Wt.destroy(),Wt=null),o.launcher?.enabled===!1&&fn&&(fn.remove(),fn=null),o.launcher?.enabled!==!1&&!Wt&&!fn){let{instance:Z,element:Ge}=th({config:o,plugins:u,onToggle:iv});Wt=Z,Z||(fn=Ge),e.appendChild(Ge)}Wt&&Wt.update(o),dl(),fs&&o.launcher?.subtitle!==void 0&&(fs.textContent=o.launcher.subtitle);let pt=o.layout?.header;if(pt?.layout!==jt&&Pe){let Z=pt?Ca(o,pt,{showClose:Be(),onClose:()=>yt(!1,"user")}):Sr({config:o,showClose:Be(),onClose:()=>yt(!1,"user")});_n.replaceHeader(Z),Pe=_n.header.element,Ht=_n.header.iconHolder,Ir=_n.header.headerTitle,fs=_n.header.headerSubtitle,qe=_n.header.closeButton,jt=pt?.layout,dl()}else if(pt){if(Ht&&(Ht.style.display=pt.showIcon===!1?"none":""),Ir&&(Ir.style.display=pt.showTitle===!1?"none":""),fs&&(fs.style.display=pt.showSubtitle===!1?"none":""),qe){let Z=Be()&&pt.showCloseButton!==!1;qe.style.display=Z?"":"none"}if($e.clearChatButtonWrapper){let Z=pt.showClearChat;if(Z!==void 0){$e.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:Ge}=$e;Ge&&!Ge.classList.contains("persona-absolute")&&(Z?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}}let Fo=o.layout?.showHeader!==!1;Pe&&(Pe.style.display=Fo?"":"none");let so=o.layout?.showFooter!==!1;He&&(He.style.display=so?"":"none"),bs(),Qt(),D!==Gt?D?yt(Ne,"auto"):(Ee=!0,Xa()):Ne!==Et&&yt(Ne,"auto"),Et=Ne,Gt=D,gl(),hv();let $o=JSON.stringify(o.toolCall)!==JSON.stringify(g),vo=JSON.stringify(o.messageActions)!==JSON.stringify(f),Qr=JSON.stringify(o.layout?.messages)!==JSON.stringify(b),hl=o.loadingIndicator?.render!==W?.render||o.loadingIndicator?.renderIdle!==W?.renderIdle||o.loadingIndicator?.showBubble!==W?.showBubble,zs=o.iterationDisplay!==V,R=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(q??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(Q)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(se);(o.future?.v5Defaults===!0!==c||$o||vo||Qr||hl||zs||R)&&T&&(Ls++,Jn(be,T.getMessages(),N));let Oe=o.features?.streamAnimation?.type;if(Oe!==me&&Oe&&Oe!=="none"){let Z=Xu(Oe,o.features?.streamAnimation?.plugins);Z&&Yl(Z,e)}let re=o.launcher??{},ut=re.headerIconHidden??!1,Ut=o.layout?.header?.showIcon,un=ut||Ut===!1,nn=re.headerIconName,bt=re.headerIconSize??Cl;if(Ht){let Z=Pe,Ge=Z?.querySelector(".persona-flex-col");if(un)Ht.style.display="none",Z&&Ge&&!Z.contains(Ge)&&Z.insertBefore(Ge,Z.firstChild);else{if(Ht.style.display="",Ht.style.height=bt,Ht.style.width=bt,Z&&Ge&&(Z.contains(Ht)?Ht.nextSibling!==Ge&&(Ht.remove(),Z.insertBefore(Ht,Ge)):Z.insertBefore(Ht,Ge)),nn){let ot=parseFloat(bt)||24,wt=le(nn,ot*.6,"currentColor",1);wt?(wt.style.width=`calc(${ot}px * var(--persona-components-header-iconScale, 0.6))`,wt.style.height=`calc(${ot}px * var(--persona-components-header-iconScale, 0.6))`,Ht.replaceChildren(wt)):Ht.textContent=re.agentIconText??"\u{1F4AC}"}else if(re.iconUrl){let ot=Ht.querySelector("img");if(ot)ot.src=re.iconUrl,ot.style.height=bt,ot.style.width=bt;else{let wt=document.createElement("img");wt.src=re.iconUrl,wt.alt="",wt.className="persona-rounded-xl persona-object-cover",wt.style.height=bt,wt.style.width=bt,Ht.replaceChildren(wt)}}else{let ot=Ht.querySelector("svg"),wt=Ht.querySelector("img");(ot||wt)&&Ht.replaceChildren(),Ht.textContent=re.agentIconText??"\u{1F4AC}"}let Ye=Ht.querySelector("img");Ye&&(Ye.style.height=bt,Ye.style.width=bt)}}let Dt=o.layout?.header?.showTitle,Xt=o.layout?.header?.showSubtitle;if(Ir&&(Ir.style.display=Dt===!1?"none":""),fs&&(fs.style.display=Xt===!1?"none":""),qe){let Z=Be()&&o.layout?.header?.showCloseButton!==!1;if(qe.style.display=Z?"":"none",!we()){let rn=re.closeButtonSize??"";qe.style.height=rn,qe.style.width=rn,qe.style.minWidth=rn,qe.style.minHeight=rn}let Ge=re.closeButtonPlacement??"inline",{closeButtonWrapper:Ye}=$e,ot=Ge==="top-right",wt=Ye?.classList.contains("persona-absolute");if(Ye&&ot!==wt)if(Ye.remove(),ot){Ye.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let rn=nl??de;rn.style.position="relative",rn.appendChild(Ye)}else{let rn=re.clearChat?.placement??"inline",sn=re.clearChat?.enabled??!0;Ye.className=sn&&rn==="inline"?"":"persona-ml-auto",Pe&&Pe.appendChild(Ye)}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 rn=re.closeButtonBorderWidth||"0px",sn=re.closeButtonBorderColor||"transparent";qe.style.border=`${rn} solid ${sn}`,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=""),Np(qe,re.closeButtonIconName??"x",{iconSize:we()?Xf:void 0,iconText:re.closeButtonIconText??"\xD7"});let dn=re.closeButtonTooltipText??"Close chat",wo=re.closeButtonShowTooltip??!0;qe.setAttribute("aria-label",dn),Ye&&an({anchor:qe,trigger:Ye,text:()=>qe?.getAttribute("aria-label")??dn,enabled:wo})}let{clearChatButton:Le,clearChatButtonWrapper:vt}=$e;if(Le){let Z=re.clearChat??{},Ge=Z.enabled??!0,Ye=o.layout?.header?.showClearChat,ot=Ye!==void 0?Ye:Ge,wt=Z.placement??"inline";if(vt){vt.style.display=ot?"":"none";let{closeButtonWrapper:dn}=$e;!we()&&dn&&!dn.classList.contains("persona-absolute")&&(ot?dn.classList.remove("persona-ml-auto"):dn.classList.add("persona-ml-auto"));let wo=wt==="top-right",rn=vt.classList.contains("persona-absolute");if(!we()&&wo!==rn&&ot){if(vt.remove(),wo){vt.className="persona-absolute persona-top-4 persona-z-50",vt.style.right="48px";let Uo=nl??de;Uo.style.position="relative",Uo.appendChild(vt)}else{vt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vt.style.right="";let Uo=$e.closeButtonWrapper;Pe&&Uo&&Uo.parentElement===Pe?Pe.insertBefore(vt,Uo):Pe&&Pe.appendChild(vt)}let sn=$e.closeButtonWrapper;sn&&!sn.classList.contains("persona-absolute")&&(wo?sn.classList.add("persona-ml-auto"):sn.classList.remove("persona-ml-auto"))}}if(ot){if(!we()){let sn=Z.size??"";Le.style.height=sn,Le.style.width=sn,Le.style.minWidth=sn,Le.style.minHeight=sn}let dn=Z.iconColor??"";if(Le.style.color=dn||Cn.actionIconColor,Np(Le,Z.iconName??"refresh-cw",{iconSize:we()?Jf:void 0}),Z.backgroundColor?(Le.style.backgroundColor=Z.backgroundColor,Le.classList.remove("hover:persona-bg-gray-100")):(Le.style.backgroundColor="",Le.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let sn=Z.borderWidth||"0px",Uo=Z.borderColor||"transparent";Le.style.border=`${sn} solid ${Uo}`,Le.classList.remove("persona-border-none")}else Le.style.border="",Le.classList.add("persona-border-none");Z.borderRadius?(Le.style.borderRadius=Z.borderRadius,Le.classList.remove("persona-rounded-full")):(Le.style.borderRadius="",Le.classList.add("persona-rounded-full")),Z.paddingX?(Le.style.paddingLeft=Z.paddingX,Le.style.paddingRight=Z.paddingX):(Le.style.paddingLeft="",Le.style.paddingRight=""),Z.paddingY?(Le.style.paddingTop=Z.paddingY,Le.style.paddingBottom=Z.paddingY):(Le.style.paddingTop="",Le.style.paddingBottom="");let wo=Z.tooltipText??"Clear chat",rn=Z.showTooltip??!0;Le.setAttribute("aria-label",wo),vt&&an({anchor:Le,trigger:vt,text:()=>Le?.getAttribute("aria-label")??wo,enabled:rn})}}let De=o.actionParsers&&o.actionParsers.length?o.actionParsers:[sc],Jt=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[yi.message,yi.messageAndClick];Ce=ic({parsers:De,handlers:Jt,getSessionMetadata:Se,updateSessionMetadata:ye,emit:oe.emit,documentRef:typeof document<"u"?document:null}),N=fA(o,Ce,M),pE(),T.updateConfig(o),Jb(),(o.features?.history?.enabled===!0!==Ve||o.features?.history?.provider!==st||o.getIdentityProof!==nt||o.clientToken!==In)&&(Ln({restoreFocus:!1}),yb()),qr(),sd(),Jn(be,T.getMessages(),N),Es(),jc(),cE(),Ja(T.isStreaming()),At!==o.contextMentions&&wv();let ao=o.voiceRecognition?.enabled===!0,on=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),gt=Hn(o.voiceRecognition?.provider);if(ao&&(on||gt))if(!ie||!Fn){let Z=ha(o);if(Z){ie=Z.button,Fn=Z.wrapper;let Ge=Po&&Po.parentElement===uc?Po:null;uc?uc.insertBefore(Fn,Ge):An?.appendChild(Fn),tt&&(tt.micButton=ie),tt?.addListener(ie,"click",cm),ie.disabled=Oo()||T.isStreaming()&&!lg()}}else{let Z=o.voiceRecognition??{},Ge=o.sendButton??{},Ye=Z.iconName??"mic",ot=Z.iconSize,wt=parseFloat(ot??"")||vn;ie.classList.add(Kn),ie.classList.toggle(Ao,!ot),ie.style.width=ot??"",ie.style.height=ot??"",ie.style.minWidth=ot??"",ie.style.minHeight=ot??"";let dn=Z.iconColor??Ge.textColor;ie.innerHTML="";let wo=le(Ye,wt,dn||"currentColor",1.5);wo?ie.appendChild(wo):ie.textContent="\u{1F3A4}";let rn=Z.backgroundColor??Ge.backgroundColor;rn?ie.style.backgroundColor=rn:ie.style.backgroundColor="",dn?ie.style.color=dn:ie.style.color="var(--persona-text, #111827)",Z.borderWidth?(ie.style.borderWidth=Z.borderWidth,ie.style.borderStyle="solid"):(ie.style.borderWidth="",ie.style.borderStyle=""),Z.borderColor?ie.style.borderColor=Z.borderColor:ie.style.borderColor="",Z.paddingX?(ie.style.paddingLeft=Z.paddingX,ie.style.paddingRight=Z.paddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),Z.paddingY?(ie.style.paddingTop=Z.paddingY,ie.style.paddingBottom=Z.paddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let sn=Z.tooltipText??"Start voice recognition",Uo=Z.showTooltip??!1;ie.setAttribute("aria-label",sn),Fn&&an({anchor:ie,trigger:Fn,text:()=>ie?.getAttribute("aria-label")??sn,enabled:Uo}),Fn.style.display="",ie.disabled=Oo()||T.isStreaming()&&!lg()}else ie&&Fn&&(Fn.style.display="none",Hn(o.voiceRecognition?.provider)?T.isVoiceActive()&&T.toggleVoice():_o&&zr());if(o.attachments?.enabled===!0){if(!Mn||!kt){let Z=o.attachments??{};En||(En=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),En.style.display="none",(ce.parentElement??An).insertBefore(En,ce)),St||(St=document.createElement("input"),St.type="file",St.accept=(Z.allowedTypes??xr).join(","),St.multiple=(Z.maxFiles??4)>1,St.style.display="none",St.setAttribute("aria-label","Attach files"),(ce.parentElement??An).insertBefore(St,ce)),Mn=S("div","persona-send-button-wrapper"),kt=S("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Kn} ${Ao}`),kt.type="button",kt.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let Ge=Z.buttonIconName??"paperclip";kt.style.fontSize="18px",kt.style.lineHeight="1";let Ye=le(Ge,vn,"currentColor",1.5);Ye?kt.appendChild(Ye):kt.textContent="\u{1F4CE}",kt.addEventListener("click",wt=>{wt.preventDefault(),St?.click()}),Mn.appendChild(kt);let ot=Z.buttonTooltipText??"Attach file";an({anchor:kt,trigger:Mn,text:()=>kt?.getAttribute("aria-label")??ot}),Lu?Lu.append(Mn):An.appendChild(Mn),tt&&(tt.attachmentButton=kt,tt.attachmentInput=St??void 0,tt.attachmentPreviews=En??void 0),!rt&&St&&En&&(rt=si.fromConfig(Z,Xh),rt.setPreviewsContainer(En),tt?.addListener(St,"change",async()=>{rt&&St?.files&&(await rt.handleFileSelect(St.files),St.value="")}))}else{Mn.style.display="";let Z=o.attachments??{};St&&(St.accept=(Z.allowedTypes??xr).join(","),St.multiple=(Z.maxFiles??4)>1),rt&&rt.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles,adapter:Z.adapter})}if(de.querySelector(".persona-attachment-drop-overlay")?.remove(),de.appendChild(hA(o.attachments?.dropOverlay)),kt){let Z=o.attachments??{},Ge=Z.buttonTooltipText??"Attach file";kt.setAttribute("aria-label",Ge),kt.textContent="";let Ye=le(Z.buttonIconName??"paperclip",vn,"currentColor",1.5);Ye?kt.appendChild(Ye):kt.textContent="\u{1F4CE}",Mn&&an({anchor:kt,trigger:Mn,text:()=>kt?.getAttribute("aria-label")??Ge})}}else Mn&&(Mn.style.display="none"),rt&&rt.clearAttachments(),de.querySelector(".persona-attachment-drop-overlay")?.remove();let _e=o.sendButton??{},Xr=_e.useIcon??!1,Kt=_e.iconText??"\u2191",Rn=_e.iconName,gr=_e.tooltipText??"Send message",um=_e.showTooltip??!1,Ks=_e.size,gm=parseFloat(Ks??"")||pf,mr=_e.backgroundColor,Gs=_e.textColor;if(Xr){if(Te.style.width=Ks??"",Te.style.height=Ks??"",Te.style.minWidth=Ks??"",Te.style.minHeight=Ks??"",Te.style.fontSize="18px",Te.style.lineHeight="1",Gs?Te.style.color=Gs:Te.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!T.isStreaming())if(Te.innerHTML="",Rn){let Z=parseFloat(_e.iconSize??"")||Math.round(gm*.5),Ge=Gs?.trim()||"currentColor",Ye=_e.iconStrokeWidth??2,ot=le(Rn,Z,Ge,Ye),wt=le(_e.stopIconName??"square",Z,Ge,Ye);ot&&wt?Te.appendChild(uf(ot,wt)):ot?Te.appendChild(ot):Te.textContent=Kt}else Te.textContent=Kt;Te.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Kn}`,mr?(Te.style.backgroundColor=mr,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",mr?(Te.style.backgroundColor=mr,Te.classList.remove("persona-bg-persona-accent")):Te.classList.add("persona-bg-persona-accent"),Gs?Te.style.color=Gs:Te.classList.add("persona-text-white");_e.borderWidth?(Te.style.borderWidth=_e.borderWidth,Te.style.borderStyle="solid"):(Te.style.borderWidth="",Te.style.borderStyle=""),_e.borderColor?Te.style.borderColor=_e.borderColor:Te.style.borderColor="",_e.paddingX?(Te.style.paddingLeft=_e.paddingX,Te.style.paddingRight=_e.paddingX):(Te.style.paddingLeft="",Te.style.paddingRight=""),_e.paddingY?(Te.style.paddingTop=_e.paddingY,Te.style.paddingBottom=_e.paddingY):(Te.style.paddingTop="",Te.style.paddingBottom=""),T.isStreaming()||Te.setAttribute("aria-label",gr),$c(),Po&&an({anchor:Te,trigger:Po,text:()=>Te.getAttribute("aria-label")??gr,enabled:um}),py(),Qu();let Iv=xp(ve.getState().activeModeIds,o.composer?.modes);ve.setActiveModeIds(Iv),Ci().length>0!==!!Zo&&$u(),Zo?.render(Iv,Ci());for(let Z of[...wi.keys()])wp(Z,o.composer?.modeGroups)||wi.delete(Z);wi.forEach(Z=>Z.repaint()),Hr?.repaint(),Io?.resolve();let xd=ds(o,we());if(Yu(),xd){be.style.maxWidth=xd,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%",Nn.style.maxWidth=xd,Nn.style.marginLeft="auto",Nn.style.marginRight="auto",Nn.style.width="100%";for(let Z of[An,Lr,En,Je])Z&&(Z.style.maxWidth=xd,Z.style.marginLeft="auto",Z.style.marginRight="auto",Z.style.width="100%")}else{be.style.maxWidth="",be.style.marginLeft="",be.style.marginRight="",be.style.width="",Nn.style.maxWidth="",Nn.style.marginLeft="",Nn.style.marginRight="",Nn.style.width="";for(let Z of[An,Lr,En,Je])Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight="",Z.style.width="")}let Co=o.statusIndicator??{};if(Pm(Je,An,Co),ei(Je,Co,T?.getStatus()??"idle"),T){let Z=T.getStatus();Ra(Je,(Ye=>Ye==="idle"?Co.idleText??_t.idle:Ye==="connecting"?Co.connectingText??_t.connecting:Ye==="connected"?Co.connectedText??_t.connected:Ye==="error"?Co.errorText??_t.error:Ye==="paused"?Co.pausedText??_t.paused:Ye==="resuming"?Co.resumingText??_t.resuming:_t[Ye])(Z),Co,Z)}Je.classList.remove("persona-text-left","persona-text-center","persona-text-right");let ET=Co.align==="left"?"persona-text-left":Co.align==="center"?"persona-text-center":"persona-text-right";Je.classList.add(ET),Fu(),dg(),mo(),Eu()},open(){Be()&&yt(!0,"api")},close(){Be()&&yt(!1,"api")},toggle(){Be()&&yt(!Ee,"api")},reconnect(){T.reconnectNow()},clearChat(){er=!1,a.clear(),r.clear(),s.clear(),l.clear(),T.clearMessages(),o.layout?.topFade&&(ne.scrollTop=0),ne.removeAttribute("data-persona-top-fade"),$t.clear(),Pn();try{localStorage.removeItem(ka),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ka}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ka)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),k?.clear&&Hc(()=>k.clear(),"[AgentWidget] Failed to clear storage adapter:"),I={},Ce.syncFromMetadata(),rt?.clearAttachments(),Oc(),xi(void 0),Lo(void 0),ks(),ft?.clear(),Zt?.reset(),ht?.update()},setMessage(i){return!ce||T.isStreaming()||Oo()?!1:(!Ee&&Be()&&yt(!0,"system"),ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(T.isStreaming()||Os())return!1;let c=i?.trim()||ce.value.trim();return c?(!Ee&&Be()&&yt(!0,"system"),ce.value="",ce.style.height="auto",ko(),hd(c,{consumeDraft:!1}),!0):!1},getComposerState(){return ve.getState()},setQuote(i){let c=i?.text?.trim();c&&Lo({...i,text:c})},clearQuote(){Lo(void 0)},startVoiceRecognition(){return T.isStreaming()?!1:Hn(o.voiceRecognition?.provider)?(T.isVoiceActive()||T.isBargeInActive()||(!Ee&&Be()&&yt(!0,"system"),Xe.manuallyDeactivated=!1,yo(),T.toggleVoice().then(()=>{Xe.active=T.isVoiceActive(),rr("user"),T.isVoiceActive()&&Qi()})),!0):_o?!0:sv()?(!Ee&&Be()&&yt(!0,"system"),Xe.manuallyDeactivated=!1,yo(),bd("user"),!0):!1},stopVoiceRecognition(){return Hn(o.voiceRecognition?.provider)?!T.isVoiceActive()&&!T.isBargeInActive()?!1:((T.isBargeInActive()?T.deactivateBargeIn():T.toggleVoice()).then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,yo(),rr("user"),ur()}),!0):_o?(Xe.manuallyDeactivated=!0,yo(),zr("user"),!0):!1},injectMessage(i){return!Ee&&Be()&&yt(!0,"system"),T.injectMessage(i)},injectAssistantMessage(i){!Ee&&Be()&&yt(!0,"system");let c=T.injectAssistantMessage(i);return Sn&&(Sn=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),c},injectUserMessage(i){return!Ee&&Be()&&yt(!0,"system"),T.injectUserMessage(i)},injectSystemMessage(i){return!Ee&&Be()&&yt(!0,"system"),T.injectSystemMessage(i)},injectMessageBatch(i){return!Ee&&Be()&&yt(!0,"system"),T.injectMessageBatch(i)},injectComponentDirective(i){return!Ee&&Be()&&yt(!0,"system"),T.injectComponentDirective(i)},injectTestMessage(i){!Ee&&Be()&&yt(!0,"system"),T.injectTestEvent(i)},async connectStream(i,c){return T.connectStream(i,c)},__pushEventStreamEvent(i){X&&(pc(),Mu(i.type,i.payload))},showEventStream(){X&&Nu()},hideEventStream(){go&&Si()},isEventStreamVisible(){return go},listConversations(i){return T.listConversations(i)},getActiveConversationId(){return T.getActiveConversationId()},openConversation(i,c){return zg(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return Kg({focusComposer:i?.focus===!0})},warmSession(){Qg()},deleteConversation(i){return jb(i)},renameConversation(i,c){return Gg(i,{title:c})},setConversationStarred(i,c){return Gg(i,{starred:c})},clearConversationHistory(i){return Vb(i)},resetHistoryIdentity(){return qb()},async getVisitorToken(){let i=Zn;if(!i)return null;let c=await i.get();return i===Zn?c:null},getHistoryIdentityStatus(){return qn?qn.getIdentityStatus():kg()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return cl({...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 Rt},showArtifacts(){xn(o)&&(er=!1,Mi=!0,ho(),Ke?.setMobileOpen(!0))},hideArtifacts(){xn(o)&&(er=!0,ho())},upsertArtifact(i){return xn(o)?(Vo(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(er=!1,Mi=!0),T.upsertArtifact(i)):null},selectArtifact(i){xn(o)&&T.selectArtifact(i)},clearArtifacts(){xn(o)&&T.clearArtifacts()},getArtifacts(){return T?.getArtifacts()??[]},getSelectedArtifactId(){return T?.getSelectedArtifactId()??null},focusInput(){return D&&!Ee&&!we()||!ce?!1:(ce.focus(),!0)},async resolveApproval(i,c,g){let b=T.getMessages().find(w=>w.variant==="approval"&&w.approval?.id===i);if(!b?.approval)throw new Error(`Approval not found: ${i}`);if(b.approval.toolType==="webmcp"){T.resolveWebMcpApproval(b.id,c);return}return T.resolveApproval(b.approval,c,g)},setFollowUpSuggestions(i){WM(i)},clearFollowUpSuggestions(){Ny()},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...I}},updatePersistentMetadata(i){ye(i)},on(i,c){return oe.on(i,c)},off(i,c){oe.off(i,c)},isOpen(){return Be()&&Ee},isVoiceActive(){return Xe.active},toggleReadAloud(i){T.toggleReadAloud(i)},stopReadAloud(){T.stopSpeaking()},getReadAloudState(i){return T.getReadAloudState(i)},onReadAloudChange(i){return T.onReadAloudChange(i)},getState(){return{open:Be()&&Ee,launcherEnabled:D,voiceActive:Xe.active,streaming:T.isStreaming()}},showCSATFeedback(i){!Ee&&Be()&&yt(!0,"system");let c=be.querySelector(".persona-feedback-container");c&&c.remove();let g=ru({onSubmit:async(f,b)=>{T.isClientTokenMode()&&await T.submitCSATFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});be.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Ee&&Be()&&yt(!0,"system");let c=be.querySelector(".persona-feedback-container");c&&c.remove();let g=su({onSubmit:async(f,b)=>{T.isClientTokenMode()&&await T.submitNPSFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});be.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,c){return T.submitCSATFeedback(i,c)},async submitNPSFeedback(i,c){return T.submitNPSFeedback(i,c)},destroy(){xg(),_s!=null&&(clearInterval(_s),_s=null),a.clear(),r.clear(),s.clear(),l.clear(),he.forEach(i=>i()),Qe.remove(),en?.remove(),Wt?.destroy(),fn?.remove(),As&&qe.removeEventListener("click",As)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:Ot,getMessages:Ot.getMessages,getStatus:Ot.getStatus,getMetadata:Ot.getPersistentMetadata,updateMetadata:Ot.updatePersistentMetadata,clearHistory:()=>Ot.clearChat(),setVoiceActive:g=>g?Ot.startVoiceRecognition():Ot.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=q=>{let Q=q.detail;(!Q?.instanceId||Q.instanceId===i)&&Ot.focusInput()};if(window.addEventListener("persona:focusInput",c),he.push(()=>{window.removeEventListener("persona:focusInput",c)}),X){let q=se=>{let me=se.detail;(!me?.instanceId||me.instanceId===i)&&Ot.showEventStream()},Q=se=>{let me=se.detail;(!me?.instanceId||me.instanceId===i)&&Ot.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",Q),he.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",Q)})}let g=q=>{let Q=q.detail;(!Q?.instanceId||Q.instanceId===i)&&Ot.showHistory()},f=q=>{let Q=q.detail;(!Q?.instanceId||Q.instanceId===i)&&Ot.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=q=>{let Q=q.detail;(!Q?.instanceId||Q.instanceId===i)&&Ot.showArtifacts()},w=q=>{let Q=q.detail;(!Q?.instanceId||Q.instanceId===i)&&Ot.hideArtifacts()},W=q=>{let Q=q.detail;Q?.instanceId&&Q.instanceId!==i||Q?.artifact&&Ot.upsertArtifact(Q.artifact)},V=q=>{let Q=q.detail;Q?.instanceId&&Q.instanceId!==i||typeof Q?.id=="string"&&Ot.selectArtifact(Q.id)},F=q=>{let Q=q.detail;(!Q?.instanceId||Q.instanceId===i)&&Ot.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",w),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",V),window.addEventListener("persona:clearArtifacts",F),he.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",w),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",V),window.removeEventListener("persona:clearArtifacts",F)})}let ro=hI(o.persistState);if(ro&&Be()){let i=yI(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&&(Wt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Ot.open(),setTimeout(()=>{if(w||W)Ot.startVoiceRecognition();else if(ro.persist?.focusInput){let V=e.querySelector("textarea");V&&V.focus()}},100)},0)),ro.persist?.openState&&(oe.on("widget:opened",()=>{i.setItem(c,"true")}),oe.on("widget:closed",()=>{i.setItem(c,"false")})),ro.persist?.voiceState&&(oe.on("voice:state",V=>{i.setItem(g,V.active?"true":"false")}),oe.on("user:message",V=>{i.setItem(f,V.viaVoice?"true":"false")})),ro.clearOnChatClear){let V=()=>{i.removeItem(c),i.removeItem(g),i.removeItem(f)},F=()=>V();window.addEventListener("persona:clear-chat",F),he.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}if(ge&&Be()&&(Wt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Ot.open()},0)),Oi(),!OM){let i=Ji(()=>{T&&(Ls++,$t.clear(),Jn(be,T.getMessages(),N))});he.push(i)}B=()=>{T&&(Ls++,$t.clear(),Jn(be,T.getMessages(),N))},T.getMessages().length>0&&Fc(),K=()=>{T&&(Ls++,$t.clear(),Jn(be,T.getMessages(),N))};let AT=Uv(()=>{T&&(Ls++,$t.clear(),Jn(be,T.getMessages(),N))});he.push(AT);let MT=ph(()=>{T&&(Ls++,$t.clear(),Jn(be,T.getMessages(),N),Ar()?.updateInlineArtifactBlocks(be,Xn.artifacts,{suppressTransition:!0}),ho())});return he.push(MT),Ot};var yA=(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},CI=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},wI=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},xI=(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.")},bA=(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"},Ph=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=""},vA=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Ph(e)},Mh=e=>{e.style.transition=""},Eh=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=""},Th=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},lu=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},SI=(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))},AI=(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)},MI=e=>{let t=Mo(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:cn(t,r)??r;return{inset:o(n?.inset,Ep),canvasBackground:o(n?.canvasBackground,Tp)}},CA=(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},EI=(e,t,n,o,r,s,a,l)=>{let d=Bn(s),p=d.reveal==="push",u=l!=null,m=l?.inset??"",h=l?.canvasBackground??"";SI(e,t,n,o,p),AI(e,t,n,o,d.side,p),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=d.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let y=e.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,x=y!=null?y.innerWidth<=C:!1;if(v&&x&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Eh(t),Mh(o),vA(o),Th(n),lu(r,o),CA(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??pn),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"),vA(o),CI(o,d.maxHeight),CA(o,u&&a,m,h),d.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Eh(t),Mh(o),Th(n),lu(r,o);let H=d.animate?"transform 180ms ease":"none",B=d.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":B;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=H,o.style.transform=A,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Mh(o),Ph(o),lu(r,o);let H=yA(d.width,e.clientWidth),B=Math.max(0,e.clientWidth),A=d.animate?"margin-left 180ms ease":"none",O=d.side==="right"?a?-H:0:a?0:-H;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${B+H}px`,t.style.transition=A,t.style.marginLeft=`${O}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Eh(t),Ph(o),Th(n),lu(r,o);let H=d.reveal==="emerge";H?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let B=a?d.width:"0px",A=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",O=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",wI(o,d.maxHeight),o.style.overflow=H||O?"hidden":"visible",o.style.transition=A,H){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let L=u?`calc(${yA(d.width,e.clientWidth)}px - (2 * ${m}))`:d.width;r.style.width=L,r.style.minWidth=L,r.style.maxWidth=L,r.style.boxSizing="border-box"}}},TI=(e,t)=>{let n=e.ownerDocument.createElement("div");return bA(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){bA(n,o)},destroy(){n.remove()}}},PI=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),p=n.createElement("aside"),u=n.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",p.appendChild(u),o.insertBefore(a,e),d.appendChild(e);let h=null,y=()=>{h?.disconnect(),h=null},v=null,C=()=>{v=t?.launcher?.detachedPanel===!0?MI(t):null};C();let x=()=>{EI(a,l,d,p,u,t,m,v)},E=null,H=()=>{E?.(),E=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(E=ya(()=>{C(),x()}))},B=()=>{y(),Bn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{x()}),h.observe(a)))},A=!1,O=()=>{x(),B(),m&&!A&&a.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,xI(a,Bn(t)))},L=a.ownerDocument.defaultView,$=()=>{O()};return L?.addEventListener("resize",$),Bn(t).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),O(),H(),{mode:"docked",host:u,shell:a,syncWidgetState(K){let ae=K.launcherEnabled?K.open:!0;m!==ae&&(m=ae,O())},updateConfig(K){t=K,(t?.launcher?.enabled??!0)===!1&&(m=!0),C(),O(),H()},destroy(){L?.removeEventListener("resize",$),E?.(),E=null,y(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},lc=(e,t)=>Ct(t)?PI(e,t):TI(e,t);var kI=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},wA=(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)},cu=[],xA=()=>[...cu],kh=e=>{let t=kI(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=lc(t,r),a,l=[],d=(x,E)=>{let B=!(E?.launcher?.enabled??!0)||Ct(E),A=o.createElement("div");if(A.setAttribute("data-persona-root","true"),B&&(A.style.height="100%",A.style.display="flex",A.style.flexDirection="column",A.style.flex="1",A.style.minHeight="0",A.style.minWidth="0"),n){let O=x.attachShadow({mode:"open"});O.appendChild(A),wA(O,o)}else x.appendChild(A),wA(x,o);return t.id&&A.setAttribute("data-persona-instance",t.id),A},p=()=>{s.syncWidgetState(a.getState())},u=()=>{l.forEach(x=>x()),l=[a.on("widget:opened",p),a.on("widget:closed",p)],p()},m=()=>{let x=d(s.host,r);a=au(x,r,{debugTools:e.debugTools}),u()},h=()=>{l.forEach(x=>x()),l=[],a.destroy()};m(),e.onChatReady?.();let y=x=>{h(),s.destroy(),s=lc(t,x),r=x,m()},v={update(x){let E=Jp(r??{},x),H=Ct(r),B=Ct(E),A=us(r),O=us(E);if(H!==B||A!==O){y(E);return}r=E,s.updateConfig(r),a.update(x),p()},destroy(){h(),s.destroy();let x=cu.indexOf(C);x!==-1&&cu.splice(x,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(v,{get(x,E,H){if(E==="host")return s.host;if(E in x)return Reflect.get(x,E,H);let B=a[E];return typeof B=="function"?B.bind(a):B}});return cu.push(C),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};var TA=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),LI=new Set(["button","a","input","select","textarea","details","summary"]),II=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Lh=/\b(product|card|item|listing|result)\b/i,Rh=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,RI=3e3,HI=100;function PA(e){let t=typeof e.className=="string"?e.className:"";if(Lh.test(t)||e.id&&Lh.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Lh.test(o.value))return!0}return!1}function kA(e){return Rh.test((e.textContent??"").trim())}function LA(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 WI(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function SA(e){let t=e.match(Rh);return t?t[0]:null}function AA(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 OI(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 BI="commerce-card",DI="result-card";function MA(e){return!PA(e)||!kA(e)||!LA(e)&&!WI(e)?0:5200}function EA(e){return!PA(e)||kA(e)||!LA(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Hh=[{id:BI,scoreElement(e){return MA(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||Rh.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(MA(e)===0)return null;let{title:n,href:o}=AA(e),r=SA((e.textContent??"").trim())??SA(t.text)??"",s=OI(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
139
|
-
`)}},{id:
|
|
140
|
-
`)}}];function
|
|
138
|
+
`)}if(!b&&!c){let Re="max-height: -moz-available !important; max-height: stretch !important;",Ue=g?"":"padding-top: 1.25em !important;",_e=g?"":`z-index: ${o.launcher?.zIndex??pn} !important;`;Qe.style.cssText+=Re+Ue+_e}Wu(),ao()},Yu=()=>{e.style.setProperty("--persona-content-max-width",ds(o,we()))},My=!1;function Ey(){o.layout?.topFade&&ne.scrollTop>1?ne.setAttribute("data-persona-top-fade","true"):ne.removeAttribute("data-persona-top-fade")}let Qu=()=>{Ey();let i=Pf(o,we());we()&&o.composer?.placement&&o.debug===!0&&!My&&(My=!0,console.warn("[persona] composer.placement is ignored in composer-bar mount mode."));let c=ys();e.setAttribute("data-persona-composer-placement",i),e.setAttribute("data-persona-conversation-state",fc),e.setAttribute("data-persona-welcome-anchor",c.anchor??"bottom"),e.style.setProperty("--persona-composer-anchor-gap",c.composerGap??Ip),yc()},Ty=()=>{if(we())return;let i=Ct(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!D)return;let f=e.ownerDocument.defaultView??window,b=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640;if(b&&f.innerWidth<=w)return;let W=mi(o);xe.style.height=W.height,xe.style.maxHeight=W.maxHeight};Gu(),ai(e,o),tc(e,o),nc(e,o),Yu(),Qu(),Cs=()=>{Gu(),Ty(),ai(e,o),tc(e,o),nc(e,o),Yu(),Qu(),Cc?e.style.setProperty("--persona-artifact-welded-outer-radius",Cc):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Xo(),Eu()};let he=[];he.push(()=>{by=!0}),he.push(()=>{h.forEach(i=>i()),m.destroy()}),he.push(()=>{document.removeEventListener("keydown",wy)}),he.push(()=>{Da!==null&&clearTimeout(Da)});let Ho=null,Wo=null;he.push(()=>{Ho?.(),Ho=null,Wo?.(),Wo=null}),$a&&he.push(()=>{$a?.disconnect(),$a=null}),he.push(()=>{Va?.(),Va=null,Ku(),Tt&&(Tt.remove(),Tt=null),Ke?.element.style.removeProperty("width"),Ke?.element.style.removeProperty("maxWidth"),Ke?.destroy()}),X&&he.push(()=>{gn=!0,It=null,kr!==null&&(cancelAnimationFrame(kr),kr=null),ht?.destroy(),ht=null,ft?.destroy(),ft=null,et=null});let xs=null,Py=()=>{xs&&(xs(),xs=null),o.colorScheme==="auto"&&(xs=ya(()=>{ai(e,o)}))};Py(),he.push(()=>{xs&&(xs(),xs=null)}),he.push(()=>{H=!0,E?.()}),he.push(()=>{L=!0});let ky=!1;he.push(()=>{ky=!0});let Xu=(i,c)=>{let g=zl(i,c);return g||!cS.includes(i)?g:(gS().then(f=>{if(ky)return;ql(f.wipe),ql(f.glyphCycle);let b=zl(i,c);b&&Yl(b,e)}).catch(()=>{}),null)},Pc=o.features?.streamAnimation;if(Pc?.type&&Pc.type!=="none"){let i=Xu(Pc.type,Pc.plugins);i&&Yl(i,e),he.push(()=>uS(e))}let tr=Jl(Lr),Ly=Jl(ku),Iy=Jl(Ha),Ss=[tr,Ly,Iy];he.push(()=>{Ss.forEach(i=>i.destroy())});let As=null,T,Ms=null,Ry=!1,Hy=0,Wy=null,Oy=i=>i.reduce((c,g)=>g.role==="user"?c+1:c,0),By=i=>{for(let c=i.length-1;c>=0;c--)if(ni(i[c]))return i[c].id??null;return null},Dy=!1,jM=()=>{Dy||o.debug!==!0||(Dy=!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".'))},_y=!1,Ny=!1,Fy=(i,c)=>{_y||o.debug!==!0||!c.enabled||c.expose||Ry||Ny&&(T.isStreaming()||i.some(ni)||(_y=!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.")))},Es=i=>{if(!T)return;let c=i??T.getMessages(),g=ie=>{ie.render([],T,ce,c)},f=ie=>{Ss.forEach(me=>{me!==ie&&g(me)})};Ms&&(Oy(c)>Hy||By(c)!==Wy)&&(Ms=null);let b=as(o);Fy(c,b);let w=b.enabled?qd(c):null,W=Ms??w,V=Ms?"host":"agent";if(W){let ie=o.suggestions?.followUps,me=ie?.placement??(ie?"auto":"composer"),st=(me==="auto"?we()?"composer":"after-message":me)==="after-message"?Iy:tr;f(st),st.render(W,T,ce,c,o.suggestionChipsConfig,{source:V,surface:"followUp",variant:ie?.variant??"chip",behavior:ie?.behavior??"send",overflow:ie?.overflow??"wrap",maxItems:ie?.maxItems??4,config:o,plugins:p,submitPrompt:fd});return}if(c.some(ie=>ie.role==="user")){Ss.forEach(g);return}let F=o.future?.v5Defaults===!0,q=_a(),Q=o.suggestions?.starters??(F?{}:void 0);if(Q){let ie=gs(ys(),c),me=Q.placement??"auto",Ve=me==="auto"?ie?"welcome":"composer":me;if(Ve==="welcome"&&!ie){jM(),Ss.forEach(g);return}let st=Ve==="welcome"?Ly:tr;f(st),st.render(Q.items??o.suggestionChips,T,ce,c,o.suggestionChipsConfig,{surface:"starter",variant:Q.variant??(F&&!q?"chip":"card"),behavior:Q.behavior??"send",overflow:Q.overflow??"wrap",maxItems:Q.maxItems??(F&&!q?3:4),config:o,plugins:p,submitPrompt:fd});return}f(tr),tr.render(o.suggestionChips,T,ce,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",maxItems:4,config:o,plugins:p,submitPrompt:fd})},$y=()=>{Ms&&(Ms=null,Es())},VM=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){$y();return}let g=T?T.getMessages():[];Ms=c,Ry=!0,Hy=Oy(g),Wy=By(g),Es(g)},Un=!1,$t=Xx(),Pi=new Map,Ts=new Map,Br=new Map,Ps=null,Dr=null;function ks(){if(!Ps)return;let i=Ps;Ps=null,Dr?.destroy(),Dr=null,$t.delete(i),de.querySelector(`#wrapper-${i}`)?.removeAttribute("data-preserve-runtime"),T&&Jn(be,T.getMessages(),N)}let Ls=0,qM=jo()!==null,jn=nS(),Vn=0,_r=null,Pn=!1,kc=!1,Nr=0,Yt=null,Is=null,Ju=!1,ki=!1,Rs=null,qa=!0,Lc=!1,Li=null,Ic=!1,Fr=()=>{Ic=!0,YM()},Zu=null,zM=4,nr=24,KM=80,GM=1e3,or=null,Uy=()=>{e.setAttribute("data-persona-scrollbar",Iu()),Iu()!=="on-scroll"&&(or!==null&&clearTimeout(or),or=null,ne.removeAttribute("data-persona-scrollbar-visible"))},YM=()=>{Iu()==="on-scroll"&&(ne.setAttribute("data-persona-scrollbar-visible",""),or!==null&&clearTimeout(or),or=setTimeout(()=>{or=null,li(ne,nr)&&ne.removeAttribute("data-persona-scrollbar-visible")},GM))};Uy(),he.push(()=>{or!==null&&clearTimeout(or)});let eg=new Map,Xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null};mo();let jy=o.voiceRecognition?.autoResume??!1,rr=i=>{oe.emit("voice:state",{active:Xe.active,source:i,timestamp:Date.now()})},yo=()=>{ye(i=>({...i,voiceState:{active:Xe.active,timestamp:Date.now(),manuallyDeactivated:Xe.manuallyDeactivated}}))},QM=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Eh(I.voiceState),c=!!i.active,g=Number(i.timestamp??0);Xe.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-g<xI&&setTimeout(()=>{Xe.active||(Xe.manuallyDeactivated=!1,vn(o.voiceRecognition?.provider)?T.toggleVoice().then(()=>{Xe.active=T.isVoiceActive(),rr("restore"),T.isVoiceActive()&&Qi()}):bd("restore"))},1e3)},XM=()=>T?SA(T.getMessages()).filter(i=>!i.__skipPersist):[],Rc=null,Vy=(i,c)=>{typeof console<"u"&&console.error(i,c)},Hc=(i,c)=>{let g=()=>{try{let W=i();return!W||typeof W.then!="function"?null:Promise.resolve(W).catch(V=>{Vy(c,V)})}catch(W){return Vy(c,W),null}},f=Rc,b=f?f.then(()=>g()??void 0):g();if(!b)return;let w=b.finally(()=>{Rc===w&&(Rc=null)});Rc=w};function Ii(i){if(!k?.save)return;let c=i?SA(i):T?XM():[],g=_&&T?.getResumableHandle();g&&(I={...I,durableResume:{executionId:g.executionId,after:g.lastEventId}});let f={messages:c,metadata:I,artifacts:Xn.artifacts,selectedArtifactId:Xn.selectedId,...Hs?{draft:Hs}:{}};Hc(()=>k.save(f),"[AgentWidget] Failed to persist state:")}let Hs,Wc=()=>!k?.save||o.persistState===!1?!1:typeof o.persistState=="object"?o.persistState.persist?.draft!==!1:!0,za=bx({write:()=>{if(!Wc())return;let i=ve.getState(),c=hx({text:i.text,mentionRefs:i.mentionRefs,contentSegments:Jg(),selectedModelId:i.selectedModelId,activeModeIds:i.activeModeIds,quote:i.quote});JSON.stringify(c)!==JSON.stringify(Hs)&&(Hs=c,Ii())}});function qy(){Wc()&&za.schedule()}function tg(){za.flush()}function zy(i){if(!Wc())return;let c=yx(i,{mentionSourceIds:(o.contextMentions?.sources??[]).map(g=>g.id),modelIds:(o.composer?.models??[]).map(g=>g.id),modes:o.composer?.modes??[]});c&&(Hs=i,ce&&!ce.value&&(ce.value=c.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),ko()),c.selectedModelId&&(ve.setSelectedModelId(c.selectedModelId),Hr?.repaint()),bc(c.activeModeIds??[]),c.quote&&Lo(c.quote),za.cancel())}function Oc(){za.cancel(),Hs&&(Hs=void 0,Wc()&&Ii())}let Ri=null,Ky=()=>Qe.querySelector("#persona-scroll-container")||ne,Hi=()=>{Ri!==null&&(cancelAnimationFrame(Ri),Ri=null),Pn=!1},Gy=()=>{_r!==null&&(cancelAnimationFrame(_r),_r=null),kc=!1,Hi()},JM=()=>Un&&og()&&($n()!=="anchor-top"||Qh()),ng=()=>{let i=Wa()||"Jump to latest",c=JM();qt.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Nr>0?(hs.textContent=String(Nr),hs.style.display="",qt.setAttribute("aria-label",`${i} (${Nr} new)`)):(hs.textContent="",hs.style.display="none",qt.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},Yy=()=>{Nr!==0&&(Nr=0,ng())},ZM=()=>{let i=Yt?.spacerHeight??0;return i<=0?li(ne,nr):Nc(i)-ne.scrollTop-ne.clientHeight<=nr},og=()=>Rr()?!jn.isFollowing():!ZM(),rg=()=>!!T&&T.getMessages().length>0,Qt=()=>{if(!PM()||CM()){qt.parentNode&&qt.remove(),qt.style.display="none";return}qt.parentNode!==de&&de.appendChild(qt),bs();let c=Go(ne)>0&&og()&&rg();c?ng():Yy(),qt.style.display=c?"":"none"},Wi=()=>{jn.pause()&&(Gy(),Qt())},kn=()=>{jn.resume(),Yy(),Qt()},$r=(i=!1)=>{Rr()&&rg()&&jn.isFollowing()&&(!i&&!Un||(_r!==null&&(cancelAnimationFrame(_r),_r=null),kc=!0,_r=requestAnimationFrame(()=>{_r=null,kc=!1,jn.isFollowing()&&eE(Ky(),i?220:140)})))},Qy=(i,c,g,f=()=>!0)=>{let b=i.scrollTop,w=c(),W=w-b;if(Hi(),Math.abs(W)<1){Pn=!0,i.scrollTop=w,Vn=i.scrollTop,Pn=!1;return}let V=performance.now();Pn=!0;let F=Q=>1-Math.pow(1-Q,3),q=Q=>{if(!f()){Hi();return}let ie=c();ie!==w&&(w=ie,W=w-b);let me=Q-V,Ve=Math.min(me/g,1),st=F(Ve),nt=b+W*st;i.scrollTop=nt,Vn=i.scrollTop,Ve<1?Ri=requestAnimationFrame(q):(i.scrollTop=w,Vn=i.scrollTop,Ri=null,Pn=!1)};Ri=requestAnimationFrame(q)},eE=(i,c=500)=>{let g=Go(i)-i.scrollTop;if(Math.abs(g)<1){Vn=i.scrollTop;return}if(Math.abs(g)>=KM){Hi(),Pn=!0,i.scrollTop=Go(i),Vn=i.scrollTop,Pn=!1;return}Qy(i,()=>Go(i),c,()=>jn.isFollowing())},Bc=()=>{if(!rg()){Qt();return}let i=Ky();Pn=!0,i.scrollTop=Go(i),Vn=i.scrollTop,Pn=!1,Qt()},Ws=i=>{let c=0,g=i;for(;g&&g!==ne;)c+=g.offsetTop,g=g.offsetParent;return c},tE=()=>{let i=ne.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ne.ownerDocument.getSelection()},Dc=()=>sS(tE(),ne),sg=()=>{if(kM()!=="last-user-turn")return!1;let i=T?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(w=>w.role==="user");if(!c)return!1;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=ne.querySelector(`[data-message-id="${g}"]`);if(!f)return!1;let b=Math.min(Math.max(0,Ws(f)-Oa()),Go(ne));return Pn=!0,ne.scrollTop=b,Vn=ne.scrollTop,Pn=!1,$n()==="follow"&&!li(ne,nr)&&jn.pause(),Qt(),!0},_c=i=>{let c=Math.max(0,Math.round(i));Qn.style.height=`${c}px`,Qn.style.display=c>0?"":"none",Yt&&(Yt.spacerHeight=Math.max(0,i))},Nc=i=>{let c=parseFloat(getComputedStyle(ne).paddingBottom)||0,g=0;for(let b of Array.from(ne.children)){if(b===Qn||b.offsetHeight===0)continue;let w=Ws(b)+b.offsetHeight;w>g&&(g=w)}let f=ne.scrollHeight-i;return g>0?Math.min(g+c,f):f},nE=()=>{if(!Yt||Yt.spacerHeight<=0)return;let i=Nc(Yt.spacerHeight),c=Math.max(0,Math.round(ne.scrollTop)+ne.clientHeight-i+nr);c<Yt.spacerHeight&&(_c(c),Qt())},bo=()=>{Is!==null&&(cancelAnimationFrame(Is),Is=null),Hi(),Yt=null,Qn.style.height="0px",Qn.style.display="none"},Xy=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),ig=i=>ne.querySelector(`[data-message-id="${Xy(i)}"]`),Jy=i=>{Is!==null&&cancelAnimationFrame(Is),Is=requestAnimationFrame(()=>{Is=null;let c=Xy(i),g=ne.querySelector(`[data-message-id="${c}"]`);if(!g)return;let f=Ws(g),b=Yt?.spacerHeight??0,w=Nc(b),{targetScrollTop:W,spacerHeight:V}=If({anchorOffsetTop:f,topOffset:Oa(),viewportHeight:ne.clientHeight,contentHeight:w,slack:nr});Yt={initialSpacerHeight:V,contentHeightAtAnchor:w,spacerHeight:V},_c(V),Qy(ne,()=>g.isConnected?Math.max(0,Ws(g)-Oa()):W,220)})},Ln=()=>{if($n()!=="anchor-top"||!Yt||!Li)return;let i=ig(Li);if(!i)return;Hi();let c=Yt.spacerHeight,g=Nc(c),{targetScrollTop:f,spacerHeight:b}=If({anchorOffsetTop:Ws(i),topOffset:Oa(),viewportHeight:ne.clientHeight,contentHeight:g,slack:nr});Yt={initialSpacerHeight:b,contentHeightAtAnchor:g,spacerHeight:b},_c(b),Pn=!0,ne.scrollTop=f,Vn=ne.scrollTop,Pn=!1,Qt()},oE=()=>{if(Rr()){if(!jn.isFollowing()||li(ne,1))return;$r(!Un);return}if(Yt&&Yt.initialSpacerHeight>0){let i=ne.scrollHeight-Yt.spacerHeight,c=iS({initialSpacerHeight:Yt.initialSpacerHeight,contentHeightAtAnchor:Yt.contentHeightAtAnchor,currentContentHeight:i});c!==Yt.spacerHeight&&_c(c)}Qt()},rE=i=>{let c=$n();c==="follow"?(kn(),$r(!0)):c==="anchor-top"&&(qa=!1,Lc=!0,Ic=!1,Li=i,Jy(i))},sE=()=>{if($n()==="anchor-top"){if(Lc){qa=!1;return}qa=!0,bo(),kn(),$r(!0)}},iE=96,aE=i=>{if(Rs===null)return!0;let c=ig(Rs),g=ig(i);if(!c||!g)return!0;let f=Ws(g)-Ws(c);return Oa()+f>ne.clientHeight-iE},lE=i=>{if($n()!=="anchor-top"||!Lc||Ic||Dc())return;let c=Rs===null;for(let g of i){if(!c){g.id===Rs&&(c=!0);continue}if(tS(g)){if(g.id===Li||!aE(g.id))return;Li=g.id,Jy(g.id);return}}},cE=i=>{let c=new Map;i.forEach(g=>{let f=eg.get(g.id);c.set(g.id,{streaming:g.streaming,role:g.role}),!f&&g.role==="assistant"&&(oe.emit("assistant:message",g),!ki&&($n()!=="anchor-top"||Qh())&&og()&&(Nr+=1,ng(),Qt(),mc(Nr===1?"1 new message below.":`${Nr} new messages below.`))),g.role==="assistant"&&f?.streaming&&g.streaming===!1&&oe.emit("assistant:complete",g),g.variant==="approval"&&g.approval&&(f?g.approval.status!=="pending"&&oe.emit("approval:resolved",{approval:g.approval,decision:g.approval.status}):oe.emit("approval:requested",{approval:g.approval,message:g}))}),eg.clear(),c.forEach((g,f)=>{eg.set(f,g)})},Ka=(i,c)=>{let g=c==="user"?"user":"assistant",f=o.layout?.messages?.[g],b=f?.width??"content",w=f?.maxWidth??(b==="full"?`var(--persona-message-${g}-max-width, 100%)`:void 0);i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${c}`,`persona-message-width-${b}`),i.classList.toggle("persona-justify-end",c==="user"),i.setAttribute("data-message-role",c),i.setAttribute("data-message-width",b),w?i.style.setProperty("--persona-message-row-max-width",w):i.style.removeProperty("--persona-message-row-max-width")},sr=(i,c)=>{let g=document.createElement("div");return g.className="persona-flex",g.id=`wrapper-${i}`,g.setAttribute("data-wrapper-id",i),Ka(g,c),g},dE=(i,c,g)=>{let f=new Set;for(let R of c){let We=R.variant==="tool"?"tool":R.variant==="reasoning"?"reasoning":null;if(!We||Zr(o,We)!=="row")continue;let Oe=We==="tool"?o.features?.toolCallDisplay:o.features?.reasoningDisplay;Oe?.expandable!==!1&&(f.add(R.id),a.observe(R,We,We==="tool"?r:s,Oe))}let b=document.createElement("div"),W=(()=>{let R=p.find(We=>We.renderLoadingIndicator);if(R?.renderLoadingIndicator)return R.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),V=(R,We)=>We==null?!1:typeof We=="string"?(R.textContent=We,!0):(R.appendChild(We),!0),F=new Set,q=new Map,Q=new Set,ie=p.some(R=>R.renderAskUserQuestion),me=[],Ve=[],st=o.enableComponentStreaming!==!1,nt=o.approval!==!1,Rn=[],At=o.messageActions,Lt=At?.showRegenerate===!0&&At.enabled!==!1&&ct.current?.isStreaming()!==!0?Ew(c):null,hn=At?.showEdit===!0&&At.enabled!==!1,Bt=At?.showQuote===!0&&At.enabled!==!1,pt=null,No=o.features?.reasoningDisplay?.completedVisibility,Fo=R=>No==="removed"?!0:No==="removed-when-short"?JC(R,o.features?.reasoningDisplay?.shortThinkThreshold):!1,so=o.features?.toolCallDisplay?.completedVisibility==="removed",io=R=>R.variant==="reasoning"&&R.reasoning?.status==="complete"?Fo(R.reasoning):so&&R.variant==="tool"&&R.toolCall?.status==="complete";if(c.forEach(R=>{if(io(R))return;if(F.add(R.id),q.set(R.id,R.role),Ps===R.id&&Dr){let De=sr(R.id,R.role);De.setAttribute("data-persona-message-edit-stub","true"),De.setAttribute("data-preserve-runtime","true"),b.appendChild(De),pt={messageId:R.id,element:Dr.element};return}let We=ie&&vr(R),Oe=nt&&R.variant==="approval"&&!!R.approval,re=!We&&R.role==="assistant"&&!R.variant&&st&&ac(R);!Oe&&Br.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),Br.delete(R.id)),!re&&Ts.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),Ts.delete(R.id));let ut=vr(R)?`:${R.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${R.agentMetadata?.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ut={canRegenerate:Lt===R.id,canEdit:hn&&Zm(R),canQuote:Bt&&!R.variant&&(R.content?.trim().length??0)>0},un=`${Ut.canRegenerate?"r":""}${Ut.canEdit?"e":""}${Ut.canQuote?"q":""}`,nn=Qx(R,Ls)+ut+`:${un}`,bt=We||Oe||re?null:Jx($t,R.id,nn);if(bt){b.appendChild(bt.cloneNode(!0)),vr(R)&&R.toolCall?.id&&R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(Q.add(R.toolCall.id),aa(R,o,$e.composerOverlay));return}let Dt=null,Xt=p.find(De=>!!(R.variant==="reasoning"&&De.renderReasoning||R.variant==="tool"&&De.renderToolCall||!R.variant&&De.renderMessage)),Le=o.layout?.messages;if(vr(R)&&R.agentMetadata?.askUserQuestionAnswered===!0){Pi.delete(R.id),i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime");return}if(ni(R)&&as(o).enabled)return;if(vr(R)&&o.features?.askUserQuestion?.enabled!==!1){let De=p.find(Jt=>typeof Jt.renderAskUserQuestion=="function");if(De&&ct.current){let Jt=Pi.get(R.id),ao=Jt!==nn,on=null;if(ao){let{payload:Ue,complete:_e}=Cr(R),Xr=R.id,Kt=()=>ct.current?.getMessages().find(Hn=>Hn.id===Xr);on=De.renderAskUserQuestion({message:R,payload:Ue,complete:_e,resolve:Hn=>{let gr=Kt();gr&&ct.current?.resolveAskUserQuestion(gr,Hn)},dismiss:()=>{let Hn=Kt();Hn?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(Hn),ct.current?.resolveAskUserQuestion(Hn,"(dismissed)"))},config:o})}let gt=Jt!=null;if(ao&&on===null&&!gt){R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(Q.add(R.toolCall.id),aa(R,o,$e.composerOverlay));return}let Re=sr(R.id,R.role);Re.setAttribute("data-ask-plugin-stub","true"),Re.setAttribute("data-preserve-runtime","true"),b.appendChild(Re),me.push({messageId:R.id,fingerprint:nn,bubble:on});return}else{R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(Q.add(R.toolCall.id),aa(R,o,$e.composerOverlay));return}}else if(Oe){let De=O();if(!De){b.appendChild(sr(R.id,R.role));return}let Jt=p.find(Re=>typeof Re.renderApproval=="function")??x,on=Br.get(R.id)!==nn,gt=null;if(on&&Jt?.renderApproval){let Re=R.id,Ue=(_e,Xr)=>{let Kt=ct.current?.getMessages().find(Hn=>Hn.id===Re);Kt?.approval&&(Kt.approval.toolType==="webmcp"?ct.current?.resolveWebMcpApproval(Kt.id,_e):ct.current?.resolveApproval(Kt.approval,_e,Xr))};gt=Jt.renderApproval({message:R,defaultRenderer:()=>De.createApprovalBubble(R,o,l),config:o,approve:_e=>Ue("approved",_e),deny:_e=>Ue("denied",_e)})}if(on&>===null)i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),Br.delete(R.id),Dt=De.createApprovalBubble(R,o,l);else{let Re=sr(R.id,R.role);Re.setAttribute("data-approval-plugin-stub","true"),Re.setAttribute("data-preserve-runtime","true"),b.appendChild(Re),Rn.push({messageId:R.id,fingerprint:nn,bubble:gt});return}}else if(Xt)if(R.variant==="reasoning"&&R.reasoning&&Xt.renderReasoning){if(!z)return;Dt=Xt.renderReasoning({message:R,defaultRenderer:()=>sh(R,o,s),config:o})}else if(R.variant==="tool"&&R.toolCall&&Xt.renderToolCall){if(!J)return;Dt=Xt.renderToolCall({message:R,defaultRenderer:()=>ch(R,o,r),config:o})}else Xt.renderMessage&&(Dt=Xt.renderMessage({message:R,defaultRenderer:()=>{let De=wa(R,g,Le,o.messageActions,vi,{loadingIndicatorRenderer:W,widgetConfig:o,actionEligibility:Ut});return R.role!=="user"&&ae(De,R,o,T),De},config:o}));if(!Dt&&re){let De=ou(R);if(De){let Jt=Ts.get(R.id),ao=Jt!==nn,on=o.wrapComponentDirectiveInBubble!==!1&&Eo.getOptions(De.component)?.bubbleChrome!==!1,gt=null;if(ao){let Re=nu(De,{config:o,message:R,transform:g});if(Re&&De.component==="PersonaArtifactInline"){let Ue=Re.hasAttribute("data-artifact-inline")?Re:Re.querySelector("[data-artifact-inline]"),_e=Ue?.getAttribute("data-artifact-inline")??"",Xr=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(_e):_e,Kt=_e?i.querySelector(`#wrapper-${R.id}`)?.querySelector(`[data-artifact-inline="${Xr}"]`)??null:null;Ue&&Kt&&Kt!==Ue&&Ar()?.hasLiveInlineArtifactBlock(Kt)&&(Ue===Re?Re=Kt:Ue.replaceWith(Kt))}if(Re)if(on){let Ue=document.createElement("div");if(Ue.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ue.id=`bubble-${R.id}`,Ue.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let _e=document.createElement("div");_e.className="persona-mb-3 persona-text-sm persona-leading-relaxed",_e.innerHTML=g({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ue.appendChild(_e)}Ue.appendChild(Re),gt=Ue}else{let Ue=document.createElement("div");if(Ue.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ue.id=`bubble-${R.id}`,Ue.setAttribute("data-message-id",R.id),Ue.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let _e=document.createElement("div");_e.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",_e.innerHTML=g({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ue.appendChild(_e)}Ue.appendChild(Re),gt=Ue}}if(gt||Jt!=null){let Re=sr(R.id,R.role);Re.setAttribute("data-component-directive-stub","true"),Re.setAttribute("data-preserve-runtime","true"),b.appendChild(Re),Ve.push({messageId:R.id,fingerprint:nn,bubble:gt});return}}}if(!Dt)if(R.variant==="reasoning"&&R.reasoning){if(!z)return;Dt=sh(R,o,s)}else if(R.variant==="tool"&&R.toolCall){if(!J)return;Dt=ch(R,o,r)}else if(R.variant==="approval"&&R.approval){if(o.approval===!1)return;let De=O();if(!De)return;Dt=De.createApprovalBubble(R,o,l)}else{let De=o.layout?.messages;De?.renderUserMessage&&R.role==="user"?Dt=De.renderUserMessage({message:R,config:o,streaming:!!R.streaming}):De?.renderAssistantMessage&&R.role==="assistant"?Dt=De.renderAssistantMessage({message:R,config:o,streaming:!!R.streaming}):Dt=wa(R,g,De,o.messageActions,vi,{loadingIndicatorRenderer:W,widgetConfig:o,actionEligibility:Ut}),R.role!=="user"&&Dt&&ae(Dt,R,o,T)}let vt=sr(R.id,R.role);vt.appendChild(Dt),Zx($t,R.id,nn,vt),b.appendChild(vt)}),$e.composerOverlay&&$e.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(We=>{let Oe=We.getAttribute("data-persona-ask-sheet-for");Oe&&!Q.has(Oe)&&ss($e.composerOverlay,Oe)}),o.features?.toolCallDisplay?.grouped){let R=[],We=[],Oe=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(re=>{if(re.variant==="tool"&&re.toolCall&&J){if(so&&re.toolCall.status==="complete")return;We.push(re);return}re.variant==="reasoning"&&(!z||re.reasoning?.status==="complete"&&Fo(re.reasoning))||((We.length>1||Oe&&We.length>0)&&R.push(We),We=[])}),(We.length>1||Oe&&We.length>0)&&R.push(We),R.forEach(re=>{let ut=re.map(Le=>Array.from(b.children).find(vt=>vt instanceof HTMLElement&&vt.getAttribute("data-wrapper-id")===Le.id)).filter(Le=>!!Le);if(ut.length<(Oe?1:2))return;let Ut=sr(`tool-group-${re[0].id}`,"assistant");if(Ut.setAttribute("data-persona-tool-group-row","true"),o.features?.toolCallDisplay?.groupedMode==="collapsible"){let Le=`tool-group-${re[0].id}`,vt=re.some(gt=>gt.toolCall?.status!=="complete"),De={...re[0],id:Le,toolCall:{id:Le,name:`${re.length} tools`,status:vt?"running":"complete",chunks:re.flatMap(gt=>gt.toolCall?.chunks??[]),success:!re.some(gt=>gt.toolCall?.success===!1)}};f.add(Le),a.observe(De,"tool",r,o.features.toolCallDisplay);let Jt=`${vt?"Using":"Used"} ${re.length} tools`,ao=o.toolCall?.renderGroupedSummary?.({messages:re,toolCalls:re.map(gt=>gt.toolCall),defaultSummary:Jt,config:o}),on=uC(De,o,r.has(Le),ao??Jt);on.bubble.classList.add("persona-tool-group"),on.body.dataset.personaToolGroupStack="true",ut[0].before(Ut),Ut.appendChild(on.bubble),ut.forEach((gt,Re)=>{gt.style.setProperty("--persona-message-row-max-width","100%"),gt.style.setProperty("--persona-activity-stagger",`${Re*40}ms`),gt.classList.add("persona-activity-group-child"),on.body.appendChild(gt)});return}let un=document.createElement("div");un.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",un.setAttribute("data-persona-tool-group","true");let nn=document.createElement("div");nn.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",nn.id=`tool-group-summary-${re[0].id}`;let bt=`Called ${re.length} ${re.length===1?"tool":"tools"}`,Dt=o.toolCall?.renderGroupedSummary?.({messages:re,toolCalls:re.map(Le=>Le.toolCall).filter(Le=>!!Le),defaultSummary:bt,config:o});V(nn,Dt)||(nn.textContent=bt);let Xt=document.createElement("div");Xt.className="persona-tool-group-stack persona-flex persona-flex-col",Xt.id=`tool-group-stack-${re[0].id}`,Xt.setAttribute("data-persona-tool-group-stack","true"),un.appendChild(nn),Oe||un.appendChild(Xt),Ut.appendChild(un),ut[0].before(Ut),ut.forEach((Le,vt)=>{if(Oe){Le.remove();return}Le.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"),vt<ut.length-1&&De.setAttribute("data-persona-tool-group-connector","true"),De.appendChild(Le),Xt.appendChild(De)})})}a.prune(f),eS($t,F);let Yr=R=>R.variant==="tool"&&!J||R.variant==="reasoning"&&!z||io(R),$o=c.some(R=>R.role==="assistant"&&R.streaming&&!Yr(R)),vo=c.length-1;for(;vo>=0&&Yr(c[vo]);)vo--;let Qr=vo>=0?c[vo]:void 0,hl=vo<c.length-1,zs=Qr?.role==="assistant"&&!Qr.streaming&&Qr.variant!=="approval"&&!hl;if(Un&&c.some(R=>R.role==="user")&&!$o&&!zs){let R={config:o,streaming:!0,location:"standalone",defaultRenderer:gi},We=p.find(re=>re.renderLoadingIndicator),Oe=null;if(We?.renderLoadingIndicator&&(Oe=We.renderLoadingIndicator(R)),Oe===null&&o.loadingIndicator?.render&&(Oe=o.loadingIndicator.render(R)),Oe===null&&(Oe=gi()),Oe){let re=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1,Ut=o.layout?.messages?.layout??"bubble";re.className=ut?ec("assistant",Ut).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),re.setAttribute("data-typing-indicator","true"),ut&&(re.style.color="var(--persona-message-assistant-text, var(--persona-text))",Ut!=="flat"&&(re.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",re.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),re.appendChild(Oe);let un=sr("typing-indicator","assistant");un.appendChild(re),b.appendChild(un)}}if(!Un&&c.length>0){let R=c[c.length-1],We={config:o,lastMessage:R,messageCount:c.length},Oe=p.find(ut=>ut.renderIdleIndicator),re=null;if(Oe?.renderIdleIndicator&&(re=Oe.renderIdleIndicator(We)),re===null&&o.loadingIndicator?.renderIdle&&(re=o.loadingIndicator.renderIdle(We)),re){let ut=document.createElement("div"),Ut=o.loadingIndicator?.showBubble!==!1;ut.className=Ut?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ut.setAttribute("data-idle-indicator","true"),ut.appendChild(re);let un=sr("idle-indicator","assistant");un.appendChild(ut),b.appendChild(un)}}if(TC(b),Op(i,b),Hm(i),pt){let{messageId:R,element:We}=pt,Oe=i.querySelector(`#wrapper-${R}`);Oe&&We.parentElement!==Oe&&(Ka(Oe,q.get(R)??"user"),Oe.replaceChildren(We))}if(me.length>0)for(let{messageId:R,fingerprint:We,bubble:Oe}of me){let re=i.querySelector(`#wrapper-${R}`);re&&(Ka(re,q.get(R)??"assistant"),Oe!==null&&(re.replaceChildren(Oe),re.setAttribute("data-bubble-fp",We),Pi.set(R,We)))}if(Pi.size>0)for(let R of Pi.keys())F.has(R)||Pi.delete(R);if(Ve.length>0)for(let{messageId:R,fingerprint:We,bubble:Oe}of Ve){let re=i.querySelector(`#wrapper-${R}`);re&&(Ka(re,q.get(R)??"assistant"),Oe!==null&&(re.replaceChildren(Oe),re.setAttribute("data-bubble-fp",We),Ts.set(R,We)))}if(Ts.size>0)for(let R of Ts.keys())F.has(R)||Ts.delete(R);if(Rn.length>0)for(let{messageId:R,fingerprint:We,bubble:Oe}of Rn){let re=i.querySelector(`#wrapper-${R}`);re&&(Ka(re,q.get(R)??"assistant"),Oe!==null&&(re.replaceChildren(Oe),re.setAttribute("data-bubble-fp",We),Br.set(R,We)))}if(Br.size>0)for(let R of Br.keys())F.has(R)||Br.delete(R)},ag=!1,Fc=()=>{ag||(ag=!0,Md().catch(()=>{ag=!1}))},Jn=(i,c,g)=>{c.length>0&&Fc(),dE(i,c,g),yy()},Ga=null,pE=()=>{if(Ga)return;let i=g=>{let f=g.composedPath();f.includes(Qe)||en&&f.includes(en)||yt(!1,"user")};Ga=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},Zy=()=>{if(!Ga)return;(e.ownerDocument??document).removeEventListener("pointerdown",Ga,!0),Ga=null};he.push(()=>Zy());let Ya=null,uE=()=>{if(Ya)return;let i=g=>{g.key==="Escape"&&(g.isComposing||yt(!1,"user"))};Ya=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},eb=()=>{if(!Ya)return;(e.ownerDocument??document).removeEventListener("keydown",Ya,!0),Ya=null};he.push(()=>eb());let Qa=!1,tb=new Set,gE=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Oi=()=>{if(!we())return;let i=$e.peekBanner,c=$e.peekTextNode;if(!i||!c)return;if(Ee){i.classList.remove("persona-pill-peek--visible");return}let g=T?.getMessages()??[],f;for(let At=g.length-1;At>=0;At--){let Lt=g[At];if(Lt.role==="assistant"&&Lt.content){f=Lt;break}}if(!f){i.classList.remove("persona-pill-peek--visible");return}let b=f.content,w=!!f.streaming,W=gE(),V=Bp(W),F=V.type!=="none"?Xu(V.type,W?.plugins):null,q=F?.isAnimating?.(f)===!0,Q=F!==null&&(w||q);Q&&F&&!tb.has(F.name)&&(Yl(F,e),tb.add(F.name));let ie=Q&&F?.containerClass?F.containerClass:null,me=c.dataset.personaPeekStreamClass??null;me&&me!==ie&&(c.classList.remove(me),delete c.dataset.personaPeekStreamClass),ie&&me!==ie&&(c.classList.add(ie),c.dataset.personaPeekStreamClass=ie),Q?(c.style.setProperty("--persona-stream-step",`${V.speed}ms`),c.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let Ve=Q?Dp(b,V.buffer,F,f,w):b;if(Q&&V.placeholder==="skeleton"&&w&&(!Ve||!Ve.trim())){let At=document.createElement("div"),Lt=Gl();Lt.classList.add("persona-pill-peek__skeleton"),At.appendChild(Lt),Op(c,At)}else{let At=Math.max(0,Ve.length-100),Lt=Ve.length>100?Ve.slice(-100):Ve,hn=br(Lt);if(!Q||!F){let Bt=Ve.length>100?`\u2026${Lt}`:Lt;c.textContent!==Bt&&(c.textContent=Bt)}else{let Bt=hn;(F.wrap==="char"||F.wrap==="word")&&(Bt=Kl(hn,F.wrap,`peek-${f.id}`,{skipTags:F.skipTags,startIndex:At}));let pt=document.createElement("div");if(pt.innerHTML=Bt,F.useCaret&&Lt.length>0){let No=_p(),Fo=pt.querySelectorAll(".persona-stream-char, .persona-stream-word"),so=Fo[Fo.length-1];so?.parentNode?so.parentNode.insertBefore(No,so.nextSibling):pt.appendChild(No)}Op(c,pt),F.onAfterRender?.({container:c,bubble:i,messageId:f.id,message:f,speed:V.speed,duration:V.duration})}}let Rn=Un||Qa;i.classList.toggle("persona-pill-peek--visible",Rn)};if(we()){let i=$e.peekBanner;if(i){let f=b=>{b.preventDefault(),b.stopPropagation(),yt(!0,"user")};i.addEventListener("pointerdown",f),he.push(()=>{i.removeEventListener("pointerdown",f)})}let c=()=>{Qa||(Qa=!0,Oi())},g=()=>{Qa&&(Qa=!1,Oi())};xe.addEventListener("pointerenter",c),xe.addEventListener("pointerleave",g),he.push(()=>{xe.removeEventListener("pointerenter",c),xe.removeEventListener("pointerleave",g)}),en&&(en.addEventListener("pointerenter",c),en.addEventListener("pointerleave",g),he.push(()=>{en.removeEventListener("pointerenter",c),en.removeEventListener("pointerleave",g)}))}let mE=i=>{let c=o.launcher?.composerBar??{},g=c.expandedSize??"anchored",f=c.bottomOffset??"16px",b=c.collapsedMaxWidth,w=c.expandedMaxWidth??"880px",W=c.expandedTopOffset??"5vh",V=c.modalMaxWidth??"880px",F=c.modalMaxHeight??"min(90vh, 800px)",q="calc(100vw - 32px)",Q="var(--persona-pill-area-height, 80px)",ie=Qe.style;if(ie.left="",ie.right="",ie.top="",ie.bottom="",ie.transform="",ie.width="",ie.maxWidth="",ie.height="",ie.maxHeight="",en){let me=en.style;me.bottom=f,me.width=b??""}if(i&&g!=="fullscreen"){if(g==="modal"){ie.top="50%",ie.left="50%",ie.transform="translate(-50%, -50%)",ie.bottom="auto",ie.right="auto",ie.width=V,ie.maxWidth=q,ie.maxHeight=F,ie.height=F;return}ie.left="50%",ie.transform="translateX(-50%)",ie.bottom=`calc(${f} + ${Q})`,ie.top=W,ie.width=w,ie.maxWidth=q}},Xa=()=>{if(Ee&&Fc(),!Be())return;if(we()){let q=(o.launcher?.composerBar??{}).expandedSize??"anchored",Q=Ee?"expanded":"collapsed";Qe.dataset.state=Q,Qe.dataset.expandedSize=q,en&&(en.dataset.state=Q,en.dataset.expandedSize=q),Qe.style.removeProperty("display"),Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),mE(Ee),de.style.display=Ee?"flex":"none",Cs(),Ee?(pE(),uE()):(Zy(),eb()),Oi();return}let i=Ct(o),c=e.ownerDocument.defaultView??window,g=o.launcher?.mobileBreakpoint??640,f=o.launcher?.mobileFullscreen??!0,b=c.innerWidth<=g,w=f&&b&&D,W=Bn(o).reveal;Ee?(Qe.style.removeProperty("display"),Qe.style.display=i?"flex":"",Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-95","persona-opacity-0"),xe.classList.add("persona-scale-100","persona-opacity-100"),Wt?(Wt.setPanelOpen(!0),Wt.element.style.display="none"):fn&&(fn.style.display="none")):(i?i&&(W==="overlay"||W==="push")&&!w?(Qe.style.removeProperty("display"),Qe.style.display="flex",Qe.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.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"),xe.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"),xe.classList.remove("persona-scale-100","persona-opacity-100"),xe.classList.add("persona-scale-95","persona-opacity-0")),Wt?(Wt.setPanelOpen(!1),Wt.element.style.display=i?"none":""):fn&&(fn.style.display=i?"none":""))},yt=(i,c="user")=>{if(!Be()||Ee===i)return;let g=Ee;Ee=i,Xa();let f=(()=>{let w=o.launcher?.sidebarMode??!1,W=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,F=o.launcher?.mobileBreakpoint??640,q=W.innerWidth<=F,Q=Ct(o)&&V&&q,ie=we()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return w||V&&q&&D||Q||ie})();if(Ee&&f){if(!Ho){let w=e.getRootNode(),W=w instanceof ShadowRoot?w.host:e.closest(".persona-host");W&&(Ho=Wf(W,o.launcher?.zIndex??pn))}Wo||(Wo=Of(e.ownerDocument))}else Ee||(Ho?.(),Ho=null,Wo?.(),Wo=null);Ee&&(gl(),sg()||($n()==="follow"?$r(!0):Bc()));let b={open:Ee,source:c,timestamp:Date.now()};Ee&&!g?oe.emit("widget:opened",b):!Ee&&g&&oe.emit("widget:closed",b),oe.emit("widget:state",{open:Ee,launcherEnabled:D,voiceActive:Xe.active,streaming:T.isStreaming()})},Ur={inputDisabled:!1,sendDisabled:!1},Oo=()=>Ur.inputDisabled,lg=()=>vn(o.voiceRecognition?.provider)&&!!T&&(T.isBargeInActive()||["listening","processing","speaking"].includes(T.getVoiceStatus())),Os=()=>Ur.inputDisabled||Ur.sendDisabled,fE=()=>(Ur.inputDisabled?Ur.inputReason:void 0)??(Ur.sendDisabled?Ur.sendReason:void 0);function cg(){if(!Te)return;if(ve.getState().phase==="streaming"){Te.disabled=!1;return}let i=rt?!rt.isReady():!1;Te.disabled=Os()||i}function $c(){if(!Po)return;let i=ve.getState(),c=o.sendButton?.visibility==="when-text"&&i.phase!=="streaming"&&i.text.trim().length===0&&i.attachments.length===0;Po.toggleAttribute("data-persona-send-hidden",c)}function hE(){let i=fE();if(we()){let c=Mn??He;i?c.setAttribute("title",i):c.removeAttribute("title"),He.toggleAttribute(La,!!i);return}if(i){Je.setAttribute("role","status"),Je.setAttribute("aria-live","polite"),Je.setAttribute(La,""),Je.textContent=i,ei(Je,o.statusIndicator??{},"idle");return}if(Je.hasAttribute(La)&&(Je.removeAttribute("role"),Je.removeAttribute("aria-live"),Je.removeAttribute(La),y)){let c=T.getStatus();Ra(Je,Pu(c),o.statusIndicator??{},c)}}function dg(){let i=pf(o.composer?.inputDisabled),c=pf(o.composer?.sendDisabled);Ur={inputDisabled:i.disabled,inputReason:i.reason,sendDisabled:c.disabled,sendReason:c.reason},ve.setInputDisabled(i.disabled),ve.setSendDisabled(c.disabled);let g=ve.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")),kt&&(kt.disabled=f),St&&(St.disabled=f);for(let w of Ft?.affordanceButtons??[])w.querySelectorAll("button").forEach(W=>{W.disabled=f});se&&(se.disabled=f||g&&!lg()),Ss.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})}),fg.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=Os()?"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)}),cg(),hE()}let Ja=i=>{ve.setStreaming(i),Gh(i?"stop":"send"),dg()},Bs=()=>{Xe.active||ce&&ce.focus()};oe.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Bs(),200)});let Ds=null,Za=!1,pg=!tn.hidden,jr=null,ug=!te,Uc=null;he.push(()=>{Uc?.cancel(),Uc=null});let yE=i=>{let c=HS(i);if(c===fc)return;fc=c,e.setAttribute("data-persona-conversation-state",c);let g=Hu();yc(),ug&&(Uc?.cancel(),Uc=IS(He,c==="active"?g:Hu(),c==="active"?"drop":"rise",ys().layout==="centered"?320:260)),Ln()},nb=null,ob,rb=null,Bi=null,gg=!1,Di=i=>{let c=ys(),g=`${c.variant}|${c.layout}|${c.dismiss}|${c.anchor??"bottom"}|${c.align??""}|${c.iconPlacement}|${c.kicker??""}|${c.title}|${c.subtitle}`;(g!==nb||c.icon!==ob)&&(nb=g,ob=c.icon,zp({host:tn,iconHolder:wM,kicker:xM,title:SM,subtitle:AM,starterSuggestions:ku},c));let f=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;f!==rb&&(rb=f,Kp(Nn,c.message,o));let b=i??(T?T.getMessages():o.initialMessages);yE(b);let w=Za,W=!w&&gs(c,b),V=W!==pg;if(pg=W,Bi){jr?.cancel(),jr=null,w!==gg&&(gg=w,w?Xf(ne,tn,null):Qf(ne,tn,Bi)),xa(ne,tn,!w);return}if(V&&!W&&!w&&c.dismiss==="on-first-message"&&ug){jr=LS(tn,q=>{jr===q&&(jr=null),!pg&&!Bi&&(xa(ne,tn,!1),Ln()),q?.cancel()});return}if(jr){if(!W&&!w)return;jr.cancel(),jr=null}let F=!tn.hidden;xa(ne,tn,W),!W&&F&&Ln()},mg=[],fg=[],hg=!1,sb=null,ib,ab=()=>{fg.length=0;let i=mg.splice(0,mg.length);for(let c of i)try{c()}catch(g){console.warn("[persona] renderWelcome cleanup threw",g)}};he.push(ab);let bE=(i,c)=>{let g=Df(i,c);if(!g)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),S("span");let f=o.suggestions?.starters,b=_f({item:{...g,behavior:g.behavior??f?.behavior??"send"},index:c,surface:"starter",source:"config",variant:f?.variant??"card",streaming:y?T.isStreaming():!1,config:o,plugins:p,chipsConfig:o.suggestionChipsConfig,session:T,getTextarea:()=>ce,eventTarget:tn,submitPrompt:fd});return fg.push(b),b},yg=()=>{if(hg)return;hg=!0;let i=ys();sb=`${i.variant}|${i.layout}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,ib=i.icon;try{ab(),Xf(ne,tn,Bi),Bi=null,gg=!1;let c=T?T.getMessages():o.initialMessages,g=gs(i,c),f=0,b=null;for(let w of p)if(w.renderWelcome&&(b=w.renderWelcome({config:i,variant:i.variant,visible:g,defaultRenderer:()=>tn,sendMessage:W=>{if(!T||T.isStreaming())return;let V=W.trim();V&&T.sendMessage(V)},requestRender:()=>yg(),renderStarter:W=>bE(W,f++),storage:v(w.id),onCleanup:W=>{mg.push(W)}}),b))break;b&&b!==tn&&(Bi=b,Qf(ne,tn,b))}finally{hg=!1}Di()},vE=()=>{let i=ys();`${i.variant}|${i.layout}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===sb&&i.icon===ib||yg()},jc=()=>{Di(),Ai||(ce.placeholder=px(ve.getState().activeModeIds,o.composer?.modes)??o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!T?.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))"},CE=!!o.setStoredConversationId,_i=i=>ye(c=>{let g={...c};return delete g[i],g}),Vc=i=>{let c=I[i];return typeof c=="string"?c:null},lb=()=>{let i=I.durableResume;if(!i||typeof i!="object")return null;let c=i;return typeof c.executionId=="string"&&c.executionId.length>0&&typeof c.after=="string"&&c.after.length>0?{executionId:c.executionId,after:c.after}:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Vc("sessionId"),setStoredSessionId:i=>{ye(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>_i("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Vc("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{ye(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>_i("conversationId"))});let cb=()=>o.clientToken??null,db=i=>gA(i,Me(),o.persistState===!1),pb=cb(),Zn=pb?db(pb):null,ir={...Zn?{visitorStore:Zn}:{},historyBootstrapReady:pe,getStoredMessageCursor:()=>Vc("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){_i("historyMessageCursor");return}ye(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=I.pendingDisplayProjections;if(!i||typeof i!="object")return null;let c=i;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(g=>typeof g=="string")}},setPendingDisplayProjections:i=>{if(!i){_i("pendingDisplayProjections");return}ye(c=>({...c,pendingDisplayProjections:i}))},getStoredResumableHandle:lb,setStoredResumableHandle:i=>{if(!i){_i("durableResume");return}ye(c=>({...c,durableResume:i}))},shouldResumeDurableConversation:()=>_&&lb()!==null,...CE?{}:{getStoredConversationRevision:()=>Vc("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){_i("conversationRevision");return}ye(c=>({...c,conversationRevision:i}))}}};if(_){let i=o.onExecutionState,c=e.ownerDocument.defaultView,g=!1,f=()=>g=!0,b=()=>g=!1;c?.addEventListener("pagehide",f),c?.addEventListener("pageshow",b),he.push(()=>{c?.removeEventListener("pagehide",f),c?.removeEventListener("pageshow",b)}),o={...o,reconnectStream:o.reconnectStream??(w=>T.getClient().reconnectClientTokenStream(w)),onExecutionState:w=>{(w||!g)&&ir.setStoredResumableHandle?.(w?{executionId:w.executionId,after:w.lastEventId}:null),i?.(w)}}}let wE=()=>{let i=cb();if(i&&Zn?.matches(i,Me(),o.persistState===!1)||!i&&!Zn)return;Zn?.destroy(),Zn=i?db(i):null;let c={...ir};Zn?c.visitorStore=Zn:delete c.visitorStore,ir=c,T.setHistoryInternals(ir)},_s=null,xE=()=>{_s==null&&(_s=setInterval(()=>{let i=be.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(_s),_s=null;return}let c=Date.now();i.forEach(g=>{let f=Number(g.getAttribute("data-tool-elapsed"));f&&(g.textContent=g.closest(".persona-activity-row")?wl(c-f):Kd(c-f))})},100))},bg=(i,c)=>{if(Object.is(i,c))return!0;if(i===null||c===null||typeof i!="object"||typeof c!="object")return!1;if(Array.isArray(i)||Array.isArray(c))return!Array.isArray(i)||!Array.isArray(c)||i.length!==c.length?!1:i.every((W,V)=>bg(W,c[V]));let g=i,f=c,b=Object.keys(g),w=Object.keys(f);return b.length===w.length&&b.every(W=>Object.prototype.hasOwnProperty.call(f,W)&&bg(g[W],f[W]))},ub=i=>{let{content:c,rawContent:g,llmContent:f,...b}=i;return b},vg=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!ac(i),SE=(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))&&vg(f)&&vg(b)&&bg(ub(f),ub(b))},Cg=null,Ni=null,Ns=null,ar=null,wg=null,AE=i=>{if(!_)return Ii(i);wg=i,queueMicrotask(()=>{wg===i&&(wg=null,Ii(i))})},qc=i=>{Cg=i;let c,g;Ni=null;for(let b=i.length-1;b>=0;b-=1){let w=i[b];if(!c&&w.role==="user"&&(c=w),!g&&w.role==="assistant"&&(g=w),!Ni&&vg(w)&&(Ni={index:b,id:w.id}),c&&g&&Ni)break}Jn(be,i,N),Ar()?.updateInlineArtifactBlocks(be,Xn.artifacts,{suppressTransition:Un}),xE(),Di(i),Es(i),$r(!Un),cE(i),i.length===0&&(bo(),qa=!0,Lc=!1,Li=null,Ic=!1),!Ju||ki?(Ju=!0,Rs=c?.id??null,Zu=g?.id??null):c&&c.id!==Rs?(Rs=c.id,rE(c.id)):g&&g.id!==Zu&&sE(),g&&(Zu=g.id),lE(i);let f=Xe.lastUserMessageId;c&&c.id!==f&&(Xe.lastUserMessageId=c.id,oe.emit("user:message",c)),Xe.lastUserMessageWasVoice=!!c?.viaVoice,AE(i),Oi()},xg=()=>{ar!==null&&(cancelAnimationFrame(ar),ar=null);let i=Ns;Ns=null,i&&qc(i)},gb=()=>{ar!==null&&cancelAnimationFrame(ar),ar=null,Ns=null},ME=i=>{let c=Ns??Cg;if(Un&&c&&Ni&&SE(c,i,Ni)){Ns=i,ar===null&&(ar=requestAnimationFrame(()=>{ar=null;let g=Ns;Ns=null,g&&qc(g)}));return}if(i.length===0){gb(),qc(i);return}xg(),qc(i)};T=new ma(o,{onMessagesChanged(i){ME(i)},onStatusChanged(i){let c=o.statusIndicator??{};Ra(Je,(f=>f==="idle"?c.idleText??_t.idle:f==="connecting"?c.connectingText??_t.connecting:f==="connected"?c.connectedText??_t.connected:f==="error"?c.errorText??_t.error:f==="paused"?c.pausedText??_t.paused:f==="resuming"?c.resumingText??_t.resuming:_t[f])(i),c,i),Tu()},onStreamingChanged(i){i||(T?.getMessages().length===0?gb():xg()),Un=i,Ja(i),Tu(),T&&Jn(be,T.getMessages(),N),i||($r(!0),nE(),Ny=!0,T&&Fy(T.getMessages(),as(o))),Qt(),mc(i?"Responding\u2026":"Response complete."),Oi()},onVoiceStatusChanged(i){if(oe.emit("voice:status",{status:i,timestamp:Date.now()}),!(i!=="disconnected"&&!vn(o.voiceRecognition?.provider)))switch(i){case"listening":ur(),Qi();break;case"processing":ur(),TT();break;case"speaking":ur(),PT();break;default:i==="idle"&&T.isBargeInActive()?(ur(),Qi(),se?.setAttribute("aria-label","End voice session")):(Xe.active=!1,ur(),rr("system"),yo());break}},onArtifactsState(i){Xn=i,i.artifacts.length===0&&(Mi=!1),Ar()?.updateInlineArtifactBlocks(be,i.artifacts,{suppressTransition:Un}),ho(),Ii()},onHistoryStateChanged(i){zh(i)},onHistoryNotice(i){Kh(i)},onReconnect(i){let{executionId:c,lastEventId:g}=i.handle;i.phase==="paused"?oe.emit("stream:paused",{executionId:c,after:g}):i.phase==="resuming"?oe.emit("stream:resuming",{executionId:c,after:g,attempt:i.attempt??1}):oe.emit("stream:resumed",{executionId:c,after:g})}},ir),ct.current=T,he.push(()=>T.cancel()),he.push(()=>{T.destroy(),Zn?.destroy(),Zn=null});let Sg=null;if(T.onReadAloudChange((i,c)=>{fy=i,hy=c,yy();let g=i??Sg;i&&(Sg=i);let f=g?T.getMessages().find(b=>b.id===g)??null:null;oe.emit("message:read-aloud",{messageId:g,message:f,state:c,timestamp:Date.now()}),c==="idle"&&(Sg=null)}),y=!0,Ju=!0,o.voiceRecognition?.enabled===!0&&vn(o.voiceRecognition.provider))try{T.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let EE=720,TE=250,Ze=Mh(o.features?.history?.copy),qn=null,Ag=!1,lt=null,zc=null,Kc="conversation",Mg=null,mn=null,Bo=null,Gc=T.getHistoryState(),Eg=null,el=0,Tg=null,Yc=null,Qc=null,Pg=`persona-history-${Math.random().toString(36).slice(2,8)}`,kg=()=>o.features?.history?.enabled===!0,Do=()=>kg()&&!!qn&&!Ag,mb=()=>{let i=T.getStatus();return Un||i==="paused"||i==="resuming"},Lg=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",g=qn?.capabilities.scopes;return!g||g.includes(c)?c:g[0]??c},Fi=()=>zc?.scope??Lg(),fb=()=>T.getClientSession()?.targetId??null,hb=i=>`${i.state}:${"reason"in i?i.reason:""}`,PE=i=>{let c=hb(i);c!==Eg&&(Eg=c,oe.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},Xc=i=>{i&&(Jo.textContent="",Jo.textContent=i)},yb=null,bb=null,kE=()=>{if(!kg())return null;let i=yA();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(yb!==c&&(yb=c,bb=c()),bb):T.isClientTokenMode()?bA({client:T.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:g=>T.bindActivatedSession(g),getClient:()=>T.getClient()}):null},vb=()=>{Yc?.(),Yc=null,Qc?.(),Qc=null,Ag=!1,qn=kE();let i={...ir};qn?i.historyProvider=qn:delete i.historyProvider,ir=i,T.setHistoryInternals(ir),qn&&(Yc=qn.subscribeAvailability?.(c=>{Ag=!c,c||In({restoreFocus:!1}),qr()})??null,Qc=qn.subscribeIdentityStatus(c=>PE(c)),Eg=hb(qn.getIdentityStatus()))},Ig=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!D||Ct(o)))return"panel";let c=Ro??de;return(c.getBoundingClientRect().width||c.clientWidth)>=EE?"rail":"panel"},eo=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},Jc="data-persona-history-suppressed",zn=null,Vr=null,Fs=null,tl=null,Rg=null,Cb="",wb=()=>Pe===Rg?Cb:o.layout?.showHeader===!1?"none":"",LE=()=>Vt==="panel"&&!!Fs&&tl===Fs.element&&o.layout?.showHeader!==!1&&wb()!=="none",IE=()=>{for(let i of Array.from(Pe.children))i!==zn&&i.setAttribute(Jc,"")},RE=()=>{for(let i of Array.from(de.querySelectorAll(`[${Jc}]`)))i.removeAttribute(Jc)},HE=()=>{let i=Fs;if(!i)return;if(Array.from(Pe.children).some(f=>f!==zn&&!f.hasAttribute(Jc))){Vr&&Vr!==Pe&&(Vr.style.removeProperty("min-height"),Vr=null);let f=Pe.offsetHeight;f>0&&(Pe.style.minHeight=`${f}px`,Vr=Pe)}zn||(zn=S("div","persona-history-header-host")),i.setHeaderPlacement("external");let g=i.getHeaderElement();g.parentNode!==zn&&zn.replaceChildren(g),zn.parentNode!==Pe&&Pe.appendChild(zn),IE()},xb=()=>{Vr&&(Vr.style.removeProperty("min-height"),Vr=null),zn&&(Fs?.setHeaderPlacement("inline"),zn.remove(),zn=null,RE())},Zc=null,Hg=()=>{if(Zc){if(ne.style.display="none",eo(ne,!0),He.hidden=!0,eo(He,!0),LE()){HE(),Pe.style.display=wb(),eo(Pe,!1);return}xb(),Pe.style.display="none",eo(Pe,!0)}};Eu=Hg;let WE=i=>{let c=ne.style.display,g=He.hidden,f=He,b=Pe,w=Pe.style.display;Rg=b,Cb=w,Zc=()=>{Zc=null,xb(),Rg=null,ne.style.display=c,eo(ne,!1),f.hidden=g,eo(f,!1),He!==f&&(He.hidden=!1,eo(He,!1)),b.style.display=w,eo(b,!1),Pe!==b&&(Pe.style.display=o.layout?.showHeader===!1?"none":"",eo(Pe,!1))},He.parentNode?.insertBefore(i,He),Hg()},$i=null,$s=null,nl=null,Ui=null,Sb=()=>[Pe,$e.closeButtonWrapper,$e.clearChatButtonWrapper,ne,He],OE=52,ed=()=>o.features?.history?.rail?.collapsible!==!1,ji=()=>o.features?.history?.rail?.side==="right"?"right":"left",Wg=200,Og=400,Bg=i=>Math.min(Og,Math.max(Wg,Math.round(i))),BE=()=>o.features?.history?.rail?.resizable===!0,ol,DE=()=>{if(ol===void 0&&(ol=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${Me()}rail-width`));i&&(ol=i)}catch{}return ol},rl=()=>Bg(DE()??o.features?.history?.rail?.width??260),_E=i=>{if(ol=i,o.persistState!==!1)try{window.localStorage.setItem(`${Me()}rail-width`,String(i))}catch{}},td=()=>ed()&&o.features?.history?.rail?.collapsedBehavior==="overlay",zt=!1,Ab=i=>{let c=S("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},NE=()=>{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=Ab(i.iconUrl):g=i.icon?le(i.icon,20):null),g?g.cloneNode(!0):null}},FE=()=>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=Ab(f.iconUrl):b=f.icon?le(f.icon,20):null}catch(w){g(w),b=null}return b},onSelect:()=>{try{f.onSelect()}catch(w){g(w)}}}})}})??[],$E=i=>{let c=FE();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},sl=null,Mb=()=>`${Me()}rail-collapsed`,Dg=()=>{if(sl===null&&(sl=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(Mb());i&&(sl=i==="1")}catch{}return sl},_g=i=>{if(sl=i,o.persistState!==!1)try{window.localStorage.setItem(Mb(),i?"1":"0")}catch{}},il=()=>Vt==="rail"&&ed()&&!td()&&Dg(),Ng=()=>{},Eb=()=>{if(td()){Ng();return}_g(!Dg()),lt?.view.setCollapsed(il()),Xo(),Ln()},Fg=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!Hp(i)?null:{combo:i,hint:Wp(i),aria:Ul(i)}},Tb=()=>{h.forEach(c=>c()),h=[];let i=Fg();i&&h.push(m.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Rt&&Vt==="rail"&&ed()||qi(),run:()=>td()?Ng():Eb()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&h.push(m.register({id:`header-action-${c.id}`,combo:c.shortcut,run:()=>{let g=e.querySelector(`[data-persona-header-action="${c.id}"]`);g?g.click():o.layout?.header?.onAction?.(c.id)}}));for(let c of p)for(let g of c.shortcuts??[])h.push(m.register({...g,id:`${c.id}:${g.id}`}))};Tb();let UE=300,nd="var(--persona-history-overlay-margin,8px)",to=null,lr=null,od=0,cr=null,Vi=null,Us=!1,$g=0,Pb=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,qi=()=>Do()&&td()&&(Vt??Ig())==="rail",jE=()=>Rt&&!zt,al=()=>{Vi!==null&&clearTimeout(Vi),Vi=null},VE=()=>{xh().catch(()=>{})},kb=()=>{al(),zt&&(Vi=setTimeout(()=>{Vi=null,!(Us||!zt)&&(cr?.contains(document.activeElement)||In({restoreFocus:!1}))},UE))},qE=(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},Ug=i=>{zt&&(Us=qE(i.clientX,i.clientY),Us?al():Vi===null&&kb())},Lb=i=>{Rt||!qi()||(zt=!0,cl({invoker:to,keyboard:i?.keyboard===!0}).then(()=>{Rt?!Us&&document.activeElement!==to&&In():zt=!1}))},Ib=()=>{let i=tl?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",zt?Ze.expandLabel:Ze.collapseLabel),i.setAttribute("aria-expanded",zt?"false":"true"))},Rb=()=>{_g(!1);let i=lt;if(!zt||!i){cl({invoker:to});return}let c=document.activeElement===to;zt=!1,rd(),i.element.remove(),Vg(i.element),Ib(),c&&id(),Ln(),qr()},zE=()=>{_g(!0),In()};Ng=()=>{!Rt||zt?Rb():zE()};let KE=()=>{let i=Fg(),c=ci({ariaLabel:Ze.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":Pg,...i?{"aria-keyshortcuts":i.aria}:{}}}),g=c.button;g.addEventListener("mouseenter",()=>{Us=!0,al(),!(Pb()||Date.now()<$g)&&Lb()}),g.addEventListener("mouseleave",()=>{Us=!1,$g=0,kb()}),g.addEventListener("focus",()=>{Rt||VE()}),g.addEventListener("click",f=>{Do()&&(f.detail!==0&&Pb()&&!Rt?Lb():Rb())}),to=g,lr=c.wrapper},ll=()=>{if(lr&&!lr.isConnected&&(lr=null,to=null),!qi()){lr?.remove(),lr=null,to=null;return}to||KE();let i=lr,c=to;if(!i||!c)return;let g=ji()!=="right"?Pe.firstChild:null;(g??Pe.lastChild)!==i&&Pe.insertBefore(i,g),i.style.display=jE()||od>0?"none":"",c.setAttribute("aria-label",Ze.expandLabel),c.setAttribute("aria-expanded",Rt?"true":"false"),cr&&Xo()},Hb=i=>{if(!zt)return;let c=i.target;c instanceof Node&&(cr?.contains(c)||lr?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||In({restoreFocus:!1}))};document.addEventListener("pointerdown",Hb,!0),he.push(()=>{document.removeEventListener("pointerdown",Hb,!0),document.removeEventListener("pointermove",Ug),zi?.(),al()});let jg=null,zi=null,Wb=16,Ob=i=>{_E(Bg(i)),Xo(),Ln()},GE=()=>{let i=S("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(Wg)),i.setAttribute("aria-valuemax",String(Og)),i.addEventListener("pointerdown",c=>{let g=$s;if(!g||c.button!==0)return;c.preventDefault(),zi?.();let f=c.clientX,b=g.getBoundingClientRect().width||rl(),w=ji()==="right"?-1:1,W=b,V=e.ownerDocument;g.style.transition="none";let F=Q=>{W=Bg(b+w*(Q.clientX-f)),g.style.flex=`0 0 ${W}px`,i.setAttribute("aria-valuenow",String(W))},q=()=>{zi=null,V.removeEventListener("pointermove",F),V.removeEventListener("pointerup",q),V.removeEventListener("pointercancel",q),g.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}Ob(W)};zi=q,V.addEventListener("pointermove",F),V.addEventListener("pointerup",q),V.addEventListener("pointercancel",q);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let g=ji()==="right"?-Wb:Wb,f=rl(),b=c.key==="ArrowRight"?f+g:c.key==="ArrowLeft"?f-g:c.key==="Home"?Wg:c.key==="End"?Og:null;b!==null&&(c.preventDefault(),Ob(b))}),i},YE=(i,c)=>{if(!BE()||il()){zi?.(),jg?.remove();return}let g=jg??GE();jg=g,g.setAttribute("aria-label",Ze.resizeLabel),g.setAttribute("aria-valuenow",String(rl())),g.nextElementSibling!==c&&i.insertBefore(g,c)};Xo=()=>{lt?.view.setRailSide(ji());let i=ji()==="right",c=cr;if(c){let V=to?to.getBoundingClientRect().bottom-de.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(V))}px + ${nd})`,c.style.width=`${rl()}px`,c.style.left=i?"":nd,c.style.right=i?nd:""}let g=$s,f=$i,b=nl;if(!g||!f||!b)return;g.style.flex=`0 0 ${il()?OE:rl()}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),YE(f,i?g:b)};let Bb=i=>{if(Ui&&$s){Ui.replaceWith(i),Ui=null,Xo();return}let c=S("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let g=S("div","persona-history-rail-conversation");g.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let f=S("div","persona-history-rail-host");f.style.cssText="display:flex;min-height:0;overflow:hidden",de.insertBefore(c,Pe.parentNode===de?Pe:ne);for(let b of Sb())b?.parentNode===de&&g.appendChild(b);c.append(f,g),f.appendChild(i),$i=c,$s=f,nl=g,Xo()},QE=()=>{if($i)return;let i=S("div","persona-history-rail-placeholder");i.style.cssText="flex:1 1 auto;min-height:0",Ui=i,Bb(i),Ln()},Db=()=>{Ui&&(rd(),Ln())},XE=i=>{let c=S("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${nd};display:flex;overflow:hidden;z-index:${fa-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,de.style.position="relative",de.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",Ug),cr=c,Xo(),Ib()},rd=()=>{Zc?.(),cr&&(Us&&($g=Date.now()+150),document.removeEventListener("pointermove",Ug),cr.remove(),cr=null);let i=$i;if(i){zi?.();for(let c of Sb())c&&i.contains(c)&&de.insertBefore(c,i);i.remove(),$i=null,$s=null,nl=null,Ui=null}},_b=i=>{tl=i,i.id=Pg,i.style.flex="1 1 auto",i.style.minHeight="0"},Vg=i=>{_b(i),(Vt!=="rail"||zt)&&Db(),Vt!=="rail"?WE(i):zt?XE(i):Bb(i)},sd=()=>{if(ll(),Yb(),!Rt||!lt)return;let i=Ig();if(i===Vt)return;let c=document.activeElement,g=c instanceof HTMLElement&&(lt.element.contains(c)||zn?.contains(c)===!0)?c:null;rd(),lt.element.remove(),lt.view.setHeaderPlacement("inline"),Vt=i,lt.view.setPresentation(i),lt.view.setCollapsed(il()),lt.requestRender(),lt.element.isConnected||Vg(lt.element),g?.isConnected?g.focus():id(),Qt(),Ln(),qr()},Nb=(i,c)=>zn?.querySelector(c)??i.querySelector(c),id=()=>{let i=lt?.element??tl;if(!i)return;let c=Nb(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let g=Nb(i,".persona-history-title")??i;g.tabIndex=-1,g.focus()},cl=async i=>{if(!Do()||Rt)return;let c=qn;if(!c)return;if(!zt&&qi()&&Dg()){ll();return}ad();let g=++el;Kc=i?.returnSurface??"conversation",Mg=i?.invoker??mn;let f=qi()&&!zt;f&&(od+=1,ll(),QE());let b;try{b=await xh()}catch{Xc(Ze.openHistoryLabel),f&&(od-=1,g===el&&(Db(),ll()));return}if(f&&(od-=1),g!==el||Rt)return;zc={scope:Lg()},Vt=Ig(),Rt=!0;let w=Vt==="panel"&&o.layout?.showHeader!==!1&&Pe.style.display!=="none"?"external":"inline",W=o.features?.history?.rowAvatar,V=Fg(),F=V?{hint:V.hint,aria:V.aria}:null,q={provider:c,context:zc,targetId:fb(),presentation:Vt,collapsible:ed(),collapsed:il(),railSide:ji(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:NE(),onToggleCollapse:Eb,...F?{collapseShortcut:F}:{},headerPlacement:w,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:W===!1?!1:typeof W=="string"?W:o.launcher?.iconUrl,activeConversationId:T.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:Q=>zg(Q,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:Q=>js(Q),attachTooltip:an,onStartNew:()=>Kg({focusComposer:!0}),onClose:()=>In(),onRequestDeleteConversation:Q=>Gb(Q),onRequestClearHistory:()=>oT(),...c.resetDevice?{onRequestResetIdentity:()=>rT()}:{}};lt=hA({plugins:p,config:o,getPresentation:()=>Vt??"panel",getReturnSurface:()=>Kc,close:()=>In(),createView:({slots:Q,renderDom:ie,onModelChange:me,railSections:Ve})=>(Fs=b.createHistoryView({...q,railSections:$E(Ve),slots:Q,renderDom:ie,onModelChange:me,onAnnounce:Xc}),Fs),onElementChanged:(Q,ie)=>{if(!ie?.isConnected)return Vg(Q);_b(Q),ie.replaceWith(Q),Hg()}}),lt.view.setNewConversationRequired(Gc.recovery==="new_conversation_required"),i?.focus!==!1&&(Vt!=="rail"||i?.keyboard===!0)&&id(),Qt(),Ln(),qr(),oe.emit("history:opened",{presentation:Vt,returnSurface:Kc,timestamp:Date.now()})},ad=()=>{},In=i=>{if(!Rt)return;el+=1;let c=Kc,g=Mg,f=lt,b=i?.restoreFocus!==!1;Rt=!1;let w=!1,W=null,V=()=>{if(!w){if(w=!0,ad=()=>{},W!==null&&clearTimeout(W),zt=!1,al(),rd(),f?.dispose(),f?.view.destroy(),f?.element.remove(),lt===f&&(lt=null,Fs=null,tl=null,Vt=null,zc=null,Mg=null),Qt(),Ln(),qr(),b){let q=g??mn;q?.isConnected?q.focus():Bs()}oe.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},F=f&&f.element===f.view.element?f.view.playExit():null;if(!F){V();return}ad=V,W=setTimeout(V,TE),F.then(V)},Fb=i=>{if(!(i.key!=="Escape"||!Rt||!lt)){if(Vt==="rail"){let c=i.target;if(!(c instanceof Node)||!(lt.element.contains(c)||zt&&lr?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),In()}};de.addEventListener("keydown",Fb),he.push(()=>de.removeEventListener("keydown",Fb));let ld=null,$b=!1,dl=()=>{if(!Ir)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&ld?.trim()||null;Ir.textContent=c??o.launcher?.title??"Chat Assistant";let g=Ir.closest(".persona-combo-btn");if(!g)return;let f=!i||T.getActiveConversationId()!==null;g.setAttribute("data-persona-menu-locked",f?"false":"true"),g.setAttribute("aria-haspopup",f?"true":"false"),f||g.setAttribute("aria-expanded","false"),g.style.cursor=f?"pointer":"default";let b=g.querySelector("svg");b&&(b.style.display=f?"":"none")},JE=i=>{i!==ld&&(ld=i,dl())},js=i=>{$b=i?.starred===!0,JE(i&&i.title.trim()||null),dl()};dl(),de.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,g=T.getActiveConversationId();g&&(c==="delete"?Gb(g):c==="star"&&T.canUpdateConversations()&&Gg(g,{starred:!$b}).catch(()=>{}))});let cd=0,ZE=250,dd=null,pd=()=>{dd&&clearTimeout(dd),dd=null};he.push(pd);let Ub=()=>{pd();let i=Ds;i&&(Za=!0,i.hidden=!1,be.style.display="none",Di())},ud=()=>{cd+=1,pd(),Ds&&(Ds.remove(),Ds=null,Za=!1,be.style.removeProperty("display"),eo(He,!1),Di())},eT=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;be.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},qg=(i,c)=>Y("div",{className:bn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),jb=()=>Y("div",{className:"persona-conversation-loading-body"},qg("58%",!1),qg("72%",!0),qg("44%",!1)),Vb=i=>{Ds?.remove(),Ds=i,i.hidden=!Za,ne.insertBefore(i,be),pd(),Za||(dd=setTimeout(Ub,ZE)),eo(He,!0)},tT=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:jb},c=null,g=p.find(f=>f.renderLoadingIndicator);g?.renderLoadingIndicator&&(c=g.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),Vb(Y("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ze.openConversationLoadingLabel}},c??jb()))},nT=i=>{let c=()=>{zg(i,{focusComposer:!0}).catch(()=>{})},g=Do()?()=>{ud(),cl()}:void 0,f=(V,F)=>{let q=Y("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:V});return q.addEventListener("click",F),q},b=()=>Y("div",{className:"persona-conversation-loading-error-body"},Y("p",{className:"persona-conversation-loading-error-title",text:Ze.openConversationErrorTitle}),Y("div",{className:"persona-conversation-loading-error-actions"},f(Ze.openConversationRetryLabel,c),g?f(Ze.openConversationBackLabel,g):null)),w=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:Ze.openConversationErrorTitle,retryLabel:Ze.openConversationRetryLabel,backLabel:Ze.openConversationBackLabel}),retry:c,...g?{back:g}:{},defaultRenderer:b}),W=null;for(let V of p)if(V.renderHistoryOpenError){try{W=V.renderHistoryOpenError(w)}catch(F){console.warn("[persona] renderHistoryOpenError threw",F),W=null}if(W)break}Vb(Y("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},W??b())),Ub()};oe.on("history:closed",()=>{Ds&&eo(He,!0)});let zg=async(i,{focusComposer:c=!1}={})=>{let g=Fi(),f=!!lt;lt?.view.setActiveConversationId(i),ud();let b=cd;tT(),Rt&&(Vt==="panel"||zt)&&In({restoreFocus:!1}),ki=!0;try{await T.openConversation(i,{scope:g})}catch(w){throw b===cd&&nT(i),w}finally{ki=!1}b===cd&&(ud(),$t.clear(),bo(),kn(),sg()||Bc(),eT(),dr(),f||js(null),oe.emit("history:conversationOpened",{conversationId:i,title:ld,scope:g,timestamp:Date.now()}),c&&Bs())},Kg=async({focusComposer:i=!1}={})=>{ud(),await T.startNewConversation({scope:Fi()}),js(null),$t.clear(),bo(),kn(),Bc(),dr();let c=T.getActiveConversationId();lt?.view.setActiveConversationId(c),oe.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),Rt&&(Vt==="panel"||zt)&&In({restoreFocus:!1}),i&&Bs()},Gg=async(i,c)=>{let g=await T.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return lt?.view.applyConversationSummary(g),!lt&&i===T.getActiveConversationId()&&js(g),g},qb=async i=>{let c=Fi(),g=T.getActiveConversationId()===i;await T.deleteConversation(i,{scope:c}),lt?.view.removeConversationSummary(i),g&&(js(null),$t.clear(),bo(),kn(),dr()),oe.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:g,timestamp:Date.now()})},zb=async i=>{let c=i?.scope??Fi(),g=i?.allTargets?null:i?.targetId??fb(),f=await T.clearConversationHistory({...g?{targetId:g}:{},scope:c});return js(null),$t.clear(),bo(),kn(),dr(),oe.emit("history:cleared",{deleted:f.deleted,scope:c,targetId:g,timestamp:Date.now()}),f},Kb=async()=>{if(!qn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await T.resetHistoryDevice()).remoteRevocationConfirmed}finally{js(null),T.clearArtifacts(),$t.clear(),Cg=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),I={},Ce.syncFromMetadata(),k?.clear&&Hc(()=>k.clear(),"[AgentWidget] Failed to clear storage adapter:"),bo(),kn(),dr(),In({restoreFocus:!1}),Bs(),Ee||Wt?.launcher.element.focus()}return Xc(i?Ze.identityResetNotice:Ze.identityResetUnconfirmedNotice),oe.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},Yg=()=>Ro?xe:de,Gb=async i=>await eu({host:Yg(),title:Ze.deleteConversationConfirmTitle,description:Ze.deleteConversationConfirm,confirmLabel:Ze.deleteConversationConfirmLabel,cancelLabel:Ze.confirmCancelLabel})?(await qb(i),"deleted"):"cancelled",oT=async()=>{let i=Fi()==="verified-user";return await eu({host:Yg(),title:Ze.clearHistoryConfirmTitle,description:i?Ze.clearHistoryVerifiedConfirm:Ze.clearHistoryConfirm,confirmLabel:Ze.clearHistoryConfirmLabel,cancelLabel:Ze.confirmCancelLabel})?(await zb(),"cleared"):"cancelled"},rT=async()=>{if(!await eu({host:Yg(),title:Ze.resetIdentityConfirmTitle,description:Ze.resetIdentityConfirm,confirmLabel:Ze.resetIdentityConfirmLabel,cancelLabel:Ze.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await Kb();return{outcome:"reset",remoteRevocationConfirmed:c}},no=S("button","persona-history-earlier");no.type="button",no.textContent=Ze.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(!(Do()&&!!Gc.nextMessageCursor&&!!T.getActiveConversationId())){no.remove();return}no.textContent=Ze.showEarlierMessagesLabel,no.parentNode!==ne&&ne.insertBefore(no,ne.firstChild)};no.addEventListener("click",()=>{let i=T.getActiveConversationId(),c=Gc.nextMessageCursor;if(!i||!c||no.disabled)return;no.disabled=!0;let g=ne.scrollHeight,f=ne.scrollTop;T.loadOlderMessages(i,c,{scope:Fi()}).then(()=>{ne.scrollTop=f+(ne.scrollHeight-g),Ln()}).catch(()=>{}).finally(()=>{no.disabled=!1,dr()})});let sT=()=>{let i=ci({ariaLabel:Ze.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(!(!Do()||mb())){if(Rt){In();return}cl({invoker:i.button,keyboard:c.detail===0})}}),i},Yb=()=>{if(!Do()){Bo?.remove(),mn=null,Bo=null;return}if(Bo&&!Bo.isConnected&&(mn=null,Bo=null),!mn&&Pe){let f=sT();mn=f.button,Bo=f.wrapper;let b=$e.clearChatButtonWrapper||$e.closeButtonWrapper;b?.parentNode&&Pe.contains(b)?b.parentNode.insertBefore(Bo,b):Pe.appendChild(Bo)}if(!mn||!Bo)return;let i=qi()||Rt&&Vt==="rail";if(Bo.style.display=i?"none":"",i){document.activeElement===mn&&id();return}let c=mb();mn.disabled=c,mn.setAttribute("aria-disabled",c?"true":"false");let g=c?Ze.openHistoryBusyLabel:Ze.openHistoryLabel;mn.setAttribute("aria-label",g),(o.features?.history?.presentation??"panel")==="panel"?(mn.removeAttribute("aria-expanded"),mn.removeAttribute("aria-controls")):(mn.setAttribute("aria-expanded",Rt?"true":"false"),mn.setAttribute("aria-controls",Pg))},gd=!1,iT=()=>{let i=$e.clearChatButton;if(i){if(Do()){gd||(Tg=i.getAttribute("aria-label")??"",gd=!0),i.setAttribute("aria-label",Ze.newConversationLabel),i.removeAttribute("title");return}gd&&(gd=!1,Tg&&i.setAttribute("aria-label",Tg))}},qr=()=>{Ze=Mh(o.features?.history?.copy),Yb(),ll(),iT(),dr()};Tu=qr,zh=i=>{Gc=i,lt?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),Ja(i.sendBlocked||Un),dr()},Kh=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&($t.clear(),bo(),kn()),Xc(i.message),lt?.view.refresh()},vb(),qr(),he.push(()=>{Yc?.(),Qc?.(),el+=1,ad(),lt?.dispose(),lt?.view.destroy(),lt=null}),o.clientToken&&(o.features?.history?.enabled===!0||o.sessionInit==="mount")&&T.initClientSession().then(()=>{if(Do())return T.reconcileBootConversation({scope:Lg()})}).then(()=>{dr()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)});let Qg=()=>T.warmClientSession(),Qb=i=>{let c=o.sessionInit??"input",g=tt?.input??ce,f=i.target;g&&(i.type==="input"?(c==="input"||c==="focus")&&f===g&&i.inputType&&g.value.trim():c==="focus"&&(i.type==="keyup"?f===g&&i.key==="Tab":(tt?.form??Mn)?.contains(f)))&&Qg()},Xb=["input","pointerdown","keyup"];Xb.forEach(i=>e.addEventListener(i,Qb));let Jb,Xg,Zb=()=>{let i=Xg;Xg=void 0;try{typeof i=="function"&&i()}catch{}},ev=()=>{let i=o.clientToken&&typeof o.sessionInit=="function"?o.sessionInit:void 0;if(i!==Jb){Zb(),Jb=i;try{Xg=i?.({warm:Qg,mount:e})}catch{}}};ev(),he.push(()=>{Xb.forEach(i=>e.removeEventListener(i,Qb)),Zb()}),(X||o.onSSEEvent)&&T.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),Mu(i,c)});let tv=()=>{let i=o.resume??(_?ir.getStoredResumableHandle?.():null);i&&typeof o.reconnectStream=="function"&&T.resumeFromHandle(i)};te?te.then(i=>{if(i){if(i.metadata&&(I=Eh(i.metadata),Ce.syncFromMetadata()),i.messages?.length){ki=!0;try{T.hydrateMessages(i.messages)}finally{ki=!1}Fc()}i.artifacts?.length&&T.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null),zy(i.draft)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{ug=!0,U(),tv()}):(zy(ue),tv());let aT=()=>{!we()||Ee||!(o.launcher?.composerBar?.expandOnSubmit??!0)||yt(!0,"auto")},lT=(i,c)=>i?c?{refs:[...i.refs,...c.refs],finalize:async()=>{let[g,f]=await Promise.allSettled([i.finalize(),c.finalize()]),b=[];return g.status==="fulfilled"?b.push(g.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",g.reason),f.status==="fulfilled"?b.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),kI(b)}}:i:c,Jg=()=>{let c=ce.getInlineMessageFields?.();return c&&c.contentSegments.some(f=>f.kind==="mention")?c.contentSegments:void 0},pr=!1,Vs=null,md=()=>{ce.value="",ce.style.height="auto",ko(),ul()},Zg="data-persona-composer-notice",Ki=null;function cT(i){mc(i),!(we()||!Je)&&(Je.hasAttribute(La)||(Je.setAttribute(Zg,""),Je.setAttribute("role","status"),Je.setAttribute("aria-live","polite"),Je.textContent=i,ei(Je,o.statusIndicator??{},"idle"),Ki&&clearTimeout(Ki),Ki=setTimeout(()=>{if(Ki=null,!!Je?.hasAttribute(Zg)&&(Je.removeAttribute(Zg),Je.removeAttribute("role"),Je.removeAttribute("aria-live"),y)){let c=T.getStatus();Ra(Je,Pu(c),o.statusIndicator??{},c)}},4e3)))}function dT(){let i=ve.getState().pendingSubmission;i&&(xi(void 0),ce&&(ce.value=i.text,ce.dispatchEvent(new Event("input",{bubbles:!0})),ko()),i.options.selectedModelId&&(ve.setSelectedModelId(i.options.selectedModelId),Hr?.repaint()),i.options.activeModeIds?.length&&bc(i.options.activeModeIds),i.options.quote&&Lo(i.options.quote),ce?.focus())}let pT=i=>{typeof console<"u"&&console.error("[AgentWidget] composer.onBeforeSend failed; the draft was preserved:",i)},nv=(i={})=>{let c=(i.overrideText??ce?.value??"").trim();return i.resolveInlineCommand&&c?(Ft?.takeInlineCommand(c)??Promise.resolve(null)).then(g=>ov(i,c,g)):ov(i,c,null)},ov=(i,c,g)=>{if(g?.kind==="action"){md(),Ft?.clear(),vs();return}let f=g?.kind==="server"?g.mentions:null,b=g?.kind==="prompt"?g.sendText:c,w=i.pending?.contentParts,W=(rt?.hasAttachments()??!1)||(w?.length??0)>0;if(!Ax({text:b,hasAttachments:W,attachmentsReady:rt?.isReady()??!0,hasMentions:Ft?.hasMentions()??!1,hasServerMentions:!!f,inputDisabled:Oo(),sendDisabled:Os()}))return;let V=T.isStreaming()?Du():"block";if(V==="defer-one"&&!i.pending){if(ve.getState().pendingSubmission){cT("One message is already queued. Edit or remove it first.");return}uT({intent:i,sendText:b,serverMentions:f});return}let F={text:b,mentionRefs:[...Ft?.getMentionRefs()??[],...f?.refs??[]],contentSegments:g?.kind==="prompt"?void 0:Jg(),options:{...ve.getState().selectedModelId&&{selectedModelId:ve.getState().selectedModelId},...ve.getState().activeModeIds.length>0&&{activeModeIds:[...ve.getState().activeModeIds]},...ve.getState().quote&&{quote:{...ve.getState().quote}}},viaVoice:i.viaVoice};i.pending&&(F.options={...i.pending.options},F.contentSegments=i.pending.contentSegments,F.mentionRefs=[...i.pending.mentionRefs],F.viaVoice=i.pending.viaVoice);let q=()=>{if(w?.length)return[...w];if(!rt?.hasAttachments())return;let nt=[...rt.getContentParts()];return F.text&&nt.push(co(F.text)),nt};F.contentParts=q();let Q=()=>{ks(),aT();let nt=Ft?.collectForSubmit()??null,Rn=lT(nt,f),At=q();i.consumeDraft!==!1&&md();let Lt={selectedModelId:F.options.selectedModelId,activeModeIds:F.options.activeModeIds},hn=V==="interrupt";hn&&T.cancel(),T.sendMessage(F.text,{contentParts:At,mentions:Rn??void 0,contentSegments:F.contentSegments,viaVoice:F.viaVoice,composerOptions:Lt,...F.options.quote&&{quote:F.options.quote},...hn&&{interrupt:!0}}),rt?.hasAttachments()&&rt.clearAttachments(),nt&&Ft?.clear(),vs();let Bt=ve.getState().activeModeIds,pt=dx(Bt,o.composer?.modes);pt.length!==Bt.length&&bc(pt),ve.getState().quote&&Lo(void 0),Oc(),Uu.release(),mo()},ie=o.composer?.onBeforeSend;if(!ie){Q();return}let me=new AbortController;Vs=me;let Ve=nt=>{if(Vs=null,nt.status==="error"){pT(nt.error);return}nt.status==="proceed"&&Q()},st=Mx(ie,F,me.signal);if(!(st instanceof Promise)){Ve(st);return}return ve.setPreparing(!0),st.then(Ve).finally(()=>ve.setPreparing(!1))};function uT(i){let c=ve.getState(),g=rt?.hasAttachments()??!1,f=g?[...rt.getContentParts()]:[];g&&i.sendText&&f.push(co(i.sendText));let b=xf({text:i.sendText,contentParts:f.length?f:void 0,mentionRefs:[...Ft?.getMentionRefs()??[],...i.serverMentions?.refs??[]],contentSegments:Jg(),options:{...c.selectedModelId&&{selectedModelId:c.selectedModelId},...c.activeModeIds.length>0&&{activeModeIds:[...c.activeModeIds]},...c.quote&&{quote:{...c.quote}}},viaVoice:i.intent.viaVoice});xi(b),i.intent.consumeDraft!==!1&&md(),g&&rt.clearAttachments(),Ft?.clear(),vs(),c.quote&&Lo(void 0),Oc(),Uu.release(),mo(),mc("Message queued. It sends when the response finishes.")}function gT(){let i=ve.getState().pendingSubmission;i&&(xi(void 0),hd(i.text,{consumeDraft:!1,pending:i}))}function mT(i){if(o.messageActions?.showEdit!==!0)return;let c=T.getMessages().find(g=>g.id===i);!c||!Zm(c)||Ps!==i&&(ks(),Ps=i,Dr=fx({messageId:i,initialText:c.content,onSave:g=>fT(i,g),onCancel:()=>ks()}),$t.delete(i),Jn(be,T.getMessages(),N),Dr.focus())}function fT(i,c){let g=Dr;if(Ps=null,Dr=null,g?.destroy(),$t.delete(i),!T.resubmitFrom(i,{reason:"edit",replacement:{text:c,mentionRefs:[],options:{}}})){Jn(be,T.getMessages(),N);return}Ln()}function hT(i){if(T.isStreaming())return;let c=Jm(T.getMessages(),i);c&&(ks(),T.resubmitFrom(c,{reason:"retry"})&&Ln())}vc={regenerate:hT,edit:mT,quote:i=>{let g=T.getMessages().find(f=>f.id===i)?.content?.trim();g&&(Lo({text:g,messageId:i}),ce?.focus())}};let pl=async i=>{if(!pr){pr=!0;try{await nv({resolveInlineCommand:!0,...i})}finally{pr=!1}}};function fd(i){Os()||(md(),hd(i,{consumeDraft:!1}))}let hd=(i,c)=>{if(pr)return;pr=!0;let g=()=>{pr=!1};try{let f=nv({...c,overrideText:i});f instanceof Promise?f.finally(g):g()}catch(f){throw g(),f}},yT=i=>{if(i.preventDefault(),T.isStreaming()){T.cancel(),Zt?.reset(),ht?.update();return}pr||pl()},bT=()=>o.features?.composerHistory!==!1,em={...Lf},tm=!1,ul=()=>{em={...Lf}},vT=()=>T.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),CT=i=>{if(!ce)return;tm=!0,ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),tm=!1;let c=ce.value.length;ce.setSelectionRange(c,c)},wT=i=>{tm||(i.isComposing||Ft?.handleInput(i.inputType??void 0),ul())},xT=()=>({submitKey:o.composer?.submitKey,insertNewlineOnTouchEnter:o.composer?.insertNewlineOnTouchEnter,coarsePointer:Ol(ce)}),ST=i=>{if(ce&&!Oo()&&!(!i.isComposing&&Ft?.handleKeydown(i))){if(bT()&&(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=Yx({direction:i.key==="ArrowUp"?"up":"down",history:vT(),currentValue:ce.value,atStart:c,state:em});if(em=g.state,g.handled){i.preventDefault(),g.value!==void 0&&CT(g.value);return}}if(Gw(i,xT())){if(T.isStreaming()){if(i.preventDefault(),Du()==="block"||pr||Os())return;ul(),pl();return}if(pr){i.preventDefault();return}if(Os()){i.preventDefault();return}ul(),i.preventDefault(),Te.click()}}},rv=i=>{if(!(i.key!=="Escape"||i.isComposing)&&i.composedPath().includes(de)){if(Vs){Vs.abort(),Vs=null,i.preventDefault(),i.stopImmediatePropagation();return}T.isStreaming()&&(T.cancel(),Zt?.reset(),ht?.update(),ul(),i.preventDefault(),i.stopImmediatePropagation())}},AT=async i=>{if(o.attachments?.enabled!==!0||!rt||Oo())return;let c=MI(i.clipboardData);c.length!==0&&(i.preventDefault(),await rt.handleFiles(c))},oo=null,_o=!1,Gi=null,Pt=null,nm=()=>o.voiceRecognition?.completionBehavior==="review";function qs(i){se?.setAttribute("data-state",i),i==="recording"?ET():im()}let sv="--persona-voice-level",om=.5,Yi=null,rm=-1,yd=0,iv=()=>{let i=[],c=Fn??se?.parentElement??null;return c&&i.push(c),He&&i.push(He),i},sm=i=>{let c=Math.round(Math.max(0,Math.min(1,i))*100)/100;if(c!==rm){rm=c;for(let g of iv())g.style.setProperty(sv,String(c))}},MT=()=>{rm=-1,yd=0;for(let i of iv())i.style.removeProperty(sv)};function ET(){if(Yi!==null)return;if(typeof requestAnimationFrame!="function"){sm(y?T.getVoiceLevel()??om:om);return}let i=()=>{Yi=requestAnimationFrame(i);let c=y?T.getVoiceLevel():null;if(c===null){sm(om);return}yd+=(c-yd)*.3,sm(yd)};Yi=requestAnimationFrame(i)}function im(){Yi!==null&&(cancelAnimationFrame(Yi),Yi=null),MT()}let av=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,bd=(i="user")=>{if(_o||T.isStreaming())return;let c=av();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=w=>{let W="",V="";for(let q=0;q<w.results.length;q++){let Q=w.results[q],ie=Q[0].transcript;Q.isFinal?W+=ie+" ":V=ie}let F=b+W+V;ce.value=F,ko(),Gi&&clearTimeout(Gi),(W||V)&&(Gi=window.setTimeout(()=>{if(ce.value.trim()&&oo&&_o){if(zr(),nm())return;pl({viaVoice:!0})}},f))},oo.onerror=w=>{w.error!=="no-speech"&&zr()},oo.onend=()=>{if(_o){let w=ce.value.trim();!nm()&&w&&w!==b.trim()&&pl({viaVoice:!0}),zr()}};try{if(oo.start(),_o=!0,Xe.active=!0,i!=="system"&&(Xe.manuallyDeactivated=!1),rr(i),yo(),mo(),se){let w=o.voiceRecognition??{};Pt={backgroundColor:se.style.backgroundColor,color:se.style.color,borderColor:se.style.borderColor,iconName:w.iconName??"mic",iconSize:parseFloat(w.iconSize??"")||Cn};let W=w.recordingBackgroundColor,V=w.recordingIconColor,F=w.recordingBorderColor;if(se.classList.add("persona-voice-recording"),qs("recording"),se.style.backgroundColor=W??"var(--persona-voice-recording-bg, #ef4444)",se.style.color=V??"var(--persona-voice-recording-indicator, #ffffff)",V){let q=se.querySelector("svg");q&&q.setAttribute("stroke",V)}F&&(se.style.borderColor=F),se.setAttribute("aria-label","Stop voice recognition")}}catch{zr("system")}},zr=(i="user")=>{if(_o){if(_o=!1,Gi&&(clearTimeout(Gi),Gi=null),oo){try{oo.stop()}catch{}oo=null}if(Xe.active=!1,rr(i),yo(),mo(),se){if(se.classList.remove("persona-voice-recording"),qs("idle"),Pt){se.style.backgroundColor=Pt.backgroundColor,se.style.color=Pt.color,se.style.borderColor=Pt.borderColor;let c=se.querySelector("svg");c&&c.setAttribute("stroke",Pt.color||"currentColor"),Pt=null}se.setAttribute("aria-label","Start voice recognition")}}},am=()=>{if(!se||Pt)return;let i=o.voiceRecognition??{};Pt={backgroundColor:se.style.backgroundColor,color:se.style.color,borderColor:se.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??"")||Cn}},lm=(i,c)=>{if(!se)return;let g=se.querySelector("svg");g&&g.remove();let f=Pt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??"")||Cn),b=le(i,f,c,1.5);b&&se.appendChild(b)},vd=()=>{se&&se.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Qi=()=>{if(!se)return;am();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,g=i.recordingIconColor,f=i.recordingBorderColor;if(vd(),se.classList.add("persona-voice-recording"),qs("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")},TT=()=>{if(!se)return;am();let i=o.voiceRecognition??{},c=T.getVoiceInterruptionMode(),g=i.processingIconName??"loader",f=i.processingIconColor??Pt?.color??"",b=i.processingBackgroundColor??Pt?.backgroundColor??"",w=i.processingBorderColor??Pt?.borderColor??"";vd(),se.classList.add("persona-voice-processing"),qs("processing"),se.style.backgroundColor=b,se.style.borderColor=w;let W=f||"currentColor";se.style.color=W,lm(g,W),se.setAttribute("aria-label","Processing voice input"),c==="none"&&(se.style.cursor="default")},PT=()=>{if(!se)return;am();let i=o.voiceRecognition??{},c=T.getVoiceInterruptionMode(),g=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",f=i.speakingIconName??g,b=i.speakingIconColor??(c==="barge-in"?i.recordingIconColor??Pt?.color??"":Pt?.color??""),w=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":Pt?.backgroundColor??""),W=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":Pt?.borderColor??"");vd(),se.classList.add("persona-voice-speaking"),qs("speaking"),se.style.backgroundColor=w,se.style.borderColor=W;let V=b||"currentColor";se.style.color=V,lm(f,V);let F=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";se.setAttribute("aria-label",F),c==="none"&&(se.style.cursor="default"),c==="barge-in"&&se.classList.add("persona-voice-recording")},ur=()=>{se&&(vd(),qs("idle"),Pt&&(se.style.backgroundColor=Pt.backgroundColor??"",se.style.color=Pt.color??"",se.style.borderColor=Pt.borderColor??"",lm(Pt.iconName,Pt.color||"currentColor"),Pt=null),se.style.cursor="",se.setAttribute("aria-label","Start voice recognition"))},cm=()=>{if(!Oo()){if(vn(o.voiceRecognition?.provider)){let i=T.getVoiceStatus(),c=T.getVoiceInterruptionMode();if(c==="none"&&(i==="processing"||i==="speaking"))return;if(c==="cancel"&&(i==="processing"||i==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,yo(),rr("user"),ur()});return}T.toggleVoice().then(()=>{Xe.active=T.isVoiceActive(),Xe.manuallyDeactivated=!T.isVoiceActive(),yo(),rr("user"),T.isVoiceActive()?Qi():ur()});return}if(_o){let i=ce.value.trim();Xe.manuallyDeactivated=!0,yo(),zr("user"),i&&!nm()&&pl()}else Xe.manuallyDeactivated=!1,yo(),bd("user")}};_u=cm;let lv=()=>T.prewarmVoice(),cv=()=>{let i=o.voiceRecognition;return i?.enabled!==!0?!1:i.prewarm??(o.clientToken?"hover":!1)},dv=i=>{cv()==="hover"&&se?.contains(i.target)&&lv()},pv=["pointerover","pointerdown","focusin"];pv.forEach(i=>e.addEventListener(i,dv));let uv,gv=null,dm,mv=()=>{let i=dm;dm=void 0;try{typeof i=="function"&&i()}catch{}},pm=()=>{let i=cv(),c=typeof i=="function"&&se?i:void 0,g=c?se:null;if(!(c===uv&&g===gv)&&(mv(),uv=c,gv=g,!(!c||!g)))try{dm=c({warm:lv,micButton:g,mount:e})}catch{}};pm(),he.push(()=>{pv.forEach(i=>e.removeEventListener(i,dv)),mv()}),se&&he.push(()=>{vn(o.voiceRecognition?.provider)?(T.isVoiceActive()&&T.toggleVoice(),ur()):zr("system")});let kT=oe.on("assistant:complete",()=>{ve.getState().pendingSubmission&&setTimeout(()=>{T.isStreaming()||gT()},0)});he.push(kT);let LT=oe.on("assistant:complete",()=>{jy&&(Xe.active||Xe.manuallyDeactivated||jy==="assistant"&&!Xe.lastUserMessageWasVoice||setTimeout(()=>{!Xe.active&&!Xe.manuallyDeactivated&&(vn(o.voiceRecognition?.provider)?T.toggleVoice().then(()=>{Xe.active=T.isVoiceActive(),rr("auto"),T.isVoiceActive()&&Qi()}):bd("auto"))},600))});he.push(LT);let IT=oe.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});he.push(IT);let fv=()=>{yt(!Ee,"user")},Wt=null,fn=null;if(D&&!we()){let{instance:i,element:c}=oh({config:o,plugins:p,onToggle:fv});Wt=i,i||(fn=c)}Wt?e.appendChild(Wt.element):fn&&e.appendChild(fn),Xa(),Es(),jc(),yg(),Ja(T.isStreaming()),sg()||($n()==="follow"?$r(!0):Bc()),QM(),Fe&&(!D||we()?setTimeout(()=>Bs(),0):Ee&&setTimeout(()=>Bs(),200));let Kr=null,hv=()=>{Kr&&(Kr.disconnect(),Kr.observe(He),Kr.observe(de),Kr.observe(tn))},yv=_a(),gl=()=>{if(we()){bs(),Xa();return}let i=Ct(o),c=o.launcher?.sidebarMode??!1,g=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640,w=g.innerWidth<=b,W=f&&w&&D;try{if(W){Cs(),Ua=Tc();return}let V=!1;ke&&(ke=!1,Cs(),V=!0);let F=Tc();if(!V&&F!==Ua&&(Cs(),V=!0),Ua=F,V&&Sc(),!D&&!i){xe.style.height="",xe.style.width="";return}if(!c&&!i){let q=mi(o);xe.style.width=q.width,xe.style.maxWidth=q.maxWidth}Ec(),Ty()}finally{bs(),yc();let V=_a();if(V!==yv&&(yv=V,Di(),Es()),Xa(),Ee&&D){let q=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),Q=o.launcher?.sidebarMode??!1,ie=o.launcher?.mobileFullscreen??!0,me=Ct(o)&&ie&&q,Ve=Q||ie&&q&&D||me;if(Ve&&!Wo){let st=e.getRootNode(),nt=st instanceof ShadowRoot?st.host:e.closest(".persona-host");nt&&!Ho&&(Ho=Wf(nt,o.launcher?.zIndex??pn)),Wo=Of(e.ownerDocument)}else Ve||(Ho?.(),Ho=null,Wo?.(),Wo=null)}}};gl();let Cd=e.ownerDocument.defaultView??window;if(Cd.addEventListener("resize",gl),he.push(()=>Cd.removeEventListener("resize",gl)),typeof ResizeObserver<"u"){Kr=new ResizeObserver(()=>{yc()}),hv(),he.push(()=>{Kr?.disconnect(),Kr=null});let i=new ResizeObserver(()=>{sd()});i.observe(de),he.push(()=>i.disconnect())}Cd.addEventListener("resize",sd),he.push(()=>Cd.removeEventListener("resize",sd)),Vn=ne.scrollTop;let bv=Go(ne),vv=()=>{Ey();let i=ne.scrollTop,c=Go(ne),g=c<bv;if(bv=c,!Rr()){Vn=i,Qt();return}let{action:f,nextLastScrollTop:b}=oS({following:jn.isFollowing(),currentScrollTop:i,lastScrollTop:Vn,nearBottom:li(ne,nr),userScrollThreshold:zM,isAutoScrolling:Pn||kc||g,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Vn=b,f==="resume"){Dc()||kn();return}f==="pause"&&Wi()};if(ne.addEventListener("scroll",vv,{passive:!0}),he.push(()=>ne.removeEventListener("scroll",vv)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{oE(),Hm(be)});i.observe(be),i.observe(ne),he.push(()=>i.disconnect())}let Cv=()=>{Rr()&&jn.isFollowing()&&Dc()&&Wi()},wv=ne.ownerDocument;wv.addEventListener("selectionchange",Cv),he.push(()=>{wv.removeEventListener("selectionchange",Cv)});let RT=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),xv=i=>{RT.has(i.key)&&(Fr(),Yh()&&Rr()&&jn.isFollowing()&&Wi())},Sv=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Fr(),Yh()&&Rr()&&jn.isFollowing()&&Wi())};ne.addEventListener("keydown",xv),ne.addEventListener("focusin",Sv),he.push(()=>{ne.removeEventListener("keydown",xv),ne.removeEventListener("focusin",Sv)});let Av=i=>{if(i.deltaY!==0&&Fr(),!Rr())return;let c=rS({following:jn.isFollowing(),deltaY:i.deltaY,nearBottom:li(ne,nr),resumeWhenNearBottom:!0});c==="pause"?Wi():c==="resume"&&!Dc()&&kn()};ne.addEventListener("wheel",Av,{passive:!0}),ne.addEventListener("touchmove",Fr,{passive:!0}),ne.addEventListener("pointerdown",Fr,{passive:!0}),he.push(()=>{ne.removeEventListener("touchmove",Fr),ne.removeEventListener("pointerdown",Fr)}),he.push(()=>ne.removeEventListener("wheel",Av)),qt.addEventListener("click",()=>{bo(),ne.scrollTop=ne.scrollHeight,Vn=ne.scrollTop,kn(),$r(!0),Qt()}),he.push(()=>qt.remove()),he.push(()=>{Gy(),bo()});let Mv=()=>{qe&&(As&&(qe.removeEventListener("click",As),As=null),Be()?(qe.style.display="",As=()=>{yt(!1,"user")},qe.addEventListener("click",As)):qe.style.display="none")};Mv(),(()=>{let{clearChatButton:i}=$e;i&&i.addEventListener("click",()=>{if(Do()){Kg({focusComposer:!0}).catch(g=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",g)});return}T.clearMessages(),o.layout?.topFade&&(ne.scrollTop=0),ne.removeAttribute("data-persona-top-fade"),$t.clear(),kn(),ss($e.composerOverlay);try{localStorage.removeItem(ka),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ka}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ka)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),k?.clear&&Hc(()=>k.clear(),"[AgentWidget] Failed to clear storage adapter:"),I={},Ce.syncFromMetadata(),rt?.clearAttachments(),Oc(),xi(void 0),Lo(void 0),ks(),ft?.clear(),Zt?.reset(),ht?.update()})})();let Ev=[["keydown",ST],["input",wT],["input",ko],["input",vs],["keyup",vs],["paste",AT],["focus",OM]],Tv=i=>{if(i)for(let[c,g]of Ev)tt?.addListener(i,c,g)},HT=i=>{if(i)for(let[c,g]of Ev)tt?.removeListener(i,c,g)},Pv=()=>{tt&&(tt.addListener(tt.form,"submit",yT),tt.addListener(tt.footer,"click",vs),Tv(ce),se&&tt.addListener(se,"click",cm),pm())};Pv();let kv=()=>{Ft?.onComposerSwap((i,c)=>{HT(c),ce=i,tt&&(tt.input=i),Tv(i),Fu(),dg(),ko()})};kv();let um=!1;function Lv(){if(!um){um=!0;try{let i=ce?.value??"",c=He.ownerDocument??document,g=ce?c.activeElement===ce:!1;im(),tt?.destroy(),tt=null,Ft?.destroy(),Ft=null;let f=null,b=()=>(f=we()?jp({config:o}):ui({config:o}),f.footer),w=sy(b)??b();_n.replaceComposer(w),He=_n.composer.footer;let W=f!==null&&w===f.footer;Ai=!W,Gh=W?f.setSendButtonMode:()=>{},ry(He),ay(He),ly(),cy(),dy(),kv(),py(),$u(),uy(),Pv();let V=Ss.indexOf(tr);if(tr.destroy(),tr=Jl(Lr),V>=0&&(Ss[V]=tr),ce&&(ce.value=i),ko(),vs(),jc(),Es(),Ja(T.isStreaming()),o.statusIndicator?.mode==="transient"&&!we()){let F=T.getStatus();Ra(Je,Pu(F),o.statusIndicator,F)}Xe.active&&qs("recording"),Cs(),hv(),bs(),mo(),$c(),g&&ce?.focus()}finally{um=!1}}}let ml=e.ownerDocument??document;ml.addEventListener("keydown",rv,!0);let Iv=()=>{tg()},Rv=()=>{ml.visibilityState==="hidden"&&tg()};typeof window<"u"&&(window.addEventListener("pagehide",Iv),ml.addEventListener("visibilitychange",Rv),he.push(()=>{window.removeEventListener("pagehide",Iv),ml.removeEventListener("visibilitychange",Rv)}));let Hv="persona-attachment-drop-active",fl=0,gm=()=>{fl=0,de.classList.remove(Hv)},Xi=()=>o.attachments?.enabled===!0&&rt!==null&&!Oo(),Wv=i=>{!iu(i.dataTransfer)||!Xi()||(fl++,fl===1&&de.classList.add(Hv))},Ov=i=>{!iu(i.dataTransfer)||!Xi()||(fl--,fl<=0&&gm())},Bv=i=>{!iu(i.dataTransfer)||!Xi()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Dv=i=>{if(!iu(i.dataTransfer)||!Xi())return;i.preventDefault(),i.stopPropagation(),gm();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&rt.handleFiles(c)},Gr=!0;de.addEventListener("dragenter",Wv,Gr),de.addEventListener("dragleave",Ov,Gr),e.addEventListener("dragover",Bv,Gr),e.addEventListener("drop",Dv,Gr);let wd=e.ownerDocument,_v=i=>{Xi()&&i.preventDefault()},Nv=i=>{Xi()&&i.preventDefault()};wd.addEventListener("dragover",_v),wd.addEventListener("drop",Nv),he.push(()=>{tt?.destroy(),tt=null,im(),Io?.destroy(),Io=null,Zo?.destroy(),Zo=null,Wr?.destroy(),Wr=null,Or?.destroy(),Or=null,Hr=null,Bu=null,tg(),za.destroy(),Ki&&clearTimeout(Ki),ks(),Vs?.abort(),Vs=null,rt?.destroy(),rt=null,ve.destroy(),ml.removeEventListener("keydown",rv,!0),Ft?.destroy()}),he.push(()=>{de.removeEventListener("dragenter",Wv,Gr),de.removeEventListener("dragleave",Ov,Gr),e.removeEventListener("dragover",Bv,Gr),e.removeEventListener("drop",Dv,Gr),wd.removeEventListener("dragover",_v),wd.removeEventListener("drop",Nv),gm()}),he.push(()=>{T.cancel()}),Wt?he.push(()=>{Wt?.destroy()}):fn&&he.push(()=>{fn?.remove()});let Ot={update(i){let c=o.future?.v5Defaults===!0,g=o.toolCall,f=o.messageActions,b=o.layout?.messages,w=o.colorScheme,W=o.loadingIndicator,V=o.iterationDisplay,F=o.features?.showReasoning,q=o.features?.showToolCalls,Q=o.features?.toolCallDisplay,ie=o.features?.reasoningDisplay,me=o.features?.streamAnimation?.type,Ve=o.features?.history?.enabled===!0,st=o.features?.history?.provider,nt=o.getIdentityProof,Rn=o.clientToken,At=o.contextMentions;o=Jp({...o,features:u},i),u=o.features,o=oc(o),d(),Gu(),ai(e,o),tc(e,o),nc(e,o),Xo(),ho(),o.colorScheme!==w&&Py();let Lt=rc.getForInstance(o.plugins);p.length=0,p.push(...Lt),Tb(),D=o.launcher?.enabled??!0,Ne=o.launcher?.autoExpand??!1,z=o.features?.showReasoning??!0,J=o.features?.showToolCalls??!0,fe=o.features?.scrollToBottom??{};let hn=$n();Ae=o.features?.scrollBehavior??{},hn!==$n()&&(bo(),kn()),Uy(),Jh(),Qt();let Bt=X;if(X=o.features?.showEventStreamToggle??!1,X&&!Bt){if(ft||(pc(),T.setSSEEventCallback((Z,Ge)=>{o.onSSEEvent?.(Z,Ge),Mu(Z,Ge)})),!at&&Pe){let Z=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"+(Z?.toggleButton?" "+Z.toggleButton:"");at=S("button",Ge),at.style.width="28px",at.style.height="28px",at.style.color=wn.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let Ye=Mt(Tr.Activity,"18px","currentColor",1.5);Ye&&at.appendChild(Ye);let ot=$e.clearChatButtonWrapper,wt=$e.closeButtonWrapper,dn=ot||wt;dn&&dn.parentNode===Pe?Pe.insertBefore(at,dn):Pe.appendChild(at),at.addEventListener("click",()=>{go?Si():Nu()})}}else!X&&Bt&&(Si(),at&&(at.remove(),at=null),ft?.clear(),et?.destroy(),ft=null,et=null,Zt?.reset(),Zt=null,It=null);if(o.launcher?.enabled===!1&&Wt&&(Wt.destroy(),Wt=null),o.launcher?.enabled===!1&&fn&&(fn.remove(),fn=null),o.launcher?.enabled!==!1&&!Wt&&!fn){let{instance:Z,element:Ge}=oh({config:o,plugins:p,onToggle:fv});Wt=Z,Z||(fn=Ge),e.appendChild(Ge)}Wt&&Wt.update(o),dl(),fs&&o.launcher?.subtitle!==void 0&&(fs.textContent=o.launcher.subtitle);let pt=o.layout?.header;if(pt?.layout!==jt&&Pe){let Z=pt?Ca(o,pt,{showClose:Be(),onClose:()=>yt(!1,"user")}):Sr({config:o,showClose:Be(),onClose:()=>yt(!1,"user")});_n.replaceHeader(Z),Pe=_n.header.element,Ht=_n.header.iconHolder,Ir=_n.header.headerTitle,fs=_n.header.headerSubtitle,qe=_n.header.closeButton,jt=pt?.layout,dl()}else if(pt){if(Ht&&(Ht.style.display=pt.showIcon===!1?"none":""),Ir&&(Ir.style.display=pt.showTitle===!1?"none":""),fs&&(fs.style.display=pt.showSubtitle===!1?"none":""),qe){let Z=Be()&&pt.showCloseButton!==!1;qe.style.display=Z?"":"none"}if($e.clearChatButtonWrapper){let Z=pt.showClearChat;if(Z!==void 0){$e.clearChatButtonWrapper.style.display=Z?"":"none";let{closeButtonWrapper:Ge}=$e;Ge&&!Ge.classList.contains("persona-absolute")&&(Z?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}}let Fo=o.layout?.showHeader!==!1;Pe&&(Pe.style.display=Fo?"":"none");let so=o.layout?.showFooter!==!1;He&&(He.style.display=so?"":"none"),bs(),Qt(),D!==Gt?D?yt(Ne,"auto"):(Ee=!0,Xa()):Ne!==Et&&yt(Ne,"auto"),Et=Ne,Gt=D,gl(),Mv();let $o=JSON.stringify(o.toolCall)!==JSON.stringify(g),vo=JSON.stringify(o.messageActions)!==JSON.stringify(f),Qr=JSON.stringify(o.layout?.messages)!==JSON.stringify(b),hl=o.loadingIndicator?.render!==W?.render||o.loadingIndicator?.renderIdle!==W?.renderIdle||o.loadingIndicator?.showBubble!==W?.showBubble,zs=o.iterationDisplay!==V,R=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(q??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(Q)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ie);(o.future?.v5Defaults===!0!==c||$o||vo||Qr||hl||zs||R)&&T&&(Ls++,Jn(be,T.getMessages(),N));let Oe=o.features?.streamAnimation?.type;if(Oe!==me&&Oe&&Oe!=="none"){let Z=Xu(Oe,o.features?.streamAnimation?.plugins);Z&&Yl(Z,e)}let re=o.launcher??{},ut=re.headerIconHidden??!1,Ut=o.layout?.header?.showIcon,un=ut||Ut===!1,nn=re.headerIconName,bt=re.headerIconSize??Cl;if(Ht){let Z=Pe,Ge=Z?.querySelector(".persona-flex-col");if(un)Ht.style.display="none",Z&&Ge&&!Z.contains(Ge)&&Z.insertBefore(Ge,Z.firstChild);else{if(Ht.style.display="",Ht.style.height=bt,Ht.style.width=bt,Z&&Ge&&(Z.contains(Ht)?Ht.nextSibling!==Ge&&(Ht.remove(),Z.insertBefore(Ht,Ge)):Z.insertBefore(Ht,Ge)),nn){let ot=parseFloat(bt)||24,wt=le(nn,ot*.6,"currentColor",1);wt?(wt.style.width=`calc(${ot}px * var(--persona-components-header-iconScale, 0.6))`,wt.style.height=`calc(${ot}px * var(--persona-components-header-iconScale, 0.6))`,Ht.replaceChildren(wt)):Ht.textContent=re.agentIconText??"\u{1F4AC}"}else if(re.iconUrl){let ot=Ht.querySelector("img");if(ot)ot.src=re.iconUrl,ot.style.height=bt,ot.style.width=bt;else{let wt=document.createElement("img");wt.src=re.iconUrl,wt.alt="",wt.className="persona-rounded-xl persona-object-cover",wt.style.height=bt,wt.style.width=bt,Ht.replaceChildren(wt)}}else{let ot=Ht.querySelector("svg"),wt=Ht.querySelector("img");(ot||wt)&&Ht.replaceChildren(),Ht.textContent=re.agentIconText??"\u{1F4AC}"}let Ye=Ht.querySelector("img");Ye&&(Ye.style.height=bt,Ye.style.width=bt)}}let Dt=o.layout?.header?.showTitle,Xt=o.layout?.header?.showSubtitle;if(Ir&&(Ir.style.display=Dt===!1?"none":""),fs&&(fs.style.display=Xt===!1?"none":""),qe){let Z=Be()&&o.layout?.header?.showCloseButton!==!1;if(qe.style.display=Z?"":"none",!we()){let rn=re.closeButtonSize??"";qe.style.height=rn,qe.style.width=rn,qe.style.minWidth=rn,qe.style.minHeight=rn}let Ge=re.closeButtonPlacement??"inline",{closeButtonWrapper:Ye}=$e,ot=Ge==="top-right",wt=Ye?.classList.contains("persona-absolute");if(Ye&&ot!==wt)if(Ye.remove(),ot){Ye.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let rn=nl??de;rn.style.position="relative",rn.appendChild(Ye)}else{let rn=re.clearChat?.placement??"inline",sn=re.clearChat?.enabled??!0;Ye.className=sn&&rn==="inline"?"":"persona-ml-auto",Pe&&Pe.appendChild(Ye)}if(qe.style.color=re.closeButtonColor||wn.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 rn=re.closeButtonBorderWidth||"0px",sn=re.closeButtonBorderColor||"transparent";qe.style.border=`${rn} solid ${sn}`,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=""),Np(qe,re.closeButtonIconName??"x",{iconSize:we()?Zf:void 0,iconText:re.closeButtonIconText??"\xD7"});let dn=re.closeButtonTooltipText??"Close chat",wo=re.closeButtonShowTooltip??!0;qe.setAttribute("aria-label",dn),Ye&&an({anchor:qe,trigger:Ye,text:()=>qe?.getAttribute("aria-label")??dn,enabled:wo})}let{clearChatButton:Le,clearChatButtonWrapper:vt}=$e;if(Le){let Z=re.clearChat??{},Ge=Z.enabled??!0,Ye=o.layout?.header?.showClearChat,ot=Ye!==void 0?Ye:Ge,wt=Z.placement??"inline";if(vt){vt.style.display=ot?"":"none";let{closeButtonWrapper:dn}=$e;!we()&&dn&&!dn.classList.contains("persona-absolute")&&(ot?dn.classList.remove("persona-ml-auto"):dn.classList.add("persona-ml-auto"));let wo=wt==="top-right",rn=vt.classList.contains("persona-absolute");if(!we()&&wo!==rn&&ot){if(vt.remove(),wo){vt.className="persona-absolute persona-top-4 persona-z-50",vt.style.right="48px";let Uo=nl??de;Uo.style.position="relative",Uo.appendChild(vt)}else{vt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vt.style.right="";let Uo=$e.closeButtonWrapper;Pe&&Uo&&Uo.parentElement===Pe?Pe.insertBefore(vt,Uo):Pe&&Pe.appendChild(vt)}let sn=$e.closeButtonWrapper;sn&&!sn.classList.contains("persona-absolute")&&(wo?sn.classList.add("persona-ml-auto"):sn.classList.remove("persona-ml-auto"))}}if(ot){if(!we()){let sn=Z.size??"";Le.style.height=sn,Le.style.width=sn,Le.style.minWidth=sn,Le.style.minHeight=sn}let dn=Z.iconColor??"";if(Le.style.color=dn||wn.actionIconColor,Np(Le,Z.iconName??"refresh-cw",{iconSize:we()?eh:void 0}),Z.backgroundColor?(Le.style.backgroundColor=Z.backgroundColor,Le.classList.remove("hover:persona-bg-gray-100")):(Le.style.backgroundColor="",Le.classList.add("hover:persona-bg-gray-100")),Z.borderWidth||Z.borderColor){let sn=Z.borderWidth||"0px",Uo=Z.borderColor||"transparent";Le.style.border=`${sn} solid ${Uo}`,Le.classList.remove("persona-border-none")}else Le.style.border="",Le.classList.add("persona-border-none");Z.borderRadius?(Le.style.borderRadius=Z.borderRadius,Le.classList.remove("persona-rounded-full")):(Le.style.borderRadius="",Le.classList.add("persona-rounded-full")),Z.paddingX?(Le.style.paddingLeft=Z.paddingX,Le.style.paddingRight=Z.paddingX):(Le.style.paddingLeft="",Le.style.paddingRight=""),Z.paddingY?(Le.style.paddingTop=Z.paddingY,Le.style.paddingBottom=Z.paddingY):(Le.style.paddingTop="",Le.style.paddingBottom="");let wo=Z.tooltipText??"Clear chat",rn=Z.showTooltip??!0;Le.setAttribute("aria-label",wo),vt&&an({anchor:Le,trigger:vt,text:()=>Le?.getAttribute("aria-label")??wo,enabled:rn})}}let De=o.actionParsers&&o.actionParsers.length?o.actionParsers:[sc],Jt=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[yi.message,yi.messageAndClick];Ce=ic({parsers:De,handlers:Jt,getSessionMetadata:Se,updateSessionMetadata:ye,emit:oe.emit,documentRef:typeof document<"u"?document:null}),N=AA(o,Ce,M),wE(),T.updateConfig(o),ev(),(o.features?.history?.enabled===!0!==Ve||o.features?.history?.provider!==st||o.getIdentityProof!==nt||o.clientToken!==Rn)&&(In({restoreFocus:!1}),vb()),qr(),sd(),Jn(be,T.getMessages(),N),Es(),jc(),vE(),Ja(T.isStreaming()),At!==o.contextMentions&&Lv();let ao=o.voiceRecognition?.enabled===!0,on=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),gt=vn(o.voiceRecognition?.provider);if(ao&&(on||gt))if(!se||!Fn){let Z=ha(o);if(Z){se=Z.button,Fn=Z.wrapper;let Ge=Po&&Po.parentElement===uc?Po:null;uc?uc.insertBefore(Fn,Ge):Mn?.appendChild(Fn),tt&&(tt.micButton=se),tt?.addListener(se,"click",cm),se.disabled=Oo()||T.isStreaming()&&!lg()}}else{let Z=o.voiceRecognition??{},Ge=o.sendButton??{},Ye=Z.iconName??"mic",ot=Z.iconSize,wt=parseFloat(ot??"")||Cn;se.classList.add(Kn),se.classList.toggle(Ao,!ot),se.style.width=ot??"",se.style.height=ot??"",se.style.minWidth=ot??"",se.style.minHeight=ot??"";let dn=Z.iconColor??Ge.textColor;se.innerHTML="";let wo=le(Ye,wt,dn||"currentColor",1.5);wo?se.appendChild(wo):se.textContent="\u{1F3A4}";let rn=Z.backgroundColor??Ge.backgroundColor;rn?se.style.backgroundColor=rn:se.style.backgroundColor="",dn?se.style.color=dn:se.style.color="var(--persona-text, #111827)",Z.borderWidth?(se.style.borderWidth=Z.borderWidth,se.style.borderStyle="solid"):(se.style.borderWidth="",se.style.borderStyle=""),Z.borderColor?se.style.borderColor=Z.borderColor:se.style.borderColor="",Z.paddingX?(se.style.paddingLeft=Z.paddingX,se.style.paddingRight=Z.paddingX):(se.style.paddingLeft="",se.style.paddingRight=""),Z.paddingY?(se.style.paddingTop=Z.paddingY,se.style.paddingBottom=Z.paddingY):(se.style.paddingTop="",se.style.paddingBottom="");let sn=Z.tooltipText??"Start voice recognition",Uo=Z.showTooltip??!1;se.setAttribute("aria-label",sn),Fn&&an({anchor:se,trigger:Fn,text:()=>se?.getAttribute("aria-label")??sn,enabled:Uo}),Fn.style.display="",se.disabled=Oo()||T.isStreaming()&&!lg()}else se&&Fn&&(Fn.style.display="none",vn(o.voiceRecognition?.provider)?T.isVoiceActive()&&T.toggleVoice():_o&&zr());if(pm(),o.attachments?.enabled===!0){if(!En||!kt){let Z=o.attachments??{};Tn||(Tn=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Tn.style.display="none",(ce.parentElement??Mn).insertBefore(Tn,ce)),St||(St=document.createElement("input"),St.type="file",St.accept=(Z.allowedTypes??xr).join(","),St.multiple=(Z.maxFiles??4)>1,St.style.display="none",St.setAttribute("aria-label","Attach files"),(ce.parentElement??Mn).insertBefore(St,ce)),En=S("div","persona-send-button-wrapper"),kt=S("button",`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Kn} ${Ao}`),kt.type="button",kt.setAttribute("aria-label",Z.buttonTooltipText??"Attach file");let Ge=Z.buttonIconName??"paperclip";kt.style.fontSize="18px",kt.style.lineHeight="1";let Ye=le(Ge,Cn,"currentColor",1.5);Ye?kt.appendChild(Ye):kt.textContent="\u{1F4CE}",kt.addEventListener("click",wt=>{wt.preventDefault(),St?.click()}),En.appendChild(kt);let ot=Z.buttonTooltipText??"Attach file";an({anchor:kt,trigger:En,text:()=>kt?.getAttribute("aria-label")??ot}),Lu?Lu.append(En):Mn.appendChild(En),tt&&(tt.attachmentButton=kt,tt.attachmentInput=St??void 0,tt.attachmentPreviews=Tn??void 0),!rt&&St&&Tn&&(rt=si.fromConfig(Z,Zh),rt.setPreviewsContainer(Tn),tt?.addListener(St,"change",async()=>{rt&&St?.files&&(await rt.handleFileSelect(St.files),St.value="")}))}else{En.style.display="";let Z=o.attachments??{};St&&(St.accept=(Z.allowedTypes??xr).join(","),St.multiple=(Z.maxFiles??4)>1),rt&&rt.updateConfig({allowedTypes:Z.allowedTypes,maxFileSize:Z.maxFileSize,maxFiles:Z.maxFiles,adapter:Z.adapter})}if(de.querySelector(".persona-attachment-drop-overlay")?.remove(),de.appendChild(MA(o.attachments?.dropOverlay)),kt){let Z=o.attachments??{},Ge=Z.buttonTooltipText??"Attach file";kt.setAttribute("aria-label",Ge),kt.textContent="";let Ye=le(Z.buttonIconName??"paperclip",Cn,"currentColor",1.5);Ye?kt.appendChild(Ye):kt.textContent="\u{1F4CE}",En&&an({anchor:kt,trigger:En,text:()=>kt?.getAttribute("aria-label")??Ge})}}else En&&(En.style.display="none"),rt&&rt.clearAttachments(),de.querySelector(".persona-attachment-drop-overlay")?.remove();let _e=o.sendButton??{},Xr=_e.useIcon??!1,Kt=_e.iconText??"\u2191",Hn=_e.iconName,gr=_e.tooltipText??"Send message",mm=_e.showTooltip??!1,Ks=_e.size,fm=parseFloat(Ks??"")||gf,mr=_e.backgroundColor,Gs=_e.textColor;if(Xr){if(Te.style.width=Ks??"",Te.style.height=Ks??"",Te.style.minWidth=Ks??"",Te.style.minHeight=Ks??"",Te.style.fontSize="18px",Te.style.lineHeight="1",Gs?Te.style.color=Gs:Te.style.color="var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))",!T.isStreaming())if(Te.innerHTML="",Hn){let Z=parseFloat(_e.iconSize??"")||Math.round(fm*.5),Ge=Gs?.trim()||"currentColor",Ye=_e.iconStrokeWidth??2,ot=le(Hn,Z,Ge,Ye),wt=le(_e.stopIconName??"square",Z,Ge,Ye);ot&&wt?Te.appendChild(mf(ot,wt)):ot?Te.appendChild(ot):Te.textContent=Kt}else Te.textContent=Kt;Te.className=`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer ${Kn}`,mr?(Te.style.backgroundColor=mr,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",mr?(Te.style.backgroundColor=mr,Te.classList.remove("persona-bg-persona-accent")):Te.classList.add("persona-bg-persona-accent"),Gs?Te.style.color=Gs:Te.classList.add("persona-text-white");_e.borderWidth?(Te.style.borderWidth=_e.borderWidth,Te.style.borderStyle="solid"):(Te.style.borderWidth="",Te.style.borderStyle=""),_e.borderColor?Te.style.borderColor=_e.borderColor:Te.style.borderColor="",_e.paddingX?(Te.style.paddingLeft=_e.paddingX,Te.style.paddingRight=_e.paddingX):(Te.style.paddingLeft="",Te.style.paddingRight=""),_e.paddingY?(Te.style.paddingTop=_e.paddingY,Te.style.paddingBottom=_e.paddingY):(Te.style.paddingTop="",Te.style.paddingBottom=""),T.isStreaming()||Te.setAttribute("aria-label",gr),$c(),Po&&an({anchor:Te,trigger:Po,text:()=>Te.getAttribute("aria-label")??gr,enabled:mm}),gy(),Qu();let Fv=xp(ve.getState().activeModeIds,o.composer?.modes);ve.setActiveModeIds(Fv),Ci().length>0!==!!Zo&&$u(),Zo?.render(Fv,Ci());for(let Z of[...wi.keys()])wp(Z,o.composer?.modeGroups)||wi.delete(Z);wi.forEach(Z=>Z.repaint()),Hr?.repaint(),Io?.resolve();let xd=ds(o,we());if(Yu(),xd){be.style.maxWidth=xd,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%",Nn.style.maxWidth=xd,Nn.style.marginLeft="auto",Nn.style.marginRight="auto",Nn.style.width="100%";for(let Z of[Mn,Lr,Tn,Je])Z&&(Z.style.maxWidth=xd,Z.style.marginLeft="auto",Z.style.marginRight="auto",Z.style.width="100%")}else{be.style.maxWidth="",be.style.marginLeft="",be.style.marginRight="",be.style.width="",Nn.style.maxWidth="",Nn.style.marginLeft="",Nn.style.marginRight="",Nn.style.width="";for(let Z of[Mn,Lr,Tn,Je])Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight="",Z.style.width="")}let Co=o.statusIndicator??{};if(Lm(Je,Mn,Co),ei(Je,Co,T?.getStatus()??"idle"),T){let Z=T.getStatus();Ra(Je,(Ye=>Ye==="idle"?Co.idleText??_t.idle:Ye==="connecting"?Co.connectingText??_t.connecting:Ye==="connected"?Co.connectedText??_t.connected:Ye==="error"?Co.errorText??_t.error:Ye==="paused"?Co.pausedText??_t.paused:Ye==="resuming"?Co.resumingText??_t.resuming:_t[Ye])(Z),Co,Z)}Je.classList.remove("persona-text-left","persona-text-center","persona-text-right");let BT=Co.align==="left"?"persona-text-left":Co.align==="center"?"persona-text-center":"persona-text-right";Je.classList.add(BT),Fu(),dg(),mo(),Eu()},open(){Be()&&yt(!0,"api")},close(){Be()&&yt(!1,"api")},toggle(){Be()&&yt(!Ee,"api")},reconnect(){T.reconnectNow()},clearChat(){er=!1,a.clear(),r.clear(),s.clear(),l.clear(),T.clearMessages(),o.layout?.topFade&&(ne.scrollTop=0),ne.removeAttribute("data-persona-top-fade"),$t.clear(),kn();try{localStorage.removeItem(ka),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ka}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ka)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),k?.clear&&Hc(()=>k.clear(),"[AgentWidget] Failed to clear storage adapter:"),I={},Ce.syncFromMetadata(),rt?.clearAttachments(),Oc(),xi(void 0),Lo(void 0),ks(),ft?.clear(),Zt?.reset(),ht?.update()},setMessage(i){return!ce||T.isStreaming()||Oo()?!1:(!Ee&&Be()&&yt(!0,"system"),ce.value=i,ce.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(T.isStreaming()||Os())return!1;let c=i?.trim()||ce.value.trim();return c?(!Ee&&Be()&&yt(!0,"system"),ce.value="",ce.style.height="auto",ko(),hd(c,{consumeDraft:!1}),!0):!1},getComposerState(){return ve.getState()},setQuote(i){let c=i?.text?.trim();c&&Lo({...i,text:c})},clearQuote(){Lo(void 0)},startVoiceRecognition(){return T.isStreaming()?!1:vn(o.voiceRecognition?.provider)?(T.isVoiceActive()||T.isBargeInActive()||(!Ee&&Be()&&yt(!0,"system"),Xe.manuallyDeactivated=!1,yo(),T.toggleVoice().then(()=>{Xe.active=T.isVoiceActive(),rr("user"),T.isVoiceActive()&&Qi()})),!0):_o?!0:av()?(!Ee&&Be()&&yt(!0,"system"),Xe.manuallyDeactivated=!1,yo(),bd("user"),!0):!1},stopVoiceRecognition(){return vn(o.voiceRecognition?.provider)?!T.isVoiceActive()&&!T.isBargeInActive()?!1:((T.isBargeInActive()?T.deactivateBargeIn():T.toggleVoice()).then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,yo(),rr("user"),ur()}),!0):_o?(Xe.manuallyDeactivated=!0,yo(),zr("user"),!0):!1},injectMessage(i){return!Ee&&Be()&&yt(!0,"system"),T.injectMessage(i)},injectAssistantMessage(i){!Ee&&Be()&&yt(!0,"system");let c=T.injectAssistantMessage(i);return An&&(An=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),c},injectUserMessage(i){return!Ee&&Be()&&yt(!0,"system"),T.injectUserMessage(i)},injectSystemMessage(i){return!Ee&&Be()&&yt(!0,"system"),T.injectSystemMessage(i)},injectMessageBatch(i){return!Ee&&Be()&&yt(!0,"system"),T.injectMessageBatch(i)},injectComponentDirective(i){return!Ee&&Be()&&yt(!0,"system"),T.injectComponentDirective(i)},injectTestMessage(i){!Ee&&Be()&&yt(!0,"system"),T.injectTestEvent(i)},async connectStream(i,c){return T.connectStream(i,c)},__pushEventStreamEvent(i){X&&(pc(),Mu(i.type,i.payload))},showEventStream(){X&&Nu()},hideEventStream(){go&&Si()},isEventStreamVisible(){return go},listConversations(i){return T.listConversations(i)},getActiveConversationId(){return T.getActiveConversationId()},openConversation(i,c){return zg(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return Kg({focusComposer:i?.focus===!0})},warmSession(){Qg()},deleteConversation(i){return qb(i)},renameConversation(i,c){return Gg(i,{title:c})},setConversationStarred(i,c){return Gg(i,{starred:c})},clearConversationHistory(i){return zb(i)},resetHistoryIdentity(){return Kb()},async getVisitorToken(){let i=Zn;if(!i)return null;let c=await i.get();return i===Zn?c:null},getHistoryIdentityStatus(){return qn?qn.getIdentityStatus():kg()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return cl({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){In(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return Rt},showArtifacts(){Sn(o)&&(er=!1,Mi=!0,ho(),Ke?.setMobileOpen(!0))},hideArtifacts(){Sn(o)&&(er=!0,ho())},upsertArtifact(i){return Sn(o)?(Vo(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(er=!1,Mi=!0),T.upsertArtifact(i)):null},selectArtifact(i){Sn(o)&&T.selectArtifact(i)},clearArtifacts(){Sn(o)&&T.clearArtifacts()},getArtifacts(){return T?.getArtifacts()??[]},getSelectedArtifactId(){return T?.getSelectedArtifactId()??null},focusInput(){return D&&!Ee&&!we()||!ce?!1:(ce.focus(),!0)},async resolveApproval(i,c,g){let b=T.getMessages().find(w=>w.variant==="approval"&&w.approval?.id===i);if(!b?.approval)throw new Error(`Approval not found: ${i}`);if(b.approval.toolType==="webmcp"){T.resolveWebMcpApproval(b.id,c);return}return T.resolveApproval(b.approval,c,g)},setFollowUpSuggestions(i){VM(i)},clearFollowUpSuggestions(){$y()},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...I}},updatePersistentMetadata(i){ye(i)},on(i,c){return oe.on(i,c)},off(i,c){oe.off(i,c)},isOpen(){return Be()&&Ee},isVoiceActive(){return Xe.active},toggleReadAloud(i){T.toggleReadAloud(i)},stopReadAloud(){T.stopSpeaking()},getReadAloudState(i){return T.getReadAloudState(i)},onReadAloudChange(i){return T.onReadAloudChange(i)},getState(){return{open:Be()&&Ee,launcherEnabled:D,voiceActive:Xe.active,streaming:T.isStreaming()}},showCSATFeedback(i){!Ee&&Be()&&yt(!0,"system");let c=be.querySelector(".persona-feedback-container");c&&c.remove();let g=ru({onSubmit:async(f,b)=>{T.isClientTokenMode()&&await T.submitCSATFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});be.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Ee&&Be()&&yt(!0,"system");let c=be.querySelector(".persona-feedback-container");c&&c.remove();let g=su({onSubmit:async(f,b)=>{T.isClientTokenMode()&&await T.submitNPSFeedback(f,b),i?.onSubmit?.(f,b)},onDismiss:i?.onDismiss,...i});be.appendChild(g),g.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,c){return T.submitCSATFeedback(i,c)},async submitNPSFeedback(i,c){return T.submitNPSFeedback(i,c)},destroy(){xg(),_s!=null&&(clearInterval(_s),_s=null),a.clear(),r.clear(),s.clear(),l.clear(),he.forEach(i=>i()),Qe.remove(),en?.remove(),Wt?.destroy(),fn?.remove(),As&&qe.removeEventListener("click",As)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:Ot,getMessages:Ot.getMessages,getStatus:Ot.getStatus,getMetadata:Ot.getPersistentMetadata,updateMetadata:Ot.updatePersistentMetadata,clearHistory:()=>Ot.clearChat(),setVoiceActive:g=>g?Ot.startVoiceRecognition():Ot.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=q=>{let Q=q.detail;(!Q?.instanceId||Q.instanceId===i)&&Ot.focusInput()};if(window.addEventListener("persona:focusInput",c),he.push(()=>{window.removeEventListener("persona:focusInput",c)}),X){let q=ie=>{let me=ie.detail;(!me?.instanceId||me.instanceId===i)&&Ot.showEventStream()},Q=ie=>{let me=ie.detail;(!me?.instanceId||me.instanceId===i)&&Ot.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",Q),he.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",Q)})}let g=q=>{let Q=q.detail;(!Q?.instanceId||Q.instanceId===i)&&Ot.showHistory()},f=q=>{let Q=q.detail;(!Q?.instanceId||Q.instanceId===i)&&Ot.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=q=>{let Q=q.detail;(!Q?.instanceId||Q.instanceId===i)&&Ot.showArtifacts()},w=q=>{let Q=q.detail;(!Q?.instanceId||Q.instanceId===i)&&Ot.hideArtifacts()},W=q=>{let Q=q.detail;Q?.instanceId&&Q.instanceId!==i||Q?.artifact&&Ot.upsertArtifact(Q.artifact)},V=q=>{let Q=q.detail;Q?.instanceId&&Q.instanceId!==i||typeof Q?.id=="string"&&Ot.selectArtifact(Q.id)},F=q=>{let Q=q.detail;(!Q?.instanceId||Q.instanceId===i)&&Ot.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",w),window.addEventListener("persona:upsertArtifact",W),window.addEventListener("persona:selectArtifact",V),window.addEventListener("persona:clearArtifacts",F),he.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",w),window.removeEventListener("persona:upsertArtifact",W),window.removeEventListener("persona:selectArtifact",V),window.removeEventListener("persona:clearArtifacts",F)})}let ro=EI(o.persistState);if(ro&&Be()){let i=TI(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&&(Wt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Ot.open(),setTimeout(()=>{if(w||W)Ot.startVoiceRecognition();else if(ro.persist?.focusInput){let V=e.querySelector("textarea");V&&V.focus()}},100)},0)),ro.persist?.openState&&(oe.on("widget:opened",()=>{i.setItem(c,"true")}),oe.on("widget:closed",()=>{i.setItem(c,"false")})),ro.persist?.voiceState&&(oe.on("voice:state",V=>{i.setItem(g,V.active?"true":"false")}),oe.on("user:message",V=>{i.setItem(f,V.viaVoice?"true":"false")})),ro.clearOnChatClear){let V=()=>{i.removeItem(c),i.removeItem(g),i.removeItem(f)},F=()=>V();window.addEventListener("persona:clear-chat",F),he.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}if(ge&&Be()&&(Wt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Ot.open()},0)),Oi(),!qM){let i=Ji(()=>{T&&(Ls++,$t.clear(),Jn(be,T.getMessages(),N))});he.push(i)}B=()=>{T&&(Ls++,$t.clear(),Jn(be,T.getMessages(),N))},T.getMessages().length>0&&Fc(),K=()=>{T&&(Ls++,$t.clear(),Jn(be,T.getMessages(),N))};let WT=Xv(()=>{T&&(Ls++,$t.clear(),Jn(be,T.getMessages(),N))});he.push(WT);let OT=gh(()=>{T&&(Ls++,$t.clear(),Jn(be,T.getMessages(),N),Ar()?.updateInlineArtifactBlocks(be,Xn.artifacts,{suppressTransition:!0}),ho())});return he.push(OT),Ot};var EA=(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},LI=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},II=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},RI=(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.")},TA=(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"},Lh=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=""},PA=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Lh(e)},Th=e=>{e.style.transition=""},Ph=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=""},kh=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},lu=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},HI=(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))},WI=(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)},OI=e=>{let t=Mo(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:cn(t,r)??r;return{inset:o(n?.inset,Ep),canvasBackground:o(n?.canvasBackground,Tp)}},kA=(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},BI=(e,t,n,o,r,s,a,l)=>{let d=Bn(s),u=d.reveal==="push",p=l!=null,m=l?.inset??"",h=l?.canvasBackground??"";HI(e,t,n,o,u),WI(e,t,n,o,d.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=d.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let y=e.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,x=y!=null?y.innerWidth<=C:!1;if(v&&x&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ph(t),Th(o),PA(o),kh(n),lu(r,o),kA(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??pn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",u&&(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"),PA(o),LI(o,d.maxHeight),kA(o,p&&a,m,h),d.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ph(t),Th(o),kh(n),lu(r,o);let H=d.animate?"transform 180ms ease":"none",B=d.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":B;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=H,o.style.transform=A,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Th(o),Lh(o),lu(r,o);let H=EA(d.width,e.clientWidth),B=Math.max(0,e.clientWidth),A=d.animate?"margin-left 180ms ease":"none",O=d.side==="right"?a?-H:0:a?0:-H;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${B+H}px`,t.style.transition=A,t.style.marginLeft=`${O}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${B}px`,n.style.maxWidth=`${B}px`,n.style.minWidth=`${B}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Ph(t),Lh(o),kh(n),lu(r,o);let H=d.reveal==="emerge";H?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let B=a?d.width:"0px",A=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",O=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${B}`,o.style.width=B,o.style.maxWidth=B,o.style.minWidth=B,o.style.minHeight="0",II(o,d.maxHeight),o.style.overflow=H||O?"hidden":"visible",o.style.transition=A,H){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let L=p?`calc(${EA(d.width,e.clientWidth)}px - (2 * ${m}))`:d.width;r.style.width=L,r.style.minWidth=L,r.style.maxWidth=L,r.style.boxSizing="border-box"}}},DI=(e,t)=>{let n=e.ownerDocument.createElement("div");return TA(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){TA(n,o)},destroy(){n.remove()}}},_I=(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"),u=n.createElement("aside"),p=n.createElement("div"),m=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",u.appendChild(p),o.insertBefore(a,e),d.appendChild(e);let h=null,y=()=>{h?.disconnect(),h=null},v=null,C=()=>{v=t?.launcher?.detachedPanel===!0?OI(t):null};C();let x=()=>{BI(a,l,d,u,p,t,m,v)},E=null,H=()=>{E?.(),E=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(E=ya(()=>{C(),x()}))},B=()=>{y(),Bn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{x()}),h.observe(a)))},A=!1,O=()=>{x(),B(),m&&!A&&a.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,RI(a,Bn(t)))},L=a.ownerDocument.defaultView,$=()=>{O()};return L?.addEventListener("resize",$),Bn(t).reveal==="push"?(l.appendChild(d),l.appendChild(u),a.appendChild(l)):(a.appendChild(d),a.appendChild(u)),O(),H(),{mode:"docked",host:p,shell:a,syncWidgetState(K){let ae=K.launcherEnabled?K.open:!0;m!==ae&&(m=ae,O())},updateConfig(K){t=K,(t?.launcher?.enabled??!0)===!1&&(m=!0),C(),O(),H()},destroy(){L?.removeEventListener("resize",$),E?.(),E=null,y(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},lc=(e,t)=>Ct(t)?_I(e,t):DI(e,t);var NI=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},LA=(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)},cu=[],IA=()=>[...cu],Ih=e=>{let t=NI(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=lc(t,r),a,l=[],d=(x,E)=>{let B=!(E?.launcher?.enabled??!0)||Ct(E),A=o.createElement("div");if(A.setAttribute("data-persona-root","true"),B&&(A.style.height="100%",A.style.display="flex",A.style.flexDirection="column",A.style.flex="1",A.style.minHeight="0",A.style.minWidth="0"),n){let O=x.attachShadow({mode:"open"});O.appendChild(A),LA(O,o)}else x.appendChild(A),LA(x,o);return t.id&&A.setAttribute("data-persona-instance",t.id),A},u=()=>{s.syncWidgetState(a.getState())},p=()=>{l.forEach(x=>x()),l=[a.on("widget:opened",u),a.on("widget:closed",u)],u()},m=()=>{let x=d(s.host,r);a=au(x,r,{debugTools:e.debugTools}),p()},h=()=>{l.forEach(x=>x()),l=[],a.destroy()};m(),e.onChatReady?.();let y=x=>{h(),s.destroy(),s=lc(t,x),r=x,m()},v={update(x){let E=Jp(r??{},x),H=Ct(r),B=Ct(E),A=us(r),O=us(E);if(H!==B||A!==O){y(E);return}r=E,s.updateConfig(r),a.update(x),u()},destroy(){h(),s.destroy();let x=cu.indexOf(C);x!==-1&&cu.splice(x,1),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(v,{get(x,E,H){if(E==="host")return s.host;if(E in x)return Reflect.get(x,E,H);let B=a[E];return typeof B=="function"?B.bind(a):B}});return cu.push(C),e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};var BA=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),FI=new Set(["button","a","input","select","textarea","details","summary"]),$I=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Rh=/\b(product|card|item|listing|result)\b/i,Wh=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,UI=3e3,jI=100;function DA(e){let t=typeof e.className=="string"?e.className:"";if(Rh.test(t)||e.id&&Rh.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Rh.test(o.value))return!0}return!1}function _A(e){return Wh.test((e.textContent??"").trim())}function NA(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 VI(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function RA(e){let t=e.match(Wh);return t?t[0]:null}function HA(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 qI(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 zI="commerce-card",KI="result-card";function WA(e){return!DA(e)||!_A(e)||!NA(e)&&!VI(e)?0:5200}function OA(e){return!DA(e)||_A(e)||!NA(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Oh=[{id:zI,scoreElement(e){return WA(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||Wh.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(WA(e)===0)return null;let{title:n,href:o}=HA(e),r=RA((e.textContent??"").trim())??RA(t.text)??"",s=qI(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
139
|
+
`)}},{id:KI,scoreElement(e){return OA(e)},formatSummary(e,t){if(OA(e)===0)return null;let{title:n,href:o}=HA(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
140
|
+
`)}}];function GI(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function YI(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,l=t.mode??"structured",d=t.maxCandidates??Math.max(500,n*10),u=e.rules??Oh;return l==="simple"&&e.rules&&e.rules.length>0?(GI(),u=[]):l==="simple"&&(u=[]),{mode:l,maxElements:n,maxCandidates:d,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:u}}function Hh(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var QI=["data-testid","data-product","data-action","data-id","data-name","data-type"];function XI(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"||FI.has(t)||n&&$I.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function FA(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 JI(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 u=0;u<e.attributes.length;u++){let p=e.attributes[u];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Bh(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Hh(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of QI){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${Hh(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=>Hh(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 ZI(e){return e==="static"?jI:UI}function $A(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Bh(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:XI(e),attributes:JI(e)}}function eR(e,t,n,o){let r=ZI(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 tR(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 nR(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 u=l,p=u.tagName.toLowerCase();if(BA.has(p)){l=a.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){l=a.nextNode();continue}}catch{}if(e.visibleOnly&&!FA(u)){l=a.nextNode();continue}let m=$A(u,e.maxTextLength),h=m.text.length>0,y=Object.keys(m.attributes).length>0&&!Object.keys(m.attributes).every(x=>x==="role");if(!h&&!y){l=a.nextNode();continue}if(o.has(m.selector)){l=a.nextNode();continue}o.add(m.selector);let{score:v,formattingRule:C}=eR(u,m,e.rules,n);r.push({el:u,domIndex:s,enriched:m,score:v,formattingRule:C}),s+=1}l=a.nextNode()}r.sort((u,p)=>{let m=u.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return m!==h?m-h:p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex});let d=[];for(let u of r){if(d.length>=e.maxElements)break;tR(d,u)||d.push(u)}return d.sort((u,p)=>{let m=u.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return m!==h?m-h:m===1&&p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex}),d.map(u=>{let p;if(u.formattingRule?.formatSummary){let h=u.formattingRule.formatSummary(u.el,u.enriched,n);h&&(p=h)}let m={...u.enriched};return p&&(m.formattedSummary=p),m})}function oR(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,u=d.tagName.toLowerCase();if(BA.has(u)){s=r.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!FA(d)){s=r.nextNode();continue}let p=$A(d,e.maxTextLength),m=p.text.length>0,h=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(y=>y==="role");if(!m&&!h){s=r.nextNode();continue}o.has(p.selector)||(o.add(p.selector),n.push(p))}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 UA(e={}){let t=YI(e),n=t.root??document.body;return n?t.mode==="simple"?oR(t,n):nR(t,n):[]}var du=100;function jA(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:
|
|
141
141
|
${s.map(a=>`- ${a.split(`
|
|
142
142
|
`).join(`
|
|
143
143
|
`)}`).join(`
|
|
@@ -151,7 +151,7 @@ ${s.join(`
|
|
|
151
151
|
${s.join(`
|
|
152
152
|
`)}`)}return o.join(`
|
|
153
153
|
|
|
154
|
-
`)}var
|
|
154
|
+
`)}var rR={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"}}},VA={components:{panel:{borderRadius:"0",shadow:"none"}}},Dh={id:"shop",label:"Shopping Assistant",config:{theme:rR,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Js},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"]}},_h={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:VA}},Nh={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:VA}},Fh={shop:Dh,minimal:_h,fullscreen:Nh};function qA(e){return Fh[e]}var zA=Ih;function KA(){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 GA(){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 YA(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:Qo(e.colors.primary,.95),100:Qo(e.colors.primary,.9),200:Qo(e.colors.primary,.8),300:Qo(e.colors.primary,.7),400:Qo(e.colors.primary,.6),500:e.colors.primary,600:Qo(e.colors.primary,.8),700:Qo(e.colors.primary,.7),800:Qo(e.colors.primary,.6),900:Qo(e.colors.primary,.5),950:Qo(e.colors.primary,.45)}}),{...t,palette:n}}}}function QA(){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 XA(){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 Qo(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 JA(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}function $h(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@${So}/dist`}function Pr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function sR(e){if(e)return{getHeaders:Pr(e.getHeaders),onFeedback:Pr(e.onFeedback),onCopy:Pr(e.onCopy),requestMiddleware:Pr(e.requestMiddleware),actionHandlers:Pr(e.actionHandlers),actionParsers:Pr(e.actionParsers),postprocessMessage:Pr(e.postprocessMessage),contextProviders:Pr(e.contextProviders),streamParser:Pr(e.streamParser)}}var ZA=`({ text, message }: any) => {
|
|
155
155
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
156
156
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
157
157
|
let cleanJson = jsonSource
|
|
@@ -164,7 +164,7 @@ ${s.join(`
|
|
|
164
164
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
165
165
|
} catch (e) { return null; }
|
|
166
166
|
return null;
|
|
167
|
-
}`,
|
|
167
|
+
}`,eM=`function(ctx) {
|
|
168
168
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
169
169
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
170
170
|
var cleanJson = jsonSource
|
|
@@ -177,7 +177,7 @@ ${s.join(`
|
|
|
177
177
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
178
178
|
} catch (e) { return null; }
|
|
179
179
|
return null;
|
|
180
|
-
}`,
|
|
180
|
+
}`,tM=`(action: any, context: any) => {
|
|
181
181
|
if (action.type !== 'nav_then_click') return;
|
|
182
182
|
const payload = action.payload || action.raw || {};
|
|
183
183
|
const url = payload?.page;
|
|
@@ -194,7 +194,7 @@ ${s.join(`
|
|
|
194
194
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
195
195
|
window.location.href = targetUrl;
|
|
196
196
|
return { handled: true, displayText: text };
|
|
197
|
-
}`,
|
|
197
|
+
}`,nM=`function(action, context) {
|
|
198
198
|
if (action.type !== 'nav_then_click') return;
|
|
199
199
|
var payload = action.payload || action.raw || {};
|
|
200
200
|
var url = payload.page;
|
|
@@ -211,27 +211,27 @@ ${s.join(`
|
|
|
211
211
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
212
212
|
window.location.href = targetUrl;
|
|
213
213
|
return { handled: true, displayText: text };
|
|
214
|
-
}`,
|
|
214
|
+
}`,iR=`(parsed: any) => {
|
|
215
215
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
216
216
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
217
217
|
if (parsed.action === 'message') return parsed.text || '';
|
|
218
218
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
219
219
|
return parsed.text || null;
|
|
220
|
-
}`,
|
|
220
|
+
}`,aR=`function(parsed) {
|
|
221
221
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
222
222
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
223
223
|
if (parsed.action === 'message') return parsed.text || '';
|
|
224
224
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
225
225
|
return parsed.text || null;
|
|
226
|
-
}`;function
|
|
227
|
-
`);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,a=r===n.length-1?",":"";return`${s}${o}${a}`})}function hu(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,
|
|
228
|
-
`)}function
|
|
229
|
-
`)}function tR(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: '${cc(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}",`),yu(o,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ms(o,"theme",e.theme," "),e.launcher&&ms(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(...fu(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(...uu(e," ")),o.push(...gu(e," ",n)),o.push(...mu(e," ")),o.push(...hu(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(${QI}),`)),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(` ${VA}`),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(` ${VA}`),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(` ${zA}`),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(` ${zA}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
|
|
230
|
-
`)}function
|
|
231
|
-
`)}function
|
|
226
|
+
}`;function lR(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 pu(e){return e.parserType??lR(e.streamParser)??"plain"}function uu(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 gu(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 mu(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 fu(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
|
|
227
|
+
`);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,a=r===n.length-1?",":"";return`${s}${o}${a}`})}function hu(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,u])=>{d!=="format"&&(typeof u=="string"?n.push(`${t} ${d}: "${u}",`):typeof u=="boolean"&&n.push(`${t} ${d}: ${u},`))}),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 Uh(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 oM(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}: {`),oM(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function ms(e,t,n,o){n&&(e.push(`${o}${t}: {`),oM(e,n,`${o} `),e.push(`${o}},`))}function yu(e,t,n){t.future?.v5Defaults!==void 0&&e.push(`${n}future: { v5Defaults: ${t.future.v5Defaults===!0} },`)}function cc(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function rM(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:sR(n.hooks)}:void 0;return t==="esm"?cR(o,r):t==="script-installer"?uR(o,r):t==="script-advanced"?mR(o,r):t==="react-component"?dR(o,r):t==="react-advanced"?pR(o,r):gR(o,r)}function cR(e,t){let n=t?.hooks,o=pu(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${cc(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}",`),yu(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ms(s,"theme",e.theme," "),e.launcher&&ms(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(...fu(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(...uu(e," ")),s.push(...gu(e," ",n)),s.push(...mu(e," ")),s.push(...hu(e," ")),s.push(...Uh(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
|
|
228
|
+
`)}function dR(e,t){let n=t?.hooks,o=pu(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: '${cc(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}",`),yu(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ms(s,"theme",e.theme," "),e.launcher&&ms(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(...fu(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(...uu(e," ")),s.push(...gu(e," ",n)),s.push(...mu(e," ")),s.push(...hu(e," ")),s.push(...Uh(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
|
|
229
|
+
`)}function pR(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: '${cc(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}",`),yu(o,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ms(o,"theme",e.theme," "),e.launcher&&ms(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(...fu(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(...uu(e," ")),o.push(...gu(e," ",n)),o.push(...mu(e," ")),o.push(...hu(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(${iR}),`)),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(` ${ZA}`),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(` ${ZA}`),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(` ${tM}`),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(` ${tM}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
|
|
230
|
+
`)}function sM(e){let t=pu(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.future?.v5Defaults!==void 0&&(o.future={v5Defaults:e.future.v5Defaults===!0}),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestions&&(o.suggestions=e.suggestions),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&(r[s]=a)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,a])=>{s!=="onFeedback"&&s!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(r[s]=a)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([a,l])=>{a!=="render"&&(typeof l=="string"||typeof l=="boolean")&&(s[a]=l)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([a,l])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof l=="object"&&l!==null)s.avatar=l;else if(a==="timestamp"&&typeof l=="object"&&l!==null){let d={};Object.entries(l).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(d[u]=p)}),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 uR(e,t){let n=sM(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="${$h(t)}/install.global.js" data-config='${s}'></script>`}function gR(e,t){let n=t?.hooks,o=pu(e),r=o!=="plain",s=$h(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: '${cc(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}",`),yu(a,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ms(a,"theme",e.theme," "),e.launcher&&ms(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(...fu(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(...uu(e," ")),a.push(...gu(e," ",n)),a.push(...mu(e," ")),a.push(...hu(e," ")),a.push(...Uh(n," ")),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),a.push(" }"),a.push(" });"),a.push("</script>"),a.join(`
|
|
231
|
+
`)}function mR(e,t){let n=t?.hooks,o=sM(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
|
|
232
232
|
`).map((a,l)=>l===0?a:" "+a).join(`
|
|
233
|
-
`)};`,""," // Constants",` var CDN_BASE = '${
|
|
234
|
-
`)}var
|
|
233
|
+
`)};`,""," // Constants",` var CDN_BASE = '${$h(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(${aR});`),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(` ${eM}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${eM}`),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(` ${nM}`),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(` ${nM}`),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: '${cc(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
|
|
234
|
+
`)}var pM=require("lucide");var iM={desktop:{w:1280,h:800},mobile:{w:390,h:844}},aM=.1,lM=.15,cM=1.5,jh=24,dM=40,fR=`
|
|
235
235
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
236
236
|
.persona-dc-root {
|
|
237
237
|
display: flex;
|
|
@@ -382,7 +382,7 @@ ${s.join(`
|
|
|
382
382
|
.persona-dc-stage {
|
|
383
383
|
height: 550px;
|
|
384
384
|
min-height: 400px;
|
|
385
|
-
padding: ${
|
|
385
|
+
padding: ${jh}px;
|
|
386
386
|
overflow: auto;
|
|
387
387
|
background: #f0f1f3;
|
|
388
388
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -472,10 +472,10 @@ ${s.join(`
|
|
|
472
472
|
min-height: 300px;
|
|
473
473
|
}
|
|
474
474
|
}
|
|
475
|
-
`;function iR(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=sR,document.head.appendChild(e)}function aR(e,t){let n=e.clientWidth-$h*2-tM,o=e.clientHeight-$h*2-tM;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function lR(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 oM(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");iR();let u=Math.max(0,Math.min(o,n.length-1)),m=r,h=s,y=null,v=1,C=!1,x=S("div","persona-dc-root"),E=S("div","persona-dc-toolbar"),H=S("div","persona-dc-toolbar-lead"),B=S("div","persona-dc-toolbar-trail"),A=Dn({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ne(-1)}),O=S("div");O.style.position="relative";let L=S("button","persona-dc-title-btn");L.type="button",L.setAttribute("aria-expanded","false"),L.setAttribute("aria-haspopup","listbox");let $=S("span","persona-dc-title-text"),K=S("span","persona-dc-title-chevron"),ae=Mt(nM.ChevronDown,12,"currentColor",2);ae&&K.appendChild(ae),L.append($,K);let oe=S("div","persona-dc-dropdown");oe.setAttribute("role","listbox"),oe.style.display="none";let P=!1;function k(){oe.innerHTML="";for(let ke=0;ke<n.length;ke++){let we=n[ke],Be=S("button","persona-dc-dropdown-item");Be.type="button",Be.setAttribute("role","option"),Be.setAttribute("aria-current",ke===u?"true":"false");let Ee=S("span");if(Ee.textContent=we.title,Be.appendChild(Ee),we.description){let Sn=S("span","persona-dc-dropdown-desc");Sn.textContent=we.description,Be.appendChild(Sn)}Be.addEventListener("click",()=>{I(),Fe(ke)}),oe.appendChild(Be)}}function _(){P=!P,oe.style.display=P?"":"none",L.setAttribute("aria-expanded",P?"true":"false"),P&&k()}function I(){P&&(P=!1,oe.style.display="none",L.setAttribute("aria-expanded","false"))}L.addEventListener("click",ke=>{ke.stopPropagation(),_()});let te=()=>I();document.addEventListener("click",te),O.append(L,oe);let U=Dn({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ne(1)}),pe=S("span","persona-dc-counter");H.append(A,O,U,pe);let ue=null;l&&(ue=Zl({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:ke=>{m=ke,dt.dataset.device=m,y=null,Et()}}),B.appendChild(ue.element));let ge=null;if(a){let ke=S("div","persona-dc-zoom-controls"),we=Dn({icon:"minus",label:"Zoom out",size:14,onClick:()=>{y=Math.max(ZA,(y??v)-JA),Et()}});ge=S("span","persona-dc-zoom-level"),ge.title="Reset to 100%",ge.style.cursor="pointer",ge.addEventListener("click",()=>{y=1,Et()});let Be=Dn({icon:"plus",label:"Zoom in",size:14,onClick:()=>{y=Math.min(eM,(y??v)+JA),Et()}}),Ee=Dn({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{y=null,Et()}});ke.append(we,ge,Be,Ee),B.appendChild(ke)}if(d){let ke=S("div","persona-dc-separator");B.appendChild(ke);let we=Zl({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:h,onSelect:Be=>{h=Be,dt.dataset.colorScheme=h,Ce()}});B.appendChild(we.element)}let Ie=S("div","persona-dc-separator");B.appendChild(Ie);let Se=Dn({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[u].url,"_blank")}});B.appendChild(Se),E.append(H,B);let ye=S("div","persona-dc-stage"),dt=S("div","persona-dc-iframe-wrapper");dt.dataset.device=m,dt.dataset.colorScheme=h;let it=S("iframe","persona-dc-iframe");it.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),it.setAttribute("loading","lazy"),it.title=n[u].title,dt.appendChild(it),ye.appendChild(dt),x.append(E,ye),e.appendChild(x);function Ce(){try{let ke=it.contentDocument?.body;if(!ke)return;h==="dark"?ke.classList.add("theme-dark"):ke.classList.remove("theme-dark")}catch{}}it.addEventListener("load",()=>Ce());function D(){let ke=n[u];$.textContent=ke.title,pe.textContent=`${u+1} / ${n.length}`,it.title=ke.title}function Ne(ke){let we=((u+ke)%n.length+n.length)%n.length;Fe(we)}function Fe(ke){ke<0||ke>=n.length||(u=ke,it.src=n[u].url,D(),p?.(u,n[u]))}function Et(){if(C)return;let ke=XA[m]??XA.desktop;v=aR(ye,ke);let we=Math.max(ZA,Math.min(eM,y??v));lR(dt,it,ke,we,m),ge&&(ge.textContent=`${Math.round(we*100)}%`)}let Gt=new ResizeObserver(()=>Et());Gt.observe(ye),D(),it.src=n[u].url,requestAnimationFrame(()=>Et());function jt(){C||(C=!0,Gt.disconnect(),document.removeEventListener("click",te),x.remove())}return{element:x,goTo:Fe,next:()=>Ne(1),prev:()=>Ne(-1),getIndex:()=>u,setDevice(ke){m=ke,dt.dataset.device=ke,ue?.setSelected(ke),y=null,Et()},setColorScheme(ke){h=ke,dt.dataset.colorScheme=ke},setZoom(ke){y=ke,Et()},destroy:jt}}ef();var rM=16e3,cR=24e3,dR=4096,pR=4,uR=1380533830;function gR(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===uR?new Uint8Array(e,44):new Uint8Array(e)}function mR(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 dc=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:rM,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:rM});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ga(cR);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=`${mR(o)}/ws/agents/${encodeURIComponent(t)}/voice`,u=new WebSocket(p,["runtype.bearer",n]);u.binaryType="arraybuffer",this.ws=u,u.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,u,r))},u.onmessage=m=>this.handleMessage(m,r),u.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},u.onclose=m=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(m.code!==1e3){let h=m.code?` (code ${m.code})`:"";this.emitError(new Error(`Voice connection closed${h}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}onLevel(t){this.levelCallbacks.push(t)}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(dR,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),p=new Int16Array(d.length),u=0;for(let m=0;m<d.length;m++){let h=Math.max(-1,Math.min(1,d[m]));u+=h*h,p[m]=h<0?h*32768:h*32767}if(o.send(p.buffer),this.levelCallbacks.length>0){let m=Math.sqrt(u/d.length),h=Math.max(0,Math.min(1,m*pR));for(let y of this.levelCallbacks)y(h)}},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=gR(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 bi=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 Ia(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new dc(e.runtype);case"browser":if(!bi.isSupported())throw new Error("Browser speech recognition not supported");return new bi(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 bu(e){if(e?.type==="custom"&&e.custom)return Ia({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Ia({type:"runtype",runtype:e.runtype});if(bi.isSupported())return Ia({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Uh(e){try{return bu(e),!0}catch{return!1}}var sM="webmcp:",fR=e=>e.startsWith(sM)?e.slice(sM.length):e,vu={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},wu=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 vu.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.deps.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s=yR(r.annotations);return{name:r.name,description:r.description,parametersSchema:bR(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 To("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let v=typeof document<"u"&&!!document.modelContext;return To(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=fR(t),a;try{a=await r.getTools()}catch(v){let C=v instanceof Error?v.message:String(v);return To(`Failed to read WebMCP registry: ${C}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(v=>v.name===s);if(!l)return To(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return To(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return To("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 To("User declined the tool call.");if(o?.aborted)return To("Aborted by cancel()");let u=new AbortController,m=!1,h=setTimeout(()=>{m=!0,u.abort()},this.timeoutMs),y=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",y,{once:!0}));try{let v=await r.executeTool(l,xR(n),{signal:u.signal});return vR(v)}catch(v){if(m)return To(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return To("Aborted by cancel()");let C=v instanceof Error?v.message:String(v);return To(C)}finally{clearTimeout(h),o&&o.removeEventListener("abort",y)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(await this.deps.loadPolyfill()).initializeWebMCPPolyfill(),this.installed=!0}catch(t){vu.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,vu.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??CR;try{return await n(t)}catch(o){return vu.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=>hR(t,o))}},hR=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Cu={type:"object",properties:{}},yR=e=>{if(!e||typeof e!="object")return;let t={...typeof e.readOnlyHint=="boolean"?{readOnlyHint:e.readOnlyHint}:{},...typeof e.untrustedContentHint=="boolean"?{untrustedContentHint:e.untrustedContentHint}:{}};return Object.keys(t).length>0?t:void 0},bR=e=>{if(e===void 0||e==="")return{...Cu};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Cu};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Cu}}catch{return{...Cu}}},vR=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:SR(t)}]}},To=e=>({isError:!0,content:[{type:"text",text:e}]}),CR=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=wR(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
475
|
+
`;function hR(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=fR,document.head.appendChild(e)}function yR(e,t){let n=e.clientWidth-jh*2-dM,o=e.clientHeight-jh*2-dM;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function bR(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 uM(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:l=!0,showColorSchemeToggle:d=!0,onChange:u}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");hR();let p=Math.max(0,Math.min(o,n.length-1)),m=r,h=s,y=null,v=1,C=!1,x=S("div","persona-dc-root"),E=S("div","persona-dc-toolbar"),H=S("div","persona-dc-toolbar-lead"),B=S("div","persona-dc-toolbar-trail"),A=Dn({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Ne(-1)}),O=S("div");O.style.position="relative";let L=S("button","persona-dc-title-btn");L.type="button",L.setAttribute("aria-expanded","false"),L.setAttribute("aria-haspopup","listbox");let $=S("span","persona-dc-title-text"),K=S("span","persona-dc-title-chevron"),ae=Mt(pM.ChevronDown,12,"currentColor",2);ae&&K.appendChild(ae),L.append($,K);let oe=S("div","persona-dc-dropdown");oe.setAttribute("role","listbox"),oe.style.display="none";let P=!1;function k(){oe.innerHTML="";for(let ke=0;ke<n.length;ke++){let we=n[ke],Be=S("button","persona-dc-dropdown-item");Be.type="button",Be.setAttribute("role","option"),Be.setAttribute("aria-current",ke===p?"true":"false");let Ee=S("span");if(Ee.textContent=we.title,Be.appendChild(Ee),we.description){let An=S("span","persona-dc-dropdown-desc");An.textContent=we.description,Be.appendChild(An)}Be.addEventListener("click",()=>{I(),Fe(ke)}),oe.appendChild(Be)}}function _(){P=!P,oe.style.display=P?"":"none",L.setAttribute("aria-expanded",P?"true":"false"),P&&k()}function I(){P&&(P=!1,oe.style.display="none",L.setAttribute("aria-expanded","false"))}L.addEventListener("click",ke=>{ke.stopPropagation(),_()});let te=()=>I();document.addEventListener("click",te),O.append(L,oe);let U=Dn({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Ne(1)}),pe=S("span","persona-dc-counter");H.append(A,O,U,pe);let ue=null;l&&(ue=Zl({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:m,onSelect:ke=>{m=ke,dt.dataset.device=m,y=null,Et()}}),B.appendChild(ue.element));let ge=null;if(a){let ke=S("div","persona-dc-zoom-controls"),we=Dn({icon:"minus",label:"Zoom out",size:14,onClick:()=>{y=Math.max(lM,(y??v)-aM),Et()}});ge=S("span","persona-dc-zoom-level"),ge.title="Reset to 100%",ge.style.cursor="pointer",ge.addEventListener("click",()=>{y=1,Et()});let Be=Dn({icon:"plus",label:"Zoom in",size:14,onClick:()=>{y=Math.min(cM,(y??v)+aM),Et()}}),Ee=Dn({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{y=null,Et()}});ke.append(we,ge,Be,Ee),B.appendChild(ke)}if(d){let ke=S("div","persona-dc-separator");B.appendChild(ke);let we=Zl({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:h,onSelect:Be=>{h=Be,dt.dataset.colorScheme=h,Ce()}});B.appendChild(we.element)}let Ie=S("div","persona-dc-separator");B.appendChild(Ie);let Se=Dn({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});B.appendChild(Se),E.append(H,B);let ye=S("div","persona-dc-stage"),dt=S("div","persona-dc-iframe-wrapper");dt.dataset.device=m,dt.dataset.colorScheme=h;let it=S("iframe","persona-dc-iframe");it.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),it.setAttribute("loading","lazy"),it.title=n[p].title,dt.appendChild(it),ye.appendChild(dt),x.append(E,ye),e.appendChild(x);function Ce(){try{let ke=it.contentDocument?.body;if(!ke)return;h==="dark"?ke.classList.add("theme-dark"):ke.classList.remove("theme-dark")}catch{}}it.addEventListener("load",()=>Ce());function D(){let ke=n[p];$.textContent=ke.title,pe.textContent=`${p+1} / ${n.length}`,it.title=ke.title}function Ne(ke){let we=((p+ke)%n.length+n.length)%n.length;Fe(we)}function Fe(ke){ke<0||ke>=n.length||(p=ke,it.src=n[p].url,D(),u?.(p,n[p]))}function Et(){if(C)return;let ke=iM[m]??iM.desktop;v=yR(ye,ke);let we=Math.max(lM,Math.min(cM,y??v));bR(dt,it,ke,we,m),ge&&(ge.textContent=`${Math.round(we*100)}%`)}let Gt=new ResizeObserver(()=>Et());Gt.observe(ye),D(),it.src=n[p].url,requestAnimationFrame(()=>Et());function jt(){C||(C=!0,Gt.disconnect(),document.removeEventListener("click",te),x.remove())}return{element:x,goTo:Fe,next:()=>Ne(1),prev:()=>Ne(-1),getIndex:()=>p,setDevice(ke){m=ke,dt.dataset.device=ke,ue?.setSelected(ke),y=null,Et()},setColorScheme(ke){h=ke,dt.dataset.colorScheme=ke},setZoom(ke){y=ke,Et()},destroy:jt}}nf();var gM=16e3,vR=24e3,CR=4096,wR=4,xR=1380533830,SR=3e4,AR=5e3,MR=3e4,ER=3e4,TR=6e5;function PR(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===xR?new Uint8Array(e,44):new Uint8Array(e)}function mM(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}`}function kR(e){return mM(e).replace(/^ws/i,"http")}function LR(e){return typeof e!="number"||!Number.isFinite(e)?MR:Math.min(TR,Math.max(ER,Math.round(e)))}var dc=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.lastPrewarmAt=Number.NEGATIVE_INFINITY;this.attached=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}prewarm(){if(this.callLive||this.attached)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t||!n||!o)return;let r=Date.now();if(!(r-this.lastPrewarmAt<SR)){this.lastPrewarmAt=r;try{this.config?.prewarmMode==="attach"?this.attach(o,t,n):this.requestPrewarm(o,t,n)}catch{}}}requestPrewarm(t,n,o){if(typeof fetch!="function")return;let r=`${kR(t)}/v1/client/agents/${encodeURIComponent(n)}/voice/prewarm`;fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`},keepalive:!0}).catch(()=>{})}attach(t,n,o){let r=new URLSearchParams({clientCapabilities:"attach"}),s=this.config?.attachIdleMs,a=LR(s);s!==void 0&&r.set("attachIdleMs",String(a));let l=new WebSocket(`${this.voiceSocketUrl(t,n)}?${r}`,["runtype.bearer","runtype.attach",o]);l.binaryType="arraybuffer";let d=()=>{},u=new Promise(m=>{d=m}),p={ws:l,state:"connecting",ready:u,settle:d,openedAt:0,idleTimer:void 0};this.attached=p,l.onopen=()=>{this.attached===p&&(p.state=l.protocol==="runtype.attach"?"attached":"live",p.openedAt=Date.now(),this.armAttachIdle(p,a),p.state==="attached"&&l.send('{"type":"ping"}'),p.settle())},l.onmessage=m=>{if(this.attached!==p||typeof m.data!="string")return;let h;try{h=JSON.parse(m.data)}catch{return}h.type==="attached"&&typeof h.idleMs=="number"&&this.armAttachIdle(p,h.idleMs-(Date.now()-p.openedAt))},l.onerror=()=>{},l.onclose=()=>{this.attached===p&&this.releaseAttached()}}armAttachIdle(t,n){clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.attached===t&&this.releaseAttached()},Math.max(0,n))}releaseAttached(){let t=this.attached;if(!t)return;this.attached=null,clearTimeout(t.idleTimer);let{ws:n}=t;if(n.onopen=null,n.onmessage=null,n.onerror=null,n.onclose=null,t.settle(),n.readyState===WebSocket.CONNECTING||n.readyState===WebSocket.OPEN)try{n.close(1e3,"prewarm released")}catch{}}async takeAttachedSocket(){let t=this.attached;if(!t)return null;if(t.state==="connecting"){let n;await Promise.race([t.ready,new Promise(o=>{n=setTimeout(o,AR)})]),clearTimeout(n)}return this.attached!==t?null:t.state==="connecting"||t.ws.readyState!==WebSocket.OPEN?(this.releaseAttached(),null):(this.attached=null,clearTimeout(t.idleTimer),{ws:t.ws,live:t.state==="live"})}voiceSocketUrl(t,n){return`${mM(t)}/ws/agents/${encodeURIComponent(n)}/voice`}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:gM,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:gM});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ga(vR);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 u=await this.takeAttachedSocket();if(r!==this.callGeneration){u?.ws.close(1e3,"client ended call");return}if(u){let{ws:m}=u;this.ws=m,this.bindCallSocket(m,r),u.live||m.send('{"type":"start"}'),this.emitStatus("listening"),this.startCapture(l,s,m,r);return}let p=new WebSocket(this.voiceSocketUrl(o,t),["runtype.bearer",n]);p.binaryType="arraybuffer",this.ws=p,p.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,p,r))},this.bindCallSocket(p,r)}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}bindCallSocket(t,n){t.onmessage=o=>this.handleMessage(o,n),t.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},t.onclose=o=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(o.code!==1e3){let r=o.code?` (code ${o.code})`:"";this.emitError(new Error(`Voice connection closed${r}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}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(CR,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),u=new Int16Array(d.length),p=0;for(let m=0;m<d.length;m++){let h=Math.max(-1,Math.min(1,d[m]));p+=h*h,u[m]=h<0?h*32768:h*32767}if(o.send(u.buffer),this.levelCallbacks.length>0){let m=Math.sqrt(p/d.length),h=Math.max(0,Math.min(1,m*wR));for(let y of this.levelCallbacks)y(h)}},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=PR(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.releaseAttached(),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 bi=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 Ia(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new dc(e.runtype);case"browser":if(!bi.isSupported())throw new Error("Browser speech recognition not supported");return new bi(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 bu(e){if(e?.type==="custom"&&e.custom)return Ia({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Ia({type:"runtype",runtype:e.runtype});if(bi.isSupported())return Ia({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Vh(e){try{return bu(e),!0}catch{return!1}}var fM="webmcp:",IR=e=>e.startsWith(fM)?e.slice(fM.length):e,vu={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},wu=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 vu.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=HR(r.annotations);return{name:r.name,description:r.description,parametersSchema:WR(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 To("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let v=typeof document<"u"&&!!document.modelContext;return To(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=IR(t),a;try{a=await r.getTools()}catch(v){let C=v instanceof Error?v.message:String(v);return To(`Failed to read WebMCP registry: ${C}`)}this.deps.recordToolDisplayTitles(a);let l=a.find(v=>v.name===s);if(!l)return To(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return To(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return To("Aborted by cancel()");let d=this.deps.getToolDisplayTitle(s),u={toolName:s,args:n,description:l.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(u))return To("User declined the tool call.");if(o?.aborted)return To("Aborted by cancel()");let p=new AbortController,m=!1,h=setTimeout(()=>{m=!0,p.abort()},this.timeoutMs),y=()=>p.abort();o&&(o.aborted?p.abort():o.addEventListener("abort",y,{once:!0}));try{let v=await r.executeTool(l,_R(n),{signal:p.signal});return OR(v)}catch(v){if(m)return To(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return To("Aborted by cancel()");let C=v instanceof Error?v.message:String(v);return To(C)}finally{clearTimeout(h),o&&o.removeEventListener("abort",y)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(await this.deps.loadPolyfill()).initializeWebMCPPolyfill(),this.installed=!0}catch(t){vu.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,vu.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??BR;try{return await n(t)}catch(o){return vu.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=>RR(t,o))}},RR=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Cu={type:"object",properties:{}},HR=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},WR=e=>{if(e===void 0||e==="")return{...Cu};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...Cu};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...Cu}}catch{return{...Cu}}},OR=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:NR(t)}]}},To=e=>({isError:!0,content:[{type:"text",text:e}]}),BR=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=DR(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
476
476
|
|
|
477
477
|
Arguments:
|
|
478
478
|
${t}`:"")+(e.description?`
|
|
479
479
|
|
|
480
|
-
${e.description}`:"");return window.confirm(n)},
|
|
480
|
+
${e.description}`:"");return window.confirm(n)},DR=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},_R=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},NR=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var xu=class extends wu{constructor(t){super(t,{recordToolDisplayTitles:Nd,getToolDisplayTitle:oa,loadPolyfill:Fd})}};function FR(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 $R(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:FR(o,n)?2:3}function hM(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Su(e,t){let n=t.trim();if(!n)return[...e].sort(hM);let o=[];for(let r of e){let s=$R(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:hM(r.item,s.item)),o.map(r=>r.item)}function UR(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 yM(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Su(e.items,t),resolve:e.resolve}}function bM(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=>Su(t,UR(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 vM(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,l=m=>{typeof m.scrollIntoView=="function"&&m.scrollIntoView({block:"nearest",inline:"nearest"})},d=m=>{let h=m;return s.findIndex(y=>y===h||y.contains(h))},u=m=>{let h=d(m.target);if(h<0)return;let y=h;if(m.key===r)y=Math.min(h+1,s.length-1);else if(m.key===o)y=Math.max(h-1,0);else if(m.key==="Home")y=0;else if(m.key==="End")y=s.length-1;else return;m.preventDefault(),y!==h&&t.onSelect(y)},p=m=>{let h=d(m.target);h>=0&&l(s[h])};return e.addEventListener("keydown",u),e.addEventListener("focusin",p),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(m,h){if(s=m,m.forEach((y,v)=>{y.setAttribute("role","tab");let C=v===h;y.setAttribute("aria-selected",C?"true":"false"),y.tabIndex=C||h<0&&v===0?0:-1}),a){let y=(h>=0?m[h]:void 0)??m[0];y&&typeof y.focus=="function"&&(l(y),y.focus())}},destroy(){e.removeEventListener("keydown",u),e.removeEventListener("focusin",p)}}}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});
|
|
481
481
|
//# sourceMappingURL=index.cjs.map
|